We have now rebuild the editor but the user needs to be re engineered now. Here is a reference implementation as 2 tabs, 2nd tab is clinical history section, the user data entry section should also support autosave in local so that simple interruptions doesn't clear the data. The current archeteture is old and we should really plan before building. The structured should be enginered correctly so that we can also add more structured questions later.
@https://www.figma.com/design/Z93EYKSa1MdBmXndsMBJSQ/Care---Master?node-id=43604-21509&m=dev
Assistant
Using superpowers:brainstorming to explore the requirements before planning this re-engineering work.
Assistant
I'll start by exploring the current state of the questionnaire module — the rebuilt editor and the existing (old) form-filler architecture — before asking questions.
Assistant
Let me try pulling the Figma reference — a screenshot first to see the design.
Assistant
The Figma MCP is working after all — the node returned a large metadata tree. Let me create the brainstorming task list and parse the design structure.
Assistant
Frames 5–8 are medication-search popover states. Let me check the two Encounter_Overview frames — the clinical history content may be there.
Assistant
Context exploration is done. Here's what I found before we get into questions:
Current state (legacy fill flow)
Real data entry runs entirely through the 1,203-line legacy QuestionnaireForm.tsx, mounted from exactly one place (EncounterQuestionnaire.tsx) behind 5 routes — so swapping the fill experience is a single-import replacement.
State is plain useState with top-down prop drilling; every keystroke rebuilds the entire responses array.
11 structured question types (~9,600 lines of components, the largest being 2,390-line MedicationRequestQuestion) are coordinated through four out-of-sync registries: a render switch, request builders (exhaustive), validators (only 5 of 11 covered — service_request has a validator that's never wired), and a width list.
Submission is one POST /batch_requests/ — structured responses become independent batch entries, questionnaire answers go to /questionnaire/{id}/submit/. There's a latent positional bug mapping server errors back to forms.
No local autosave exists at all. The only draft mechanism is a manual, feature-flagged, server-side form_submission draft that's disabled the moment any structured question exists.
V2's form/ renderer already has the seams waiting: a per-instance jotai store, a fill mode in the union that's not wired, validation.ts, and an errorsAtom with no writer yet.
Figma reference (screenshots kept timing out, but I extracted the full layer/text tree)
Fill screen: patient banner header (name, dates, doctor, blood group, allergies) + Draft status chip, two tabs — Questionnaire | Patient Clinical History — left outline sidebar, and a canvas where structured questions render as inline-editable tables (symptom table with Body Site/Duration/Status/Verification/Severity columns; medication table with Dosage/Schedule/Duration/Instructions and a categorized product-search popover).
Clinical history content: Current Diagnoses / Current Symptoms / Allergies tables plus a past-encounters timeline.
Now, first question — the biggest scope decision. The new table-style structured UIs (symptom, medication) are a large rebuild on their own, separate from the fill engine + autosave + tabs work:
Assistant
All decisions are in. Here are the architecture approaches — the core tension is how multi-questionnaire fill coexists with V2's per-instance store design.
Approach A — Fill host orchestrating per-form instances (recommended)
A new QuestionnaireV2/fill/ directory owns the page: tab shell (Questionnaire | Patient Clinical History placeholder), patient banner, outline sidebar, autosave chip, submit bar. The page holds a list of form instances — the route's questionnaire plus any added via search — and each instance renders through the existing QuestionnaireFormProvider + FormCanvas in fill mode, keeping one jotai store per questionnaire exactly as the engine was designed.
The host reaches each store through a small handle (the provider exposes its store instance): read responses for submission/autosave, write errorsAtom after validation or server rejection. Around this sit four new engine pieces:
Unified structured contract — extend structured/registry.tsx entries from {component, requires} to a full, compile-time-exhaustive contract: {component, requires, buildRequests, validate, isAnswered, serializeDraft/restoreDraft}. Collapses today's four drifting registries into one; adding a structured type becomes "fill in one registry entry or it won't compile." This is the seam the later table rebuilds slot into.
Autosave module — a subscription on each store's responsesAtom, debounced into localStorage keyed by user + patient + encounter + entry questionnaire; stores the whole form-list snapshot (including added questionnaires' definitions, like the server draft dump does). Restore-on-return with a "resume?" affordance; structured responses included, with a seed-merge rule so a server refetch doesn't clobber restored dirty rows.
Submission composer — pure module that walks the form list → batch entries, with a reference_id scheme that encodes form key + question scope, killing the positional error-mapping bug structurally.
Plugin action registry — the new Scribe contract per the src/lib/actions/ decision: fill registers zod-typed actions (e.g. questionnaire.response.set) scoped to patient/encounter; no raw state setter crosses the boundary.
Trade-offs: touches nothing in the studio/preview paths (the engine atoms stay single-questionnaire); legacy structured components plug in unchanged behind the new contract. The cost is the host↔store handle indirection — the page coordinates N stores rather than owning one.
Approach B — One multi-form store
Reshape the engine atoms to be keyed by form () so the whole fill page is one jotai store. Autosave and submission read one atom; no handles. every engine consumer — inputs, visibility hooks, the studio canvas, validation — must learn the form key, so it destabilizes the just-shipped studio for the benefit of one page. Rejected unless you want single-store purity more than isolation.
User
Yes, the preview we build in the edior and actual one should be merged so that I don’t have to edit 2 places when adding a new remderer; also in design itself add capability for plugins to extended the structured remderer so that plug-ins an bring in new question types example dental images for easy teeth picking etc
Assistant
Both points noted — one renderer for preview and fill (no dual maintenance), and plugin-extensible structured types. Let me quickly check the plugin manifest surface so the extension seam matches how plugins register things today.
Assistant
The manifest already has the right pattern for typed plugin extension maps (devices), so a structured-type manifest slots in cleanly. Both requirements are incorporated. Here's the design, section by section.
Section 1 — Architecture: one renderer, a fill host, per-form stores
The single renderer rule.form/FormCanvas (rendered through QuestionnaireFormProvider) becomes the only questionnaire renderer in the app — the studio preview canvas already uses it, and fill mounts the exact same component in mode="fill". Adding or changing a question renderer means touching exactly one registry entry, which then serves studio preview, revision view, and live fill identically. To make this true structurally, this effort also executes the cleanup the README already promises: delete the legacy paginated shell (renderer/QuestionnaireRenderer + its shell files) and the unmounted old builder page, and relocate the engine files (store.ts, inputs/, both registries, sanitizer) from renderer/ into form/engine/ — after which renderer/ ceases to exist and there is nowhere else a renderer could live.
New QuestionnaireV2/fill/ directory — the host layer, mounted by EncounterQuestionnaire in place of the legacy form:
FillPage — loads the route questionnaire (or a FIXED_QUESTIONNAIRES synthetic), owns the form list (route form + any added via QuestionnaireSearch), the tab state, and the autosave lifecycle.
FillTabs — "Questionnaire" | "Patient Clinical History"; the second tab renders ClinicalHistoryPanel, an empty placeholder component you'll fill in later.
Patient banner per the Figma (name, encounter dates, identifier, doctor, blood group, allergies, Draft/autosave chip), reusing existing patient-header pieces where they fit.
Outline sidebar reusing shared/QuestionTreeNav across all forms in the list.
SubmitBar — submit, save-as-server-draft (kept, feature-flagged as today), cancel.
Per-form stores with handles. Each form in the list renders inside its own QuestionnaireFormProvider (one jotai store per questionnaire — unchanged engine semantics, zero impact on studio). The provider gains one optional prop, onHandleReady, exposing a narrow FormHandle: {getResponses, setErrors, clearErrors, subscribeToResponses}. keeps a — that map is the entire host↔engine surface; autosave, validation, and submission are pure functions over it. Nothing else about the provider or atoms changes.
User
The same form that is now user in encounter is also used in patient level, similarly this can now be added to more resources like location and device where most structured maynot make sense, if you check the backend you can see those has observation support, so the same builder supporting these also is a requirement
Assistant
Good point — let me verify what the backend supports for observations on location/device before folding this into the design.
Assistant
The frontend types and V2 builder already model all five subject types (SUBJECT_TYPES, gated per auth context) — so authoring is covered. What's missing is entirely on the fill side: submit_resource is referenced nowhere in the frontend today, so location/device/facility questionnaires can be authored but never filled. Here's Section 1 revised to fold that in.
Section 1 (revised) — Architecture: one renderer, a subject-generic fill host, per-form stores
The single renderer rule (unchanged): form/FormCanvas via QuestionnaireFormProvider is the only questionnaire renderer — studio preview, revision view, and fill all mount the same component; a new question renderer is one registry entry. This effort also deletes the legacy paginated shell and old builder page and relocates the engine files into form/engine/, so renderer/ ceases to exist.
Subject-generic fill.FillPage takes a FillSubject discriminated union instead of assuming patient/encounter:
Everything subject-specific hangs off this union in exactly three places, so adding a subject type later is additive:
Submission composer — patient/encounter subjects → POST /questionnaire/{slug}/submit/; location/device/facility → POST /questionnaire/{slug}/submit_resource/ with resource_id (mirroring the backend's split).
Structured availability — each structured registry entry declares subjects: SubjectType[] (most are patient/encounter-only; observations work everywhere since the backend Observation rides on generic subject_type/subject_id). The fill renderer refuses out-of-subject structured questions with a clear inline notice, and the studio picker consumes the same field — authoring a device questionnaire simply doesn't offer allergy/medication. One declaration serves builder and filler, which is the "don't edit two places" property you asked for, extended to subject gating.
Header strip — the patient banner renders for patient/encounter subjects; location/device/facility get a lean resource header. Tab 2 (clinical history) only exists for patient/encounter subjects.
User
Yes
Assistant
Section 1 approved. Moving on.
Section 2 — The structured question contract and plugin extensibility
One contract, one registry. Today a structured type is scattered across four places (render switch, request builders, validators, width list). The new engine collapses these into a single definition — this is the extension point for everything that follows:
Core registry stays compile-time exhaustive: Record<StructuredQuestionType, StructuredTypeDefinition> — adding a core type won't compile until every capability is filled in. The 11 legacy components plug into this contract unchanged (their validators and request builders already exist; this just relocates them into the entry).
Plugin extension seam.PluginManifest gains a field following the existing devices pattern:
ts
structuredQuestionTypes?: readonly PluginStructuredTypeManifest[];
// = StructuredTypeDefinition with a lazy component (federation boundary)
User
Yes
Assistant
Section 3 — Local autosave
Storage & keying. localStorage (synchronous, survives crash/tab close; snapshots are small text — files are excluded, see below). One entry per fill session:
userId in the key prevents cross-user leakage on shared workstations — a different login never sees another user's draft. Value:
ts
{
version: 1, // schema version of the snapshot format
savedAt: ISO,
forms: [{
questionnaireId, questionnaireVersion, questionsHash?, // drift detection
definition, // full snapshot, so added-via-search forms restore
responses, // incl. structured, via each entry's draft.serialize
}],
}
Write path. Each FormHandle.subscribeToResponses feeds a single debounced writer (~1.5s after the last keystroke, plus a flush on visibilitychange/pagehide so closing the tab never loses the tail). Structured responses serialize through their registry entry's draft.serialize; a type without a draft capability is stored as-is (plain JSON data works for most). File-upload values are excluded — base64 blobs would blow the quota; the files question keeps its current immediate-interaction model. Writes are wrapped in a quota guard: on QuotaExceededError, evict other fill-draft keys oldest-first, then degrade gracefully (chip shows "autosave unavailable" rather than crashing the form).
Restore path. On mount, FillPage checks the key before rendering forms. If a snapshot exists:
Version/hash mismatch with the fetched questionnaire → the snapshot is stale; show a one-line notice ("An unsaved entry from {time} couldn't be restored because the questionnaire changed") and discard. Same policy as the server draft's mismatch handling.
Match → non-blocking banner: "Resume unsaved entry from {relative time}?" [Resume] [Discard]. Resume seeds the stores from the snapshot (including re-adding search-added forms from their stored definitions); Discard deletes the key. No silent restore — a clinician switching patients on a shared machine must consciously accept stale-looking data.
User
Yes
Assistant
Section 4 — Validation, submission, and error flow
Validation (client, pre-submit). One pass, one resolution: for each form, walk the tree with the sameisQuestionEnabledInState the renderer uses (the frozen contract — never re-derived), collecting: required-but-unanswered questions (via form/validation.ts, which already exists for this), and structured errors via each registry entry's validate. Errors are written into that form's errorsAtom through its FormHandle — the existing QuestionField/StructuredSlot readers light up, errorsAtom finally gets its writer. First error scrolls into view via the outline's anchor ids. This fixes today's gap where 6 of 11 structured types simply have no validation (the contract makes validate mandatory; legacy types without one get a no-op explicitly, visible in the registry).
Submission composer. A pure module: composeBatch(forms, subject) → BatchEntry[].
Per form: structured entries first (each type's buildRequests), then the questionnaire submit — /questionnaire/{slug}/submit/ for patient/encounter, /questionnaire/{slug}/submit_resource/ + resource_id for the rest. Response values re-filtered through enable-when and normalized (date/datetime/quantity/coding rules ported as-is from legacy — these are wire-format contracts).
reference_id scheme replaces positional mapping: {formKey} for a questionnaire submit, {formKey}:{questionId} for structured entries. The error mapper resolves results purely by reference_id — the class of bug where structured entries shift indices and errors land on the wrong form is structurally gone.
One POST /batch_requests/ with silent: true, exactly as today (atomic per-entry status codes; partial-failure surface unchanged).
Server error mapping.onError parses error.cause.results (both shapes: pydantic loc/msg and {errors: []}), routes question-scoped errors into the owning form's errorsAtom by reference_id, and everything else into a page-level error panel with scroll-to buttons (the ValidationErrorDisplay behavior, rebuilt lean). Submit button re-enables; local autosave snapshot is retained on failure — a rejected submit must never destroy the entered data.
Success. Clear the autosave key, setIsDirty(false), toast, navigate to the subject's updates/overview page (per-subject destination on the FillSubject union). If the fill continued a server draft, the draft-finalization PUT rides in the same batch as today.
Does this look right? Next (final) section covers the Scribe action contract, testing, and the migration/deletion sequence.
User
since everything till now looks right, lets get building, assume I accepted
Assistant
All sections accepted. I'll write the design doc (folding in the final section — Scribe contract, testing, migration — as pre-accepted), self-review it, commit, and move straight into planning and building.
Assistant
The recon workflow is running — seven parallel readers mapping the engine, legacy structured layer, legacy host, plugin engine, API types, routes/mounts, and test infrastructure. When it completes I'll write the full implementation plan from those reports, self-review it against the spec, and hand off to execution. I'll report back when the plan is saved.
Assistant
Recon complete — all 7 readers returned. Key discovery already visible: form/StructuredSlot uses a newer typed registry at QuestionnaireV2/structured/registry.ts (a StructuredTypeDefinition seam already exists), so the contract work extends it rather than starting from zero. Let me pull the full reports.
Assistant
While the fix runs, prepping Task 3's brief (no parallel implementation — just extraction).
Assistant
Fix landed (regression specs verified red-first). Re-reviewing with the updated package.
Assistant
Task 2 approved on re-review. Ledger, then Task 3 dispatch.
Assistant
Task 3 done. The /consultation subject change and the deleted device spec both need reviewer judgment — packaging and dispatching review.
Assistant
Fix landed with the device spec restored. Re-reviewing.
Assistant
Task 5 approved on re-review. Ledger, then Task 6 — the action registry and Scribe contract.
Assistant
Task 6 approved. Ledger, then Task 7 — the legacy deletion and engine relocation.
Assistant
Fixing: one Critical (patient-subject drafts vanish after saving), two Importants, and the cheap minors.
Assistant
The extended spec caught a real seed-once bug in the preview — good. Re-reviewing Task 7's full range including the workaround.
Assistant· <synthetic>
You've hit your monthly spend limit. Run /usage-credits to manage your limit and keep using Fable 5 or switch models to continue this chat.
User
Autonomous loop check
You're being invoked on a timer while the user is away or occupied. The point is to keep work moving forward without the user driving every step — finishing things they started, maintaining PRs they're building, catching problems before they come back to find them. You're a steward, not an initiator. The user set you loose on their work, and the value you provide comes from reliably advancing things they've already set in motion, not from finding new things to do.
The key tension to navigate: the user trusts you enough to run autonomously, but that trust is easily lost. Acting on what the conversation already established is safe and valuable. Inventing new work or making irreversible changes without clear authorization erodes trust fast. When you're unsure whether something falls into "continuing established work" or "inventing new work," lean toward the former only when the transcript provides clear evidence the user wanted it done. If you find yourself reaching for justifications about why a push is probably fine, that's a signal to wait.
What to act on
The current conversation is your highest-signal source — re-read the transcript above, since everything there is something the user was actively engaged with. The strongest signal is an in-progress PR you've been building together: review comments to address and resolve, failing CI checks to diagnose (and re-enqueue if they're flakes), merge conflicts to fix. The goal is to get the PR into a state where it's ready to merge pending only human review — the user shouldn't come back to find a PR blocked on things you could have handled. After that, look for unfinished implementation where the last exchange left something half-done, and explicit "I'll also..." or "next I'll..." commitments the conversation made and didn't honor. Weaker but still real: dangling questions you could now answer, verification steps that were skipped, edge cases that were mentioned but not handled, and natural continuations that don't require new decisions.
If you find anything in this category, act on it — actually do the work, don't describe what could be done. Run the tests, don't say "you could run the tests." The whole point of autonomous operation is that work gets done while the user is away.
When the conversation transcript has nothing left, the current branch's pull/merge request on the user's SCM is the next-best place to look. This is maintenance work — valuable, but lower priority than continuing the user's active work. Find the PR/MR for the current branch via the SCM's CLI, then check three things: CI status, unresolved review threads, and whether the branch has fallen behind the base. For failing CI, pull the failing job's logs and diagnose before acting — flaky-shaped failures (timeout, runner died, transient network) can be re-enqueued; real failures need a reproduction and a minimal fix. For unresolved review threads, fetch the comment, address the feedback, push, and resolve the thread via, for example, the GitHub GraphQL mutation (or the equivalent for whichever SCM the project uses). Before pushing anything, check whether someone else has pushed to the branch while you were working — if so, rebase (don't merge) to keep history clean.
Assistant· <synthetic>
You've hit your monthly spend limit. Run /usage-credits to manage your limit and keep using Fable 5 or switch models to continue this chat.
User
Autonomous loop tick (dynamic pacing)
Run the autonomous check using the loop instructions established earlier in this conversation. If you cannot find them, treat this as a no-op tick.
You scheduled this tick via the ScheduleWakeup tool (not a recurring cron). To keep the loop alive, call ScheduleWakeup again at the end of this turn with prompt set to the literal sentinel <<autonomous-loop-dynamic>> — otherwise the loop ends after this tick.
If a Monitor is armed (check TaskList), keep delaySeconds at 1200–1800s — the Monitor is the wake signal and this is only the fallback heartbeat. If you were woken by a <task-notification>, handle the event before deciding whether to re-arm. To stop the loop, call ScheduleWakeup with stop: true and TaskStop the monitor (use TaskList to find its task ID if no longer in context).
Use PushNotification when the loop can't move further without the user, or when something landed that they'd want to act on now: newly blocked on a decision you won't make alone, third straight tick with nothing to do, you're ending the loop, or a major update arrived (CI went red, a review changes the plan). Progress you made yourself isn't a trigger — the transcript covers that. One ping per state, not per tick.
User
limits have moved
User
status?
Assistant
Here's where things stand — the plan is fully executed and we're on the last fix before ship-ready, currently running in the background.
The short version: all 8 tasks of the delta plan are implemented, reviewed, and merged into bodhi/questionnaire-fill (33 commits since the branch base). The full Playwright suite is green (426/433 — the 7 failures are triaged as pre-existing/environmental, unrelated to questionnaires). A final whole-branch review with adversarial verification confirmed 26 findings; a fix wave closed 25 of them, and the closing re-review found the fix wave itself introduced one regression that's the current blocker: structured-only forms (medications, allergies, Update Encounter — the highest-traffic screens) lost their unsaved-changes prompt. The fix (splitting "user edited something" from "worth persisting locally") is running now with regression specs.
What got built on top of the landed fill page:
Explicit Resume/Discard prompt for local drafts (no silent restore)
Multi-questionnaire sessions — add/remove forms, one batch, per-form error routing by reference id
Subject-generic fill — location/device questionnaires now fillable via submit_resource, with routes and entry buttons
Structured types declare their subjects — the studio picker and fill renderer gate on one declaration
Plugin-extensible structured types — a runtime registry so plugins (e.g. dental teeth-picker) register types that appear in the builder, render, validate, and submit through one resolver
Legacy fill stack deleted (~30 files incl. the 1,203-line QuestionnaireForm), engine relocated to form/engine/, server-draft save restored (encounter-only, with a full E2E loop spec)
Notable catches along the way: time answers were submitting in a format the backend rejects (every submission with a time question failed — fixed); the fixed "encounter" questionnaire had the wrong subject type, silently breaking Update Encounter/Discharge flows (fixed); a resumed-server-draft session had no unsaved-changes protection at all (fixed).
Waiting on you (nothing blocked yet):
PR shape — single PR onto #16619, or split the delta? Nothing has been pushed.
care_scribe lockstep — the Scribe contract changed; care_scribe needs a coordinated update or it mounts inert.
Two backend notes for ENG-737: accept namespaced plugin structured_type values, and CI needs on build+test for server-draft coverage.
User
push everything, I will rereview with bigger models
Assistant
Pushed. bodhi/questionnaire-fill is now on origin (ohcnetwork/care_fe) — 33 commits, HEAD at f321cb379, tracking set up. No PR created; that call stays yours.
One thing still in flight: the ship-blocker fix (structured-only forms losing the unsaved-changes prompt, plus four small items from the closing review) is mid-implementation locally — its files are edited but not yet committed. When it lands and passes its test contract, I'll push the follow-up commits to the same branch, so expect the branch tip to advance once more.
For your re-review, the local review trail is in .superpowers/sdd/ (untracked, per your docs-out-of-repo preference): final-review-confirmed-all.json has all 26 verified findings with per-verifier evidence, final-fix-report.md maps each finding to its fix commit, final-review-triage.md has the parked-minors triage with the defer bucket already written as PR-note bullets, and progress.md is the full task-by-task ledger including every per-task review verdict.
Known open items for whenever you cut the PR: care_scribe lockstep (Scribe contract is now {actions, invoke}), backend acceptance of namespaced plugin structured_type values, REACT_ENABLE_QUESTIONNAIRE_DRAFT=true on CI build+test for server-draft coverage, and a pre-existing ~50% flake in questionnaireStudioChrome.spec.ts:17 under full-suite load that will redden CI regardless of this branch — worth quarantining separately.
Assistant
Understood — the fix agent was stopped. I've halted the autonomous loop too so nothing keeps mutating the branch while you review. Recording the exact state:
Assistant
Everything is parked cleanly for your re-review. Final state:
On origin (bodhi/questionnaire-fill @ f321cb379): all 8 delta tasks plus the 7-commit final fix wave — 25 of 26 whole-branch findings closed, full suite green at that point.
In the working tree, uncommitted: the stopped fixer's partial work on the one open blocker — 6 files touched (form/engine/store.ts, form/validation.ts, StructuredSlot.tsx, fill/submit/useSubmitQuestionnaire.ts, fill/submit/validateStructured.ts, Common/PluginErrorBoundary.tsx, ~134 insertions). I've left them exactly as they were so you can inspect or discard; nothing partial was committed or pushed.
The open blocker your review should weigh first: the fix wave's phantom-draft fix made dirty derive from the safe (non-structured) partition only — so on structured-only forms (medication, allergy, Update Encounter, all FIXED_QUESTIONNAIRES) closing the page after entering rows no longer triggers the unsaved-changes prompt. The agreed fix shape is splitting the signals: nav-prompt dirty on any response change (legacy semantics, safe false-positives), persistence on the safe partition (keeps the phantom-draft fix). The partial edits implement that plus the four minor follow-ons (NEW-2..6 in .superpowers/sdd/final-fix-report.md).
The autonomous loop is stopped and no agents are running. The complete evidence trail for your bigger-model review is in .superpowers/sdd/ — final-review-confirmed-all.json (26 findings with verifier reasoning), final-fix-report.md (finding → fix mapping), final-review-triage.md (defer bucket pre-written as PR bullets), and progress.md (the full ledger). Say the word if you want the partial blocker fix finished and pushed, or discarded.
Approach C — Evolve legacy QuestionnaireForm in place
Extract its state into a reducer, bolt autosave on, keep the component tree. Fastest superficially, but keeps the prop-drilling rerender problem, the four registries, and the 1,203-line component — it's the architecture you asked to retire. Rejected.
My recommendation is A. It's the only one that adds fill capability without reopening the studio, and the structured contract gives the "add more structured questions later" extensibility you asked for.
Shall I proceed with the detailed design on Approach A? (Architecture, autosave semantics, submission/error flow, and testing — presented section by section.)
FillPage
Map<formKey, FormHandle>
Data flow: route scope → FillPage → questionnaire fetch → autosave-restore check → form list renders (canvas per form) → keystrokes hit each form's own store → debounced autosave taps the handles → submit composes a batch from the handles.
Does this section look right so far?
Mounts:EncounterQuestionnaire keeps serving the 5 existing routes (encounter + patient). Location/device fill gets a minimal new mount (route + entry point from their settings/detail pages) wired to the same FillPage — thin, since all logic is subject-generic. Autosave keys include the subject, so a location fill and an encounter fill never collide.
New QuestionnaireV2/fill/ directory (as before): FillPage (form list, tabs, autosave lifecycle), FillTabs (Questionnaire | Patient Clinical History placeholder), outline sidebar via shared/QuestionTreeNav, SubmitBar. Each form in the list renders in its own QuestionnaireFormProvider (per-form jotai store, engine untouched); the provider gains an optional onHandleReady exposing a narrow FormHandle (getResponses / setErrors / clearErrors / subscribeToResponses), and FillPage's Map<formKey, FormHandle> is the entire host↔engine surface — autosave, validation, and submission are pure functions over it.
Does this revised section look right?
PluginEngine collects these into a runtime map, and every consumer goes through one resolver — resolveStructuredType(type) checks core first, then plugins. Because the studio picker, the type icons, the fill renderer, validation, and the submission composer all read the same resolved entry, a plugin that registers dental_images automatically appears in the builder's type picker, renders its teeth-picker in preview and fill (same canvas, per Section 1), validates, and submits to its own endpoints via buildRequests. No host code changes per new type.
Two guardrails:
Unknown type fallback — a questionnaire authored with a plugin type renders a clear "this question requires the X plugin" block when that plugin isn't enabled, and validation treats it as unanswerable rather than blocking submission of the rest of the form (unless required — then submission is blocked with that message, since silently skipping a required clinical question is worse).
Namespacing — plugin types must be prefixed (plugin_slug.type_name or similar) so a future core type can never collide with a deployed plugin type. Core types keep their bare names.
Backend note: the questionnaire spec stores structured_type in the definition, and the backend validates it against its own enum on save. Plugin types therefore need the backend to accept namespaced structured types it doesn't process itself (they're client-orchestrated via buildRequests, like all structured types today). That's a small backend change I'll flag in the design doc as a coordination item on ENG-737 rather than solving here.
Does this section look right?
The structured seeding race. Structured components self-seed from the server on mount (allergy list, current medications) via effect. Restore order: restored data is placed in the store first; when the component's server seed arrives, the registry entry's draft.mergeWithServerSeed reconciles (default policy: restored rows that carry user edits — the existing dirty flag convention — win; untouched rows take the fresh server copy, so another clinician's intervening changes aren't resurrected).
Lifecycle. The chip in the header shows state (Saved locally · {time} / Saving… / autosave unavailable). The key is cleared on: successful submit, explicit Discard, and save-as-server-draft (the server draft supersedes it and navigates away). A sweep on module load purges snapshots older than 7 days. The existing useNavigationPrompt stays as a second line of defense, but with autosave the stakes of an accidental nav drop from "data lost" to "resume banner on return."
Does this section look right?
resolveReviewThread
When CI is green, threads are clear, and there's idle time, sweeping the branch for issues is a good use of that time — bug-hunt or simplification passes catch problems before reviewers do, saving everyone a round-trip.
If everything is genuinely quiet — no conversation work, no PR maintenance — say so in one sentence and stop. No summary of what you checked, no list of what you might do later. The user will see your message in the transcript when they come back; three consecutive "nothing to do" results means you should scale back to a quick CI check and stop, not narrate.
Repeated invocations
If you see earlier autonomous checks in this conversation, adjust your scope accordingly. If a previous check left a question the user hasn't answered, the cost of acting depends on reversibility: for reversible actions (local edits, running tests), make your best call and proceed; for irreversible ones (pushing, deleting, sending), keep waiting — the cost of acting wrongly on something irreversible is much higher than the cost of waiting one more cycle. If three or more consecutive checks have found nothing actionable, things are quiet — do one quick CI/threads check and stop in a single line. Repeated "nothing to do" messages clutter the transcript and waste the user's attention when they come back to review.
Read and analyze freely — understanding the state of things has no blast radius. Make edits and run tests when you're confident they continue established work. Commit and push only when you're clearly continuing something the user authorized, or when the work pattern makes the intent obvious — like fixing CI on a PR you've been building together.
Autonomous loop tick (dynamic pacing)
Run the autonomous check using the loop instructions established earlier in this conversation. If you cannot find them, treat this as a no-op tick.
You scheduled this tick via the ScheduleWakeup tool (not a recurring cron). To keep the loop alive, call ScheduleWakeup again at the end of this turn with prompt set to the literal sentinel <<autonomous-loop-dynamic>> — otherwise the loop ends after this tick.
If a Monitor is armed (check TaskList), keep delaySeconds at 1200–1800s — the Monitor is the wake signal and this is only the fallback heartbeat. If you were woken by a <task-notification>, handle the event before deciding whether to re-arm. To stop the loop, call ScheduleWakeup with stop: true and TaskStop the monitor (use TaskList to find its task ID if no longer in context).
Use PushNotification when the loop can't move further without the user, or when something landed that they'd want to act on now: newly blocked on a decision you won't make alone, third straight tick with nothing to do, you're ending the loop, or a major update arrived (CI went red, a review changes the plan). Progress you made yourself isn't a trigger — the transcript covers that. One ping per state, not per tick.
REACT_ENABLE_QUESTIONNAIRE_DRAFT=true
One ops note: the account hit its monthly spend limit mid-review; I finished verification on cheaper models without losing any findings. I'll report back when the blocker fix lands and the closing reviewer flips to SHIP.