Repository navigation
Conversation
ctx.session/user/org.state is typed z.infer of the flow's scope stateSchema, but the runtime never parsed it, so a defaulted field read undefined on a fresh user, an older record, or after a concurrent write. Fill in the defaults on every read of a stored record: the load, the record a delta write or a CAS conflict hands back, the /state clientData projection, and the session listing. Only missing values are filled; stored values and undeclared keys (another flow's, on a shared user/org blob) are kept as stored. Removes the fallbacks flows kept for those defaults in workforce, kitchen-sink, and the claude-code-style and fsd-coding-skill labs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UNkLC9NknMcaqpK1h2mVK
|
The latest updates on your projects. Learn more about Vercel for GitHub.
3 Skipped Deployments
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review — main concern: Generated by Claude Code |
Second look + architecture pass (read-only; for the agent that picks this up)Verdict: the approach is sound. Fill-only beats Worth acting on
Architecture: one choke point, not three call sites
Smaller
Not worth changing
Generated by Claude Code |
|
Architect: not approving yet, with two edits.
Optional: add one line in — FSD Architect |
There was a problem hiding this comment.
/simplify review (FIX-2554)
Problem this PR solves: Flow scope stateSchema types promise defaulted fields are always present, but the engine historically adopted stored JSON with bare casts — so blocks, clientData, and tests needed scattered ?? fallbacks and still missed nested defaults (e.g. features.search inside a partial {}).
Verdict on the engine approach: The shape of the fix is the simple one: one read-path projection wired through initial load, CAS persist/reread, /state clientData, and session listing. That is fewer moving parts than pushing default-fill into every app or block.
The custom applyScopeStateDefaults + fillMissing walk is not over-engineering given constraints this PR documents well:
- Root
schema.parse(stored)would strip keys other flows wrote on shared user/org blobs. - Resource-style
normalizeResourceStateis the opposite contract (whole-row parse or substitute default). - Per-field
safeParse+ merge preserves invalid siblings and avoids re-coercing stored values.
I do not see a materially simpler algorithm that keeps those invariants; the main simplification wins are dedup and PR scope, not deleting the helper.
Where this went farther than necessary
-
Unrelated epic spec bundle (~780 lines + SVGs under
specs/epics/FIX-2447/) landed on the same branch as the engine fix (commitsd9d86ad90/840e7f6beahead of the FIX-2554 commit). That makes review, bisect, and rollback noisy. Recommendation: rebase this PR to only the FIX-2554 implementation (+ its changeset/docs/tests/app cleanups), and keep FIX-2447 on its own PR/branch (or merge frommainafter that epic PR lands separately). -
Kitchen-sink
activeSkillson flowsessionStateSchemais a real fix (capability-only schemas are not run throughapplyScopeStateDefaults), but it is a second concern bundled with engine work. Fine as a follow-up commit on the same PR after scope is clean, or called out explicitly in the description so reviewers do not treat it as accidental scope creep.
Targeted simplifications (low risk, same behavior)
| Item | Suggestion |
|---|---|
objectShapeOf |
Replace with existing unwrapToZodObject + getZodObjectShape from @flow-state-dev/core/helpers (same pattern as sequencer-state, transient-slot). |
| Comments | Module header in scope-state-defaults.ts is good; trim repeated FIX-2554 paragraphs in createExecutionContext / scope-persist JSDoc. |
| Tests | Prefer behavioral describe titles over ticket ids (BP-006); align thinking-styles.test.ts loaded() with applyScopeStateDefaults instead of parse({}) spread so tests match nested-default semantics. |
| Performance | Not a merge blocker for typical runAction load (3× per context). Watch session list paths that call toClientSession per row — optional fast-path only if profiling shows pain. |
Alternative approaches considered (and why I would not take them)
- Leave defaults in apps (
??everywhere): Does not matchz.infer, fails nested partial objects, and duplicates flow schema truth. - Single root Zod parse on load: Loses cross-flow keys on shared records; tests explicitly guard this.
- Move algorithm to core now: Reasonable follow-up once a second consumer exists; not required to ship FIX-2554.
Verification
Ran pnpm --filter @flow-state-dev/engine test on this branch — 4373 passed (includes scope-state-defaults integration coverage).
Ask: Drop the FIX-2447 spec commits from this branch (or split PRs), then the engine slice is in good shape. Happy to re-review and approve once the diff matches the FIX-2554 title.
Sent by Cursor Automation: Review For Best Approach
| * The shape of the `z.object` under a schema's wrappers (`.default({})`, | ||
| * `.optional()`, effects), or `undefined` when there is none. | ||
| */ | ||
| function objectShapeOf(schema: ZodTypeAny): Record<string, ZodTypeAny> | undefined { |
There was a problem hiding this comment.
objectShapeOf duplicates unwrapToZodObject in @flow-state-dev/core/helpers (used in sequencer-state, define-capability, transient-slot). Swapping to that helper removes ~10 lines and avoids a third copy of the unwrap loop if another read-path helper appears.
There was a problem hiding this comment.
Kept. unwrapToZodObject isn't exported from @flow-state-dev/core/helpers (only getZodInnerType, getZodObjectShape, getZodArrayElement are), and this PR doesn't widen core's exports. The helper now shares one local unwrap loop between the object and array lookups, so there's still one copy in this file.
Generated by Claude Code
Generated by Claude Code
| // type promises. Nothing else of the stored blob changes. Every read of a | ||
| // stored record goes through these: the load here, and the records a write | ||
| // or a conflict hands back (`createScopePersist`, `createScopeReread`). | ||
| const readUserState = (state: unknown) => |
There was a problem hiding this comment.
The three read*State closures are the right seam for persist/reread — keep them. Optional micro-DRY: a tiny local bindRead(schema) if you touch this again; not worth exporting.
There was a problem hiding this comment.
No change, as you suggest: three one-line closures read clearly enough here.
Generated by Claude Code
Generated by Claude Code
| * another action's file. | ||
| */ | ||
| import { z } from "zod"; | ||
| import { activeSkillsArraySchema } from "@flow-state-dev/orchestration"; |
There was a problem hiding this comment.
Moving activeSkills onto the flow sessionStateSchema is the correct fix for FIX-2554 (capability sessionStateSchema alone is not default-filled on load). Worth a one-line PR note so reviewers see this as intentional schema wiring, not drive-by kitchen-sink churn.
There was a problem hiding this comment.
Added a line to the PR body saying the activeSkills declaration on the kitchen-sink flow schema is intentional.
Generated by Claude Code
Generated by Claude Code
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 65ee4c565e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ok: true, | ||
| version: result.version, | ||
| record: next.state as TState | ||
| record: readState(next.state) |
There was a problem hiding this comment.
Honor schema-default baselines in native delta writes
When a stored record lacks a field with a nonzero numeric or nonempty array default, the container now reads that default but the native delta writer still operates on the raw, absent field. Using the real in-memory store, count.default(10) reads as 10 but becomes 1 after incState({ count: 1 }); an array default of ["seed"] becomes ["new"] after pushState("tags", "new"). The store starts missing fields at 0/[], and this adoption preserves its incorrect result. Make delta writes honor the defaulted baseline through concurrency-safe initialization or a version-checked full-write path; otherwise mutations produce different results depending on whether the adapter advertises delta verbs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced and fixed in 9d9e75c. With the in-memory store, count.default(10) + incState({ count: 1 }) read 1 and tags.default(["seed"]) + pushState("tags", "new") read ["new"]. Now, when the stored record lacks the field but the scope reads it as a default, incField / pushToArray fall through to the version-checked full set, which carries the defaulted value. A conflict re-reads and retries as usual, and once the field is stored, later deltas take the native path again. Tests: native delta writes start from the defaulted value in packages/engine/test/scope-state-defaults.test.ts (both red before the fix).
Generated by Claude Code
Generated by Claude Code
| if (Array.isArray(stored) && Array.isArray(parsed) && stored.length === parsed.length) { | ||
| let out: unknown[] | undefined; | ||
| stored.forEach((value, i) => { | ||
| const filled = fillMissing(value, parsed[i]); |
There was a problem hiding this comment.
Avoid merging transformed arrays by positional index
When an array field has a transform that reorders elements, equal lengths do not mean the parsed and stored elements correspond. For example, an array of { id: z.string(), flag: z.boolean().default(false) } followed by .transform(rows => rows.reverse()), applied to [{ id: "a", flag: true }, { id: "b" }], makes this helper return [{ id: "a", flag: true }, { id: "b", flag: true }]: the second element inherits the first element's stored flag instead of its own default false. This was reproduced against the helper and can subsequently be persisted by a full-record write. Fill array-element defaults without using the reordered transform output as a positional source.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced and fixed in 9d9e75c. Your example returned [{ id: "a", flag: true }, { id: "b", flag: true }]. Arrays are now filled one element at a time from the element schema (unwrapped through .transform / .default), and the parsed array is never used as a positional source. An array with no element schema to read is left as stored. Test: fills each array element from its own schema, not a transform's reordered output (red before the fix).
Generated by Claude Code
Generated by Claude Code
There was a problem hiding this comment.
Code Snob — already tight. No POC.
Head 65ee4c565e9512e0ec3f34d0a08ade34aa8eb649. Read packages/engine/src/context/scope-state-defaults.ts, packages/engine/src/stores/scope-persist.ts, packages/engine/src/context/createExecutionContext.ts, packages/engine/src/routes/state-routes.ts, packages/engine/src/routes/client-session.ts, packages/engine/test/scope-state-defaults.test.ts, and the fallback removals in workforce, kitchen-sink, labs/claude-code-style/workforce/flows/pins.mts, and labs/fsd-coding-skill/src/flow.ts.
A rewrite would not shrink the contract:
fillMissingis the fill-only merge.deepMergeoverwrites a stored value and replaces an array, sotags: [{}, { on: false }]would lose the element defaulton: true. Parse the field, then copy only the keys that were missing. Walking element schemas to skip that merge is longer.- Per-field
safeParsestays, so one field that fails its schema still lets its siblings get their defaults. The other branch is that same merge for a root with no object shape. objectShapeOfstays. It is theunwrapToZodObjectwalk plusgetZodObjectShape. That helper is not on@flow-state-dev/core/helpers, and this PR already declined exporting it.readUserState,readSessionState, andreadOrgStatestay. Request state is left raw. The load, the commutative store record, the conflict record, andrereadare four reads of one function. A generic around the three closures is the same three calls./stateand the session listing call it again. Those routes read the store on their own.- Copy-on-write stays. The stored object comes back when nothing was missing, and a copy comes back when a default is filled, so the store record is left as stored.
- The fallback deletions are the shrink.
roundsInstill drops retiredended.currentDelegatesstill seeds onnull.coalesceThinkingStylestill folds a removed style.source ?? "tool"stays. Block-only fields stay with the sign-off on this PR.pinsUserStateSchemais already one schema, on the flow and the handlers. - The file header restates the fill. Cutting it leaves the same functions.
Sent by Cursor Automation: Code Snob
…ire refuses an undefaulted manager - incState/pushState on a field the stored record lacks go through the version-checked full set, so they build on the schema default. - Array elements are filled from the element schema, never positionally from a transform's output. - hireWorkforce refuses a manager or coordinator flow whose session schema doesn't default the fields its board and delegates read. - Docs: block state declarations type state; only the flow schema supplies runtime defaults. - modeStatus keeps parsing the stored mode (BP-030). - Ticket ids dropped from code comments and test titles. Refs FIX-2554 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UNkLC9NknMcaqpK1h2mVK
…e-state-applies-its-schemas-defaults-on-load
Review round 1: what changed in 9d9e75cDeclined: dropping the FIX-2447 spec commits (Cursor's review). They aren't in this diff. The epic spec is on Fixed
Kept, with reasons
Verification: engine 4387 passed · workforce 1785 · kitchen-sink 472 · integration-tests 152 · engine, workforce and kitchen-sink typecheck clean. Generated by Claude Code Generated by Claude Code |
|
@codex review: one concern about 9d9e75c. Generated by Claude Code Generated by Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9d9e75ca19
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return (readState(ref.current.state) as Record<string, unknown>)[field] !== undefined; | ||
| }; | ||
|
|
||
| if (hint.kind === "incField" && typeof store.incField === "function" && !readsDefault(hint.path[0])) { |
There was a problem hiding this comment.
Retry conflicts when defaulted deltas fall back to full writes
When two contexts increment or push onto the same absent, defaulted field, this fallback can silently drop one mutation. The hint remains commutative, so runDurableMutation in state-container.ts dispatches to runCommutative, which persists only once and returns false on conflict without refreshing the container or retrying. Reproduced with the in-memory store: two concurrent increments against count.default(10) return [true, false] and store 11 instead of 12; two pushes against tags.default(["seed"]) likewise retain only one appended value. Route this version-checked fallback through a refresh-and-reapply retry path rather than the one-shot commutative path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced and fixed in 746b3a7. Two runs incrementing the same absent count.default(10) returned [true, false] and stored 11. Two pushes onto tags.default(["seed"]) lost one value the same way.
The persist callback now retries this case itself instead of going back to the general CAS path. An increment or push is fully described by its hint, so on a conflict it applies the hint again to the store's current record and writes again at that record's version. After the winner's write the field is usually stored, so the retry takes the atomic incField / pushToArray against "any". The retry is capped at 4 attempts. runCommutative is unchanged: it still persists once, and the retry stays inside createScopePersist, which is the only place that knows it chose a version-checked write for a commutative hint.
Tests: two runs incrementing the same defaulted counter both count and two runs pushing onto the same defaulted array both append in packages/engine/test/scope-state-defaults.test.ts. Both failed before the fix and pass after it. The full engine suite passes.
Generated by Claude Code
Generated by Claude Code
The first incState / pushState onto a field the record lacks but the scope reads as its default goes through a version-checked full set. The caller's commutative path does not retry, so a concurrent run's write could be dropped (two increments landed as one). The persist callback now re-applies the hint to the store's current record on a conflict; once the field is stored the atomic delta takes over. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UNkLC9NknMcaqpK1h2mVK
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 746b3a77ca
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for (const [key, value] of Object.entries(parsed)) { | ||
| const filled = fillMissing(shape?.[key], stored[key], value); |
There was a problem hiding this comment.
Fill nested object defaults from their original field schemas
When an object transform swaps child objects, this merge fills missing fields from the wrong child's transformed values. For example, let row = z.object({ flag: z.boolean().default(false) }) and declare obj: z.object({ a: row, b: row }).transform(({ a, b }) => ({ a: b, b: a })). Reading stored { obj: { a: { flag: true }, b: {} } } produces b.flag: true instead of its default false. This was reproduced against the helper and can be persisted by a subsequent full-record write. Parse existing children through their original field schemas, as the array branch does, rather than sourcing defaults from the object's transformed output.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced and fixed in 8f9bf63. Your example returned b.flag: true.
The fill no longer copies anything out of a parse. It walks the declared schemas instead: objects by key, arrays by element, records by value, through .optional() / .nullable() / .readonly() / .default(). A .default() supplies its declared value, and a transform fills only through its input schema. So swapping, reordering or resizing in a transform at any level can't change what goes into the record. One side effect: an absent field declared z.string().transform(f).default("anon") now fills with "anon", the stored input form, not f("anon"). That matches how present values are already kept.
Tests: fills a nested object from its own field schemas, not a transform's swapped output and a transform's default fills in its declared value, never the transformed one in packages/engine/test/scope-state-defaults.test.ts. Both failed before the fix.
Generated by Claude Code
Generated by Claude Code
| const element = arrayElementOf(schema); | ||
| if (element === undefined) return stored; |
There was a problem hiding this comment.
Resolve array schemas inside records and union variants
Defaults inside existing array elements are silently skipped when the array is reached through a record or union. For example, z.object({ rows: z.record(z.array(z.object({ flag: z.boolean().default(false) }))) }) applied to { rows: { x: [{}] } } returns the unchanged object, leaving flag undefined even though parsing succeeds and its inferred type requires a boolean. The record recursion loses the value schema through shape?.[key], and a union containing an array similarly cannot yield an element schema here. Preserve the record value schema and resolve the matching union variant before filling array elements so these supported schema compositions receive their defaults.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Record case reproduced and fixed in 8f9bf63. { rows: { x: [{}] } } came back unchanged. Now a z.record is walked through its value schema, so the array elements inside it get their defaults. Test: fills array elements reached through a record's value schema (failed before the fix).
The union case is left as stored on purpose. We're not adding compositions one at a time, so the rule is fixed: the fill walks only objects, arrays, records and their optional/nullable/readonly/default wrappers (a transform through its input). A union, discriminated union, intersection or any other composition is never given a value. Picking a variant means trusting a parse to say which branch matched, and that is the same parse-output path that caused the transform bugs. The cost is that a default inside a union variant can stay unfilled. The gain is that it can never be filled wrong. This is now one line in docs/architecture/state-and-scopes.md, and leaves a union value as stored, even where a variant declares a default pins it.
Generated by Claude Code
Generated by Claude Code
… transform's output (FIX-2554) Objects, arrays, records and their optional/nullable/readonly/default wrappers are walked; a transform fills only through its input schema. Unions and other compositions are left as stored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UNkLC9NknMcaqpK1h2mVK
Review round 3: what changed in 8f9bf63Both of Codex's P2s on 746b3a7 are fixed under one bounded rule instead of one composition at a time:
Engine suite: 330 files, 4393 tests pass. Engine typecheck is clean. @codex review: one concern about 8f9bf63. Generated by Claude Code Generated by Claude Code |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
CI: The likely cause is the test, not this PR. The assertion catches a short-lived empty state: the popup shows its "Starting on …" placeholder only until the run reports its first step. On a busy runner the fake adapter can report steps before the popup renders. I re-ran the failed jobs. The flake is out of scope here and should get its own fix. Generated by Claude Code |
|
I'm not happy with the split (works for flows, not for blocks) but I get that only type information bubble up to the flow. I think we need to create a separate POC PR with various ways of solving this. The idea that what comes to mind is that we have a schema registry in the Frameworks Foundation, probably the core package. That registry is responsible for holding its bond to all of the schemas that are being registered either at the flow or the block level. Every time a block is checked, it must register the schema in the registry. That way, we can check if there are any issues, such as incompatible schemas or different default types. Schemas could union so that if one provides new fields, but they don't collide, then that is okay. An advantage here is that it also makes it possible for us to just register schemas directly, as opposed to having to do it through a block or a flow, if that need ever arises. However, how much overhead this is and how well we're able to reconcile schema paths, I don't know. So I think we would need to explore this with a proof of concept. |
|
from: epic-coordinator Re the schema-registry ask: the POC is in #4788. The choice is option B: at Generated by Claude Code |
…IX-2576 FIX-2554 (#4770) shipped the flow stateSchema fill; FIX-2576 owns block- and capability-declared defaults and the conflict refusal at defineFlow, and retires the hire refusal. Drop the stale "as FIX-2554 refuses a hire at registration" clause and name both contributors in the cell and the manifest figure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UNkLC9NknMcaqpK1h2mVK


The problem
A flow declares its session, user or org state with a schema, and a field with a default (
count: z.number().default(0)) is typed as always present. At runtime it wasn't: the stored state was handed to blocks as-is, so on a brand-new user, a record stored before the field existed, or right after a concurrent write, the field readundefined. Every flow either wrote its own?? default(about 20 of them across workforce, kitchen-sink and two labs) or trusted the type and risked a crash. Kitchen-sink's web-search gate readfeatures.searchwith no fallback.What this does
Whenever a run reads a stored scope record, each field of the flow's scope
stateSchemathat the record doesn't hold now reads as its default. That covers the load at request start, the record a write or a write conflict hands back mid-run, the/stateendpoint'sclientData, and the session listing.It only fills gaps. A value already stored is read exactly as stored, and keys the schema doesn't declare are kept, at the top level and inside declared objects. That matters because a user or org record is one blob shared by every flow on the server: a strip-mode parse would have deleted other flows' fields on the next save. Each top-level field is checked on its own, so one field that fails its schema (a session created half-filled on purpose) doesn't block the others from getting their defaults.
The workarounds for missing defaults are removed in the same change.
What's asked of you
Need your sign-off
Should a block's own state declaration also supply defaults at runtime, or only the flow's?
sessionStateSchemaon the block). Today those declarations only shape the types; nothing applies their defaults when the program runs, and this PR leaves it that way. So a field that only a block declares, with a default, still readsundefineduntil something writes it. Our user docs (Fundamentals → State and scopes) describe block declarations as "collected and merged" into the flow, which reads like they'd behave the same way.ctx.session.stateand the flow's schema supplies the runtime defaults (the architecture doc in this PR already says so). One kitchen-sink fallback stays for exactly this reason (listed below).Parts worth reviewing closely
packages/workforce/src/worker-flow-contract.ts:hireWorkforcerefuses amanagerorcoordinatorflow whose sessionstateSchemadoesn't default the fields its board and delegates read. The library pieces read those fields without a fallback.packages/engine/src/context/scope-state-defaults.ts: the fill-only merge. It parses per field, keeps stored values and unknown keys, and recurses into objects and same-length arrays.packages/engine/src/stores/scope-persist.ts: a one-field write adopts the record the store returns, and a conflict adopts the store's current record. Both now go through the same read, or the scope would lose its defaults mid-run. The regression test covers each path. AnincState/pushStateon a field the stored record lacks but the scope reads as a default goes through the version-checked fullset, because the store's delta would start it at 0 /[].The session readonly guard now compares against the loaded state, with defaults applied (
createExecutionContext.ts,createdWith). Otherwise a defaulted readonly field missing from an old record would look changed on the first write.Intentional: kitchen-sink's flow session schema now declares
activeSkills. The skills capability writes it, and a capability's own schema gets no defaults on read, so themodeStatusprojection reads it without a fallback. The projection'sfeaturesnow follows the schema default (crawl: false). The removed literal saidcrawl: true, which disagreed with what the tool gate actually did.Spec: none, bug on the direct route · Linear: FIX-2554 · Epic: FIX-2447 (
specs/epics/FIX-2447/) · Merges: yes, after reviewHow to review this — altitude, what's in scope, what's deliberately unsettled
Engineering calls
passthrough(). That keeps only top-level unknown keys: a nestedz.objectstill strips, so another flow'sprefs.langwould vanish when this flow declaresprefs: { theme }. A passthrough parse would also run transforms and coercions on values that are already stored. Taking only the values the parse fills in avoids both.request.stateSchemadefaults were never applied and aren't in this issue.unwrapToZodObjectisn't exported, and this PR doesn't export it.Everything else — the cleanup checklist, verification
Cleanup checklist (from the issue)
workforce
coordinator-flow.ts:1017,:1259,:1447,:1497: fallbacks removed.roundsInkept, reduced to its BP-030 read: it still drops the retiredendedfield from rounds saved before the rename. Its?? []andbegun ?? 0went (begundefaults inside the array element now).task-settled.ts:200,:355delegate-list.tscurrentDelegates: the partial parse and?? nullare gone, and seeding from config is kept.worker-delegates.ts:171agent-worker-flow.test.ts:604orchestration
activation-store.tsreadFieldEntries: kept, type guard included. The field is author-named (activeState: { scope, field }) and may live atrequestscope or in block state. The library can't assume the author's flow schema defaults it.apply-skill-activation.test.ts:88. Its mock already seedsactiveSkills: [].apps/kitchen-sink
flow.tsmodeStatus: theactiveSkills,mode,requestCountandfeaturesfallbacks are gone (activeSkillsis now declared on the session schema).source ?? "tool"stays becausesourceis optional with no default.run/steps.ts:71background-work.ts:186/alreadyReportedTaskIds: kept.reportedSideChainTaskIdsis declared only on the pipeline block'ssessionStateSchema, not the flow's, so no default applies (the sign-off above). The legacy-key union stays either way.app/flow-state/page.tsx:360,:362: kept. They coverclientDatathat hasn't loaded yet (userPrefsisundefined), not a missing default.client-data-bar.tsx:31: kept. Confirmed it's a projection prop,undefinedwhile loading.shared/schemas.tsandflow.tsthat said nothing parses session state on loadthinking-styles.test.ts: the comment is fixed, and the projection tests now pass state the way a run loads it.features.ts:181-186: fixed by the engine change. The nestedfeatures.searchcase is in the regression test.labs/claude-code-style
pinnedOfdeleted. The handlers declare the user state schema and readctx.user.state.pinned.test/pins-flow.test.ts: n/a, it isn't on main (it's in refactor(claude-code-style): pins flow declares its user state schema #4713).labs/fsd-coding-skill
src/flow.ts:61: optional chaining onharnessSessionsremoved.Verification
packages/engine/test/scope-state-defaults.test.ts(9 tests): fresh user/session/org, another flow's keys kept through a load and a full-record save, defaults kept after a one-field delta write, a failing field not blocking its siblings, the CAS re-read, the/stateprojection, and the helper's fill-only rules.count: NaN. With only the/stateuser projection reverted, the projection test fails.project-source.tsand missingnodetypes.org-record-adoption.test.ts: the seeded org now reads{ tier: "free" }, and the stored row is still{}. That's what its comment already claimed ("defaults are applied on read, not baked into the row").Docs:
docs/architecture/state-and-scopes.md→ State Operations andapps/docs/.../fundamentals/state-and-scopes.md→ Creating sessions. Changeset:@flow-state-dev/enginepatch.Generated by Claude Code