Skip to content

Add v2 API redesign plan - #6

Merged
eralmansouri merged 34 commits into
mainfrom
claude/v2-plan-review-e13a11
Jul 7, 2026
Merged

eralmansouri merged 34 commits into
mainfrom
claude/v2-plan-review-e13a11

Conversation

@eralmansouri

Copy link
Copy Markdown
Owner

Plan for the ergonomics-driven v2: arktype type expressions with
auto-scoped bindings, always-required resultType verified against eval,
correlated eval binding types, associativity derived from tail shape,
numeric-only precedence, built-in boolean/null/undefined literals, and
string escape handling.

Co-Authored-By: Claude Fable 5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C

claude added 23 commits July 6, 2026 21:48
Plan for the ergonomics-driven v2: arktype type expressions with
auto-scoped bindings, always-required resultType verified against eval,
correlated eval binding types, associativity derived from tail shape,
numeric-only precedence, built-in boolean/null/undefined literals, and
string escape handling.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
…() closing rule

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Schemas as arktype scopes with .get()/keyof() resolution, compiled
rules exposed as arktype Types (Standard Schema ecosystem), ArkErrors
for evaluation failures, match-based eval dispatch, set-operation
constraint matching with ambiguity linting, and a usage-discipline
section covering perf and stability caveats.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Type-level: 500-deep recursion with per-level arktype assignability
checks adds ~3k instantiations over control thanks to TS memoization
of finite def sets; ~1.2k instantiations one-time per distinct def.
Runtime: extends/get/keyof/scope-spread/match/narrow/toJsonSchema all
verified; three API-shape corrections recorded in RESULTS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Breaking redesign per V2-PLAN.md:
- Constraints and resultTypes are arktype defs compiled in the parser's
  scope; matching is assignability (memoized extends), not name equality
- Binding references replace sameAs/fromBinding: rhs('left') means
  'assignable to what left parsed as', resultType 'then' derives from
  the binding; resultType is required for all constructing nodes and
  supports object defs
- Associativity derives from the pattern's tail shape (lhs tail = left
  fold, rhs tail = right recursion); the associativity property and the
  'atom' precedence sentinel are gone (highest level = leaf level)
- expr() elements must be closed by a constVal (precedence-leak guard)
- Schemas are arktype object defs: identifier/path types resolve via
  Type.get, values are validated against the schema on evaluate(),
  refinements erase for typing but enforce on values
- Eval return types are verified against the declared resultType at
  compile time (EvalReturn + NoInfer)
- Type-level engine deferred to Phase 3 (placeholder Parse<>); typecheck,
  87 runtime tests, build, and package checks all green

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
rhs(overlapping('left')) accepts an operand whose type OVERLAPS the
referenced binding's type instead of requiring a subtype, so x == 1 and
1 == x both parse for x: string | number while disjoint comparisons
still fail. Fixture eq switched to the symmetric form. Also fixes a
type-level inference bug where intersecting a found pattern element
with the PatternSchemaBase union polluted constraint inference.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Literal-mode parse()/evaluate() are compile-time validated again:
numeric grammar computation with leaf-last levels, tail-shape
associativity (tail-recursive left fold), constraint assignability via
type.infer over literal defs, overlapping() as non-never intersection,
binding references resolved against the parsed prefix, and typed
evaluate() results. Restores the full type-level test suite with
recursion canaries (30-term chains, 8-term pow, 3-deep parens).

Notable: arktype's type.validate/type.infer as sibling parameters of a
conditional-typed input parameter poison generic inference — evaluate()
wraps values in NoInfer and eager schema-leaf validation lives on
safeParse only; widened or never precedence types now resolve the
grammar to never instead of recursing unboundedly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
…nism, parsebox escape findings, distribute() reminder

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GQrzid8mJPWM4HMb6Cf6C
Plan review corrections (V2-PLAN.md):
- D5 mechanism was wrong: TS 5.9 does not narrow sibling properties
  through typeof on a shared property (needs unit-type discriminants);
  the distributed union's payoff is arktype match (D14), verified
  empirically before building on it
