The strategy doc lived alone under files-internal/ while every sibling strategy doc (logging, events, server-secrets) lived under docs-internal/. Move it next to the others and update plan/spec references. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
75 KiB
| title | type | status | date |
|---|---|---|---|
| refactor: Extract fabro-client crate and lift domain DTOs to fabro-types | refactor | active | 2026-04-20 |
Historical note (2026-04-21): the follow-up auth-surface tightening removed LoopbackClassification, target.loopback_classification(), ensure_refresh_target_transport, and the plain-HTTP refresh rejection. References to those APIs below describe the planned state at the time, not the current implementation.
refactor: Extract fabro-client crate and lift domain DTOs to fabro-types
Overview
Extract the typed Fabro-API client currently embedded in fabro-cli into a new reusable crate, fabro-client. Lift the domain data types the client uses (RunSummary, EventEnvelope, RunProjection, and an artifact-upload DTO) from fabro-store and fabro-workflow down to fabro-types, so fabro-client stays light on dependencies. Apply a short list of in-flight naming cleanups while we touch this code.
Problem Frame
lib/crates/fabro-cli/src/server_client.rs is a 1941-line file that implements a fully-featured HTTP client for the Fabro API (40+ typed method wrappers, OAuth refresh, SSE streaming, error classification, Unix-socket transport, artifact multipart uploads). The logic is reusable in spirit, but today it:
- lives inside the CLI binary crate, so nothing else in the workspace can reuse it
- imports
fabro-storeDTOs (RunSummary,EventEnvelope,RunProjection) — entangling every consumer of the client with the storage layer - imports
fabro-workflow::artifact_snapshot::CapturedArtifactInfo— pulling the workflow engine in for four artifact fields - mixes CLI concerns (subprocess autostart, dev-token-from-disk lookup, TOML-driven target resolution) with SDK concerns (make-a-request, parse-a-response) in the same file
- carries several awkward names (
ClientBundle,RefreshableOAuth,ResolvedBearer,HttpResponseFailure,RunAttachEventStream,CapturedArtifactInfo) that fight domain-driven naming
These were all reasonable while the client had exactly one caller. They prevent a second caller (an SDK, an IDE extension, future automation tooling) from emerging cleanly, and they block the layering story "fabro-client is to the API server what a typed SDK is to any HTTP service."
Requirements Trace
- R1. A new
fabro-clientcrate exists atlib/crates/fabro-client/, declared in the workspace, publishing a typedClientand its connection machinery. - R2.
fabro-clientdoes not depend onfabro-cli,fabro-store,fabro-workflow,fabro-server,fabro-config, or any other CLI-bound or server-bound crate. - R3.
fabro-clientreturns rich domain types fromfabro-types(RunSummary,EventEnvelope,RunProjection,StageId,RunId,RunBlobId,RunEvent,ArtifactUpload) and wire-shape types re-exported fromfabro-api::types(e.g.SystemInfoResponse,PreviewUrlResponse,SecretMetadata,PruneRunsRequest,ModelTestResult). - R4.
fabro-storeno longer ownsRunSummary,EventEnvelope, orRunProjection(at the struct level).fabro-workflowno longer ownsCapturedArtifactInfo. - R5. Type renames applied:
ClientBundle→ inlined intoClient(no separate type).RefreshableOAuth→OAuthSession.ResolvedBearer→Credential.HttpResponseFailure→ApiError.RunAttachEventStream→RunEventStream.CapturedArtifactInfo→ArtifactUpload.
- R6.
ServerTargetis canonical-by-construction using lexical-only canonicalization (nofs::canonicalize, no existence checks).ServerTargetKeyis deleted;ServerTargetserves as its own map key. - R7.
AuthStorelives infabro-client, defaults to~/.fabro/auth.json, and keys OAuth entries byServerTargetdirectly. - R8.
fabro-clikeeps CLI-owned orchestration: subprocess autostart, server-record lookup, dev-token-from-disk loading,[cli.target]TOML resolution, and the wrapper that stitches these together into a ready-to-usefabro_client::Client. - R9. The full workspace build passes (
cargo build --workspace), clippy is clean (cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings), rustfmt check passes, and all workspace tests continue to pass (cargo nextest run --workspace).
Review Adjustments
- Remaining gaps against this plan in the current landed code:
HttpResponseFailure→ApiErrorrename is still open.ServerTargetcanonical-by-construction / lexical-only Unix-path canonicalization is still open; canonicalization still partly lives inAuthStore.RunAttachEventStream→RunEventStreamrename is still open at the CLI boundary.- Because the two rename cleanups above are still open, Unit 11's "no leaked old names" grep is currently expected to fail until that follow-up cleanup lands.
- Clarifications after implementation review:
RunProjectionownership moved tofabro-types; external callers may continue to import it throughfabro_store's re-export. Verification should check type ownership and dependency boundaries, not the literal import spelling.Client::from_http_client(...)is the required public constructor.Client::new_no_proxy(...)may remain as a convenience wrapper, primarily for tests.TransportConnectoris an acceptable internal helper insidefabro-clientwhen needed to preserve caller-specific transport configuration across refresh/rebuild flows.fabro-climay retain multiple thinconnect_*convenience wrappers so long as they preserve CLI-only orchestration and funnel intoClient::builder()under the hood.
Scope Boundaries
In scope:
- Creating the
fabro-clientcrate. - Lifting the four DTOs to
fabro-types(RunSummary,EventEnvelope,RunProjection,ArtifactUpload). - The six type renames above.
ServerTargetcanonical-by-construction +ServerTargetKeydeletion.- Updating import sites across
fabro-cli,fabro-server,fabro-store,fabro-workflow,fabro-retro(compiler-driven). - Keeping the existing behavior of every CLI command intact.
Out of scope:
- Renaming
RunSummary,EventEnvelope,RunProjection,AuthEntry,StoredSubject(structure moves, names stay; deferred per user direction). - Publishing
fabro-clientto crates.io or adding external-consumer documentation. - Writing a second consumer of
fabro-client(SDK example, IDE integration, etc.) — the crate exists to enable that, not to deliver it. - Changing wire semantics (OpenAPI contract stays identical).
- Migrating existing
~/.fabro/auth.jsonentries. The canonical key format for HTTP targets remains identical (samenormalized_http_base_urllogic); Unix-socket canonicalization changes fromfs::canonicalize(symlink-resolving) to lexical-only (./..cleanup, no symlink chasing). Existing sessions against socket paths written as absolute non-symlinked paths continue to match. Users with symlinked socket paths may need to re-login — acceptable perCLAUDE.md("We don't care about migration"). RunEventunknown-variant handling. Already present today viaEventBody::Unknownatlib/crates/fabro-types/src/run_event/mod.rs:695(covered by:974). Unit 2 verifies theEventEnveloperestructure preserves this existing behavior — no new variant, no new code.- Splitting the ~40 client methods into separate
client/runs.rs,client/secrets.rs, etc. modules. A singleclient.rsis acceptable at ~900 lines; cosmetic domain splitting can happen later if the file grows.
Context & Research
Relevant Code and Patterns
lib/crates/fabro-cli/src/server_client.rs:1-1941— the entire current client implementation, includingClient,ClientBundle, connection builders, error classification,send_api/send_http,RunAttachEventStream, and 40 typed wrapper methods.lib/crates/fabro-cli/src/auth_store.rs— file-locked~/.fabro/auth.jsonpersistence. ItsServerTargetKeyis the canonical-key type that's about to go away.lib/crates/fabro-cli/src/loopback_target.rs— pure URL classification, no dependencies outsidefabro-httpandthiserror. Moves cleanly.lib/crates/fabro-cli/src/sse.rs— pure SSE line-buffer parser. Moves cleanly.lib/crates/fabro-cli/src/user_config.rs— today ownsServerTarget,normalized_http_base_url,cli_http_client_builder, and TOML target resolution.ServerTargetandnormalized_http_base_urlmove tofabro-client; the rest stays.lib/crates/fabro-cli/src/commands/server/{start,record}.rs— CLI-owned autostart + pidfile. Stays.lib/crates/fabro-store/src/types.rs— home ofRunSummary,EventEnvelope, andEventPayload.RunSummarymoves cleanly.EventEnveloperestructures (new shape{ seq, event: RunEvent }) and moves;EventPayloadstays behind as an internal validation helper.lib/crates/fabro-store/src/run_state.rs— home ofRunProjection. The struct moves tofabro-typeswith its pure-data accessors; the event-reducer methods (apply_event,apply_events) move into aRunProjectionReducertrait infabro-storeimplemented onfabro_types::RunProjection. See Unit 3.lib/crates/fabro-workflow/src/artifact_snapshot.rs:20-26—CapturedArtifactInfodefinition. Four pure-data fields, serde derives only.docs/api-reference/fabro-api.yaml:3452-3461— OpenAPI definesEventEnvelopeasallOf [EventSeq, RunEvent], wire format{ seq, event_fields_flattened_in }.fabro_types::EventEnvelope { seq: u32, #[serde(flatten)] event: RunEvent }matches the wire contract exactly — no serialization change, only the Rust representation changes.lib/crates/fabro-types/Cargo.toml— deps are already lightweight (chrono,fabro-model,fabro-util,serde,serde_json). Our new DTOs fit inside this dep envelope.- Plan format precedent:
docs/plans/2026-04-20-001-fix-cli-server-same-host-assumptions-plan.md— recently-landed refactor in the same subsystem; we model frontmatter and section style on it.
Institutional Learnings
- No
docs/solutions/directory in this repo — no prior captured learnings apply. Historical plans indocs/plans/around CLI/server boundary (2026-04-02-001-feat-server-daemon-management-plan.md,2026-04-05-cli-deglobalize-server-url-and-storage-dir-plan.md,2026-04-20-001-fix-cli-server-same-host-assumptions-plan.md) have tightened the target-resolution contract progressively. This plan'sfabro-clientextraction is the next step in that direction: after target resolution became disciplined, pull the pure client out of the CLI and make its purity enforceable by the crate graph. CLAUDE.mdreminds: "We want the simplest change possible. We don't care about migration. Code readability matters most, and we're happy to make bigger changes to achieve it." We lean on this for theServerTargetcanonicalization change and the "delete the alias" step in theClientrename we just finished.docs-internal/testing-strategy.md— most existing CLI tests exercise the client through CLI-level commands; those tests continue to live infabro-cliand don't need to migrate. Tests of internal helpers (auth-store round-trips,ServerTargetKeycanonicalization, loopback classification, SSE parsing, dev-token resolution) fall into three buckets: (a) auth-store/SSE/loopback/ServerTarget tests migrate tofabro-client; (b) dev-token resolution tests stay infabro-cli; (c) server-client unit tests for refresh-token transport checks migrate.
External References
None. Internal refactor; the patterns are all established locally.
Key Technical Decisions
-
fabro-clienthas zero CLI/server/workflow/store coupling. Its dep list isfabro-api,fabro-http,fabro-model,fabro-types,fabro-util, plus general-purpose async/serialization crates. Rationale: this is the whole point — make reuse a compile-time guarantee, not a convention. Consumers inherit the transitive surface of these deps (reqwest viafabro-http, progenitor-generated client viafabro-api, chrono/serde via the rest) — not minimal, but consistent with the crate's "typed SDK for the Fabro HTTP API" scope. -
Domain DTOs live in
fabro-types; wire shapes live infabro-api. Rich Rust types (RunSummarywithHashMap<String,String>andRunIdnewtype,RunProjectionwith all thefabro-typessub-records) belong with the rest of the domain vocabulary. Single-use request/response shapes (PruneRunsRequest,SandboxFileEntry, etc.) stay in the auto-generatedfabro-api::typesand are re-exported fromfabro-client::types. -
EventEnveloperestructure. Change from{ seq, payload: EventPayload(serde_json::Value) }to{ seq: u32, #[serde(flatten)] event: RunEvent }. The wire contract is unchanged (OpenAPI already specifiesallOf [EventSeq, RunEvent]). The Rust representation becomes typed end-to-end, eliminating.payload.as_value() → RunEvent::from_ref(...)conversions at every consumer.EventPayloadstays infabro-storeas an internal validation helper used by the storage path. -
RunProjectionmethod split viaRunProjectionReducerextension trait. Move the struct (data) tofabro-types, including its pure-data accessors (node,iter_nodes,is_empty,set_node,list_node_visits,node_mut,current_visit_for,reset_for_rewind) aspubinherent methods. DefineRunProjectionReducerinfabro-storewithapply_event/apply_events(andimpl RunProjectionReducer for fabro_types::RunProjection) so storage behavior stays infabro-storewhile call-site syntax remains method-style:use fabro_store::RunProjectionReducer; projection.apply_event(ev)?. The trait form preserves OOP-style method chaining at ~10 call sites and fits the workspace's preferred convention (methods over free helpers).build_summarystays as apub(crate)free function infabro-store— it's a projection-derived summary, not a mutation on the projection itself. -
ServerTargetcanonical-by-construction, lexical only.ServerTarget::from_urlapplies today's full HTTP canonicalization inline: lowercase scheme, lowercase host, strip default ports (:443on https,:80on http), strip trailing/, strip/api/v1suffix, rebuild authority as{scheme}://{host}[:{port}].ServerTarget::from_unix_pathapplies lexical./..resolution (no FS access, no symlink chasing).PartialEq/Eq/Hashoperate on the canonical form directly.ServerTargetKeyis deleted;ServerTargetitself serves as theAuthStoremap key. In OOP style: construction is the canonicalizer — no separatecanonicalize()method. Related helpers attach toServerTargetas inherent methods (target.loopback_classification(),target.build_public_http_client()) rather than free functions. -
AuthStoremoves tofabro-client. Default path remains~/.fabro/auth.jsonviafabro_util::Home. The public API (get/put/remove/list) is narrow enough that we keep it concrete — noTokenRefreshertrait abstraction. Callers wanting alternative storage can pass an explicit path toAuthStore::new. If external-consumer flexibility becomes a real need later, we extract a trait then, not now. -
Renames applied inline with moves. We don't do a separate rename pass — the DTOs and internal types are renamed as they move. This keeps the compiler-driven find-all-callers loop honest: every broken import is both a move and a rename in one commit.
-
Connection API centers on one builder. Today's
connect_*functions inserver_client.rsare CLI-opinionated convenience wrappers.fabro-clientexposesClient::builder().target(t).credential(c).oauth_session(s).connect().await?as the underlying connection API.fabro-climay keep several thinconnect_*wrappers, but they must remain orchestration-only and funnel into the builder instead of duplicating transport/session assembly logic. -
Refresh rebuilds may use a transport connector hook. If the CLI needs request-transport customization across OAuth refresh rebuilds (for example, preserving a CLI-specific user-agent),
fabro-clientmay carry aTransportConnector-style helper as an internal implementation detail. This does not count as a second public connection API. -
OAuthSessionrefresh fallback viaCredentialFallbacktrait. Today's refresh flow falls back to a dev-token-from-disk when the OAuth entry is missing, expired, or revoked. That fallback lookup reads CLI-owned sources (FABRO_DEV_TOKENenv,~/.fabro/dev-token, storage-dir dev-token file, fabro-server pidfile record) that don't belong infabro-client.OAuthSessiontakes an optionalBox<dyn CredentialFallback>at build time:// Directional — not implementation pub trait CredentialFallback: Send + Sync { fn resolve(&self) -> Option<Credential>; }On refresh failure modes that previously triggered fallback,
OAuthSessioncallsfallback.resolve(). IfSome(Credential), the session rebuilds the client bundle with that credential; ifNone, it surfaces "session expired." The CLI provides a concrete impl infabro-clithat wraps the existing dev-token-loading logic. Named trait (vs bareFnclosure) makes the role obvious at theOAuthSession::buildercall site. -
fabro_types::RunEventalready tolerates unknown event names.EventBody::Unknown { name, properties }atlib/crates/fabro-types/src/run_event/mod.rs:695is the existing fallback — a newer server's unknown event type deserializes into this variant without error. Unit 2's responsibility is to preserve this behavior across theEventEnvelope { seq, #[serde(flatten)] event: RunEvent }restructure, not to add a new variant. -
Phased delivery. DTO lift must land before the client extraction — otherwise
fabro-client's deps can't be correct. We split the work into three phases (DTO lift →fabro-clientextraction →fabro-clirewire) and land each phase as a coherent chunk. Each phase compiles and tests pass at its boundary.
Open Questions
Resolved During Planning
- Where do
apply_events/apply_eventlive afterRunProjectionmoves? Infabro-storeas an extension traitRunProjectionReducerimplemented onfabro_types::RunProjection. Preserves OOP-style method-call syntax at call sites viause fabro_store::RunProjectionReducer;. Chosen over free functions because the workspace leans toward methods over free helpers. - HTTP canonicalization scope in
ServerTarget::from_url. Preserve today's full normalization: lowercase scheme + lowercase host + strip default ports + strip trailing/+ strip/api/v1suffix + rebuild authority. Matches today'scanonical_http_targetinauth_store.rs:350-383and the existinghttps_normalization_collapses_equivalent_urlstest at line 507. Simpler "strip slash + api-v1 only" form was rejected because it would silently invalidate AuthStore entries for users whose URLs differed only in case or default-port. - OAuthSession refresh fallback mechanism. Add a
CredentialFallbacktrait;fabro-cliimplements it against its dev-token sources;OAuthSessionholdsOption<Box<dyn CredentialFallback>>and callsfallback.resolve()on the failure modes that previously fell back to dev-token. Named trait (not bareFn) chosen for role clarity. RunEventunknown-variant forward-compat. Already handled today viaEventBody::Unknownatlib/crates/fabro-types/src/run_event/mod.rs:695(tested at:974). Unit 2 verifies theEventEnveloperestructure preserves this existing behavior — no new variant, no new code.- Does
EventEnvelopeneedEventPayloadto travel with it? No. OpenAPI already defines the wire shape asseq + RunEvent flattened.EventPayloadis a storage-internal validation helper and stays behind. - Does
AuthStoreneed a trait-based abstraction? No. Concrete type with a configurable file path is sufficient; we extract a trait the day a second implementation exists. - Does
ArtifactUploadlive infabro-typesorfabro-client?fabro-types. Source isfabro-workflow(capture) → sink isfabro-client(upload). Placing the DTO infabro-typespreventsfabro-workflowfrom having to depend onfabro-client. - How do we handle the
Client::new_no_proxy(base_url)constructor used by CLI tests today? ExposeClient::from_http_client(base_url, http_client)as the stable publicpub fn.Client::new_no_proxy(base_url)may remain as a small convenience wrapper (infabro-clientor CLI-local test code) if it continues to earn its keep. convert_typeserde round-trip helper — does it stay in the CLI or move with the client? Moves with the client. It's how the client bridgesfabro_api::types::RunSummary(wire) →fabro_types::RunSummary(domain) at response boundaries.
Deferred to Implementation
- Exact module file layout inside
fabro-client/src/may shift slightly as we go (e.g., whethercredential.rsandsession.rsstay separate or merge). Guide: keep the sketched layout unless one file shrinks under ~50 lines, at which point merge. - Whether any
pub(crate)items inside the currentserver_client.rsneed to becomepubwhen exposed fromfabro-client. Driven by compiler errors whenfabro-cliimports across the crate boundary. - Exact form of the CLI's
Credential-building helper after the move (currently calledresolve_target_bearer). The shape depends on what survives infabro-cliafter the extraction. - Whether
Clientends up#[derive(Debug)]or implementsDebugmanually. Today it isn't. Driven by whether any downstream consumer needs it.
High-Level Technical Design
This illustrates the intended approach and is directional guidance for review, not implementation specification. The implementing agent should treat it as context, not code to reproduce.
Target crate dependency graph
flowchart TB
subgraph New["After refactor"]
cli2[fabro-cli]
client2[fabro-client]
api2[fabro-api]
types2[fabro-types]
workflow2[fabro-workflow]
store2[fabro-store]
http2[fabro-http]
server2[fabro-server]
cli2 --> client2
cli2 --> workflow2
cli2 --> store2
cli2 --> server2
client2 --> api2
client2 --> types2
client2 --> http2
workflow2 --> types2
store2 --> types2
server2 --> store2
server2 --> api2
api2 --> types2
end
Key property: fabro-client has no arrow into fabro-store, fabro-workflow, fabro-server, fabro-cli, or fabro-config.
fabro-client module layout
lib/crates/fabro-client/
├── Cargo.toml
└── src/
├── lib.rs — re-exports, crate docs, `pub use types` from fabro-api
├── client.rs — Client struct (flattened, no Bundle), send_api/send_http,
│ Client::builder(), all ~40 wrapper methods
├── target.rs — ServerTarget (canonical-by-construction), Display, FromStr
├── credential.rs — Credential { DevToken, OAuth }
├── session.rs — OAuthSession, refresh_access_token flow
├── auth_store.rs — AuthStore, AuthEntry, StoredSubject
├── error.rs — ApiError, classify_api_error, classify_http_response, map_api_error
├── sse.rs — drain_sse_payloads, RunEventStream
└── loopback.rs — LoopbackClassification (accessed via target.loopback_classification())
Phase sequencing
flowchart TB
P1[Phase 1: DTO lift to fabro-types]
P2[Phase 2: Create fabro-client crate]
P3[Phase 3: Rewire fabro-cli]
P4[Phase 4: Verification]
P1 --> P2
P2 --> P3
P3 --> P4
subgraph P1u[Phase 1 units]
U1[Unit 1: Move RunSummary]
U2[Unit 2: Move + restructure EventEnvelope]
U3[Unit 3: Move RunProjection struct]
U4[Unit 4: Move + rename ArtifactUpload]
end
subgraph P2u[Phase 2 units]
U5[Unit 5: Scaffold fabro-client crate]
U6[Unit 6: Move pure helpers + ServerTarget]
U7[Unit 7: Move AuthStore]
U8[Unit 8: Move Client + session + credential]
end
subgraph P3u[Phase 3 units]
U9[Unit 9: Rewire CLI orchestrator]
U10[Unit 10: Delete moved fabro-cli modules]
end
U1 -.-> P1
U2 -.-> P1
U3 -.-> P1
U4 -.-> P1
U5 -.-> P2
U6 -.-> P2
U7 -.-> P2
U8 -.-> P2
U9 -.-> P3
U10 -.-> P3
Within a phase, units may execute in parallel when independent; across phases, the order is strict.
Connection API shape
// Directional sketch — not implementation.
// fabro-client exposes one builder that replaces today's four connect_* fns.
Client::builder()
.target(ServerTarget::from_str("https://fabro.example.com/api/v1")?)
.credential(Credential::DevToken("fabro_dev_...".into()))
.oauth_session(session) // optional; enables auto-refresh on 401
.connect()
.await?
// fabro-cli's orchestrator becomes roughly:
// 1. resolve ServerTarget from args + settings
// 2. if Unix + not running: ensure_server_running_on_socket
// 3. build Credential from env / auth_store / dev-token-file
// 4. Client::builder().target(t).credential(c).oauth_session(s).connect()
Implementation Units
Phase 1 — DTO lift to fabro-types
- Unit 1: Move
RunSummarytofabro-types
Goal: Relocate the RunSummary struct from fabro-store to fabro-types so that crates consuming runs-list data no longer depend on the storage layer.
Requirements: R3, R4.
Dependencies: None.
Files:
- Create:
lib/crates/fabro-types/src/run_summary.rs - Modify:
lib/crates/fabro-types/src/lib.rs(addpub mod run_summary;+ re-export) - Modify:
lib/crates/fabro-store/src/types.rs(deleteRunSummarydefinition; keep re-exportpub use fabro_types::RunSummary;during transition, or update all call sites and delete outright — prefer the latter) - Modify: call sites across
lib/crates/fabro-cli/(~4 files),lib/crates/fabro-server/src/server.rs,lib/crates/fabro-store/(internal uses), any others the compiler surfaces - Test:
lib/crates/fabro-types/src/run_summary.rs(inline#[cfg(test)]module with a round-trip serde test)
Approach:
- Copy the struct verbatim from
fabro-store/src/types.rs:10-24into a newfabro-types/src/run_summary.rs. The struct already references onlyfabro_typestypes (RunId,RunStatus,BlockedReason, etc.), so no type-substitution is needed. - Re-export from
fabro-types/src/lib.rs:pub use run_summary::RunSummary;. - In
fabro-store/src/types.rs, delete the struct and update any store-internal references to import fromfabro_types::RunSummary. - Update import sites. Compiler drives the list; expect ~6 files.
Patterns to follow:
- Mirror the style of existing small DTO modules in
fabro-types:fabro-types/src/run_blob_id.rs,fabro-types/src/sandbox_record.rs.
Test scenarios:
- Happy path:
RunSummaryserialized and round-tripped throughserde_jsonproduces an identical value. (Carry over or adapt any existing test fromfabro-store.)
Verification:
cargo build --workspacesucceeds.cargo nextest run -p fabro-types -p fabro-store -p fabro-server -p fabro-clipasses.grep -rn "fabro_store::RunSummary\|fabro_store::types::RunSummary" lib/returns no results outsidefabro-storeinternals.
- Unit 2: Move and restructure
EventEnvelopeinfabro-types
Goal: Replace fabro-store's EventEnvelope { seq, payload: EventPayload(serde_json::Value) } with fabro-types's EventEnvelope { seq: u32, #[serde(flatten)] event: RunEvent }. The wire format is unchanged (OpenAPI already flattens RunEvent fields alongside seq).
Requirements: R3, R4.
Dependencies: None (independent of Unit 1, can run in parallel).
Files: (verified call-site inventory; compiler drives any residual sites)
Construction sites (switch to fabro_types::EventEnvelope { seq, event }):
- Create:
lib/crates/fabro-types/src/event_envelope.rs - Modify:
lib/crates/fabro-types/src/lib.rs(module + re-export) - Modify:
lib/crates/fabro-store/src/types.rs(delete oldEventEnvelope; keepEventPayloadinternal; update tests at lines 127 and 171) - Modify:
lib/crates/fabro-store/src/slate/run_store.rs(production constructors at lines 194 and 342) - Modify:
lib/crates/fabro-store/src/run_state.rs(apply_event body at line 79; test fixtures at lines 728, 741, 1086, 1112; test assertions at lines 1133, 1137) - Modify:
lib/crates/fabro-cli/src/commands/run/runner.rs:372-373(write path that also constructs an envelope)
Read sites (switch from envelope.payload.as_value() / &envelope.payload → &envelope.event):
- Modify:
lib/crates/fabro-server/src/server.rs(7 sites: 888, 1776, 1794, 3307, 3581, 8770, 8771 — includes theapi_event_envelope_from_storemerge-seq logic and two test assertions) - Modify:
lib/crates/fabro-retro/src/retro_agent.rs:311 - Modify:
lib/crates/fabro-workflow/src/lib.rs:95(extract_stage_durations_from_events) - Modify:
lib/crates/fabro-workflow/src/event.rs:3169(test read) - Modify:
lib/crates/fabro-workflow/src/operations/create.rs:1026(test read) - Modify:
lib/crates/fabro-cli/src/commands/run/logs.rs:91, 271 - Modify:
lib/crates/fabro-cli/src/commands/run/attach.rs:395, 465, 480 - Modify:
lib/crates/fabro-cli/src/commands/store/rebuild.rs:20(read-then-write hybrid). Reads becomeenvelope.event; write-path re-validation becomesEventPayload::new(event.to_value()?, run_id)?— noteRunEvent::to_value()returnsserde_json::Result<Value>(was infallible.as_value().clone()), so the?propagates. Callers that already returnanyhow::Resultabsorb it naturally. - Modify:
lib/crates/fabro-cli/tests/it/workflow/mod.rs:59 - Modify:
lib/crates/fabro-cli/tests/it/cmd/support.rs:794 - Modify:
lib/crates/fabro-cli/tests/it/cmd/runner.rs:32 - Modify:
lib/crates/fabro-cli/tests/it/cmd/rewind.rs(seven.payload.as_value()reads at 132, 156, 160, 165, 169, 173, 177)
Type-only references (import switch; no body change needed — compiler drives):
lib/crates/fabro-cli/src/server_client.rs,src/commands/store/{dump,run_export}.rslib/crates/fabro-workflow/src/run_dump.rslib/crates/fabro-cli/tests/it/support/mod.rs
Write-path EventPayload::new sites (UNAFFECTED — stay in fabro-store as internal validation; listed here to document scope):
lib/crates/fabro-store/src/slate/mod.rs:346lib/crates/fabro-workflow/src/operations/create.rs:259lib/crates/fabro-workflow/src/event.rs:2625, 2643lib/crates/fabro-server/src/server.rs:5226, 8025- Test fixtures in
lib/crates/fabro-cli/src/commands/store/dump.rs:669and the store's own test modules
Approach:
- New struct in
fabro-types:// Directional — not implementation pub struct EventEnvelope { pub seq: u32, #[serde(flatten)] pub event: RunEvent, } - Confirm today's
EventBody::Unknown { name, properties }fallback (atlib/crates/fabro-types/src/run_event/mod.rs:695) continues to round-trip through the newEventEnvelope { seq, #[serde(flatten)] event: RunEvent }shape — the#[serde(flatten)]interacts cleanly with the existing catch-all. No new variant is added; we are only confirming the existing forward-compat behavior survives. fabro-storekeepsEventPayloadstrictly internal — every existing write path continues to callEventPayload::new(value, run_id)?forexpected_run_idvalidation before persisting (unchanged behavior). No write path bypasses that check. Only the external-facing read-path return type changes.- At the store's read boundary (
slate/run_store.rs:194, 342— where the oldEventEnvelope { seq, payload }was constructed by pairing a separately-tracked seq with decoded payload bytes): deserialize the raw bytes asRunEvent(the on-disk format is raw RunEvent JSON withoutseq), then wrap infabro_types::EventEnvelope { seq, event }. The write path atslate/run_store.rs:201-203continues to persistserde_json::to_vec(payload)?of theEventPayload; theseqcomes from a separate counter, same as today. - CLI callers that did
event.payload.as_value()+RunEvent::from_ref(...)→ change to&event.event. This is a win at every call site (fewer conversions). runner.rs:372-373currently builds anEventPayload::new(event.to_value()?, run_id)?+EventEnvelope { seq, payload }. After this unit, buildfabro_types::EventEnvelope { seq, event }directly.
Patterns to follow:
- Serde
#[serde(flatten)]usage elsewhere infabro-types(fabro-types/src/run_event/has flatten in some variants). - OpenAPI contract at
docs/api-reference/fabro-api.yaml:3452-3461.
Test scenarios:
- Happy path:
EventEnveloperound-trips throughserde_jsonpreserving bothseqand allRunEventfields, and deserializes the existing wire format identically. - Integration: existing
fabro-storetestwire_event_envelope_round_tripsstill passes after porting (adapt it to construct the new struct shape). - Integration: CLI integration tests that consume events over SSE or HTTP (e.g.,
fabro-cli/tests/it/workflow/mod.rs,cmd/attach.rs) continue to pass — proves the wire shape is unchanged. - Forward-compat regression guard: an
EventEnvelopeJSON payload whose event name is unknown to this build offabro-typesdeserializes into the existingEventBody::Unknown { name, properties }without error and re-serializes losslessly. (Covers: theEventEnveloperestructure did not break today's fallback atrun_event/mod.rs:695.)
Verification:
cargo build --workspacesucceeds.cargo nextest run --workspacepasses, including allfabro-cli::itevent-consuming tests.grep -rn "EventPayload" lib/crates/fabro-cli/src/shows onlyrunner.rs/rebuild.rs/dump.rsusage that persists into the store (legitimate — those write events into storage and need the validating wrapper). Read paths no longer touchEventPayload.
- Unit 3: Move
RunProjectionstruct tofabro-types
Goal: Relocate RunProjection (the data struct) to fabro-types. Move pure-data methods with it. Keep event-reducer methods (apply_event, apply_events) in fabro-store behind a RunProjectionReducer extension trait implemented on fabro_types::RunProjection, so call-site syntax stays method-style (OOP preference).
Requirements: R3, R4.
Dependencies: Unit 2 (apply_event references EventEnvelope's new shape).
Files:
- Create:
lib/crates/fabro-types/src/run_projection.rs(structRunProjection+PendingInterviewRecord+NodeState; pub inherent data-method accessors) - Modify:
lib/crates/fabro-types/src/lib.rs(add module + re-exports) - Modify:
lib/crates/fabro-store/src/run_state.rs:- Delete the struct definitions moving to
fabro-types. - Keep
EventProjectionCache(storage-internal). - Define
RunProjectionReducertrait withapply_event/apply_eventsandimpl RunProjectionReducer for fabro_types::RunProjection. - Keep
build_summaryas apub(crate)free function (it's a derived projection-to-summary builder, not a reducer).
- Delete the struct definitions moving to
- Modify: call sites in
lib/crates/fabro-cli/(~4 store/dump/rebuild/runner files),lib/crates/fabro-retro/src/retro_agent.rs,lib/crates/fabro-workflow/src/run_dump.rs,lib/crates/fabro-server/src/server.rs— adduse fabro_store::RunProjectionReducer;where the trait methods are called.
Approach:
- Copy
RunProjection,PendingInterviewRecord,NodeStateintofabro-types/src/run_projection.rs. All field types are already infabro-types, so this is a straight move. - Move the struct's data-operating methods with it to
fabro-typesaspubinherent methods:node,iter_nodes,is_empty,set_node,list_node_visits,node_mut,current_visit_for,reset_for_rewind. These touch onlyselffields andfabro-typestypes. Private fields (e.g.,nodes: HashMap<StageId, NodeState>) stay private; the reducer trait infabro-storecalls these public methods to perform its mutations. - In
fabro-store/src/run_state.rs, define the reducer trait:
Call-site change:// Directional — not implementation pub trait RunProjectionReducer { // Primitive reducer: mutate the projection with one event. fn apply_event(&mut self, envelope: &EventEnvelope) -> Result<()>; // Constructor helper: build a fresh projection by folding events over Default. fn apply_events(events: &[EventEnvelope]) -> Result<RunProjection> where Self: Sized; } impl RunProjectionReducer for fabro_types::RunProjection { fn apply_event(&mut self, envelope: &EventEnvelope) -> Result<()> { /* moved from impl */ } fn apply_events(events: &[EventEnvelope]) -> Result<RunProjection> { let mut state = RunProjection::default(); for event in events { state.apply_event(event)?; } Ok(state) } }projection.apply_event(envelope)?keeps working with one addeduse fabro_store::RunProjectionReducer;per file that uses it (~5-6 files). - Orphan rule permits this —
RunProjectionReduceris local tofabro-store,fabro_types::RunProjectionis foreign but we're implementing the local trait on it. build_summary(projection: &RunProjection, run_id: RunId, ...) -> RunSummarystays as apub(crate)free function infabro-store— it's a pure builder from projection → summary, not a mutation on the projection.
Patterns to follow:
- Extension-trait-on-foreign-struct pattern:
trait LocalTrait { ... }+impl LocalTrait for foreign::Struct { ... }. Standard Rust. The trait nameRunProjectionReducercommunicates the role (it reduces events into the projection). - The workspace's OOP preference: callers invoke
projection.apply_event(ev)?as a method, notsome_module::apply_event(&mut projection, ev)?as a free function.
Test scenarios:
- Happy path: constructing a default
RunProjectionand applying a sequence of events produces the same projection as before the move (carry over existing fabro-store tests). - Integration:
fabro-clistore-dump and rebuild scenarios continue to produce byte-identical output (existing scenario tests intests/it/scenario/provide this coverage implicitly).
Verification:
cargo build --workspacesucceeds.cargo nextest run --workspacepasses.grep -rn "struct RunProjection" lib/crates/fabro-store lib/crates/fabro-typesshows the concrete struct definition only infabro-types; external callers may import eitherfabro_types::RunProjectionor thefabro-storere-export.
- Unit 4: Rename and move
CapturedArtifactInfo→ArtifactUploadinfabro-types
Goal: Rename CapturedArtifactInfo to ArtifactUpload and move it from fabro-workflow to fabro-types. Break the fabro-client → fabro-workflow dependency chain (not yet active — prevents it from forming during Phase 2).
Requirements: R3, R4, R5.
Dependencies: None (independent of Units 1-3; can run in parallel).
Files:
- Create:
lib/crates/fabro-types/src/artifact.rs(structArtifactUploadwith the same four fields). - Modify:
lib/crates/fabro-types/src/lib.rs(add module + re-export). - Modify:
lib/crates/fabro-workflow/src/artifact_snapshot.rs(deleteCapturedArtifactInfo; updateArtifactCollectionSummary.captured_assetstoVec<ArtifactUpload>; update constructor sites to buildArtifactUpload). - Modify:
lib/crates/fabro-workflow/src/artifact_upload.rs,src/lifecycle/artifact.rs— update type refs. - Modify:
lib/crates/fabro-cli/src/server_client.rs,src/commands/run/runner.rs— update type refs.
Approach:
- Define
ArtifactUploadinfabro-types/src/artifact.rswith identical fields:path: String,mime: String,content_md5: String,content_sha256: String,bytes: u64. Same serde derives. - Delete
CapturedArtifactInfofromfabro-workflow/src/artifact_snapshot.rs. - Compiler drives the renames across ~6 files.
Patterns to follow:
- DTO placement: mirror
fabro-types/src/sandbox_record.rs. - Field naming stays identical — no rename of fields, only the struct name.
Test scenarios:
- Happy path: round-trip serde test for
ArtifactUpload(inline in the module). - Integration: fabro-workflow's artifact-collection integration tests continue to pass with no behavior change.
Verification:
cargo build --workspacesucceeds.cargo nextest run -p fabro-types -p fabro-workflow -p fabro-clipasses.grep -rn "CapturedArtifactInfo" lib/ docs/returns only results indocs/plans/(historical) — no code hits.
Phase 2 — Create fabro-client crate
- Unit 5: Scaffold
fabro-clientcrate
Goal: Create the new crate with its Cargo.toml, empty module structure, and workspace registration. No logic yet.
Requirements: R1.
Dependencies: None (can start any time, but Phase 1 must complete before Units 6-8 can compile).
Files:
- Create:
lib/crates/fabro-client/Cargo.toml - Create:
lib/crates/fabro-client/src/lib.rs(empty except forpub moddeclarations and crate-level docs) - Create:
lib/crates/fabro-client/src/{client,target,credential,session,auth_store,error,sse,loopback}.rsas empty stubs - Modify: root
Cargo.toml— the workspacemembers = ["lib/crates/*", ...]glob already picks up the new crate; also registerfabro-client = { path = "lib/crates/fabro-client" }under[workspace.dependencies]if that pattern is used (it is — seefabro-httpandfabro-testentries in rootCargo.toml).
Approach:
- Model
Cargo.tomlonlib/crates/fabro-http/Cargo.toml(similar scope: a typed wrapper over an HTTP layer). Dependencies:fabro-api, fabro-http, fabro-model, fabro-types, fabro-util, anyhow, bytes, chrono, futures, fs2, progenitor-client, rand, serde, serde_json, thiserror, tokio, tokio-util, tracing [dev-dependencies]:tempfile.- Mirror fabro-types's
publish = false,edition.workspace = true,version.workspace = true,[lints] workspace = true. - Crate-level doc comment in
lib.rsexplaining: typed client for the Fabro HTTP API; the CLI'sfabro-cliuses this crate; future SDKs will too.
Patterns to follow:
lib/crates/fabro-http/Cargo.toml— similar scope (infrastructure crate, no domain logic).lib/crates/fabro-types/Cargo.toml— modest dep list,doctest = false, workspace lints.
Test scenarios:
- Test expectation: none — pure scaffolding. This unit introduces no behavior.
Verification:
cargo build -p fabro-clientsucceeds (should be a no-op build — no code yet).cargo build --workspacestill succeeds (adding an empty crate doesn't break anything).
- Unit 6: Move pure helpers and
ServerTargetintofabro-client
Goal: Move modules with no CLI coupling: SSE parsing, loopback classification, error classification, and the ServerTarget enum with canonical-by-construction behavior. Delete ServerTargetKey.
Requirements: R2, R5, R6.
Dependencies: Unit 5 (crate must exist).
Files:
- Modify:
lib/crates/fabro-client/src/sse.rs— populate fromlib/crates/fabro-cli/src/sse.rs. - Modify:
lib/crates/fabro-client/src/loopback.rs— populate fromlib/crates/fabro-cli/src/loopback_target.rs(rename module). - Modify:
lib/crates/fabro-client/src/error.rs— populate withApiError(ex-HttpResponseFailure),ApiFailure,StructuredApiError,classify_api_error,classify_http_response,map_api_error,parse_error_response_value,is_not_found_error,raw_response_failure_error. - Modify:
lib/crates/fabro-client/src/target.rs— populate withServerTarget { Http(Url), Unix(PathBuf) },FromStr,Display,PartialEq/Eq/Hashon the canonical form. Includenormalized_http_base_urlas a private helper used at construction. - Modify:
lib/crates/fabro-client/src/lib.rs— re-exportServerTarget,LoopbackClassification,ApiError. - Delete from
fabro-cli:lib/crates/fabro-cli/src/loopback_target.rs(after Phase 3 rewires CLI to usefabro-client). For this unit, replace each CLI file's entire content with a one-line re-export — e.g.,pub(crate) use fabro_client::*;(or the specific items the CLI consumes). The file stays on disk as a thin forwarder until Unit 10 deletes it. This avoids duplicate-symbol errors during the intermediate state. Alternative: skip the shim and update every call site in the same commit per-module — more churn per commit, but no intermediate layer to reason about.
Approach:
- Rename
HttpResponseFailure→ApiError. LeaveApiFailure(internal, used inshould_refreshlogic) as-is — it's not in the user-facing rename list. - Canonicalization in
ServerTarget::from_url: parse viafabro_http::Url::parse, then apply today's fullcanonical_http_targetnormalization (lowercase scheme, lowercase host, strip default ports:443/:80, strip trailing/, strip/api/v1suffix, rebuild authority as{scheme}://{host}[:{port}]). Store the canonicalUrl. ImplementDisplayto return the canonical string.PartialEq/Eq/Hashon the canonical form directly. - Canonicalization in
ServerTarget::from_unix_path: lexical cleanup of./..components; no FS access. UsePath::components()+ manualPathBufreconstruction, or consider adding thepath-cleancrate if the hand-rolled version proves ugly (deferred — try stdlib first). - OOP-style methods on
ServerTarget(replacing today's free helpers):target.loopback_classification() -> Result<LoopbackClassification, TargetSchemeError>(wasis_loopback_or_unix_socket(&target))target.build_public_http_client() -> Result<(HttpClient, String)>(wasbuild_public_http_client(&target))
- Delete
ServerTargetKeyentirely.AuthStorewill key byServerTargetdirectly (Unit 7). cli_http_client_builder()currently lives infabro-cli/src/user_config.rs. It stays infabro-cli— the user-agent string identifies the CLI specifically; other consumers offabro-clientwill build their ownHttpClientwith their own UA. The builder APIClient::builder()will accept a pre-builtHttpClientwhen the caller wants control, or default to a barefabro_http::HttpClientBuilder::new()for generic consumers.
Patterns to follow:
lib/crates/fabro-cli/src/sse.rsandsrc/loopback_target.rs— copy verbatim into new locations; these modules have no CLI-specific deps.- Error-classification pattern from
server_client.rs:1625-1790— move wholesale with the rename. Urlcanonicalization:reqwest/urlcrate's default behavior handles scheme lowercase, default port stripping. We addtrim_end_matches('/')andstrip_suffix("/api/v1")on top.- Lexical path cleaning: standard idiom is to iterate
Path::components()and skip., pop on.., otherwise append.
Test scenarios:
- Happy path:
ServerTarget::from_url("https://fabro.example.com/api/v1/")andServerTarget::from_url("https://fabro.example.com")produce equal values. - Happy path:
ServerTarget::from_url("https://EXAMPLE.COM/"),"https://example.com:443", and"https://example.com"all compare equal (migrates today'shttps_normalization_collapses_equivalent_urlstest fromauth_store.rs:507). - Happy path:
ServerTarget::from_url("http://127.0.0.1:80/")and"http://127.0.0.1"compare equal (default-port strip for http). - Happy path:
ServerTarget::from_unix_path("/tmp/./foo/../fabro.sock")canonicalizes toServerTarget::Unix("/tmp/fabro.sock"). - Edge case:
ServerTarget::from_url("not a url")returns a parse error. - Edge case:
ServerTarget::from_unix_path("relative/path")returns an error (relative paths rejected — today's contract). - Edge case: two distinct URL inputs with different casing on scheme (
HTTPS://vshttps://) produce equalServerTargets. - Edge case: Unix paths with trailing
/canonicalize identically to without it. - Happy path:
target.loopback_classification()tests (migrate today'sis_loopback_or_unix_sockettests fromloopback_target.rs). - Happy path:
drain_sse_payloadsparsing tests (migrate today's tests fromsse.rs). - Happy path:
ApiError(ex-HttpResponseFailure) classification for 401/404/500 preserves status, body, and parsed error codes.
Verification:
cargo build --workspacesucceeds after the shim is added tofabro-cli.- Migrated tests pass in
fabro-client. grep -rn "HttpResponseFailure\|RunAttachEventStream\|CapturedArtifactInfo\|RefreshableOAuth\|ResolvedBearer\|ClientBundle\|ServerTargetKey" lib/returns no results outsidedocs/plans/after all Phase 2 units complete. (This unit handlesHttpResponseFailureandServerTargetKey; others land in later units.)
- Unit 7: Move
AuthStore,AuthEntry,StoredSubjectintofabro-client
Goal: Relocate the file-locked OAuth token store, keyed by ServerTarget (not ServerTargetKey).
Requirements: R2, R6, R7.
Dependencies: Unit 6 (ServerTarget canonical-by-construction must exist).
Files:
- Modify:
lib/crates/fabro-client/src/auth_store.rs— populate withAuthStore,AuthEntry,StoredSubject,AuthStoreError,LockError, adapted to key by&ServerTargetdirectly (viaServerTarget::to_string()as the on-disk key). - Modify:
lib/crates/fabro-client/src/lib.rs— re-exportAuthStore,AuthEntry,StoredSubject. - Modify:
lib/crates/fabro-cli/src/auth_store.rs— replace content withpub use fabro_client::{AuthStore, AuthEntry, StoredSubject};shim. Deleted in Unit 10. - Modify:
lib/crates/fabro-cli/Cargo.toml— addfabro-clientdep; removefs2(moves tofabro-client). - Modify:
lib/crates/fabro-client/Cargo.toml— addfs2 = "0.4".
Approach:
- Wholesale move of
lib/crates/fabro-cli/src/auth_store.rs:1-440(non-test code) into the new location. AuthStoreAPI changes:get(&self, target: &ServerTarget) -> ...instead ofget(&self, key: &ServerTargetKey) -> ...- Same for
put,remove,list(returnsVec<(ServerTarget, AuthEntry)>)
- On-disk key stored as
ServerTarget::to_string()canonical form (which is whatServerTargetKey::as_str()returns today — bit-exact for HTTP targets, different for symlinked Unix sockets). AuthStoreError::InvalidServerTargetbecomes unreachable becauseServerTargetis validated at construction — consider removing or keeping as defensive.- Move the test module too. Tests that constructed
ServerTargetKey::new(&target)simplify to using theServerTargetdirectly.
Patterns to follow:
- Preserve file-locking semantics (flock-based, currently via
fs2::FileExt). - Preserve the
FABRO_AUTH_FILEenv override. - Default path resolution via
fabro_util::Home::from_env().root().join("auth.json")stays identical.
Test scenarios:
- Happy path: put/get round-trip for an HTTP target (migrated from
auth_store.rstests). - Happy path: put/get round-trip for a Unix-socket target.
- Edge case: two HTTP URLs that differ only in trailing
/or case canonicalize to the same key and collide on put (last write wins). - Edge case: list returns all stored entries sorted by key.
- Integration: concurrent shared-lock readers don't deadlock with exclusive writers (migrate any existing test of this behavior).
- Error path: corrupt JSON file surfaces
AuthStoreError::Corrupt. - Security: after
put(), the on-diskauth.jsonhas mode0o600on Unix (permission bits exactly owner-rw).
Verification:
cargo build --workspacesucceeds.cargo nextest run -p fabro-client -p fabro-clipasses.- No remaining
fabro_cli::auth_store::ServerTargetKeyreferences.
- Unit 8: Move
Client,Credential,OAuthSession, and wire the connection builder
Goal: Move the Client struct and all its wrapper methods into fabro-client, flatten ClientBundle inline, rename RefreshableOAuth → OAuthSession, rename ResolvedBearer → Credential, rename RunAttachEventStream → RunEventStream, and expose Client::builder() as the new connection API.
Requirements: R1, R2, R3, R5.
Dependencies: Units 1-4 (DTOs must be in fabro-types), Units 5-7 (crate, helpers, ServerTarget, AuthStore must exist).
Files:
- Modify:
lib/crates/fabro-client/src/credential.rs— populate withCredential { DevToken(String), OAuth(AuthEntry) },bearer_token() -> &str, and theCredentialFallbacktrait. - Modify:
lib/crates/fabro-client/src/session.rs— populate withOAuthSession { target, auth_store, fallback: Option<Box<dyn CredentialFallback>> }and therefresh_access_tokenflow logic. - Modify:
lib/crates/fabro-client/src/client.rs— populate withClient(state flattened, noBundle),Client::builder(),send_api,send_http,send_http_response, all 40 typed method wrappers,RunEventStream(formerlyRunAttachEventStream). - Modify:
lib/crates/fabro-client/src/lib.rs— re-exportClient,Credential,OAuthSession,RunEventStream, pluspub mod types→pub use fabro_api::types;. - Modify:
lib/crates/fabro-cli/src/server_client.rs— replace entire content withpub use fabro_client::{Client, RunEventStream, Credential, OAuthSession};+ any CLI-specific helpers that don't move (e.g.,load_dev_token_if_available,wait_for_local_dev_token,resolve_target_bearer). File shrinks from 1941 → ~200 lines. - Modify:
lib/crates/fabro-cli/Cargo.toml— remove deps now owned byfabro-clientonly (e.g.,progenitor-client,tokio-util,bytesif no other CLI callers remain — verify).
Approach:
- Flattening
ClientBundle:Clientbecomes
The old// Directional — not implementation pub struct Client { state: Arc<RwLock<ClientState>>, base_url: String, session: Option<OAuthSession>, refresh_lock: Arc<Mutex<()>>, } struct ClientState { api: fabro_api::ApiClient, http: fabro_http::HttpClient, bearer: Option<String>, }ClientBundlename disappears;ClientStateis private to the module. Client::builder(): new public API. It becomes the underlying connection API. The CLI may keep thinconnect_*orchestration wrappers around it (handled in Unit 9), but transport/session assembly should live in the builder path rather than being duplicated across wrappers.RunEventStreamrename: the struct, itsnext_event/buffer_sse_eventsmethods, and theVecDeque<EventEnvelope>field.EventEnvelopeis nowfabro_types::EventEnvelope.- Method bodies: the 40 wrappers move verbatim. They call
send_api(|client| ...)—clientis thefabro_api::ApiClientfromClientState.convert_type::<_, fabro_types::RunSummary>(...)continues to bridge wire → domain. Client::from_http_client(base_url, http_client)— publicpub fnconstructor for test use and non-builder callers.Client::new_no_proxy(base_url)may remain as a small convenience wrapper built on top of it.- Preserve
send_api's 401 → refresh → retry auto-logic.OAuthSessionowns the refresh state it needs (target,auth_store, optionalfallback); the actual refresh HTTP call uses a bespoke HTTP client built viatarget.build_public_http_client()(method onServerTarget, not a free function — OOP style). - If preserving caller-specific transport behavior across refresh rebuilds requires it,
Clientmay carry an internalTransportConnectorhelper that can rebuild the transport with the same customization after credentials change. CredentialFallbacktrait lives infabro-client::credential:
When refresh fails with missing/expired/revoked entry,// Directional — not implementation pub trait CredentialFallback: Send + Sync { fn resolve(&self) -> Option<Credential>; }OAuthSessionconsultsfallback.resolve(). IfSome(Credential), the session rebuilds the client bundle with that credential; ifNone, it raises "session expired" and clears its auth-store entry as today.fabro-cliprovides a concreteCliDevTokenFallbackimpl (in the CLI's auth layer) that wraps today'sload_dev_token_if_availablelogic.target.loopback_classification() -> Result<LoopbackClassification, TargetSchemeError>replaces today'sis_loopback_or_unix_socket(&target)free helper. Used byOAuthSessionto enforce the plain-HTTP/loopback guard before refresh.ensure_refresh_target_transportandrefresh_transport_errormove with the refresh logic. They useLoopbackClassification(moved in Unit 6).- CLI-specific helpers that stay in
fabro-cli:load_dev_token_if_available,load_dev_token_if_available_from_sources,wait_for_local_dev_token,apply_bearer_token_auth,apply_dev_token_auth,build_authed_unix_socket_client,build_unix_socket_probe_client,try_connect_unix_socket_api_client_bundle,connect_unix_socket_api_client_bundle,check_server_ready,wait_for_server_ready. These read fabro-server state on disk or stage dev tokens — CLI concerns. TheClient::builder()infabro-clientoffers sufficient primitives for the CLI to compose these around.
Patterns to follow:
send_apigeneric wrapper pattern atserver_client.rs:603-632— preserve its shape.- OAuth refresh flow at
server_client.rs:642-749— preserve its error-path branching.
Test scenarios:
- Happy path:
Client::builder().target(http_target).connect()produces a usableClientwhose wrappedfabro_api::ApiClientpoints at the canonical base URL (derived from the target). - Happy path:
Client::builder().target(unix_target).connect()produces a usableClientwithhttp://fabrobase URL and a Unix-socket-dialingHttpClient. - Happy path: call
Client::get_health()against a mock HTTP server (mockitoor similar) — fire and forget. - Happy path: each of the 40 wrapper methods continues to work (this is implicitly covered by the full
fabro-cliintegration test suite — no need for per-method unit tests). - Error path: 401 with
access_token_expiredcode triggers refresh viaOAuthSession(migrated from today's server-client tests). - Error path: refresh fails with
refresh_token_expired→AuthStoreentry is removed and session-expired error surfaces when no fallback is configured. - Error path: refresh fails with
refresh_token_expiredand aCredentialFallbackreturnsSome(Credential::DevToken(...))→ client rebuilds with the dev-token credential and the subsequent call succeeds. This preserves today's silent-degrade behavior for local dev targets. - Error path: refresh fails and
CredentialFallback::resolve()returnsNone→ session-expired error surfaces (same as no-fallback case). - Error path:
refresh_access_tokenrejects plain-HTTP non-loopback targets (migrate the existingrefresh_access_token_rejects_plain_http_non_loopback_targetstest). - Error path:
refresh_access_tokenagainst an HTTP target whose hostname resolves to loopback but isn't a loopback literal is rejected (classification is by literal authority, not DNS). - Happy path:
refresh_access_tokenagainsthttp://127.0.0.1:3000andhttp://[::1]:3000succeeds (loopback literals accepted). - Happy path:
refresh_access_tokenagainsthttps://non-loopback.example.comsucceeds (HTTPS accepted regardless of host). - Security:
Credential::DevToken(...),Credential::OAuth(entry),OAuthSession, andAuthEntryeither do not deriveDebugor theirDebugoutput does not contain the raw token string. - Edge case:
RunEventStream::next_eventhandles SSE chunk boundaries (migrated from today's sse.rs tests). - Integration:
fabro-cliintegration tests continue to pass against the real localfabro server. These prove the connection wire-up is correct without fabro-client needing its own integration server.
Verification:
cargo build --workspacesucceeds.cargo nextest run --workspacepasses (4395 tests).cargo +nightly-2026-04-14 clippy -p fabro-client --all-targets -- -D warningsclean.grep -rn "fabro_cli::server_client::" lib/returns zero hits outsidefabro-cli/src/server_client.rs(shim) — all external callers go throughfabro_client::....
Phase 3 — Rewire fabro-cli
- Unit 9: Rewire CLI orchestrator to use
Client::builder()
Goal: Update connect_server_with_settings and its helpers to build a fabro_client::Client via the new builder, pulling Credential and OAuthSession from CLI-owned sources (env vars, dev-token files, AuthStore).
Requirements: R8, R9.
Dependencies: Unit 8 (Client::builder() exists).
Files:
- Modify:
lib/crates/fabro-cli/src/server_client.rs— shrink the remaining file to just the orchestrator + CLI-specific helpers. Remove dead imports. - Modify:
lib/crates/fabro-cli/src/commands/auth/{login,logout,status}.rs— importfabro_client::{AuthStore, AuthEntry, StoredSubject}instead ofcrate::auth_store::. - Modify:
lib/crates/fabro-cli/src/commands/install.rs,src/commands/run/runner.rs, and any other file currently importingcrate::server_client::{Client, RunEventStream, ...}— update tofabro_client::. - Modify:
lib/crates/fabro-cli/src/user_config.rs—ServerTargetmoves tofabro-client; re-export fromuser_configfor CLI convenience or update all in-crate call sites. Prefer the latter (update call sites) for cleanliness.
Approach:
connect_server_with_settings(args, settings, base_config_path)becomes roughly:- Resolve
ServerTargetfrom args + settings (CLI-owned). - If Unix and no server responds to
/health: callstart::ensure_server_running_on_socket(CLI-owned). - Build
CredentialfromFABRO_DEV_TOKENenv /AuthStoreOAuth entry / dev-token file (CLI-owned). - Build optional
OAuthSessionif the credential is OAuth. Client::builder().target(t).credential(c).oauth_session(s).connect().await.
- Resolve
resolve_target_bearerstays (renamed toresolve_credential) but returnsfabro_client::Credentialand calls intofabro_client::AuthStore.build_public_http_client(target) -> (HttpClient, String)moves tofabro-client(as an inherent method onServerTargetor a module-level helper) becauseOAuthSession::refresh_access_tokenis its only caller after the split. This is UA-neutral: the refresh call deliberately does not stamp the CLI's user-agent onto OAuth-server traffic.cli_http_client_builderis distinct — it stays infabro-cliand applies thefabro-cli/{version}user-agent to command traffic from this binary. The two coexist for different purposes; the names communicate the intent.
Patterns to follow:
- Today's
connect_managed_unix_socket_api_client_bundleatserver_client.rs:219-251shows the try-connect-fail-autostart-retry pattern. Preserve it. - Today's
connect_local_api_client_bundleatserver_client.rs:253-282shows the CLI's storage-first flow. Preserve it.
Test scenarios:
- Integration:
fabro-cliintegration tests continue to pass. No new unit tests needed — behavior is unchanged from the user's perspective. - Happy path: the three current
connect_*flows (with-settings, target-direct, local-storage) still produce working clients. Covered by existing tests infabro-cli/tests/it/.
Verification:
cargo build --workspacesucceeds.cargo nextest run --workspacepasses.grep -rn "crate::auth_store\|crate::server_client" lib/crates/fabro-cli/src/ --include="*.rs"returns only the shrunkserver_client.rsandauth_store.rsshim files themselves.
- Unit 10: Delete moved fabro-cli modules and clean up shims
Goal: Remove the transitional shim files and dead code from fabro-cli. Final dep-list cleanup.
Requirements: R9.
Dependencies: Unit 9 (all callers must already use fabro_client::... imports).
Files:
- Delete:
lib/crates/fabro-cli/src/sse.rs - Delete:
lib/crates/fabro-cli/src/loopback_target.rs - Delete:
lib/crates/fabro-cli/src/auth_store.rs - Modify:
lib/crates/fabro-cli/src/server_client.rs— trim to only the CLI-specific orchestrator + helpers. Likely ends up ~200-400 lines. - Modify:
lib/crates/fabro-cli/src/main.rsorsrc/lib.rs— removepub mod sse;,pub mod loopback_target;,pub mod auth_store;. - Modify:
lib/crates/fabro-cli/Cargo.toml— remove deps now used only byfabro-client(fs2, possiblyprogenitor-client,tokio-util,bytes,randif no other consumer — verify each by grep).
Approach:
- Delete the shim files that were added in Units 6-8.
- Verify no residual references to the deleted modules:
grep -rn "mod sse\|mod loopback_target\|mod auth_store" lib/crates/fabro-cli/. - Dep cleanup: for each candidate-removed dep in
fabro-cli/Cargo.toml, greplib/crates/fabro-cli/src/for direct usage. Remove only if no usage remains.
Patterns to follow:
- Previous dep-cleanup pattern from
docs/plans/2026-04-20-001-fix-cli-server-same-host-assumptions-plan.md— audit Cargo.toml against direct usage.
Test scenarios:
- Test expectation: none — pure deletion. Existing tests provide the regression safety net.
Verification:
cargo build --workspacesucceeds.cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warningsclean (catches unused deps viaunused_crate_dependenciesif enabled, or viacargo macheteoptionally).cargo nextest run --workspacepasses.ls lib/crates/fabro-cli/src/no longer showssse.rs,loopback_target.rs, orauth_store.rs.
Phase 4 — Verification
- Unit 11: Full workspace verification
Goal: Confirm the refactor is complete, clean, and behaviorally identical.
Requirements: R9.
Dependencies: Units 1-10.
Files:
- None modified; pure verification.
Approach:
- Run the full verification matrix from this repo's
CLAUDE.md:cargo +nightly-2026-04-14 fmt --check --allcargo build --workspacecargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warningscargo nextest run --workspace
- Confirm dep graph:
cargo tree -p fabro-client | grep -E "fabro-(cli|store|workflow|server|config)"returns no rows. - Confirm no leaked old names:
grep -rn "ClientBundle\|RefreshableOAuth\|ResolvedBearer\|HttpResponseFailure\|RunAttachEventStream\|CapturedArtifactInfo\|ServerTargetKey" lib/ --include="*.rs"returns zero. - Confirm doc
docs/reference/anddocs/administration/don't mention removed internals.
Test scenarios:
- Test expectation: none — this unit runs existing tests.
Verification:
- All four verification commands pass.
- Both grep checks return empty.
cargo tree -p fabro-clientdeps align with the Target graph in the High-Level Technical Design section.
System-Wide Impact
- Interaction graph: The touched crates are
fabro-types(gains DTOs),fabro-store(loses DTOs, keeps free-function reducers overfabro_types::RunProjection),fabro-workflow(CapturedArtifactInfo→ArtifactUpload),fabro-retro(imports shift),fabro-server(imports shift),fabro-cli(loses the 1941-lineserver_client.rs; the residual orchestrator still depends onfabro-serverforBind,fabro-configforStorage, and other CLI-scoped crates — "the client surface moves out; CLI orchestration stays"),fabro-client(new). Downstream test crates (fabro-test,test/twin/openai,test/twin/github) should not need changes since they don't import from the moved modules — verify during implementation. - Error propagation:
ApiError(ex-HttpResponseFailure) is now infabro-client. CLI commands that match on its fields (status,body,headers) continue to work via re-export; no behavior change. - State lifecycle risks:
AuthStorefile format is unchanged for HTTP targets (same canonicalization). For Unix-socket targets, the switch fromfs::canonicalizeto lexical-only means existing keys with symlinked socket paths may no longer match after the change. Acceptable per user direction ("We don't care about migration"); users with OAuth sessions against symlinked sockets will re-login. - API surface parity: No wire-format changes. OpenAPI spec unchanged.
fabro-servercontinues to emit the same JSON forEventEnvelopeandRunSummaryresponses. - Integration coverage: Existing
fabro-cliintegration tests exercise every code path — 4395 tests provide strong safety net. No new integration tests needed. - Unchanged invariants:
- Subprocess autostart (
fabro serverself-spawn) remains a CLI concern. - Dev-token-from-disk loading (reads
~/.fabro/dev-token, storage-dir dev-token, fabro-server pidfile record) stays CLI-owned. - TOML-driven
[cli.target]resolution stays infabro-cli/src/user_config.rs. - OAuth login browser-popup flow (
fabro auth login) stays infabro-cli. - The CLI's
ServerTargetArgs,ServerConnectionArgs, and command-context plumbing (command_context.rs) are untouched.
- Subprocess autostart (
Risks & Dependencies
| Risk | Mitigation |
|---|---|
EventEnvelope restructure breaks a serde consumer that relied on payload.as_value() round-tripping unknown JSON. |
OpenAPI already defines the wire shape as seq + RunEvent flattened — all wire consumers already get the typed shape. EventPayload stays in fabro-store for write-path validation, so the store-internal round-trip is preserved. Compiler drives CLI/server read-path updates. |
RunProjection extension-trait split requires use fabro_store::RunProjectionReducer; at call sites that invoke reducer methods. |
One added use per file (~5-6 files); call sites keep method-call syntax unchanged. |
ServerTarget canonical form diverges from today's ServerTargetKey::as_str() for symlinked Unix sockets, invalidating existing AuthStore entries. |
Accepted per user direction. HTTP target canonicalization is bit-identical to today's, so most users are unaffected. |
fabro-client ends up with a leaky CLI dep we didn't catch (e.g., the cli_http_client_builder user-agent string or a hidden fabro_util::Home call). |
Unit 11 grep check + cargo tree -p fabro-client dep-graph audit catches any leak. fabro-util is an allowed dep (we need Home for AuthStore default); the check is "no fabro-cli, fabro-store, fabro-workflow, fabro-server, fabro-config". |
Tests in fabro-cli/tests/it/ rely on Client::new_no_proxy via internal visibility. |
Replace with fabro_client::Client::from_http_client(base_url, http_client) public constructor + local CLI test helper that wraps no_proxy() builder. |
Phased rollout leaves fabro-cli in a partially-migrated state if we stop after Phase 2. |
Each phase compiles and tests pass at its boundary. If we stop mid-refactor, the shim layer keeps fabro-cli working. But we shouldn't stop mid-refactor — commit the whole thing. |
fabro-store::EventPayload validation semantics subtly change if Unit 2 restructures how events are built server-side. |
Server-side write path stays in fabro-store and continues to use EventPayload::new for validation. Only the read-path return type changes. Unit 2 explicitly calls this out. |
progenitor-client version drift between fabro-api (0.13) and fabro-client's direct use. |
Match versions exactly. Check today's fabro-cli/Cargo.toml to confirm progenitor-client = "0.13"; copy that version literal. |
Security Considerations
This is a pure refactor — no new endpoints, data stores, or attack surface. However, security-sensitive code is moving, so preserve these invariants across the move:
auth.jsonfile mode.AuthStore::putmust write the file with mode0600on Unix (owner read/write only). Add or carry forward whatever umask/OpenOptions::modethe current implementation uses, and add a unit test asserting the resulting permission bits afterput(). Do not assume umask handles this; set it explicitly.- Refresh-flow plain-HTTP/loopback guard. The guard that refuses to send refresh-token credentials over plaintext HTTP to non-loopback targets (today's
ensure_refresh_target_transport+is_loopback_or_unix_socket) is being split acrossloopback.rs(Unit 6),session.rs(Unit 8), andtarget.rscanonicalization (Unit 6). Beyond migrating the existingrefresh_access_token_rejects_plain_http_non_loopback_targetstest, add Unit 8 scenarios for: (a) refresh againsthttps://non-loopbacksucceeds; (b) refresh against an IP literal that happens to be loopback (e.g.,http://127.0.0.1:3000) succeeds; (c) refresh against a hostname that resolves to loopback but is not a loopback literal is rejected (classification is based on literal authority, not DNS — preserve that). Debug/Displayimpls on token-bearing types.Credential(holds raw bearer strings),OAuthSession(carriesAuthStorewhich holdsAuthEntry), andAuthEntrymust not deriveDebugin a form that prints token bytes. Either don't deriveDebugat all, or implement it manually to redactaccess_token/refresh_tokenfields (usefabro-util's redaction helper if it suits). Add one unit test per secret-bearing type asserting theDebugoutput does not contain a known fixture token. TheOpen Questionsentry aboutClientderivingDebugis resolved here for the token-bearing types: do not auto-derive anything that prints tokens.ServerTargetsymlink trust boundary. Switching fromfs::canonicalizeto lexical canonicalization means theServerTargetkey is a best-effort identity, not a security boundary — two symlinked paths that point to the same socket now compare unequal, and a third-party-writable symlink could cause anAuthStorelookup against path A to return a token that's presented to a socket opened via path B. This is fine for the intended operating model (fabro's socket lives under user-controlled~/.fabro/and the user trusts that directory). Document this as an explicit assumption in thefabro-clientcrate docs so a future consumer choosing a non-home socket path understands the trust boundary.
Documentation / Operational Notes
- No user-facing documentation changes. Reference docs (
docs/reference/,docs/administration/) describe the CLI from the outside; internal crate reorganization is invisible to users. - No rollout / monitoring / migration concerns — pure refactor.
- Consider adding a
lib/crates/fabro-client/README.mdlater that describes the crate's purpose and points to integration examples. Deferred to follow-up work (not part of this plan). - The file
CLAUDE.md's "Rust crates" inventory at line 43 mentionsfabro-cli,fabro-workflow,fabro-agent,fabro-server, etc. Add a one-line entry forfabro-clientduring Unit 5 or 11.
Sources & References
- Origin document: No
ce:brainstormrequirements doc — this plan was scoped directly through conversation. Problem frame, decisions, and scope were confirmed interactively. - Prior plans in the same subsystem:
docs/plans/2026-04-20-001-fix-cli-server-same-host-assumptions-plan.md— tightened the CLI/server target contract; this plan continues that direction.docs/plans/2026-04-05-cli-deglobalize-server-url-and-storage-dir-plan.md— made target resolution explicit; precondition for this extraction.docs/plans/2026-04-02-002-feat-http-store-client-auto-start-plan.md— introduced the autostart logic this plan explicitly keeps infabro-cli.
- Primary code:
lib/crates/fabro-cli/src/server_client.rslib/crates/fabro-cli/src/auth_store.rslib/crates/fabro-cli/src/loopback_target.rslib/crates/fabro-cli/src/sse.rslib/crates/fabro-cli/src/user_config.rslib/crates/fabro-store/src/types.rslib/crates/fabro-store/src/run_state.rslib/crates/fabro-workflow/src/artifact_snapshot.rs
- OpenAPI contract:
docs/api-reference/fabro-api.yaml:3452-3461(EventEnvelope schema confirmsseq + RunEvent flattenedwire shape).