- API sketch still showed directional rhs('left') for eq; the
  implemented design uses the symmetric overlapping('left')
- Handoff bullet said "version 0.1.0", contradicting D10 (0.0.x only)
- Risks 1/2/4 marked resolved; D3 cross-references the passthrough
  exemption; migration table distinguishes operand-slot vs
  equality-operator sameAs migrations

Phase 4 implementation:
- InferEvaluatedBindings types reference-linked bindings as a
  distributed union over the root's constraint members, split at DEF
  granularity ("string | number" distributes; "boolean" stays one
  branch), chains resolving to one group, cross product across groups
- Fixture add is cast-free via match over the correlated union;
  matchers must be wrapped (eval's second argument would land in
  arktype's traversal-context slot)
- createParser(nodes, { dev }) asserts each eval output against the
  node's per-parse resolved Type via precompiled allows(); defaults to
  on outside NODE_ENV=production; deserialized ASTs skip the check
- OUTPUT_TYPE symbol moved to runtime/types.ts so the evaluator reads
  it without an import cycle

Bug fix found during review: runtime/types.ts contained a raw NUL byte
in the assignability-cache key (git treated the file as binary), and
the overlap cache used a space separator, which can collide because
arktype expressions contain spaces. Both keys now use the escaped "\0".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
…caveat scope

From an adversarial review of 34af413 (which also confirmed the add
fixture's lhs()-tail pattern is correct per D6 associativity-by-shape):
- dev-mode assertions now default ON when no process global exists,
  matching the documented "on outside NODE_ENV=production" behavior in
  browsers without a bundler define
- result-assertion messages no longer read "a undefined"/"a object"
- the correlated-bindings soundness caveat now also covers overlapping()
  referencers straddling via union-typed identifiers, not just roots

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
lhs/rhs read as left/right position, but they encode which grammar LEVEL
the slot parses at (tighter vs same) — the tail's role is what derives
associativity. operand() and rest() say what they do. Role strings in
schema data and all internal helper names renamed to match; expr()
unchanged. Remaining lhs/rhs mentions in V2-PLAN.md are v1 references
(migration table's v1 column, D6's v1 rationale).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
- New leaf pattern elements boolean() (true/false), nullVal(),
  undefinedVal(); keyword-prefix guard via whole-identifier comparison
  (nullable never matches null), mirrored in the type engine
- Keyword literals carry base types (boolean/null/undefined), matching
  the number-literal convention; unit result types stay deferred
- Escape-aware string scanner replaces parsebox Token.String in BOTH
  engines: \n \t \r \\ \" \' \` \0 \b \f \v, unknown escapes resolve to
  the escaped char; \xHH/\uHHHH decode at runtime only (literal mode
  rejects them — hex is undecodable at the type level)
- StringNode now carries raw (source escapes intact) + value (unescaped)
- Fixture gains bool/null/undefined leaf nodes ordered before variable
  (alternation is ordered; keywords must win over identifiers)
- 13 new tests pin the two verified parsebox differences: escaped-quote
  termination and real-character escape values

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
- Boolean-output rules compile to predicate Types: schema validation
  (refinements included) then narrow with ctx.reject({expected,
  actual: '', path}) so failures are field-attributed ArkErrors and
  secret values never leak into messages
- Other rules compile to morph Types: values in, evaluated result out
- CompiledRule typing: literal predicates type as Type<values>, literal
  morphs as Type<(In: values) => Out<result>>, dynamic strings as
  morph-to-unknown; compile accepts dynamic strings (rules live in
  config) and throws StringentParseError on invalid input
- Standard Schema surface verified against ~standard directly; JSON
  Schema export of predicate rules documented to need the predicate
  fallback (it throws otherwise — D12 nuance recorded in the plan)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
- DESIGN.md now describes the v2 architecture: arktype type environment,
  assignability matching, refinement erasure, binding references and
  overlapping(), correlated eval bindings + match idiom, associativity
  by tail shape, keyword literals and escapes, dev-mode assertions,
  compile() rule-as-Type, two error domains, engine divergences
- README quickstart rewritten to the v2 API and verified to compile
  (caught a stale example calling x*2 with no mul node)
- vitest bench suite (pnpm bench): safeParse shapes, evaluateAst
  dev-on/off (~2% assertion overhead — validates the default),
  compiled-rule pass/fail, createParser construction

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
All 8 doc pages and the playground grammar rewritten for v2: operand()/
rest() roles and associativity by tail shape, arktype defs with
assignability matching, binding references and overlapping(), correlated
bindings + match idiom, keyword literals and string escapes, compile()
rules-as-Standard-Schemas, dev-mode assertions, and the two-domain error
model. Every substantial snippet was extracted and verified against the
real engine (tsc --noEmit + vitest), quoted error messages and results
are actual engine output, and the docs site builds green (twoslash
compiles snippets on every build).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
The whole-string restriction on binding references is lifted — the owner
challenged its justification and the spike proved them right:

- spike/union-defs: scoped inference (type.infer<"left | null",
  {left: Acc}>) costs ~10 instantiations per level at depth 500 (+5k
  over control) thanks to TS union normalization reaching a fixed
  point; the blowup only exists for TEXTUAL def synthesis, which dies
  with TS2589 at depth 30. The original concern was attached to the
  wrong mechanism.

Constraints and resultTypes may now EMBED binding names in larger defs
(rest("left | null"), resultType: { value: "left" }):
- runtime: TypeEnv.compileDefIn extends the parser's scope with the
  parsed sibling Types (memoized by def + alias expressions, ~160ns);
  compile.ts classifies such defs as "template" kinds, validated at
  construction via resolvesWith (const bindings excluded)
- type level: ResolveDefIn resolves defs with type.infer<def, scope>,
  keeping plain defs literal (display + memoization) and wrapping
  scope-dependent results in a ResolvedDef carrier ({"~resolved": T} —
  reserved key), since a TS type cannot be turned back into a def string
- template outputs feed downstream constraint checks in both engines;
  chained templates normalize to a fixed point (pinned by tests)
- eval-binding typing through templates stays conservative (unknown)

DESIGN.md, the schemas guide, and the plan (D17 + superseded bullets)
updated; 5 runtime tests + 7 type-level assertions added.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
Owner directive: no hand-waving — every limit, odd behavior, and
divergence stated in DESIGN.md now carries a small code snippet, and
each snippet is pinned by an executable twin so claims cannot rot:
src/design-claims.test.ts (23 runtime demos) and
src/design-claims.typetest.ts (compile-time demos with load-bearing
expect-error directives).

The audit corrected the document in four places:
- the object-overlap corner is the one NON-conservative divergence
  (parse("a == b") over disjoint-prop objects compiles, then throws) —
  DESIGN previously claimed all divergences were conservative
- unknowns in overlapping() slots diverge conservatively the other way:
  zz == yy parses at runtime (fails at evaluation) but is a compile
  error in literal mode
- an unknown identifier leading a left-fold level reports
  UNEXPECTED_INPUT rather than TYPE_MISMATCH (the fold never starts and
  the prefix parses alone) — recorded under the ranking weakness
- the ranking-weakness section now shows the actual misleading message
  ("Expected a boolean expression", not the missing ')')

Also pinned: safeParse leaf-typo compile errors vs evaluate's
runtime-only check, refinement erasure vs values enforcement, sibling
non-narrowing, the bare-matcher crash, the straddle hole, tail-shape
associativity flips (3 vs 7 from the same tokens), keyword ordering
trap, dev assertions, secret-free predicate errors, and the JSON Schema
predicate fallback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
Owner asked for elaboration; bisection sharpened the claim into two
distinct mechanisms, both now demonstrated in design-claims.typetest.ts
against the real ValidatedInput/EvaluateResult signature types (exported
for that purpose):

1. DETERMINISTIC: a bare type.infer<TSchema> values parameter lets the
   values ARGUMENT leak in as an inference candidate — TS inverts the
   mapped type inside infer and unions the candidates, fixing TSchema to
   {x: "number"} | {x: 41}; the 41 leaf is not a def, so Parse<> over
   that branch fails and the conditional input collapses to never. The
   reveal-the-generic probe pins the union exactly. NoInfer on values
   removes the candidate; this is why it is load-bearing.

2. METASTABLE: type.validate on the schema of a signature whose input is
   the deferred-conditional ValidatedInput sits on TS's instantiation
   edge — the byte-identical declaration+call typechecks in one file and
   collapses to input: never in another whose declarations are ordered
   differently (it even typechecks project-wide when placed on the real
   evaluate — tried and reverted). An API whose inference depends on
   unrelated neighbors is unshippable, which is why leaf validation
   lives on safeParse only: validate + a PLAIN input parameter infers
   exactly (also pinned).

DESIGN.md's validation-layer section, the Parser interface JSDoc, and
the V2-PLAN gotcha now state the two-mechanism version instead of the
blanket "poisons generic inference".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
F1 (medium-low): distinct morphs share an .expression, so the
expression-keyed assignability and scoped-def caches collided for
morph-typed schema leaves — a fresh parser THREW out of safeParse
("intersection of distinct morphs is indeterminate") while a seeded one
silently accepted. Fixed: morph-containing Types get a per-instance id
appended to every cache key, and extends/overlaps are wrapped so an
indeterminate intersection is a conservative false instead of a throw —
safeParse stays no-throw in both orders (regression-pinned).

F2 (low-medium): the "~resolved" carrier key was documented as reserved
but not enforced — a user resultType of { "~resolved": "number" } built
fine and silently inferred the def-string literal type. createParser now
rejects it at construction.

F3 (low, DX): a template applying a refinement to a reference
(rest("left > 5")) failed construction with "'left' is unresolvable" —
a lie. The error now says references validate as 'unknown' at
construction and refinements must live on the referenced operand's own
constraint.

All three pinned in design-claims.test.ts under "review findings".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
Comment thread src/createParser.test.ts Outdated
const p = createParser([num, variable, dateVar] as const, {
scope: { Timestamp: "number" },
});
// Known limitation (deferred): compile-time schema validation is

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not good at all

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The scope-blind casts are gone in PR #7 (94c6ee3): the parser's inferred scope now threads through type.validate, literal-mode parsing, and result typing, so { created: "Timestamp" } validates at the leaf and types end-to-end with no casts. (Constraint-side aliases were dropped instead — the pattern builder is self-contained by design, so a node is fully checkable at its definition site.)


Generated by Claude Code

Comment thread src/schema/index.ts
export function isSameAs(value: unknown): value is SameAsRef {
/** Runtime type guard for the overlapping() marker */
export function isOverlapsRef(value: unknown): value is OverlapsRef {
return (

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The whole project depends on arktype, why are you randomly doing these checks here?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As of PR #7, all def checking is arktype's — compile time (builder type.validate) and construction time. isOverlapsRef is only the discriminant for the overlapping() marker object (string-vs-marker), not a hand-rolled type check.


Generated by Claude Code

Comment thread src/schema/index.ts
? undefined // widened string type → unconstrained
: Exclude<C, undefined>
: undefined;
export type ConstraintSpec = string | OverlapsRef;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again where is the validation? operand("asfsdafsdaf"), operand("nmbr"), and so on. What is the purpose of the project if not to be type-safe?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in PR #7 (19eba92): patterns are now authored through a fluent builder whose chained calls validate every def via arktype's type.validate<def, $>, with earlier bindings as scope aliases — operand("nmbr") no longer compiles; it errors at that exact call with arktype's own message. Pinned in design-claims.typetest.ts "pattern builder".


Generated by Claude Code

Comment thread src/schema/index.ts Outdated
readonly precedence: TPrecedence;
readonly resultType?: TResultType;
readonly associativity?: TAssoc;
readonly lazy?: TLazy;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer that lazy is always true and avoid having unnecessary props like this.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in PR #7 (12984be): lazy is deleted and evaluation is uniformly lazy — eval always receives memoized thunks, so short-circuiting needs no opt-in and side-effecting children evaluate at most once (pinned in evaluate.test.ts "uniform laziness").


Generated by Claude Code

Comment thread src/schema/index.ts Outdated
readonly resultType?: TResultType;
readonly associativity?: TAssoc;
readonly lazy?: TLazy;
readonly eval?: (

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are the runtime values not typed or inferred in any way?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honest answer: it couldn't be typed — the values object's shape is only known per evaluate() call, never at defineNode. And nothing used it (ident/path elements already deliver resolved, typed values as bindings). So PR #7 (12984be) deletes the parameter entirely; if ambient value access is ever needed it comes back as a designed, typed feature.


Generated by Claude Code

Comment thread src/schema/index.ts Outdated
export type InferNodeType<TSchema extends PatternSchemaBase> =
TSchema extends NumberSchema ? NumberNode
: TSchema extends StringSchema ? StringNode
: TSchema extends BooleanSchema ? BooleanNode

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How are these different than just re-using or effectively aliasing ConstSchema<'"true" | "false"> etc.?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You were right — they're the same thing. PR #7 (2c43980) deletes the keyword schemas entirely: keywords are ordinary const-pattern nodes (pattern: (p) => p.constVal("null").result("null").eval(() => null)). The enabler is a word-boundary rule on identifier-like const values (implemented in both engines via parsebox's ident tokenizer), so nullable never matches constVal("null") — pinned in parser.test.ts and design-claims.test.ts.


Generated by Claude Code

Comment thread src/schema/index.ts
* arktype def. (Used for bindings outside correlation groups — linked
* bindings go through CorrelatedGroups below instead.)
*/
type InferEvaluatedTypeInPattern<

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Complete mess that I won't even bother to even look at

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleted wholesale in PR #7 (12984be). Eval bindings are now a flat per-binding map with a small tail-recursive reference resolver; arktype match remains the polymorphic idiom over the flat type, with .default("assert") as the runtime guard.


Generated by Claude Code

Comment thread src/schema/index.ts Outdated

/** Resolve a named element's evaluated type, or TFallback when absent.
* Gated via a conditional (NOT an intersection with PatternSchemaBase —
* intersecting pollutes constraint inference with the wide base union). */

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get what you're saying here but for the 100th time, every time you make a claim like this, I always always want to see a reference or an inline example snippet of code demonstrating the problem concretely

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The machinery this comment sat on is deleted in PR #7 (12984be), and the no-hand-waving rule is now enforced repo-wide: every surviving comment claim traces to a pinned test, a design-claims entry, or a measured canary (final sweep in 1c81987).


Generated by Claude Code

Comment thread src/schema/index.ts Outdated
: never;

/** Follow reference chains to their root binding (a ← b ← c ⇒ a for all).
* TSeen guards malformed cyclic inputs (createParser rejects them). */

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alwayssss demonstrate the problem

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gone with the correlation machinery in PR #7 (12984be); the claims sweep (1c81987) covers what survived — every claim now has a demonstration or a pin.


Generated by Claude Code

Comment thread src/schema/index.ts Outdated
: never;

/** All binding names covered by some correlation group. */
type CorrelatedNames<

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like any of the above few hundred lines of code code.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same deletion as the thread above — all of it is gone in PR #7 (12984be).


Generated by Claude Code

Comment thread src/createParser.test.ts

it("names the offending nested key", () => {
it("rejects invalid nested schema leaves", () => {
expect(() =>

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

safeParse.... throws?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not anymore — PR #7 (13c8810) makes safeParse never throw: an invalid schema returns { success: false, error: { code: "INVALID_SCHEMA", position: 0 } }. parse/evaluate/compile still throw (as they do for bad input), now uniformly via StringentParseError carrying the same structured error.


Generated by Claude Code

eval: ({ left, right }) => left - right,
});

export const mul = defineNode({

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want a clear explanation of why assoc property was present, why lhs/rhs were added, demonstrate the issues with that design and why this change fixed it.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Written up in PR #7 (1c81987) as "Why there is no associativity property (history)" in the defining-a-grammar guide: the old property could lie (the runtime reinterpreted a left level's rhs() tail regardless of the declared value), and lhs/rhs named position when what they encoded was the parse LEVEL — which is exactly what associativity derives from. Includes the same-tokens-different-math demo (10-5-2 → 3 vs 7), pinned in design-claims.test.ts; the fixture comment links to it.


Generated by Claude Code

Comment thread src/runtime/evaluate.ts Outdated
return schema.eval(evaluated, values);
const result = schema.eval(evaluated, values);

if (options?.assertResults === true) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like any of this, and also creating random options with nonsensical props that you invented is not good. Never again please.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of it is deleted in PR #7 (12984be): the dev option, assertResults, EvaluateOptions, the NODE_ENV sniffing, and the runtime assertion block. The compile-time eval-return check (now at the .eval() chain call) is the check. Understood on inventing options — noted as a standing rule.


Generated by Claude Code

claude and others added 11 commits July 7, 2026 10:01
Converts all 13 review threads into ordered work items (R1-R10) with
anchors, acceptance criteria, and the owner's standing directives
(type-safety first, no invented API surface, no speculative type
machinery, demonstrate everything). Intended for a fresh session or
delegated agents; records the measured hazards a rework must not
rediscover.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Qf5rtrHafZNCm8U79iqUW
Evaluation is now uniformly lazy: eval always receives memoized thunks,
so short-circuiting needs no opt-in and each child evaluates at most
once (pinned in evaluate.test.ts "uniform laziness"). The lazy prop, the
invented dev/assertResults option surface, the NODE_ENV sniffing, and
the runtime output-assertion block are deleted — the compile-time
EvalReturn check is the check. eval's untypeable second parameter
(runtimeValues) is deleted; ident/path elements already deliver typed
values as bindings.

The correlated-bindings type machinery (13 aliases incl. a type-level
def-string splitter) is deleted wholesale. InferEvaluatedBindings is a
flat per-binding map; reference chains resolve transitively to the root
constraint's type via a tail-recursive ResolveReference. arktype match
stays the polymorphic idiom over the flat type, with .default("assert")
as the runtime guard (straddle pin kept in design-claims.test.ts).

EvalReturn now resolves resultType defs that EMBED binding references
("v | null", { value: "v" }) in a scope of the pattern's bindings,
mirroring the engines' per-parse scoped resolution — previously unknown.

DESIGN.md, V2-PLAN.md (D4/D5 reversal notes), and all docs snippets
updated in the same commit; docs build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
…ike consts

Answers the PR #6 review question "how are these different than just
re-using ConstSchema?" — they aren't, once const matching is correct.
BooleanSchema/NullSchema/UndefinedSchema, their factories, the three
keyword node types, ParseKeywordPrimitive, and parseKeyword are deleted
from both engines. Keyword literals are ordinary const-pattern nodes:
{ pattern: [constVal("null")], resultType: "null", eval: () => null }.

The enabler is the word-boundary rule, implemented identically in both
engines via parsebox's ident tokenizer: a const value that is one whole
identifier matches only a whole identifier in the input, so `nullable`
never matches constVal("null") and `andy` never matches constVal("and")
(pinned in parser.test.ts, types.typetest.ts, design-claims.test.ts).
Non-identifier values ("+", "==") match as raw text, unchanged.

Also fixes a latent eraseRefinements bug this surfaced: the arktype JSON
round-trip is lossy for unit types (the `undefined` keyword came back as
the STRING literal "undefined"); erasure now round-trips only when a
refinement was actually stripped. Unit keyword resultTypes are pinned
working end-to-end (resultType "true" satisfies "boolean" slots).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
Answers the PR #6 review comment "safeParse.... throws?". An
unresolvable schema def now returns { success: false, error: { code:
"INVALID_SCHEMA", position: 0 } } instead of throwing — safeParse never
throws, full stop. parse/evaluate/compile keep throwing for programmer
errors, but now uniformly via StringentParseError carrying the same
structured error (one error class, four codes) instead of an anonymous
Error. Pinned in createParser.test.ts; DESIGN.md error model and the
error-handling guide updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
The core of the PR #6 rework ("What is the purpose of the project if
not to be type-safe?"). defineNode patterns are now authored through a
fluent builder — pattern: (p) => p.operand("number | string").as("left")
.constVal("+").operand("left").as("right").result("left").eval(...) —
whose chained calls validate every arktype def against the bindings
accumulated so far, via type.validate<def, $> in direct parameter
positions (the scoped-validate twin of the D17 infer machinery):

- operand("nmbr") is a compile error AT that call, with arktype's own
  message; rest("left") and rest("left | null") compile ("left" is a
  scope alias); refinement-on-reference, position-0/forward references,
  const-binding references, duplicate/reserved/type-shadowing binding
  names, and typo'd result defs all error at their exact call sites.
- .result()/.eval() are chain methods, NOT config siblings: a pattern-
  dependent sibling property makes tuple inference order-sensitive
  (property order flips the result — demonstrated and pinned in
  design-claims.typetest.ts, alongside the validation pins). The chain
  sees the pattern's types locally and is order-robust by construction.
- The builder is construction-and-validation only: NodeSchema still
  stores the same declarative pattern tuple both engines interpret —
  grammar computation and both parsers are untouched.
- eval's return is checked against .result()'s def at the .eval() call;
  "resultType required unless passthrough" is now also structural
  (.eval only exists after .result).
- Standalone element factories are gone from the public API (builder
  methods now); overlapping() remains as the symmetric-constraint marker.
- Constraint-side createParser scope aliases become a runtime-only
  affordance (cast + construction check); call-site schemas keep full
  alias support.

Cost: 1,083,879 → 1,136,550 whole-project instantiations (+4.9%) for
complete definition-site validation; measured threshold noted in
types.typetest.ts. Fixture, all suites, docs, playground, and README
rewritten to the builder in the same commit; docs build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
…peline

Kills the "scope aliases are runtime-only" caveat and its documented
as-never casts ("Not good at all" — PR #6 review). createParser now
carries TScope; the inferred scope (arktype's own scope.infer) threads
through Parser (safeParse/compile schemas validate via
type.validate<TSchema, $>), evaluate's values (type.infer<TSchema, $>),
Context, and the parse-level def algebra — so { created: "Timestamp" }
validates at the leaf, resolves in literal mode, and types the result,
cast-free (pinned in design-claims.typetest.ts and createParser.test.ts).

Two load-bearing perf rules, both canary-pinned in types.typetest.ts:
defs resolve UNSCOPED-FIRST (scoped inference engages only for
alias-referencing defs — paying arktype's deep generic path per
constraint check breaks the 30-term fold), and alias leaf defs resolve
ONCE at ident/path parse time into the existing "~resolved" carrier
(mirroring the runtime, where nodes carry their resolved Type). The
fold-accumulated result chain stays unscoped — threading it doubles
per-level forcing depth (measured); result defs cannot name parser
aliases anyway (builder-validated), leaving only a documented
conservative corner for template results over alias-typed operands.

Also pins a pre-existing, previously-uncanaried floor: identifier-led
left chains cap near 20 terms (literal-led: 30+) — true before this
change too. Whole-project instantiations 1,136,550 → 1,274,619
including the new canaries; threshold note updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
Answers the PR #6 request for "a clear explanation of why assoc property
was present, why lhs/rhs were added, demonstrate the issues with that
design and why this change fixed it": the defining-a-grammar guide gains
"Why there is no associativity property (history)" — the property could
lie (the old runtime reinterpreted a left level's rhs() tail regardless
of the declared value), lhs/rhs named position when they encoded parse
LEVEL, and the shape-derived rule makes the pattern the single source of
truth, with the 3-vs-7 demo pinned in design-claims.test.ts. The fixture
links to it.

Comment-claim sweep: every behavioral claim in source comments now
traces to a pinned test, a design-claims entry, or a measured canary.
HANDOFF.md (the pre-rework work plan) is retired; V2-PLAN's session
handoff is marked CLOSED with a summary of what the rework changed.
DESIGN.md remains the current contract.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
…anaries

An editor report (TS2589 on plain evaluate() calls, a spurious
"shadows a resolvable type" on .as("r")) exposed that the type-level
machinery sat too close to the instantiation-depth cliff on TypeScript
versions with less headroom than the 5.9 toolchain: 5.5-5.8 failed the
scoped canary in batch, and editor tsserver contexts (per-file, cold)
hit collapses even earlier.

Three fixes, verified against TS 5.5.4 / 5.7.2 / 5.8.3 / 5.9.3 / 6.0.3:

- The def algebra is now fully SCOPE-FREE: since alias leaf defs resolve
  once at ident/path parse into the "~resolved" carrier, the scoped
  string/object fallback in InferOfDef was dead code on every in-contract
  path — removing it (and the $ params on DefAssignable/DefOverlaps/
  CheckConstraint/ScopeOfBindings/ResolveSpec) makes constraint-check
  instantiations identical for scoped and unscoped parsers: one shared
  memoization set, ~41k fewer whole-project instantiations.
- ValidateBindingName FAILS OPEN on a collapsed validate: under a tight
  budget arktype's type.validate can degrade to never, and
  [never] extends [TName] is true — that surfaced as the spurious
  "shadows a resolvable type" error on good names. Construction time
  remains the authority for real shadowing.
- Canaries pin COLD floors measured across the version range (scoped
  constant chain 25, alias-led chain 12) — a warm neighboring evaluation
  was masking regressions that editors then hit first; comments document
  the 5.9 capacities and the cross-version measurement procedure.
  DESIGN.md's limits section now states the version dependence.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
…-tested: gone)

Prompted by the owner probing the pinned inference-poisoning limit with
a validate-carrying signature. That probe was the quartet's plain-input
variant (works, but surrenders input validation — "x+" compiles, typed
by its parsed prefix, throws at runtime — and its bare type.infer values
param SILENTLY unions the values argument into TSchema; both now
pinned). But it motivated re-testing the load-bearing half: is
validate + the deferred-conditional input still METASTABLE post-rework?

It is not. Re-tested across 8 declaration-order permutations (including
the original bisect's flip trigger) x TS 5.7.2/5.9.3/6.0.3, warm and
cold, plus a scoped-alias variant: exact inference everywhere. The
rework's depth reductions (scope-free def algebra, carrier resolution)
moved the shape off the instantiation edge.

So parse() and evaluate() now carry type.validate<TSchema, $> on their
schema parameter: a typo'd leaf like { x: "numbr" } is a compile error
at the leaf on EVERY entry point, in the parser's scope. evaluate's
values stay NoInfer-wrapped — the values-candidate poisoning is
unchanged and now pinned in both its loud and validate-masked silent
forms. design-claims.typetest.ts's quartet is rewritten around the
shipped shape (permutation canaries included); DESIGN.md, the guide,
and V2-PLAN gotcha carry the history note.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
… demo

- constVal is now an ordered ALTERNATION (first match wins): one
  booleanLit node replaces the trueLit/falseLit pair everywhere —
  p.constVal("true", "false").as("word").result("boolean")
  .eval(({ word }) => word() === "true"). ConstSchema carries a values
  tuple; both engines try members in order with the word-boundary rule
  per member; ordering semantics pinned (longest-first when members
  overlap) alongside the matched-text binding.

- StringentError is a discriminated union: PARSE_ERROR / TYPE_MISMATCH
  carry required expected+found, UNEXPECTED_INPUT keeps expected
  genuinely optional (the continuation hint), INVALID_SCHEMA is
  position: 0 with neither. Variant interfaces exported;
  StringentParseError (a class cannot be a union) exposes the structured
  union on .error for narrowing. Error-handling guide shows the
  narrow-on-code idiom.

- Pinned the arktype-generics alternative for correlated pairs
  (type("<t extends string | number>", { l: "t", r: "t" }),
  instantiated per member) next to the match idiom in
  design-claims.test.ts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KVGCmuDTgVEC96mwK3WDKQ
@eralmansouri
eralmansouri merged commit 73facc3 into main Jul 7, 2026
2 checks passed
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.

2 participants