From 65bc075ea1ae174a54111b7122302137064a4b27 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:33 +0700 Subject: [PATCH 01/14] style(router): use is_none() in the domain route sort key clippy 1.94 rejects `!r.domain.is_some()` (nonminimal_bool) under -D warnings. --- crates/rustasea-router/src/router.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rustasea-router/src/router.rs b/crates/rustasea-router/src/router.rs index 0e521cd..44e4222 100644 --- a/crates/rustasea-router/src/router.rs +++ b/crates/rustasea-router/src/router.rs @@ -396,7 +396,7 @@ impl Router { /// Return all registered routes, domain-constrained first. pub fn get_routes(&self) -> Vec { let mut routes = self.routes.clone(); - routes.sort_by_key(|r| !r.domain.is_some()); + routes.sort_by_key(|r| r.domain.is_none()); routes } From b44c18b6b65ce774ccf27fabdef6cddd8c5a93c7 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:33 +0700 Subject: [PATCH 02/14] fix(orm): decode a UUID stored in a column declared UUID on SQLite SQLite gives a column declared `UUID` NUMERIC affinity, so the driver reports neither UUID nor BLOB and the row decoder returned null for the id. The scaffold migrations declare ids this way, so a row read through fetch_json lost its id on the default SQLite connection. Try a UUID decode as the last fallback. --- crates/rustasea-orm/src/value.rs | 7 +++++++ crates/rustasea-orm/tests/raw_execution.rs | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/rustasea-orm/src/value.rs b/crates/rustasea-orm/src/value.rs index 78cc462..68dc2ca 100644 --- a/crates/rustasea-orm/src/value.rs +++ b/crates/rustasea-orm/src/value.rs @@ -215,6 +215,13 @@ where if let Ok(v) = row.try_get::(index) { return v; } + // Last resort: a UUID stored in a column whose declared type the driver + // does not report as UUID/BLOB. SQLite gives a column declared `UUID` + // (the portable DDL the scaffold migrations emit) NUMERIC affinity, so the + // 16-byte value matches none of the hints above. + if let Ok(v) = row.try_get::(index) { + return serde_json::Value::String(v.to_string()); + } serde_json::Value::Null } diff --git a/crates/rustasea-orm/tests/raw_execution.rs b/crates/rustasea-orm/tests/raw_execution.rs index b8faa47..7461b07 100644 --- a/crates/rustasea-orm/tests/raw_execution.rs +++ b/crates/rustasea-orm/tests/raw_execution.rs @@ -134,3 +134,25 @@ async fn raw_binds_injection_payload_as_data() { assert_eq!(count, Some(0), "payload must be bound, not executed"); pool.close().await; } + +/// Positive: a UUID bound into a column declared `UUID` reads back as its +/// hyphenated string on SQLite, where that declared type has NUMERIC affinity +/// and the driver reports neither `UUID` nor `BLOB` as the column type. +#[tokio::test] +async fn uuid_column_declared_as_uuid_round_trips_on_sqlite() { + let pool = DbPool::connect("sqlite::memory:").await.unwrap(); + pool.execute_raw("CREATE TABLE things (id UUID PRIMARY KEY)", &[]) + .await + .unwrap(); + let id = uuid::Uuid::new_v4(); + pool.execute_raw("INSERT INTO things (id) VALUES ($1)", &[Value::Uuid(id)]) + .await + .unwrap(); + + let rows = pool + .fetch_json("SELECT id FROM things WHERE id = $1", &[Value::Uuid(id)]) + .await + .unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0]["id"].as_str(), Some(id.to_string().as_str())); +} From f2ad0a542d185a2b421930fbbd57d76528f73e5c Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:33 +0700 Subject: [PATCH 03/14] feat(queue): persist failed sync jobs through the database connection A failed inline (sync) dispatch was only tracked in a process-local list, so it vanished on exit and never showed in queue:failed. When a database connection is registered the failure is now written to its failed_jobs table as a full job envelope, so queue:retry can re-enqueue it; without one, or if the insert fails, it still falls back to the in-memory sink. The job body is captured before the run: executing a job consumes it, so every sync dead letter previously stored a null payload. --- crates/rustasea-queue/src/driver.rs | 53 +++++++++++- crates/rustasea-queue/src/registry.rs | 32 ++++--- .../rustasea-queue/tests/sync_failed_sink.rs | 83 +++++++++++++++++++ 3 files changed, 152 insertions(+), 16 deletions(-) create mode 100644 crates/rustasea-queue/tests/sync_failed_sink.rs diff --git a/crates/rustasea-queue/src/driver.rs b/crates/rustasea-queue/src/driver.rs index c30beb1..d20875f 100644 --- a/crates/rustasea-queue/src/driver.rs +++ b/crates/rustasea-queue/src/driver.rs @@ -164,11 +164,13 @@ impl QueueDriver for SyncDriver { } } -/// Placeholder dead-letter sink shared by the driver stubs. +/// Process-local dead-letter sink. /// -/// The database driver persists dead letters to a real `failed_jobs` table; -/// this in-memory sink backs the sync/redis drivers and keeps the contract -/// testable without a server. +/// The database driver persists dead letters to a real `failed_jobs` table, and +/// inline `sync` failures are persisted there too once a `database` connection +/// is registered (see [`dead_letter_sync`]). This in-memory sink is the +/// fallback when no database is available and keeps the contract testable +/// without a server. static FAILED: std::sync::OnceLock>> = std::sync::OnceLock::new(); /// Record a dead-letter entry for a permanently failed job. @@ -179,6 +181,49 @@ pub(crate) fn record_failed(job: FailedJob) { } } +/// Dead-letter a failure from an inline (`sync`) dispatch. +/// +/// When a `database` connection is registered the entry is persisted to its +/// `failed_jobs` table, so it survives the process and is listed by +/// `queue:failed`. The stored payload is the full [`JobPayload`] envelope +/// addressed to that connection, so `queue:retry` re-enqueues a job a worker +/// can resolve. Without a database driver, or when the insert fails, the entry +/// falls back to the process-local sink: a failed job is never dropped. +pub(crate) async fn dead_letter_sync( + type_key: &str, + queue: Option<&str>, + body: serde_json::Value, + exception: String, +) { + if let Ok(database) = crate::registry::driver(DATABASE_CONNECTION) { + let queue = queue + .map(str::to_string) + .or_else(|| { + crate::registry::Queue::resolve(type_key) + .ok() + .map(|route| route.queue.to_string()) + }) + .unwrap_or_else(|| crate::config::DEFAULT_QUEUE.to_string()); + let envelope = JobPayload::new( + queue.clone(), + DATABASE_CONNECTION, + Some(type_key.to_string()), + body.clone(), + ); + let payload = serde_json::to_value(&envelope).unwrap_or_else(|_| body.clone()); + let persisted = FailedJob::new(SYNC_CONNECTION, queue, payload, exception.clone()); + match database.dead_letter(persisted).await { + Ok(()) => return, + Err(error) => tracing::warn!( + job = type_key, + %error, + "persisting a sync failed job failed; keeping it in the in-memory sink" + ), + } + } + record_failed(FailedJob::new(SYNC_CONNECTION, type_key, body, exception)); +} + /// Snapshot the current dead-letter entries. pub fn failed_jobs() -> Vec { let Some(list) = FAILED.get() else { diff --git a/crates/rustasea-queue/src/registry.rs b/crates/rustasea-queue/src/registry.rs index 8627386..7d4718b 100644 --- a/crates/rustasea-queue/src/registry.rs +++ b/crates/rustasea-queue/src/registry.rs @@ -10,10 +10,10 @@ use std::sync::Arc; use crate::batch::BatchId; use crate::driver::{ - record_failed, DatabaseDriver, QueueDriver, DATABASE_CONNECTION, SYNC_CONNECTION, + dead_letter_sync, DatabaseDriver, QueueDriver, DATABASE_CONNECTION, SYNC_CONNECTION, }; use crate::error::{QueueError, Result}; -use crate::job::{run_erased, DispatchHandle, ErasedJob, FailedJob, Job, JobId, JobOutcome}; +use crate::job::{run_erased, DispatchHandle, ErasedJob, Job, JobId, JobOutcome}; use crate::metrics::{QueueMetrics, Queues}; use crate::unique::DispatchOutcome; @@ -124,12 +124,16 @@ impl Queue { /// Execute an erased job inline on the sync connection. /// /// Runs the body and returns the `JobOutcome`. `Failed` outcomes are - /// dead-lettered; `Retrying` cannot be re-enqueued on sync (no worker to + /// dead-lettered (to the `database` connection's `failed_jobs` table when + /// one is registered, else the process-local sink); `Retrying` cannot be re-enqueued on sync (no worker to /// release it later), so it is dead-lettered too — a sync dispatch never /// silently drops a failed job. `Skipped` outcomes (missing-model /// suppression, FR-605) are recorded as diagnostics but never dead-lettered /// nor retried. The driver buffer is untouched. pub(crate) async fn execute_sync(handle: &DispatchHandle) -> Result { + // Running the job consumes its body, so the payload a dead letter + // needs is captured first. + let body = handle.exec.as_json(); let outcome = run_erased(handle.exec.as_ref()).await; // A sync dispatch has no later worker to release a retry, so both // `Failed` and `Retrying` are dead-lettered with the attempt's trace. @@ -143,12 +147,13 @@ impl Queue { ), JobOutcome::Succeeded | JobOutcome::Skipped => return Ok(outcome), }; - record_failed(FailedJob::new( - SYNC_CONNECTION, + dead_letter_sync( handle.exec.type_key(), - handle.exec.as_json(), + handle.queue.as_deref(), + body, format!("JobError::MaxAttemptsExceeded: {trace}{suffix}"), - )); + ) + .await; Ok(outcome) } @@ -170,18 +175,21 @@ impl Queue { pub async fn chain(jobs: Vec>) -> Result> { let mut outcomes = Vec::with_capacity(jobs.len()); for exec in jobs { + // Captured before the run consumes the job body (see `execute_sync`). + let body = exec.as_json(); let outcome = run_erased(exec.as_ref()).await; let stopped = !matches!(outcome, JobOutcome::Succeeded); if matches!( outcome, JobOutcome::Failed { .. } | JobOutcome::Retrying { .. } ) { - record_failed(FailedJob::new( - SYNC_CONNECTION, + dead_letter_sync( exec.type_key(), - exec.as_json(), - "JobError::MaxAttemptsExceeded", - )); + None, + body, + "JobError::MaxAttemptsExceeded".to_string(), + ) + .await; } outcomes.push(outcome); if stopped { diff --git a/crates/rustasea-queue/tests/sync_failed_sink.rs b/crates/rustasea-queue/tests/sync_failed_sink.rs new file mode 100644 index 0000000..c8b67cd --- /dev/null +++ b/crates/rustasea-queue/tests/sync_failed_sink.rs @@ -0,0 +1,83 @@ +//! Persistent dead-letter sink for inline `sync` dispatches (M4). +//! +//! Positive: once a `database` connection is registered, a failed sync dispatch +//! lands in the `failed_jobs` table as a retryable envelope instead of the +//! process-local sink, and `retry_failed` re-enqueues it on that connection. +//! +//! One test owns this binary's process-wide registry, so the two phases +//! (before and after registering the database driver) run in a fixed order. + +use rustasea_orm::DbPool; +use rustasea_queue::{ + failed_jobs, register_database_driver, Job, JobError, JobOutcome, Queue, QueueDriver, +}; +use serde::{Deserialize, Serialize}; + +/// A job that always fails permanently. +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Doomed { + /// Marker carried through the stored payload. + order_id: u64, +} + +#[async_trait::async_trait] +impl Job for Doomed { + /// Fail on every attempt. + async fn handle(self) -> std::result::Result<(), JobError> { + Err(JobError::Exception("boom".into())) + } +} + +/// Dead-letter entries in the in-memory sink for the `Doomed` job type. +fn in_memory() -> usize { + failed_jobs() + .into_iter() + .filter(|f| f.queue == std::any::type_name::()) + .count() +} + +#[tokio::test] +async fn sync_failures_persist_once_a_database_connection_exists() { + // Without a database connection the failure stays in the in-memory sink. + let outcome = Queue::dispatch_sync(Doomed { order_id: 1 }) + .await + .expect("dispatch"); + assert!(!matches!(outcome, JobOutcome::Succeeded)); + assert_eq!(in_memory(), 1); + // The dead letter keeps the job body even though running the job consumed it. + let kept = failed_jobs() + .into_iter() + .find(|f| f.queue == std::any::type_name::()) + .expect("in-memory entry"); + assert_eq!(kept.payload["order_id"], 1); + + let pool = DbPool::connect("sqlite::memory:").await.expect("pool"); + rustasea_queue::queue_migrator() + .run(&pool) + .await + .expect("queue migrations"); + let driver = register_database_driver(pool); + + Queue::dispatch_sync(Doomed { order_id: 2 }) + .await + .expect("dispatch"); + + // Persisted, and the in-memory sink did not grow. + assert_eq!(in_memory(), 1); + let failed = driver.failed_jobs().await.expect("failed rows"); + assert_eq!(failed.len(), 1); + let row = &failed[0]; + assert_eq!(row.connection, "sync"); + assert_eq!(row.queue, "default"); + assert!(row.exception.contains("boom"), "{}", row.exception); + assert_eq!( + row.payload["job"].as_str(), + Some(std::any::type_name::()) + ); + assert_eq!(row.payload["payload"]["order_id"], 2); + + // The stored envelope is retryable on the database connection. + driver.retry_failed(row.id).await.expect("retry"); + assert!(driver.failed_jobs().await.expect("failed rows").is_empty()); + assert_eq!(driver.pending_size("default").await.expect("pending"), 1); +} From 60138f090712c57da2da4f7df2ee6f9ccde1bee8 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:33 +0700 Subject: [PATCH 04/14] feat(auth): add DatabaseUserProvider over the users table The store-backed UserProvider for registration, login, password reset, email verification, and profile/timezone updates, against the scaffold users table. Soft-deleted users do not resolve, a malformed id is treated as an unknown user, and any database failure surfaces as AuthError::StoreUnavailable. --- crates/rustasea-auth/src/lib.rs | 4 +- crates/rustasea-auth/src/users.rs | 4 +- crates/rustasea-auth/src/users/provider.rs | 7 +- .../src/users/provider/database.rs | 350 ++++++++++++++++++ .../tests/database_user_provider.rs | 270 ++++++++++++++ 5 files changed, 631 insertions(+), 4 deletions(-) create mode 100644 crates/rustasea-auth/src/users/provider/database.rs create mode 100644 crates/rustasea-auth/tests/database_user_provider.rs diff --git a/crates/rustasea-auth/src/lib.rs b/crates/rustasea-auth/src/lib.rs index 03b367c..94f2358 100644 --- a/crates/rustasea-auth/src/lib.rs +++ b/crates/rustasea-auth/src/lib.rs @@ -79,7 +79,9 @@ pub use two_factor::{ MemoryTwoFactorStore, SecretCipher, TwoFactorEnrollment, TwoFactorRecord, TwoFactorService, TwoFactorStore, DEFAULT_WINDOW, DIGITS, RECOVERY_CODE_COUNT, SECRET_BYTES, STEP_SECS, }; -pub use users::provider::{DenyAllProvider, MemoryUserProvider, NewUserRecord, UserProvider}; +pub use users::provider::{ + DatabaseUserProvider, DenyAllProvider, MemoryUserProvider, NewUserRecord, UserProvider, +}; pub use verification::{EmailVerification, MemoryEmailVerification}; /// Alias kept for documentation parity (`Auth::guard(...)`). diff --git a/crates/rustasea-auth/src/users.rs b/crates/rustasea-auth/src/users.rs index f396af5..add88ed 100644 --- a/crates/rustasea-auth/src/users.rs +++ b/crates/rustasea-auth/src/users.rs @@ -9,7 +9,9 @@ use std::sync::RwLock; pub mod provider; -pub use provider::{DenyAllProvider, MemoryUserProvider, NewUserRecord, UserProvider}; +pub use provider::{ + DatabaseUserProvider, DenyAllProvider, MemoryUserProvider, NewUserRecord, UserProvider, +}; /// Minimal user record the auth layer needs. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/rustasea-auth/src/users/provider.rs b/crates/rustasea-auth/src/users/provider.rs index 411f4b0..9035eac 100644 --- a/crates/rustasea-auth/src/users/provider.rs +++ b/crates/rustasea-auth/src/users/provider.rs @@ -34,8 +34,9 @@ /// call asynchronously inside its boxed future — `find_by_email` issues a /// `SELECT`, `create` an `INSERT`, and so on. There is no pre-loading and no /// feature gate: the async boundary is the trait itself, so the ORM adapter -/// returns its boxed query future directly. This crate stays DB-agnostic and -/// never depends on `sqlx`/`rustasea-orm`. +/// returns its boxed query future directly. [`DatabaseUserProvider`] is that +/// adapter over the `rustasea-orm` connection pool and the scaffold `users` +/// table. use std::future::Future; use std::pin::Pin; @@ -43,8 +44,10 @@ use crate::error::{AuthError, Result}; use super::{AuthUserRecord, UserLookup}; +mod database; mod memory; +pub use database::DatabaseUserProvider; pub use memory::MemoryUserProvider; /// Input for [`UserProvider::create`] (registration). diff --git a/crates/rustasea-auth/src/users/provider/database.rs b/crates/rustasea-auth/src/users/provider/database.rs new file mode 100644 index 0000000..507c98d --- /dev/null +++ b/crates/rustasea-auth/src/users/provider/database.rs @@ -0,0 +1,350 @@ +/// Database-backed [`UserProvider`] over the ORM connection pool. +/// +/// Reads and writes the `users` table created by the scaffold migration +/// (`create_users_table`): `id` (UUID), `name`, `email` (unique), `password` +/// (Argon2 PHC hash), `email_verified_at`, `timezone`, `created_at`, +/// `updated_at`, `deleted_at`. This is the store-backed counterpart to the +/// in-memory [`super::MemoryUserProvider`] and the fail-closed +/// [`super::DenyAllProvider`]: install it at boot so registration, login +/// ([`crate::SessionGuard::login_with_provider`]), password reset, and profile +/// updates persist across restarts and processes. +/// +/// # Semantics +/// +/// - **Soft-deleted users do not exist.** Every read and write filters on +/// `deleted_at IS NULL`, so a soft-deleted account can neither log in nor be +/// mutated. +/// - **A malformed id is "no such user".** Ids are UUIDs; a string that does not +/// parse resolves to `Ok(None)` on reads and [`AuthError::UserNotFound`] on +/// writes, never a storage error. +/// - **Timestamps are RFC 3339.** `email_verified_at` is bound as a native +/// timestamp and read back as an RFC 3339 string; an unparsable value is +/// rejected with [`AuthError::Disabled`] before any write. +/// +/// # Error handling +/// +/// Every database failure (unreachable server, missing `users` table) surfaces +/// as [`AuthError::StoreUnavailable`] — never a panic and never a silent +/// `Ok(None)`, so an outage cannot be mistaken for "unknown user". +use std::future::Future; +use std::pin::Pin; + +use chrono::{DateTime, Utc}; +use rustasea_orm::{DbPool, Value}; +use uuid::Uuid; + +use crate::error::{AuthError, Result}; +use crate::users::AuthUserRecord; + +use super::{NewUserRecord, UserProvider}; + +/// Default table name, matching the scaffold `create_users_table` migration. +const DEFAULT_TABLE: &str = "users"; + +/// Columns selected for an [`AuthUserRecord`]. +const COLUMNS: &str = "id, email, password, email_verified_at, timezone"; + +/// A [`UserProvider`] persisting users in a relational `users` table. +#[derive(Debug, Clone)] +pub struct DatabaseUserProvider { + pool: DbPool, + table: String, +} + +impl DatabaseUserProvider { + /// Build a provider over `pool` against the default `users` table. + pub fn new(pool: DbPool) -> Self { + Self { + pool, + table: DEFAULT_TABLE.to_string(), + } + } + + /// Override the table name (builder form). + /// + /// The name is interpolated into SQL, so it is validated as a plain + /// identifier on every query; an invalid name fails every call with + /// [`AuthError::StoreUnavailable`]. + pub fn with_table(mut self, table: impl Into) -> Self { + self.table = table.into(); + self + } + + /// The configured table name. + pub fn table(&self) -> &str { + &self.table + } + + /// Access the underlying pool (for callers that own the schema). + pub fn pool(&self) -> &DbPool { + &self.pool + } + + /// The table name, validated as a plain SQL identifier. + fn checked_table(&self) -> Result<&str> { + let table = self.table.trim(); + let mut chars = table.chars(); + let valid = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_'); + if valid { + Ok(table) + } else { + Err(AuthError::StoreUnavailable) + } + } + + /// Fetch the single live user matching `column = value`. + async fn find_where(&self, column: &str, value: Value) -> Result> { + let table = self.checked_table()?; + let sql = format!( + "SELECT {COLUMNS} FROM {table} WHERE {column} = $1 AND deleted_at IS NULL LIMIT 1" + ); + let rows = self.pool.fetch_json(&sql, &[value]).await.map_err(store)?; + Ok(rows.first().and_then(record_from_row)) + } + + /// Run an `UPDATE … SET , updated_at = now WHERE id = `. + /// + /// `assignments` uses placeholders `$1..$n` for `bindings`; the timestamp and + /// id are appended as the next two placeholders. Fails with + /// [`AuthError::UserNotFound`] when no live row matched. + async fn update_user( + &self, + user_id: &str, + assignments: &str, + mut bindings: Vec, + ) -> Result<()> { + let table = self.checked_table()?; + let not_found = || AuthError::UserNotFound { + id: user_id.to_string(), + }; + let id = Uuid::parse_str(user_id).map_err(|_| not_found())?; + let next = bindings.len() + 1; + let sql = format!( + "UPDATE {table} SET {assignments}, updated_at = ${next} \ + WHERE id = ${} AND deleted_at IS NULL", + next + 1 + ); + bindings.push(Value::Timestamp(Utc::now())); + bindings.push(Value::Uuid(id)); + let affected = self + .pool + .execute_bind(&sql, &bindings) + .await + .map_err(store)?; + if affected == 0 { + return Err(not_found()); + } + Ok(()) + } +} + +impl UserProvider for DatabaseUserProvider { + fn find_by_email<'a>( + &'a self, + email: &'a str, + ) -> Pin>> + Send + 'a>> { + Box::pin(async move { + self.find_where("email", Value::Text(email.to_string())) + .await + }) + } + + fn find_by_id<'a>( + &'a self, + user_id: &'a str, + ) -> Pin>> + Send + 'a>> { + Box::pin(async move { + match Uuid::parse_str(user_id) { + Ok(id) => self.find_where("id", Value::Uuid(id)).await, + Err(_) => Ok(None), + } + }) + } + + fn create<'a>( + &'a self, + new_user: NewUserRecord, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + let table = self.checked_table()?; + let verified_at = timestamp_value(new_user.email_verified_at.as_deref())?; + let exists = || AuthError::UserExists { + email: new_user.email.clone(), + }; + if self.email_taken(&new_user.email, None).await? { + return Err(exists()); + } + let id = Uuid::new_v4(); + let now = Utc::now(); + let mut bindings = vec![ + Value::Uuid(id), + Value::Text(new_user.name.clone()), + Value::Text(new_user.email.clone()), + Value::Text(new_user.password_hash.clone()), + Value::Timestamp(now), + Value::Timestamp(now), + ]; + let verified_at = placeholder(&mut bindings, verified_at); + let timezone = placeholder(&mut bindings, new_user.timezone.clone().map(Value::Text)); + let sql = format!( + "INSERT INTO {table} \ + (id, name, email, password, created_at, updated_at, email_verified_at, timezone) \ + VALUES ($1, $2, $3, $4, $5, $6, {verified_at}, {timezone})" + ); + let inserted = self.pool.execute_bind(&sql, &bindings).await; + if let Err(error) = inserted { + // A concurrent registration can win the unique-email race + // between the check above and this insert; report it as the + // typed collision rather than a storage failure. + return Err(match self.email_taken(&new_user.email, None).await { + Ok(true) => exists(), + _ => store(error), + }); + } + // Read the row back so the returned record carries the values as + // the database normalized them (timestamp precision and offset). + self.find_where("id", Value::Uuid(id)) + .await? + .ok_or(AuthError::StoreUnavailable) + }) + } + + fn update_password<'a>( + &'a self, + user_id: &'a str, + password_hash: &'a str, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + self.update_user( + user_id, + "password = $1", + vec![Value::Text(password_hash.to_string())], + ) + .await + }) + } + + fn set_email_verified_at<'a>( + &'a self, + user_id: &'a str, + verified_at: Option<&'a str>, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + let mut bindings = Vec::new(); + let value = placeholder(&mut bindings, timestamp_value(verified_at)?); + self.update_user(user_id, &format!("email_verified_at = {value}"), bindings) + .await + }) + } + + fn update_profile<'a>( + &'a self, + user_id: &'a str, + name: &'a str, + email: &'a str, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + let Ok(id) = Uuid::parse_str(user_id) else { + return Err(AuthError::UserNotFound { + id: user_id.to_string(), + }); + }; + if self.email_taken(email, Some(id)).await? { + return Err(AuthError::UserExists { + email: email.to_string(), + }); + } + self.update_user( + user_id, + "name = $1, email = $2", + vec![ + Value::Text(name.to_string()), + Value::Text(email.to_string()), + ], + ) + .await + }) + } + + fn update_timezone<'a>( + &'a self, + user_id: &'a str, + timezone: Option, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + let mut bindings = Vec::new(); + let value = placeholder(&mut bindings, timezone.map(Value::Text)); + self.update_user(user_id, &format!("timezone = {value}"), bindings) + .await + }) + } +} + +impl DatabaseUserProvider { + /// Whether `email` is owned by a row other than `except`. + /// + /// Soft-deleted rows count: the unique index on `email` still covers them, + /// so their address cannot be reused. + async fn email_taken(&self, email: &str, except: Option) -> Result { + let table = self.checked_table()?; + let sql = format!("SELECT id FROM {table} WHERE email = $1"); + let rows = self + .pool + .fetch_json(&sql, &[Value::Text(email.to_string())]) + .await + .map_err(store)?; + let except = except.map(|id| id.to_string()); + Ok(rows.iter().any(|row| { + let owner = row.get("id").and_then(|v| v.as_str()); + owner.is_none() || owner != except.as_deref() + })) + } +} + +/// Map any database failure to the typed "store unreachable" error. +fn store(_error: rustasea_orm::OrmError) -> AuthError { + AuthError::StoreUnavailable +} + +/// Convert an optional RFC 3339 string into a bindable timestamp. +fn timestamp_value(value: Option<&str>) -> Result> { + value + .map(|text| { + DateTime::parse_from_rfc3339(text) + .map(|at| Value::Timestamp(at.with_timezone(&Utc))) + .map_err(|_| { + AuthError::Disabled(format!("email_verified_at {text:?} is not RFC 3339")) + }) + }) + .transpose() +} + +/// Push `value` onto `bindings` and return its `$n` placeholder, or the SQL +/// literal `NULL` when absent. +/// +/// A NULL is written as a literal rather than bound: the ORM binds +/// [`Value::Null`] as a typed integer NULL, which Postgres rejects for a +/// timestamp column. +fn placeholder(bindings: &mut Vec, value: Option) -> String { + match value { + Some(value) => { + bindings.push(value); + format!("${}", bindings.len()) + } + None => "NULL".to_string(), + } +} + +/// Build an [`AuthUserRecord`] from a JSON row, or `None` when a required +/// column is missing. +fn record_from_row(row: &serde_json::Value) -> Option { + let text = |column: &str| row.get(column).and_then(|v| v.as_str()).map(str::to_string); + Some(AuthUserRecord { + id: text("id")?, + email: text("email")?, + password_hash: text("password")?, + email_verified_at: text("email_verified_at"), + timezone: text("timezone"), + }) +} diff --git a/crates/rustasea-auth/tests/database_user_provider.rs b/crates/rustasea-auth/tests/database_user_provider.rs new file mode 100644 index 0000000..1f192c1 --- /dev/null +++ b/crates/rustasea-auth/tests/database_user_provider.rs @@ -0,0 +1,270 @@ +//! Integration tests for the database-backed [`DatabaseUserProvider`] (M3). +//! +//! Exercises the provider over a real in-memory SQLite pool and the `users` +//! table shape from the scaffold migration (`create_users_table`): +//! +//! * **positive** — register, resolve by email and id, rotate the password, +//! verify/unverify the email, update the profile and timezone; +//! * **negative** — duplicate email, unknown / malformed / soft-deleted user, +//! an unparsable timestamp, and a missing `users` table (typed +//! `AuthError::StoreUnavailable`, never a panic or a silent `Ok(None)`). + +use rustasea_auth::users::{DatabaseUserProvider, NewUserRecord, UserProvider}; +use rustasea_auth::AuthError; +use rustasea_orm::DbPool; + +/// The scaffold `create_users_table` DDL. +const CREATE_USERS: &str = "CREATE TABLE users ( + id UUID PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL UNIQUE, + password VARCHAR(255) NOT NULL, + email_verified_at TIMESTAMPTZ NULL, + two_factor_secret TEXT NULL, + two_factor_recovery_codes TEXT NULL, + two_factor_confirmed_at TIMESTAMPTZ NULL, + remember_token VARCHAR(100) NULL, + timezone VARCHAR(64) NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + deleted_at TIMESTAMPTZ NULL +);"; + +/// A provider over a fresh in-memory database with the `users` table. +async fn provider() -> DatabaseUserProvider { + let pool = DbPool::connect("sqlite::memory:").await.expect("pool"); + pool.execute_script(CREATE_USERS).await.expect("schema"); + DatabaseUserProvider::new(pool) +} + +/// Register a user and return the stored record. +async fn register( + provider: &DatabaseUserProvider, + email: &str, +) -> rustasea_auth::users::AuthUserRecord { + provider + .create(NewUserRecord::new("Ada Lovelace", email, "phc-hash")) + .await + .expect("create") +} + +#[tokio::test] +async fn create_then_resolve_by_email_and_id() { + let provider = provider().await; + let created = register(&provider, "ada@example.com").await; + assert_eq!(created.email, "ada@example.com"); + assert_eq!(created.password_hash, "phc-hash"); + assert_eq!(created.email_verified_at, None); + assert_eq!(created.timezone, None); + + let by_email = provider + .find_by_email("ada@example.com") + .await + .expect("find"); + assert_eq!(by_email.as_ref(), Some(&created)); + let by_id = provider.find_by_id(&created.id).await.expect("find"); + assert_eq!(by_id, Some(created)); + + assert_eq!( + provider + .find_by_email("nobody@example.com") + .await + .expect("find"), + None + ); +} + +#[tokio::test] +async fn create_persists_verification_and_timezone() { + let provider = provider().await; + let created = provider + .create( + NewUserRecord::new("Ada", "ada@example.com", "phc-hash") + .with_email_verified_at(Some("2026-01-02T03:04:05Z")) + .with_timezone(Some("Asia/Jakarta")), + ) + .await + .expect("create"); + let verified = created.email_verified_at.expect("verified"); + assert!(verified.starts_with("2026-01-02T03:04:05"), "{verified}"); + assert_eq!(created.timezone.as_deref(), Some("Asia/Jakarta")); +} + +#[tokio::test] +async fn duplicate_email_is_a_typed_collision() { + let provider = provider().await; + register(&provider, "ada@example.com").await; + let error = provider + .create(NewUserRecord::new("Other", "ada@example.com", "phc-hash")) + .await + .expect_err("duplicate"); + assert!(matches!(error, AuthError::UserExists { email } if email == "ada@example.com")); +} + +#[tokio::test] +async fn writes_update_the_stored_record() { + let provider = provider().await; + let user = register(&provider, "ada@example.com").await; + + provider + .update_password(&user.id, "new-hash") + .await + .expect("password"); + provider + .set_email_verified_at(&user.id, Some("2026-05-06T07:08:09Z")) + .await + .expect("verify"); + provider + .update_timezone(&user.id, Some("Europe/London".to_string())) + .await + .expect("timezone"); + provider + .update_profile(&user.id, "Ada King", "countess@example.com") + .await + .expect("profile"); + + let stored = provider + .find_by_id(&user.id) + .await + .expect("find") + .expect("user"); + assert_eq!(stored.password_hash, "new-hash"); + assert_eq!(stored.email, "countess@example.com"); + assert_eq!(stored.timezone.as_deref(), Some("Europe/London")); + assert!(stored.email_verified_at.is_some()); + + // Clearing writes a NULL back. + provider + .set_email_verified_at(&user.id, None) + .await + .expect("unverify"); + provider + .update_timezone(&user.id, None) + .await + .expect("clear timezone"); + let stored = provider + .find_by_id(&user.id) + .await + .expect("find") + .expect("user"); + assert_eq!(stored.email_verified_at, None); + assert_eq!(stored.timezone, None); +} + +#[tokio::test] +async fn update_profile_rejects_an_email_owned_by_another_user() { + let provider = provider().await; + let ada = register(&provider, "ada@example.com").await; + register(&provider, "grace@example.com").await; + + let error = provider + .update_profile(&ada.id, "Ada", "grace@example.com") + .await + .expect_err("taken"); + assert!(matches!(error, AuthError::UserExists { .. })); + + // Re-asserting the caller's own email is not a collision. + provider + .update_profile(&ada.id, "Ada K.", "ada@example.com") + .await + .expect("own email"); +} + +#[tokio::test] +async fn unknown_and_malformed_ids_are_not_found() { + let provider = provider().await; + for id in ["0190a1b2-0000-7000-8000-000000000000", "not-a-uuid"] { + assert_eq!(provider.find_by_id(id).await.expect("find"), None); + let error = provider + .update_password(id, "hash") + .await + .expect_err("missing"); + assert!( + matches!(error, AuthError::UserNotFound { .. }), + "{id}: {error}" + ); + let error = provider + .update_profile(id, "n", "e@example.com") + .await + .expect_err("missing"); + assert!( + matches!(error, AuthError::UserNotFound { .. }), + "{id}: {error}" + ); + } +} + +#[tokio::test] +async fn soft_deleted_users_do_not_resolve() { + let provider = provider().await; + let user = register(&provider, "ada@example.com").await; + provider + .pool() + .execute_script("UPDATE users SET deleted_at = '2026-01-01T00:00:00Z';") + .await + .expect("soft delete"); + + assert_eq!( + provider + .find_by_email("ada@example.com") + .await + .expect("find"), + None + ); + assert_eq!(provider.find_by_id(&user.id).await.expect("find"), None); + let error = provider + .update_password(&user.id, "hash") + .await + .expect_err("deleted"); + assert!(matches!(error, AuthError::UserNotFound { .. })); + // The address stays reserved by the unique index. + let error = provider + .create(NewUserRecord::new("Again", "ada@example.com", "phc-hash")) + .await + .expect_err("reserved"); + assert!(matches!(error, AuthError::UserExists { .. })); +} + +#[tokio::test] +async fn unparsable_verification_timestamp_is_rejected_before_writing() { + let provider = provider().await; + let user = register(&provider, "ada@example.com").await; + let error = provider + .set_email_verified_at(&user.id, Some("yesterday")) + .await + .expect_err("bad timestamp"); + assert!(matches!(error, AuthError::Disabled(_))); + let stored = provider + .find_by_id(&user.id) + .await + .expect("find") + .expect("user"); + assert_eq!(stored.email_verified_at, None); +} + +#[tokio::test] +async fn missing_table_is_store_unavailable() { + let pool = DbPool::connect("sqlite::memory:").await.expect("pool"); + let provider = DatabaseUserProvider::new(pool); + let error = provider + .find_by_email("ada@example.com") + .await + .expect_err("no table"); + assert!(matches!(error, AuthError::StoreUnavailable)); + let error = provider + .create(NewUserRecord::new("Ada", "ada@example.com", "phc-hash")) + .await + .expect_err("no table"); + assert!(matches!(error, AuthError::StoreUnavailable)); +} + +#[tokio::test] +async fn invalid_table_name_fails_closed() { + let pool = DbPool::connect("sqlite::memory:").await.expect("pool"); + let provider = DatabaseUserProvider::new(pool).with_table("users; DROP TABLE users"); + let error = provider + .find_by_email("ada@example.com") + .await + .expect_err("bad table"); + assert!(matches!(error, AuthError::StoreUnavailable)); +} From 1251e6a503d7cc07e1165d6c701400bf5a3225cd Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:33 +0700 Subject: [PATCH 05/14] feat(rustasea): re-export rustasea-mail as rustasea::mail Adds the mail-smtp and mail-templates features forwarding to the mail crate's smtp and templates features. --- Cargo.lock | 1 + crates/rustasea/Cargo.toml | 10 ++++++++++ crates/rustasea/src/lib.rs | 5 +++++ 3 files changed, 16 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index addd704..afbbaa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6839,6 +6839,7 @@ dependencies = [ "rustasea-livewire", "rustasea-logging", "rustasea-macros", + "rustasea-mail", "rustasea-modules", "rustasea-mongo", "rustasea-openapi", diff --git a/crates/rustasea/Cargo.toml b/crates/rustasea/Cargo.toml index 2d36dd5..572079a 100644 --- a/crates/rustasea/Cargo.toml +++ b/crates/rustasea/Cargo.toml @@ -48,6 +48,10 @@ rustasea-storage = { path = "../rustasea-storage" } rustasea-search = { path = "../rustasea-search" } rustasea-jsonapi = { path = "../rustasea-jsonapi" } rustasea-ai = { path = "../rustasea-ai", optional = true } +# Mail (M6): Mailable/Mailer contracts and queued notifications. Always linked +# because `rustasea-authlog` already depends on it; the SMTP transport and the +# template hook stay opt-in behind `mail-smtp` / `mail-templates`. +rustasea-mail = { path = "../rustasea-mail" } # MongoDB document store (ADR-0010); opt-in so the core build never links the # `mongodb`/`bson` driver tree (pay-for-what-you-use, NFR-Sca-02). rustasea-mongo = { path = "../rustasea-mongo", optional = true } @@ -134,6 +138,12 @@ scaffold = ["dep:rustasea-scaffold", "dep:clap"] # M6 AI SDK is additive; `ai-search`/`ai-storage`/`ai-mcp` forward the # deferred-loader features of rustasea-ai itself. ai = ["dep:rustasea-ai"] +# Mail SMTP transport (`lettre`, TLS via rustls). Forwards to `rustasea-mail`'s +# `smtp` feature; off by default (pay-for-what-you-use, NFR-Sca-02). +mail-smtp = ["rustasea-mail/smtp"] +# Mail template rendering hook (AUTH-018). Forwards to `rustasea-mail`'s +# `templates` feature, which renders mailables through the runtime view engine. +mail-templates = ["view-runtime-templates", "rustasea-mail/templates"] ai-search = ["dep:rustasea-ai", "rustasea-ai/search"] ai-storage = ["dep:rustasea-ai", "rustasea-ai/storage"] # `ai-mcp` also enables the CLI's `mcp:serve` command (ADOPT-015) so an diff --git a/crates/rustasea/src/lib.rs b/crates/rustasea/src/lib.rs index af5ea40..98fd2da 100644 --- a/crates/rustasea/src/lib.rs +++ b/crates/rustasea/src/lib.rs @@ -150,6 +150,11 @@ pub use rustasea_jsonapi as jsonapi; pub use rustasea_search as search; pub use rustasea_storage as storage; +/// M6 mail re-export: `Mailable`/`Mailer` contracts, the `Mail` facade, and +/// queued notifications. The SMTP transport and the template hook need the +/// `mail-smtp` / `mail-templates` features. +pub use rustasea_mail as mail; + /// M6 AI SDK re-export — only with the `ai` feature (NFR-Sca-02). #[cfg(feature = "ai")] pub use rustasea_ai as ai; From 48b3f01333f1758cca39a1a5f2d8850d5b2cffc5 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:10:19 +0700 Subject: [PATCH 06/14] feat(ai): serve gemini and bedrock through their OpenAI-compatible endpoints provider_from_env rejected both names. Gemini now resolves to the Gemini API's OpenAI-compatible base URL with GEMINI_API_KEY; Bedrock resolves to the regional bedrock-runtime /openai/v1 endpoint with a Bedrock API key (AWS_BEARER_TOKEN_BEDROCK) and AWS_REGION, so no SigV4 signing is needed. --- crates/rustasea-ai/src/providers/client.rs | 57 ++++++++++++++++++++ crates/rustasea-ai/src/providers/mod.rs | 3 +- crates/rustasea-ai/tests/http_providers.rs | 60 ++++++++++++++++++++++ 3 files changed, 119 insertions(+), 1 deletion(-) diff --git a/crates/rustasea-ai/src/providers/client.rs b/crates/rustasea-ai/src/providers/client.rs index 73cc8a7..f99de60 100644 --- a/crates/rustasea-ai/src/providers/client.rs +++ b/crates/rustasea-ai/src/providers/client.rs @@ -219,7 +219,23 @@ impl HttpProviderConfig { }, &lookup, ), + // Gemini's OpenAI-compatible surface (chat completions, embeddings). + "gemini" => resolve_env( + "gemini", + EnvSpec { + key_env: Some("GEMINI_API_KEY"), + key_required: true, + base_env: Some("GEMINI_BASE_URL"), + default_base: "https://generativelanguage.googleapis.com/v1beta/openai", + model_env: "GEMINI_MODEL", + default_model: "gemini-4-hydrogen", + auth: AuthStyle::Bearer, + style: ProviderStyle::OpenAi, + }, + &lookup, + ), "azure" => azure_from_env(&lookup), + "bedrock" => bedrock_from_env(&lookup), other => Err(AiError::UnknownProvider(other.to_string())), } } @@ -322,6 +338,47 @@ where }) } +/// Resolve Amazon Bedrock's OpenAI-compatible endpoint (region-scoped). +/// +/// Authenticates with a Bedrock API key sent as a bearer token +/// (`AWS_BEARER_TOKEN_BEDROCK`), so no SigV4 request signing is involved. The +/// endpoint host is built from `AWS_REGION` (or `AWS_DEFAULT_REGION`) unless +/// `BEDROCK_BASE_URL` overrides it. +fn bedrock_from_env(lookup: &F) -> Result +where + F: Fn(&str) -> Option, +{ + let missing = |env: &str| { + AiError::configuration(format!("{env} is not set (required for provider bedrock)")) + }; + let api_key = + lookup("AWS_BEARER_TOKEN_BEDROCK").ok_or_else(|| missing("AWS_BEARER_TOKEN_BEDROCK"))?; + let base_url = match lookup("BEDROCK_BASE_URL") { + Some(base) => base, + None => { + let region = lookup("AWS_REGION") + .or_else(|| lookup("AWS_DEFAULT_REGION")) + .ok_or_else(|| missing("AWS_REGION"))?; + format!( + "https://bedrock-runtime.{}.amazonaws.com/openai/v1", + region.trim() + ) + } + }; + Ok(HttpProviderConfig { + provider: "bedrock", + base_url: base_url.trim_end_matches('/').to_string(), + api_key: Some(api_key), + default_model: lookup("BEDROCK_MODEL") + .unwrap_or_else(|| "openai.gpt-oss-120b-1:0".to_string()), + style: ProviderStyle::OpenAi, + auth: AuthStyle::Bearer, + api_version: None, + timeout: DEFAULT_TIMEOUT, + max_tokens: 1024, + }) +} + /// Build the shared reqwest client with the configured timeout. pub(crate) fn build_client(timeout: Duration) -> Result { reqwest::Client::builder() diff --git a/crates/rustasea-ai/src/providers/mod.rs b/crates/rustasea-ai/src/providers/mod.rs index 86150c4..fbfdd70 100644 --- a/crates/rustasea-ai/src/providers/mod.rs +++ b/crates/rustasea-ai/src/providers/mod.rs @@ -22,7 +22,8 @@ use crate::provider::AiProvider; /// Returns [`crate::error::AiError::ConfigurationError`] when a required /// credential is missing (never a silent stub) and /// [`crate::error::AiError::UnknownProvider`] for names without an HTTP -/// adapter (`gemini`, `bedrock`). Callers wanting deterministic offline +/// adapter. `gemini` and `bedrock` are served through their OpenAI-compatible +/// endpoints. Callers wanting deterministic offline /// behaviour should construct [`crate::adapters::InProcessProvider`] instead. pub fn provider_from_env(name: &str) -> Result> { let config = HttpProviderConfig::from_env(name)?; diff --git a/crates/rustasea-ai/tests/http_providers.rs b/crates/rustasea-ai/tests/http_providers.rs index 55b56ba..6d4fa6d 100644 --- a/crates/rustasea-ai/tests/http_providers.rs +++ b/crates/rustasea-ai/tests/http_providers.rs @@ -286,6 +286,66 @@ fn config_resolution_covers_compatible_providers() { assert!(ollama.api_key.is_none()); } +/// Gemini and Bedrock resolve to their OpenAI-compatible endpoints. +#[test] +fn gemini_and_bedrock_resolve_openai_compatible_endpoints() { + let gemini = HttpProviderConfig::from_env_with("gemini", |key| match key { + "GEMINI_API_KEY" => Some("secret".to_string()), + _ => None, + }) + .unwrap(); + assert_eq!(gemini.style, ProviderStyle::OpenAi); + assert_eq!(gemini.auth, AuthStyle::Bearer); + assert_eq!( + gemini.base_url, + "https://generativelanguage.googleapis.com/v1beta/openai" + ); + + let bedrock = HttpProviderConfig::from_env_with("bedrock", |key| match key { + "AWS_BEARER_TOKEN_BEDROCK" => Some("secret".to_string()), + "AWS_DEFAULT_REGION" => Some("ap-southeast-3".to_string()), + _ => None, + }) + .unwrap(); + assert_eq!(bedrock.style, ProviderStyle::OpenAi); + assert_eq!(bedrock.auth, AuthStyle::Bearer); + assert_eq!( + bedrock.base_url, + "https://bedrock-runtime.ap-southeast-3.amazonaws.com/openai/v1" + ); + + // An explicit base URL needs no region. + let custom = HttpProviderConfig::from_env_with("bedrock", |key| match key { + "AWS_BEARER_TOKEN_BEDROCK" => Some("secret".to_string()), + "BEDROCK_BASE_URL" => Some("https://proxy.internal/openai/v1/".to_string()), + "BEDROCK_MODEL" => Some("custom-model".to_string()), + _ => None, + }) + .unwrap(); + assert_eq!(custom.base_url, "https://proxy.internal/openai/v1"); + assert_eq!(custom.default_model, "custom-model"); +} + +/// NEGATIVE — Gemini and Bedrock name the missing credential or region. +#[test] +fn gemini_and_bedrock_report_missing_configuration() { + let missing = |provider: &str, env: &[(&str, &str)]| { + let error = HttpProviderConfig::from_env_with(provider, |key| { + env.iter() + .find(|(name, _)| *name == key) + .map(|(_, value)| value.to_string()) + }) + .unwrap_err(); + match error { + AiError::ConfigurationError(message) => message, + other => panic!("unexpected error: {other}"), + } + }; + assert!(missing("gemini", &[]).contains("GEMINI_API_KEY")); + assert!(missing("bedrock", &[("AWS_REGION", "us-east-1")]).contains("AWS_BEARER_TOKEN_BEDROCK")); + assert!(missing("bedrock", &[("AWS_BEARER_TOKEN_BEDROCK", "secret")]).contains("AWS_REGION")); +} + /// Factory surfaces the typed error for real providers without credentials. #[test] fn factory_requires_credentials_for_remote_providers() { From 194f431476efb3c68e1dd823de96b586ace7a85b Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:12:34 +0700 Subject: [PATCH 07/14] fix(ai): send an embedding model, not the chat model, on embeddings requests OpenAiProvider::embeddings posted the provider's default chat model, which an embeddings endpoint rejects, so provider-backed Str::to_embeddings could not work with the default configuration. The config now carries an embedding model: _EMBEDDING_MODEL, else the provider's known embedding model (openai, gemini, mistral), else the default model as before. --- crates/rustasea-ai/src/providers/client.rs | 30 +++++++++++++++++++ crates/rustasea-ai/src/providers/openai.rs | 2 +- crates/rustasea-ai/tests/http_providers.rs | 34 ++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/rustasea-ai/src/providers/client.rs b/crates/rustasea-ai/src/providers/client.rs index f99de60..b1c7e28 100644 --- a/crates/rustasea-ai/src/providers/client.rs +++ b/crates/rustasea-ai/src/providers/client.rs @@ -45,6 +45,8 @@ pub struct HttpProviderConfig { pub api_key: Option, /// Model used when a request does not override it. pub default_model: String, + /// Model used for `embeddings`; `None` reuses `default_model`. + pub embedding_model: Option, /// Wire style spoken by the provider. pub style: ProviderStyle, /// Credential placement. @@ -240,6 +242,19 @@ impl HttpProviderConfig { } } + /// The model sent with an `embeddings` request. + pub fn embedding_model(&self) -> &str { + self.embedding_model + .as_deref() + .unwrap_or(&self.default_model) + } + + /// Override the embeddings model. + pub fn with_embedding_model(mut self, model: impl Into) -> Self { + self.embedding_model = Some(model.into()); + self + } + /// Override the base URL (endpoint root without trailing slash). pub fn with_base_url(mut self, base_url: impl Into) -> Self { self.base_url = base_url.into().trim_end_matches('/').to_string(); @@ -293,11 +308,24 @@ where .and_then(lookup) .unwrap_or_else(|| spec.default_base.to_string()); let default_model = lookup(spec.model_env).unwrap_or_else(|| spec.default_model.to_string()); + // `_EMBEDDING_MODEL`, else the provider's embedding model: a chat + // model is not accepted by an embeddings endpoint. + let embedding_model = + lookup(&spec.model_env.replace("_MODEL", "_EMBEDDING_MODEL")).or_else(|| { + match provider { + "openai" => Some("text-embedding-3-small"), + "gemini" => Some("gemini-embedding-001"), + "mistral" => Some("mistral-embed"), + _ => None, + } + .map(str::to_string) + }); Ok(HttpProviderConfig { provider, base_url: base_url.trim_end_matches('/').to_string(), api_key, default_model, + embedding_model, style: spec.style, auth: spec.auth, api_version: None, @@ -328,6 +356,7 @@ where ), api_key: Some(api_key), default_model: deployment, + embedding_model: None, style: ProviderStyle::OpenAi, auth: AuthStyle::Header("api-key"), api_version: Some( @@ -371,6 +400,7 @@ where api_key: Some(api_key), default_model: lookup("BEDROCK_MODEL") .unwrap_or_else(|| "openai.gpt-oss-120b-1:0".to_string()), + embedding_model: lookup("BEDROCK_EMBEDDING_MODEL"), style: ProviderStyle::OpenAi, auth: AuthStyle::Bearer, api_version: None, diff --git a/crates/rustasea-ai/src/providers/openai.rs b/crates/rustasea-ai/src/providers/openai.rs index 557d5ab..5146170 100644 --- a/crates/rustasea-ai/src/providers/openai.rs +++ b/crates/rustasea-ai/src/providers/openai.rs @@ -152,7 +152,7 @@ impl AiProvider for OpenAiProvider { async fn embeddings(&self, inputs: &[String]) -> Result { let body = json!({ - "model": self.config.default_model, + "model": self.config.embedding_model(), "input": inputs, }); let request = with_api_version( diff --git a/crates/rustasea-ai/tests/http_providers.rs b/crates/rustasea-ai/tests/http_providers.rs index 6d4fa6d..3e87ab2 100644 --- a/crates/rustasea-ai/tests/http_providers.rs +++ b/crates/rustasea-ai/tests/http_providers.rs @@ -346,6 +346,40 @@ fn gemini_and_bedrock_report_missing_configuration() { assert!(missing("bedrock", &[("AWS_BEARER_TOKEN_BEDROCK", "secret")]).contains("AWS_REGION")); } +/// Embeddings use the provider's embedding model, not its chat model. +#[test] +fn embeddings_use_a_dedicated_embedding_model() { + let key = |_: &str| Some("secret".to_string()); + let openai = HttpProviderConfig::from_env_with("openai", |name| match name { + "OPENAI_API_KEY" => key(name), + _ => None, + }) + .unwrap(); + assert_eq!(openai.embedding_model(), "text-embedding-3-small"); + assert_ne!(openai.embedding_model(), openai.default_model); + + // The env override wins over the built-in default. + let overridden = HttpProviderConfig::from_env_with("openai", |name| match name { + "OPENAI_API_KEY" => key(name), + "OPENAI_EMBEDDING_MODEL" => Some("text-embedding-3-large".to_string()), + _ => None, + }) + .unwrap(); + assert_eq!(overridden.embedding_model(), "text-embedding-3-large"); + + // A provider with no known embedding model keeps using its default model. + let groq = HttpProviderConfig::from_env_with("groq", |name| match name { + "GROQ_API_KEY" => key(name), + _ => None, + }) + .unwrap(); + assert_eq!(groq.embedding_model(), groq.default_model); + assert_eq!( + groq.with_embedding_model("custom-embed").embedding_model(), + "custom-embed" + ); +} + /// Factory surfaces the typed error for real providers without credentials. #[test] fn factory_requires_credentials_for_remote_providers() { From d230116b2def45cfc1aea83cfa19acb8a1a51f17 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:29:21 +0700 Subject: [PATCH 08/14] feat(app): read users from the database when the users table exists After boot the app replaces the fail-closed user provider with DatabaseUserProvider when the default guard's provider is ORM-backed (eloquent) and the users table is reachable, so registration and login persist. A dev seed user still wins, and with no database or no users table auth stays fail-closed. --- crates/rustasea-app/src/bootstrap/app.rs | 3 +- crates/rustasea-app/src/bootstrap/auth.rs | 169 +++++++++++++++++++++- crates/rustasea-app/src/main.rs | 4 + crates/rustasea-app/src/routes/helpers.rs | 7 +- crates/rustasea-app/src/routes/mod.rs | 2 + 5 files changed, 179 insertions(+), 6 deletions(-) diff --git a/crates/rustasea-app/src/bootstrap/app.rs b/crates/rustasea-app/src/bootstrap/app.rs index 2f0dca7..50f7d73 100644 --- a/crates/rustasea-app/src/bootstrap/app.rs +++ b/crates/rustasea-app/src/bootstrap/app.rs @@ -248,8 +248,7 @@ fn install_broadcasting(_app: &Application) {} /// `DATABASE__URL` overlay, then the default connection from /// `config/database.toml` (`DatabaseConfig::resolve_url(None)`), then the legacy /// top-level `database_url` key. -#[cfg(feature = "queue-dashboard")] -fn resolve_database_url(loader: &rustasea::ConfigLoader) -> Result { +pub(crate) fn resolve_database_url(loader: &rustasea::ConfigLoader) -> Result { for key in ["DATABASE_URL", "DATABASE__URL"] { if let Ok(url) = std::env::var(key) { if !url.trim().is_empty() { diff --git a/crates/rustasea-app/src/bootstrap/auth.rs b/crates/rustasea-app/src/bootstrap/auth.rs index 5389436..292709b 100644 --- a/crates/rustasea-app/src/bootstrap/auth.rs +++ b/crates/rustasea-app/src/bootstrap/auth.rs @@ -25,9 +25,16 @@ //! [`DenyAllProvider`], which resolves no credentials and refuses every write. //! The guard and provider are installed together by [`install_session_guard`]. //! +//! After boot, `main` calls [`install_database_user_provider`]: when the default +//! guard's provider is ORM-backed and the `users` table is reachable, the +//! fail-closed provider is replaced by the database-backed +//! [`DatabaseUserProvider`], so registration and login persist. With no table +//! (or no database) nothing changes. +//! //! [`SessionGuard`]: rustasea::auth::SessionGuard //! [`UserProvider`]: rustasea::auth::UserProvider //! [`DenyAllProvider`]: rustasea::auth::DenyAllProvider +//! [`DatabaseUserProvider`]: rustasea::auth::DatabaseUserProvider //! [`Container`]: rustasea::foundation::Container //! [`StaticLookup`]: rustasea::auth::users::StaticLookup @@ -35,7 +42,10 @@ use std::sync::Arc; use rustasea::auth::users::AuthUserRecord; use rustasea::auth::verify::{Argon2Verifier, PasswordVerifier}; -use rustasea::auth::{DenyAllProvider, MemoryUserProvider, SessionGuard, UserProvider}; +use rustasea::auth::{ + AuthConfig, DatabaseUserProvider, DenyAllProvider, MemoryUserProvider, SessionGuard, + UserProvider, +}; use rustasea::config::ConfigLoader; use rustasea::foundation::{Container, CONFIG_LOADER_KEY}; @@ -250,6 +260,90 @@ pub fn build_user_provider() -> Arc { Arc::new(provider) } +/// Whether the default guard reads its users through the ORM. +/// +/// True when the default guard's provider (`[auth.providers.]`) uses the +/// `eloquent` driver — the name `config/auth.toml` keeps for ORM-backed +/// providers — or its plain alias `database`. A missing or malformed `[auth]` +/// table is `false`: nothing is inferred from a broken config. +pub fn uses_database_provider(loader: &ConfigLoader) -> bool { + AuthConfig::from_loader(loader) + .ok() + .and_then(|config| { + config + .provider_for(config.default_guard()) + .ok() + .map(|provider| provider.driver.to_ascii_lowercase()) + }) + .is_some_and(|driver| driver == "eloquent" || driver == "database") +} + +/// Build the database-backed [`UserProvider`] over the `users` table at `url`. +/// +/// Returns `None` — so the caller keeps the fail-closed provider — when the +/// database is unreachable or has no `users` table (the migrations have not +/// run). The probe looks up an empty email: it matches no user, and succeeds +/// only when the table can be queried. +pub async fn database_user_provider(url: &str) -> Option> { + let pool = match rustasea::orm::DbPool::connect(url).await { + Ok(pool) => pool, + Err(error) => { + eprintln!("auth: database unreachable, user provider stays fail-closed: {error}"); + return None; + } + }; + let provider = DatabaseUserProvider::new(pool); + match provider.find_by_email("").await { + Ok(_) => Some(Arc::new(provider)), + Err(_) => { + eprintln!( + "auth: no usable `users` table (run the migrations); \ + user provider stays fail-closed" + ); + None + } + } +} + +/// Install the database-backed user provider when the app is configured for it. +/// +/// Called once from `main` after boot. The provider replaces the fail-closed +/// default only when all of these hold: no dev seed user is set (an explicit +/// `RUSTASEA_DEV_SEED_USER` wins), the default guard's provider is ORM-backed +/// ([`uses_database_provider`]), a database URL resolves, and the `users` table +/// is reachable ([`database_user_provider`]). Otherwise nothing changes and auth +/// stays fail-closed. +/// +/// # Returns +/// +/// `true` when the database provider was installed. +pub async fn install_database_user_provider(app: &rustasea::Application) -> bool { + if std::env::var(DEV_SEED_USER_ENV).is_ok() { + return false; + } + let Some(loader) = app.config() else { + return false; + }; + if !uses_database_provider(loader) { + return false; + } + let url = match super::app::resolve_database_url(loader) { + Ok(url) => url, + Err(error) => { + eprintln!("auth: {error}; user provider stays fail-closed"); + return false; + } + }; + match database_user_provider(&url).await { + Some(provider) => { + crate::routes::install_user_provider(provider); + println!("auth: users resolved from the database `users` table"); + true + } + None => false, + } +} + /// Build the provider and install it into `container` under [`USER_PROVIDER_KEY`]. /// /// Mirrors [`install_session_guard`]: it stores the built value as a container @@ -287,3 +381,76 @@ pub fn user_provider(container: &Container) -> Option> { .get::>(USER_PROVIDER_KEY) .cloned() } + +#[cfg(test)] +mod tests { + use super::*; + use rustasea::auth::NewUserRecord; + + /// A unique scratch path under the system temp directory. + fn scratch(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("rustasea-app-{name}-{}", uuid::Uuid::new_v4())) + } + + /// Load an `[auth]` table whose default guard uses `driver`. + fn loader_with_provider_driver(driver: &str) -> ConfigLoader { + let base = scratch("auth"); + let toml = format!( + "[auth.defaults]\nguard = \"web\"\n\ + [auth.guards.web]\ndriver = \"session\"\nprovider = \"users\"\n\ + [auth.providers.users]\ndriver = \"{driver}\"\n" + ); + let file = base.with_extension("toml"); + std::fs::write(&file, toml).expect("write auth.toml"); + let loader = ConfigLoader::load_from(&[&base.to_string_lossy()]).expect("load"); + let _ = std::fs::remove_file(file); + loader + } + + #[test] + fn only_orm_backed_drivers_select_the_database_provider() { + assert!(uses_database_provider(&loader_with_provider_driver( + "eloquent" + ))); + assert!(uses_database_provider(&loader_with_provider_driver( + "Database" + ))); + assert!(!uses_database_provider(&loader_with_provider_driver( + "memory" + ))); + } + + #[tokio::test] + async fn database_provider_is_built_only_when_the_users_table_exists() { + let path = scratch("users").with_extension("sqlite"); + let url = format!("sqlite://{}?mode=rwc", path.display()); + + // No `users` table yet: stay fail-closed. + assert!(database_user_provider(&url).await.is_none()); + + let pool = rustasea::orm::DbPool::connect(&url).await.expect("pool"); + pool.execute_script( + "CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, \ + email VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, \ + email_verified_at TIMESTAMPTZ NULL, timezone VARCHAR(64) NULL, \ + created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, \ + deleted_at TIMESTAMPTZ NULL);", + ) + .await + .expect("schema"); + + let provider = database_user_provider(&url).await.expect("provider"); + let created = provider + .create(NewUserRecord::new("Ada", "ada@example.com", "phc-hash")) + .await + .expect("create"); + let found = provider + .find_by_email("ada@example.com") + .await + .expect("find"); + assert_eq!(found.map(|user| user.id), Some(created.id)); + + pool.close().await; + let _ = std::fs::remove_file(path); + } +} diff --git a/crates/rustasea-app/src/main.rs b/crates/rustasea-app/src/main.rs index cecee77..9178df8 100644 --- a/crates/rustasea-app/src/main.rs +++ b/crates/rustasea-app/src/main.rs @@ -27,6 +27,10 @@ async fn main() -> anyhow::Result<()> { // `bootstrap/app.rs` — the README-mandated `Application::configure` home. let app = bootstrap::app::configure()?; + // Read users from the database when auth is configured for it and the + // `users` table exists; otherwise the fail-closed provider stays in place. + bootstrap::auth::install_database_user_provider(&app).await; + // Build the real route table from the concern-scoped tables // (`routes::{web,auth,settings,console}`) and print what is actually // served — the print reflects the compiled table, not a placeholder. diff --git a/crates/rustasea-app/src/routes/helpers.rs b/crates/rustasea-app/src/routes/helpers.rs index 4416afe..f780c98 100644 --- a/crates/rustasea-app/src/routes/helpers.rs +++ b/crates/rustasea-app/src/routes/helpers.rs @@ -59,11 +59,12 @@ pub(crate) fn user_provider() -> Arc { } } -/// Test-only override of the process-wide [`UserProvider`] seam. +/// Replace the process-wide [`UserProvider`] seam. /// -/// The handlers resolve the provider through [`user_provider`], so a test that +/// The handlers resolve the provider through [`user_provider`]. Boot installs +/// the database-backed provider here (see +/// [`crate::bootstrap::auth::install_database_user_provider`]), and a test that /// needs a real credential match seeds it here first. -#[cfg(test)] pub(crate) fn install_user_provider(provider: Arc) { if let Ok(mut slot) = provider_cell().write() { *slot = provider; diff --git a/crates/rustasea-app/src/routes/mod.rs b/crates/rustasea-app/src/routes/mod.rs index cb3a118..4c390f9 100644 --- a/crates/rustasea-app/src/routes/mod.rs +++ b/crates/rustasea-app/src/routes/mod.rs @@ -25,6 +25,8 @@ pub mod errors; /// surface. pub mod examples; mod helpers; + +pub(crate) use helpers::install_user_provider; /// Dev-only log viewer surface (`/_logs`, `/_logs/json`) — ADOPT-014, compiled /// only with the `log-viewer` feature. #[cfg(feature = "log-viewer")] From 4c579228bfd721c893ea5209a1d4658b1cdd5690 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:31:41 +0700 Subject: [PATCH 09/14] docs: bring milestone status and changelog in line with the code Records the database user provider, persisted sync failed jobs, the Gemini and Bedrock providers, the embedding model fix, and the mail re-export, and corrects claims that had gone stale: boot already mounts the config loader, the app's AppServiceProvider is not a no-op, a database session store exists, and provider-backed embeddings were already implemented. M4 moves to Done. --- CHANGELOG.md | 35 ++++++++++++++++ crates/rustasea-app/Cargo.toml | 3 +- docs/milestones.md | 75 ++++++++++++++++++---------------- 3 files changed, 76 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b77a1b2..5678c4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,28 @@ Per the same section, each tag is expected to pass `cargo xtask ci` and ### Added +- 2026-11-18 - Database-backed user provider: `DatabaseUserProvider` implements + the async `UserProvider` seam over the scaffold `users` table (registration, + login, password reset, email verification, profile and timezone updates; + soft-deleted users do not resolve), and the runnable app installs it at boot + when the default guard's provider is ORM-backed and the table exists, + otherwise staying fail-closed (M3; `feat(auth): add DatabaseUserProvider over + the users table`; `feat(app): read users from the database when the users + table exists`). +- 2026-11-18 - Gemini and Bedrock providers through their OpenAI-compatible + endpoints: `provider_from_env("gemini")` uses `GEMINI_API_KEY`, and + `provider_from_env("bedrock")` uses a Bedrock API key + (`AWS_BEARER_TOKEN_BEDROCK`) with `AWS_REGION`; the provider-native APIs are + not implemented (M6; `feat(ai): serve gemini and bedrock through their + OpenAI-compatible endpoints`). +- 2026-11-18 - Failed inline `sync` dispatches are persisted to `failed_jobs` + through the registered `database` connection as a retryable job envelope, so + they survive the process and appear in `queue:failed`; without a database + connection they still fall back to the in-memory list (M4; `feat(queue): + persist failed sync jobs through the database connection`). +- 2026-11-18 - `rustasea::mail` re-export of `rustasea-mail` from the umbrella + crate, with `mail-smtp` and `mail-templates` features (M6; `feat(rustasea): + re-export rustasea-mail as rustasea::mail`). - 2026-09-24 - `storage-s3` umbrella feature forwarding to `rustasea-storage/aws` (the `aws` feature needs rustc 1.89+ through `object_store`'s `crc-fast` dependency), and a Docker-backed RustFS suite @@ -129,6 +151,19 @@ Per the same section, each tag is expected to pass `cargo xtask ci` and ### Changed +- 2026-11-18 - Embeddings requests send an embedding model instead of the + provider's chat model: `_EMBEDDING_MODEL`, else the provider's known + embedding model (openai, gemini, mistral), else the default model as before + (M6; `fix(ai): send an embedding model, not the chat model, on embeddings + requests`). +- 2026-11-18 - Sync dead letters keep the job payload: the body is captured + before the job runs, where it was previously read after execution had consumed + it and stored as `null` (M4; `feat(queue): persist failed sync jobs through + the database connection`). +- 2026-11-18 - A UUID stored in a column declared `UUID` now reads back on + SQLite, where rows fetched through `fetch_json` previously returned `null` for + the id (M2; `fix(orm): decode a UUID stored in a column declared UUID on + SQLite`). - 2026-09-24 - `s3` disks now work with S3-compatible services such as RustFS and MinIO: an explicit `http://` endpoint enables `object_store`'s `allow_http` (previously every request failed with a reqwest builder error, diff --git a/crates/rustasea-app/Cargo.toml b/crates/rustasea-app/Cargo.toml index 64a9447..5b4c381 100644 --- a/crates/rustasea-app/Cargo.toml +++ b/crates/rustasea-app/Cargo.toml @@ -62,7 +62,8 @@ tower-http = { workspace = true, features = ["fs"] } tower-sessions = { workspace = true } # `rustasea-mail` supplies the `Mailable`/`Mailer` contracts the email # verification flow (AUTH-014) renders and delivers through. The `rustasea` -# facade does not re-export it, so it is a direct dependency. The `templates` +# facade re-exports it as `rustasea::mail`; the app keeps this direct dependency +# for its existing `rustasea_mail::` paths. The `templates` # feature (AUTH-018) adds the `rustasea-view`-backed rendering hook so auth # emails render branded HTML from `resources/views/mail/`. rustasea-mail = { path = "../rustasea-mail", features = ["templates"] } diff --git a/docs/milestones.md b/docs/milestones.md index 264b8bf..0187110 100644 --- a/docs/milestones.md +++ b/docs/milestones.md @@ -1,6 +1,6 @@ # RustaSea Milestone Status -> **Last updated:** 2026-09-17 +> **Last updated:** 2026-11-18 > **Scope:** Authoritative done / partial / missing status for milestones **M0–M6**, plus the **gap-closure program** progress (P0–P5). ## Purpose @@ -40,13 +40,13 @@ section records the reason. | Milestone | Goal | Status | Headline evidence | |---|---|---|---| -| **M0** | Bootstrap & Core | **Partial** | Container, provider DAG, and config auto-discovery real (`crates/rustasea-foundation/src/lib.rs:275`, `:296`; `crates/rustasea-config/src/lib.rs:89`); bootstrap registries populated (`bootstrap/providers.rs:35`, `bootstrap/commands.rs:12`) but `AppServiceProvider` stays a no-op (`bootstrap/providers.rs:17`) and the config loader is not mounted in app boot | +| **M0** | Bootstrap & Core | **Partial** | Container, provider DAG, and config auto-discovery real (`crates/rustasea-foundation/src/lib.rs:275`, `:296`; `crates/rustasea-config/src/lib.rs:89`); bootstrap registries populated (`bootstrap/providers.rs:35`, `bootstrap/commands.rs:12`) ; boot mounts the config loader (`crates/rustasea-foundation/src/lib.rs:309`) and the app's `AppServiceProvider` binds environment-derived defaults (`crates/rustasea-app/src/bootstrap/providers.rs:124`); remaining: no database/cache/queue container bindings at boot | | **M1** | Routing & HTTP | **Partial** | Router DSL + controller dispatch real (`crates/rustasea-router/src/dispatch.rs:23`, `:62`); `route:list` renders the live 6-column table published at boot via `RouteSource` (`crates/rustasea-cli/src/routes.rs:19`, `:33`; `crates/rustasea-app/src/bootstrap/app.rs:57`; `crates/rustasea-cli/src/commands/inspect.rs:44`); `show:model` now parses `app/models/{snake}.rs` with `syn` for source-level metadata (`crates/rustasea-cli/src/model_inspect.rs:123`, `:217`; `crates/rustasea-cli/src/commands/inspect.rs:129`) and the HTTP client idle (inter-chunk) timeout is now enforced for streamed bodies (`crates/rustasea-http/src/idle.rs:23`, wired in `crates/rustasea-http/src/lib.rs:448`) | | **M2** | ORM & Database | **Done** | Real sqlx pool + async execution (`crates/rustasea-orm/src/db.rs:24`, `db/exec.rs:72`); model CRUD (`model_ops.rs:28`), transactions (`tx.rs:67`), custom `Migrator` (`migration.rs:131`, `:189`), eager loading (`eager.rs:59`), pgvector (`vector.rs:100`); `raw`/`raw_sql` remain display-only fragments (`execution.rs:239`, `:247`) | -| **M3** | Auth, Middleware & Validation | **Partial** | JWT/CSRF/throttle/validation real; session guard now real via `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`, `impl Guard` `:291`, login `:296`, parse `:352`, refresh `:380`, logout `:408`); declarative attributes are consumed at runtime through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:109`) and `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:135`); remaining: in-memory default session store and fail-closed static user lookup (see section) | -| **M4** | Queue, Cache, Scheduling & Events | **Partial** | Database/Redis queue drivers + worker + persistent failed jobs real (`crates/rustasea-queue/src/driver/database.rs:36`, `driver/worker.rs:75`); `queue:work`/`queue:failed`/`queue:retry` CLI real (`crates/rustasea-cli/src/commands/queue.rs:18`, `ops.rs:21`, `:72`); Redis cache store real behind the `redis` feature (`crates/rustasea-cache/src/redis.rs:155`); async listeners enqueue (`crates/rustasea-events/src/dispatcher.rs:82`); declarative job attributes bind through `JobPolicy` at registration (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`); remaining: `SyncDriver` in-memory failed jobs (`crates/rustasea-queue/src/driver.rs:171`) | +| **M3** | Auth, Middleware & Validation | **Partial** | JWT/CSRF/throttle/validation real; session guard now real via `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`, `impl Guard` `:291`, login `:296`, parse `:352`, refresh `:380`, logout `:408`); declarative attributes are consumed at runtime through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:109`) and `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:135`); store-backed options are real: `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`) and `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`); remaining: scaffolded apps do not wire the database user provider yet (see section) | +| **M4** | Queue, Cache, Scheduling & Events | **Done** | Database/Redis queue drivers + worker + persistent failed jobs real (`crates/rustasea-queue/src/driver/database.rs:36`, `driver/worker.rs:75`); `queue:work`/`queue:failed`/`queue:retry` CLI real (`crates/rustasea-cli/src/commands/queue.rs:18`, `ops.rs:21`, `:72`); Redis cache store real behind the `redis` feature (`crates/rustasea-cache/src/redis.rs:155`); async listeners enqueue (`crates/rustasea-events/src/dispatcher.rs:82`); declarative job attributes bind through `JobPolicy` at registration (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`); failed `sync` dispatches persist to `failed_jobs` through the registered `database` connection (`crates/rustasea-queue/src/driver.rs:192`) | | **M5** | DX, CLI & Testing | **Partial** | CLI + 17 `make:*` generators real (canonical `enum Kind`: `crates/rustasea-cli/src/generators/mod.rs:19-54`; registrations `crates/rustasea-cli/src/commands/mod.rs:17-31`); `cargo rustasea new --variant` real (`crates/rustasea/src/bin/cargo-rustasea.rs:46`); real `xtask` cycle detection (`xtask/src/cycles.rs:32`) and `xtask migrate` (`xtask/src/main.rs:37`); testcontainers-backed `PostgresTestDb` (`crates/rustasea-testing/src/fixtures.rs:49`) with a Docker-gated suite (`crates/rustasea/tests/feature/`); remaining: integration tests are opt-in and generated controllers still need manual route registration (`crates/rustasea-cli/src/generators/kinds/controller.rs:35`) | -| **M6** | Advanced (Broadcast, Search, FS, AI) | **Partial** | Broadcast WS/SSE, `object_store` storage + `config/storage.toml` facade, JSON:API, `rustasea-mail`, `rustasea-view`/`rustasea-inertia`/`rustasea-livewire`/`rustasea-scaffold`, real AI HTTP providers (`crates/rustasea-ai/src/providers/mod.rs:27`), AI queueing (`crates/rustasea-ai/src/queue.rs:41`), MCP client (`crates/rustasea-ai/src/mcp/client.rs:40`), and feature-gated pgvector (`crates/rustasea-search/src/pgvector.rs:24`) all real; remaining: Gemini/Bedrock unsupported (`crates/rustasea-ai/src/providers/client.rs:223`), deterministic stub embeddings (`crates/rustasea-search/src/embeddings.rs:97`), and `InProcessProvider` kept for tests (`crates/rustasea-ai/src/adapters.rs:50`) | +| **M6** | Advanced (Broadcast, Search, FS, AI) | **Partial** | Broadcast WS/SSE, `object_store` storage + `config/storage.toml` facade, JSON:API, `rustasea-mail`, `rustasea-view`/`rustasea-inertia`/`rustasea-livewire`/`rustasea-scaffold`, real AI HTTP providers (`crates/rustasea-ai/src/providers/mod.rs:27`), AI queueing (`crates/rustasea-ai/src/queue.rs:41`), MCP client (`crates/rustasea-ai/src/mcp/client.rs:40`), and feature-gated pgvector (`crates/rustasea-search/src/pgvector.rs:24`) all real; Gemini/Bedrock served through their OpenAI-compatible endpoints (`crates/rustasea-ai/src/providers/client.rs:225`, `:376`); remaining: provider-native Gemini/Bedrock APIs, and `InProcessProvider` kept for deterministic tests | --- @@ -57,8 +57,9 @@ container, provider lifecycle, and graceful shutdown. **Status: Partial** — the application boots, resolves container bindings, orders providers by a real dependency DAG, loads all `config/*.toml`, and shuts down -gracefully. `AppServiceProvider` remains a no-op scaffold and the config loader -is not mounted in the application boot path. +gracefully. Boot mounts the config loader in the container and the runnable +app's `AppServiceProvider` binds environment-derived defaults. Remaining: no +database, cache, or queue bindings are installed in the container at boot. **Done** - Service container with `bind` / `singleton` / `instance` / `get` — `crates/rustasea-foundation/src/lib.rs:103`, `:114`, `:125`, `:136`. @@ -71,18 +72,18 @@ is not mounted in the application boot path. - Runnable app boots, registers routes, serves real handlers, and shuts down — `crates/rustasea-app/src/main.rs` (`configure()`, `app.shutdown()`). **Partial (reason)** -- `AppServiceProvider` is a no-op scaffold — `bootstrap/providers.rs:17`; it participates in the DAG but registers/boots nothing. -- The config loader is not mounted in the application boot path — the only consumers are the CLI and xtask (`crates/rustasea-cli/src/commands/ops/migration.rs:41`, `xtask/src/migrate.rs:21`). -- No app-level service bindings beyond the scaffold. +- The runnable app's `AppServiceProvider` binds only environment-derived defaults (environment name, password policy, destructive-command guard) — `crates/rustasea-app/src/bootstrap/providers.rs:124`; `AuthServiceProvider` installs the session guard (`:173`). +- The config loader is mounted at boot (`crates/rustasea-foundation/src/lib.rs:309`, read back through `Application::config` `:299`), but no database pool, cache manager, or queue driver is bound in the container; features that need a pool connect on their own (the queue dashboard, and the database user provider — `crates/rustasea-app/src/bootstrap/auth.rs:320`). +- The root `bootstrap/` directory is an uncompiled skeleton mirror; its `AppServiceProvider` is a no-op (`bootstrap/providers.rs:17`). The compiled bootstrap is `crates/rustasea-app/src/bootstrap/`. **Missing** -- Real `AppServiceProvider` bindings (database, cache, queue) wired at boot. +- Database, cache, and queue bindings installed in the container at boot. **Evidence:** `crates/rustasea-foundation/src/lib.rs:27-452`; `crates/rustasea-config/src/lib.rs:32-89`; `bootstrap/{app.rs,providers.rs,commands.rs}`; `crates/rustasea-app/src/main.rs`; tasks `GAP-001`, `GAP-019`. **Next actions** -- Populate `AppServiceProvider` with real container bindings. -- Mount the config loader in the app boot sequence. +- Bind the database pool, cache manager, and queue drivers in the container at boot. +- Remove or regenerate the uncompiled root `bootstrap/` mirror. --- @@ -166,8 +167,9 @@ security defaults. **Status: Partial**: JWT, CSRF, throttling, and validation are real, the session guard is a working `tower-sessions`-backed guard (GAP-007), and the declarative attributes are consumed at runtime through the router registries. -Remaining: the default session store is in-memory and the default user lookup is -the fail-closed static lookup. +A database session store and a database-backed user provider are implemented and +selectable. Remaining: both defaults stay in-memory / fail-closed until +configured, and scaffolded apps do not wire the database user provider yet. **Done** - JWT guard — `crates/rustasea-auth/src/jwt.rs`. @@ -183,17 +185,19 @@ the fail-closed static lookup. - Sentry error tracking (ADOPT-004): opt-in `sentry` feature forwarding a request-context middleware (`crates/rustasea-http/src/sentry.rs`) and a logging layer with a `before_send` secret-scrubbing hook (`crates/rustasea-logging/src/sentry/mod.rs`); inert until a DSN is bound (`crates/rustasea/Cargo.toml:128`). **Partial (reason)** -- Default session store is in-memory (`MemoryStore`); a shared store (Redis/SQLx) must be injected via `SessionGuard::with_store` (`crates/rustasea-auth/src/session.rs:187`). -- Default user lookup is the fail-closed `StaticLookup` (`crates/rustasea-auth/src/session.rs:194`); replace via `with_lookup` (`:217`) where a real user source exists. +- The default session store is in-memory (`MemoryStore`). `driver = "database"` in `config/session.toml` selects the persistent `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`), built by `SessionGuard::from_config_database` (`crates/rustasea-auth/src/session.rs:155`); the `redis` driver is rejected at load time. +- The guard's default synchronous lookup is the fail-closed `StaticLookup` (`crates/rustasea-auth/src/session.rs:194`). The database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`) covers registration, login, password reset, verification, and profile updates over the `users` table; the runnable app installs it at boot when the default guard's provider is ORM-backed and the table exists (`crates/rustasea-app/src/bootstrap/auth.rs:320`, called from `crates/rustasea-app/src/main.rs:32`). +- `DatabaseUserProvider` is exercised on SQLite only (`crates/rustasea-auth/tests/database_user_provider.rs`); it has not been run against Postgres or MySQL. **Missing** -- A store-backed default session store and a database-backed default user lookup. +- Database user provider wiring in the scaffold templates (`crates/rustasea-scaffold/src/templates/`), so generated apps get it without hand-wiring. +- A Redis session store. **Evidence:** `crates/rustasea-auth/src/{jwt,csrf,guard,session}.rs`; `crates/rustasea-auth/src/rbac/`; `crates/rustasea-activitylog/`; `crates/rustasea-authlog/`; `crates/rustasea-http/src/sentry.rs`; `crates/rustasea-logging/src/sentry/`; `crates/rustasea-auth/Cargo.toml:20`; `crates/rustasea-router/src/{metadata.rs:237,authorize.rs:216,dispatch.rs:109,135}`; tasks `GAP-003`, `GAP-007`, `ADOPT-001`–`ADOPT-004`. **Next actions** -- Provide a store-backed default session store for multi-process deployments. -- Provide a database-backed default user lookup. +- Wire `DatabaseUserProvider` into the scaffold templates. +- Run the `DatabaseUserProvider` suite against Postgres in the Docker-backed integration tests. --- @@ -202,13 +206,13 @@ the fail-closed static lookup. **Goal recap:** Async workloads, caching, scheduling, and event dispatch with observable queue metrics. -**Status: Partial** — in-memory cache, the sync queue driver, inline events, and +**Status: Done** — in-memory cache, the sync queue driver, inline events, and the scheduler exist; the gap-closure program added real `database`/`redis` queue drivers with a worker loop, persistent failed jobs, `queue:work`/ `queue:failed`/`queue:retry` CLI, a real feature-gated Redis cache store, queue-backed async listeners, and a runtime consumer for the declarative job -attributes. Remaining: the in-process `SyncDriver` still tracks failed jobs in -memory. +attributes. A failed inline `sync` dispatch is persisted through the `database` +connection when one is registered. **Done** - In-memory cache store (lock-guarded map; no `moka` dependency) — `crates/rustasea-cache/src/memory.rs:35`. @@ -225,15 +229,15 @@ memory. - Broadcast fan-out (ADOPT-022): Pusher HTTP driver (HMAC-SHA256 request signing + MD5 body digest, `pusher`/`private-`/`presence-` channel auth) and a Redis Pub/Sub driver for cross-process fan-out behind the `pusher`/`redis` features (`crates/rustasea-broadcast/src/`, `crates/rustasea-app/src/routes/broadcasting.rs`). **Partial (reason)** -- The in-process `SyncDriver` still tracks failed jobs in a `OnceLock>>` — `crates/rustasea-queue/src/driver.rs:171`. +- None. Note: a failed `sync` dispatch is written to the `failed_jobs` table only when a `database` connection is registered (`dead_letter_sync`, `crates/rustasea-queue/src/driver.rs:192`; callers `crates/rustasea-queue/src/registry.rs:150`, `:186`). Without one, or when the insert fails, it falls back to the process-local list (`crates/rustasea-queue/src/driver.rs:174`), which does not survive the process. **Missing** -- A persistent failed-job sink for the in-process `SyncDriver`. +- None. **Evidence:** `crates/rustasea-cache/src/{memory,redis}.rs`; `crates/rustasea-queue/src/driver.rs:115-197`; `crates/rustasea-queue/src/driver/{database,redis,worker}.rs`; `crates/rustasea-queue/src/policy.rs:21-55`; `crates/rustasea-queue/src/migrations.rs`; `crates/rustasea-events/src/dispatcher.rs:82-182`; `crates/rustasea-schedule/src/lib.rs:20`; `crates/rustasea-queue-dashboard/`; `crates/rustasea-broadcast/`; tasks `GAP-004`–`GAP-009`, `ADOPT-021`, `ADOPT-022`. **Next actions** -- Move `SyncDriver` failed-job tracking to a persistent sink (or delegate to `DatabaseDriver`). +- None. --- @@ -304,8 +308,10 @@ features. **Status: Partial** — broadcasting (WS/SSE), `object_store`-backed storage with a TOML config facade, JSON:API, the mail crate, the presentation crates (view/Inertia/Livewire/scaffold), real HTTP-backed AI providers, AI queueing, and -MCP are all real. Remaining: Gemini/Bedrock are unsupported, embeddings default -to a deterministic stub, and the in-process AI provider is kept for tests. +MCP are all real. Gemini and Bedrock are served through their OpenAI-compatible +endpoints and provider-backed embeddings send a dedicated embedding model. +Remaining: the provider-native Gemini/Bedrock APIs are not implemented, and the +in-process AI provider is kept for tests. **Done** - Broadcasting: WebSocket (`axum/ws`, feature-gated default) + SSE + `ShouldBroadcast` — `crates/rustasea-broadcast/Cargo.toml:20`, `:22`; `crates/rustasea-broadcast/src/lib.rs:35`. @@ -316,7 +322,7 @@ to a deterministic stub, and the in-process AI provider is kept for tests. - Image manipulation (ADOPT-024) — `crates/rustasea-image` (fluent pipeline, EXIF orient, storage round-trip, queued transforms). - Google service-account auth (ADOPT-026) — `crates/rustasea-google`: service-account JSON parse/validate, RS256 JWT assertion, token exchange + cached access token (single-flight refresh at 80% lifetime); `GoogleCredentials` block in `config/services.toml` (`crates/rustasea-config/src/services.rs`); umbrella feature `google`. - JSON:API resources with correct content type — `crates/rustasea-jsonapi/src/wire.rs:7`. -- Mail & notifications (`GAP-020`) — `crates/rustasea-mail/`: `Mailable` (`mailable.rs:11`), `Mailer`/`ArrayMailer`/`LogMailer` (`mailer.rs:12`, `:22`, `:73`), `SmtpMailer` (feature `smtp`, `smtp.rs:14`), `QueuedNotification` dispatched through the queue (`notification.rs:41`). +- Mail & notifications (`GAP-020`) — `crates/rustasea-mail/`: `Mailable` (`mailable.rs:11`), `Mailer`/`ArrayMailer`/`LogMailer` (`mailer.rs:12`, `:22`, `:73`), `SmtpMailer` (feature `smtp`, `smtp.rs:14`), `QueuedNotification` dispatched through the queue (`notification.rs:41`); re-exported from the umbrella as `rustasea::mail` (`crates/rustasea/src/lib.rs:156`) with the `mail-smtp` / `mail-templates` features (`crates/rustasea/Cargo.toml:143`, `:146`). - View layer — `rustasea-view` with askama (default) + minijinja (`runtime-templates`) — `crates/rustasea-view/Cargo.toml:14`, `:17`, `:22`; `crates/rustasea-view/src/askama_engine.rs:35`. - Inertia protocol + WASM client + framework adapters — `crates/rustasea-inertia/src/page.rs:25` (`Page`), `crates/rustasea-inertia-client/`, `crates/rustasea-inertia-adapters/` (Dioxus for react, Leptos for vue, Sycamore for svelte: `crates/rustasea-inertia-adapters/src/{dioxus,leptos,sycamore}_adapter.rs`; umbrella features `wasm-dioxus`/`wasm-leptos`/`wasm-sycamore` at `crates/rustasea/Cargo.toml:112`, `:118`, `:124`). - Livewire analogue — `crates/rustasea-livewire/src/authorizer.rs:27` (`ActionAuthorizer`). @@ -330,20 +336,17 @@ to a deterministic stub, and the in-process AI provider is kept for tests. - Timezone mapping (ADOPT-006, `glhd/laravel-timezone-mapper` parity): `crates/rustasea-timezone`: IANA validation plus a deterministic user-timezone resolution chain (stored preference, session, request header, app default) and UTC/local formatting helpers (`crates/rustasea-timezone/src/{lib,mapper}.rs`). **Partial (reason)** -- Gemini/Bedrock are not wired — `provider_from_env` rejects unknown names with `AiError::UnknownProvider` (`crates/rustasea-ai/src/providers/client.rs:223`). -- Default embeddings are a deterministic hashing stub — `crates/rustasea-search/src/embeddings.rs:97` (`stub_embedding`, model `"stub"`). +- Gemini and Bedrock resolve to their OpenAI-compatible endpoints only (`crates/rustasea-ai/src/providers/client.rs:225`, `bedrock_from_env` `:376`): chat completions, streaming, and embeddings in the OpenAI wire format, with `GEMINI_API_KEY` / a Bedrock API key (`AWS_BEARER_TOKEN_BEDROCK`). The provider-native APIs (Gemini `generateContent`, Bedrock Converse with SigV4) are not implemented. Neither provider has been called against the live service from this repository. +- Provider-backed embeddings are real: `StrToEmbeddings` (`crates/rustasea-ai/src/embed.rs:18`) calls `AiProvider::embeddings`, and the HTTP adapter sends the configured embedding model (`crates/rustasea-ai/src/providers/client.rs:246`, `:313`; `crates/rustasea-ai/src/providers/openai.rs:155`). The engine-agnostic `Str::to_embeddings` in `rustasea-search` still falls back to a deterministic hashing stub when its closure yields no vector (`crates/rustasea-search/src/embeddings.rs:97`). - `InProcessProvider` remains for deterministic tests — `crates/rustasea-ai/src/adapters.rs:50`. -- `rustasea-mail` is not yet re-exported from the `rustasea` umbrella crate (`crates/rustasea/Cargo.toml`); use it as a direct workspace dependency for now. **Missing** -- Gemini/Bedrock adapters. -- Real embedding-model integration (provider-backed `to_embeddings`). +- Provider-native Gemini and Bedrock adapters. **Evidence:** `crates/rustasea-broadcast/{Cargo.toml,src/lib.rs}`; `crates/rustasea-storage/{Cargo.toml,src/manager.rs:56-171,src/facade.rs}`; `config/storage.toml`; `crates/rustasea-jsonapi/src/wire.rs:7`; `crates/rustasea-mail/`; `crates/rustasea-view/`; `crates/rustasea-ai/src/{providers,queue.rs,mcp,adapters.rs}`; `crates/rustasea-search/{src/pgvector.rs,src/embeddings.rs}`; `crates/rustasea-google/`; `crates/rustasea-config/src/services.rs`; `crates/rustasea-i18n/`; `crates/rustasea-timezone/`; tasks `GAP-012`, `GAP-014`, `GAP-015`, `GAP-020`, `ADOPT-005`, `ADOPT-006`, `ADOPT-026`. **Next actions** -- Add Gemini/Bedrock adapters behind the existing provider abstraction. -- Replace the stub embedding path with a real provider call. +- Add provider-native Gemini/Bedrock adapters where the OpenAI-compatible surface is not enough. --- From 5371789191d747c68396c60001ba413164ba4540 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:47:00 +0700 Subject: [PATCH 10/14] fix(storage): accept russh 0.65's PublicKeyOrCertificate in the SFTP host-key check The russh bump changed Handler::check_server_key to take a PublicKeyOrCertificate, so rustasea-storage no longer compiled with the sftp feature. The pin now compares the fingerprint of the presented key, or of the key a host certificate certifies. --- crates/rustasea-storage/src/sftp/connection.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/rustasea-storage/src/sftp/connection.rs b/crates/rustasea-storage/src/sftp/connection.rs index 2a7e097..d16d27f 100644 --- a/crates/rustasea-storage/src/sftp/connection.rs +++ b/crates/rustasea-storage/src/sftp/connection.rs @@ -32,9 +32,13 @@ impl client::Handler for ClientHandler { /// Verify the server host key against the configured pin (if any). async fn check_server_key( &mut self, - server_public_key: &russh::keys::ssh_key::PublicKey, + server_public_key: &russh::keys::PublicKeyOrCertificate, ) -> std::result::Result { - let actual = server_public_key.fingerprint(HashAlg::Sha256).to_string(); + // A host certificate is pinned by the fingerprint of the key it certifies. + let actual = server_public_key + .public_key() + .fingerprint(HashAlg::Sha256) + .to_string(); match &self.expected_fingerprint { Some(expected) => Ok(actual == *expected), None => Ok(true), From 4b6bc70737f056ea3e900ed662723b8c0cd2ae07 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:41:57 +0700 Subject: [PATCH 11/14] docs: sync milestone status and Laravel parity with the code Returns M4 to Partial: the scheduler cannot dispatch a due command, schedule pause state is per-process, and after-response events are never flushed. The previous docs commit marked M4 Done on the strength of the failed-job sink alone; that was wrong. Records, with path:line evidence, facts found while checking the planning documents: the AI agent runtime echoes the prompt instead of calling a provider, domain routes ignore the request Host, JwtGuard::logout is a no-op, and a bare-word in: rule list rejects every value. Updates the parity rows for events, batches, unique jobs, sessions, the user provider, mail, notifications, the gate, the password-reset store, the scheduler, and the AI SDK, and adds a resolution note to the gap audit. --- CHANGELOG.md | 11 ++++++++++ docs/gap-analysis/README.md | 2 ++ docs/laravel-parity.md | 42 ++++++++++++++++++------------------- docs/milestones.md | 40 +++++++++++++++++++++++++++-------- 4 files changed, 65 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5678c4c..4379fdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -151,6 +151,17 @@ Per the same section, each tag is expected to pass `cargo xtask ci` and ### Changed +- 2026-11-18 - Documentation brought in line with the code: `docs/laravel-parity.md` + rows for events, batches, unique jobs, sessions, the user provider, mail, + notifications, the gate, the password-reset store, the scheduler, and the AI + SDK; as-built status on the roadmap and sprint documents; and a checked Status + column with open items on the 110 implementation-task rows under + `.agents/documents/application/modules/` (55 done, 53 partial, 2 not + started). `docs/milestones.md` returns M4 to Partial (the scheduler cannot + dispatch a due command, schedule pause state is per-process, and + after-response events are never flushed) and records that the AI agent + runtime does not call a provider (M0-M6; `docs: sync planning and status + documents with the code`). - 2026-11-18 - Embeddings requests send an embedding model instead of the provider's chat model: `_EMBEDDING_MODEL`, else the provider's known embedding model (openai, gemini, mistral), else the default model as before diff --git a/docs/gap-analysis/README.md b/docs/gap-analysis/README.md index 6df57c4..1613983 100644 --- a/docs/gap-analysis/README.md +++ b/docs/gap-analysis/README.md @@ -32,6 +32,8 @@ Direction of drift is mostly "documentation lags implementation": six gaps (GAP- | GAP-030 | P4 | HTTP client idle timeout unenforced in runtime transport | `crates/rustasea-http/src/lib.rs` vs `README.md`, `docs/milestones.md` | Partial (`idle_timeout` stored, never applied) | | GAP-031 | P4 | Missing 500-line file limit linter enforcement in CI / xtask | `docs/adr/ADR-0009.md` vs `xtask/` and `.github/workflows/ci.yml` | Not enforced (no `lines:check` task, no CI step) | +> **Resolution note (2026-11-18):** the Implementation Status column above is the state on the audit date. Every finding has since had a closing change land: `docs: [GAP-022] synchronize canonical crate inventory to 44 workspace packages`, `docs: [GAP-023] update stale route:list and attribute consumption documentation`, `docs: [GAP-024] document complete artisan CLI command surface in README`, `docs: [GAP-025] reconcile make:* generator count to 17 across documentation`, `docs: [GAP-026] align laravel-parity and milestones with all 31 ADOPT implementations`, `docs: [GAP-027] document ADOPT crates and umbrella features in README`, `docs: [GAP-028] add CHANGELOG, CONTRIBUTING, and SECURITY governance documents`, `feat(cli): [GAP-029] implement source-level show:model introspection with JSON output`, `feat(http): [GAP-030] enforce per-chunk idle timeout on streamed response bodies`, and `feat(xtask): [GAP-031] add lines:check 500-line linter and enforce in xtask ci`. For this note only two oracles were re-checked on the current tree: GAP-028 (the three root documents exist and are linked from `README.md`) and GAP-031 (`cargo xtask lines:check` runs and passes). The other falsification checks below were not re-run, so treat their closure as recorded, not re-verified. Documentation has drifted again since the audit; the current as-built status is [`docs/milestones.md`](../milestones.md). + Legend for Implementation Status: **Implemented** means the code exists and is reachable. **Partial** means the code exists but does not deliver the documented behaviour. **Not created** / **Not enforced** means the artifact does not exist. In every case the gap describes the documentation or enforcement shortfall, not a missing feature. ## Detailed Breakdown diff --git a/docs/laravel-parity.md b/docs/laravel-parity.md index 5737c10..a1ecc0f 100644 --- a/docs/laravel-parity.md +++ b/docs/laravel-parity.md @@ -1,6 +1,6 @@ # RustaSea × Laravel 13.x — API-Surface Parity Map -> **Last updated:** 2026-09-17 +> **Last updated:** 2026-11-18 > **Scope:** Maps the Laravel 13.x **API surface** (namespaces, contracts/interfaces, traits, notable classes) to RustaSea crates/modules, with an adoption status per row. > **Companion docs:** [`docs/laravel-13-research.md`](laravel-13-research.md) (feature-level research) · [`docs/milestones.md`](milestones.md) (M0–M6 implementation status). @@ -56,26 +56,26 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | `Illuminate\Support\Facades` | — | **N-A** | ADR-0007: no global facades; managers live in `AppState` and flow through `axum::extract::State`. | | `Illuminate\Config` | `rustasea-config` (`ConfigLoader`) | **Partial** | TOML + env overlay real; only `config/app` is auto-loaded today. | | `Illuminate\Console` | `rustasea-cli` (`Artisan`, `Command`, `CommandRegistry`) | **Adopted** | `cargo artisan` registry + generators are real. | -| `Illuminate\Console\Scheduling` | `rustasea-schedule` (`Schedule`, `Scheduler`, `ScheduleCommand`) | **Partial** | Pause/resume + ticks real; cron-cache mutexes / background tasks absent. | +| `Illuminate\Console\Scheduling` | `rustasea-schedule` (`Schedule`, `Scheduler`, `ScheduleCommand`) | **Partial** | Frequency builder, pause/resume, and `schedule:run` / `schedule:list` exist, but a due command cannot run: `dispatch_command` returns an error because no queue dispatch path is wired (`crates/rustasea-schedule/src/scheduler.rs:146`). Pause state is per-process (`crates/rustasea-schedule/src/pause.rs:28`); `onOneServer` takes no lock; `schedule:run` runs a single tick. | | `Illuminate\Database` | `rustasea-orm` (`DbPool`, `Executor`, `Migrator`) | **Adopted** | Real sqlx pool + async query execution + transactions + migrations/seeders/factories (`crates/rustasea-orm/src/db.rs:24`, `db/exec.rs:70`, `migration.rs:190`). | | `Illuminate\Database\Eloquent` | `rustasea-orm` (`Model`, `QueryBuilder`, `Relation`, `SoftDeletes`, `Timestamps`) | **Partial** | `#[derive(Model)]` + eager loading and relation serde round-trip real (`crates/rustasea-orm/src/eager.rs:59`); `show:model` source-level introspection (attributes/casts/soft-delete/relations, both `#[derive(Model)]` and hand-written `impl Model`) real (`crates/rustasea-cli/src/model_inspect.rs:123`); live DB column reflection pending. | | `Illuminate\Database\Migrations` | `rustasea-orm` (`Migration`, `Migrator`, `MigrationRecord`) | **Adopted** | Runner executes against the live pool — `run`/`rollback`/`fresh`/`seed` (`crates/rustasea-orm/src/migration.rs:190`). | | `Illuminate\Database\Query` | `rustasea-orm` (`QueryBuilder`, `Value`, `JsonFilter`) | **Adopted** | Fluent builder + async execution real (`crates/rustasea-orm/src/builder/exec.rs:105`). | -| `Illuminate\Events` | `rustasea-events` (`Dispatcher`, `Event`, `Listener`) | **Partial** | Inline dispatch real; queue-backed listeners unwired. | +| `Illuminate\Events` | `rustasea-events` (`Dispatcher`, `Event`, `Listener`) | **Partial** | Inline dispatch real; queue-enabled listeners are serialized into a `ListenerJob` and pushed through the queue (`crates/rustasea-events/src/dispatcher.rs:137`, `:145`). `dispatchAfterResponse` only buffers into `EventSink` (`:254`) and nothing flushes it. | | `Illuminate\Routing` | `rustasea-router` (`Router`, `RouteEntry`, `ControllerRef`) | **Partial** | DSL + controller dispatch real; `route:list` introspection live (6-column table published at boot via `RouteSource`: `crates/rustasea-cli/src/routes.rs:19`, `:33`; `crates/rustasea-app/src/bootstrap/app.rs:57`; `crates/rustasea-cli/src/commands/inspect.rs:44`). | | `Illuminate\Http` | `rustasea-http` (`AppState`, `JsonResponse`, `HttpError`) | **Partial** | Request/response + CORS real; idle (inter-chunk) timeout enforced for streamed bodies (`crates/rustasea-http/src/idle.rs:23`). | | `Illuminate\Http\Client` | `rustasea-http` (`HttpClient`) | **Adopted** | reqwest wrapper with `throw` / `try_throw` semantics. | | `Illuminate\Http\Resources\JsonApi` | `rustasea-jsonapi` (`JsonApiResource`, `Document`, `ResourceBuilder`) | **Adopted** | Sparse fieldsets, links, JSON:API content type real. | | `Illuminate\Cache` | `rustasea-cache` (`Store`, `CacheManager`, `Repository`, `Lock`) | **Partial** | Memory store real; Redis store real behind the opt-in `redis` feature (`GAP-004`; `crates/rustasea-cache/src/redis.rs:155`; `crates/rustasea-cache/Cargo.toml:12`) — typed `StoreUnavailable` only when the feature is off or Redis is unreachable; driver matrix incomplete. | | `Illuminate\Queue` | `rustasea-queue` (`Queue`, `QueueDriver`, `Job`, `QueueRegistry`) | **Adopted** | Sync + real database/Redis drivers + worker loop (`crates/rustasea-queue/src/driver/{database,redis,worker}.rs`). | -| `Illuminate\Bus` | `rustasea-queue` (`BatchHandle`, `BatchId`) | **Partial** | Batch handles exist; no durable batch repository. | +| `Illuminate\Bus` | `rustasea-queue` (`BatchHandle`, `BatchId`) | **Partial** | Batch handles plus a durable `DatabaseBatchRepository` over the `job_batches` table (`crates/rustasea-queue/src/batch_db.rs:77`). | | `lorisleiva/laravel-actions` | `rustasea-action` (`Action`, `ActionController`, `ActionJob`, `ActionCommand`, `ActionListener`) | **Partial** | One action unit invoked from HTTP/queue/CLI/events with validate/authorize hooks; `make:action` generator; scaffold auth actions demonstrate the pattern (ADOPT-028). | | `Laravel\Horizon` | `rustasea-queue-dashboard` (`DashboardConfig`, `sampler`, `QueueMetricsHistory`) | **Partial** | Queue dashboard (`/queue`): live depth/age, `queue_metrics` history + retention, failed-job retry/forget, worker heartbeats; feature `queue-dashboard` (ADOPT-021). No supervisor/balancing/auto-scaling yet. | -| `Illuminate\Auth` | `rustasea-auth` (`AuthManager`, `Guard`, `JwtGuard`, `SessionGuard`) | **Partial** | JWT/CSRF/throttle real; session guard real over `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`); default store is in-memory. | +| `Illuminate\Auth` | `rustasea-auth` (`AuthManager`, `Guard`, `JwtGuard`, `SessionGuard`) | **Partial** | JWT/CSRF/throttle real; session guard real over `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`) with an in-memory default store and a database store (`crates/rustasea-auth/src/session/database.rs:74`); users resolve through the database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`), which the runnable app installs at boot when the `users` table exists (`crates/rustasea-app/src/bootstrap/auth.rs:320`). | | `Illuminate\Auth\Access` | `rustasea-router` (`AuthorizeRegistry`, `AuthorizeResource`, `#[authorize]` metadata) | **Adopted** | `#[authorize]` metadata is resolved and enforced at dispatch: `Router::authorize_meta` consumes the macro-emitted tuple (`crates/rustasea-router/src/authorize.rs:216`), and `apply_authorize` wraps the route in a fail-closed authorization layer (`crates/rustasea-router/src/dispatch.rs:135`). | | `Illuminate\Validation` | `rustasea-validation` (`Validatable`, `Rules`, `ErrorBag`, `FormRequest`) | **Partial** | Rules + ErrorBag + form requests real; DB presence verifier absent. | | `Illuminate\Hashing` | `rustasea-auth` (`PasswordVerifier`, `Argon2Verifier`) | **Partial** | Argon2 verifier real; no hasher manager / rehash policy. | -| `Illuminate\Session` | `rustasea-auth` (`SessionGuard`, `SessionPolicy`) | **Partial** | `tower-sessions`-backed session guard real (`crates/rustasea-auth/src/session.rs:99`); default store is in-memory, inject a shared store via `with_store` (`:187`). | +| `Illuminate\Session` | `rustasea-auth` (`SessionGuard`, `SessionPolicy`) | **Partial** | `tower-sessions`-backed session guard real (`crates/rustasea-auth/src/session.rs:99`); the default store is in-memory and `driver = "database"` in `config/session.toml` selects the persistent `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`, built by `from_config_database` `crates/rustasea-auth/src/session.rs:155`). No Redis/file/cookie store. | | `Illuminate\Cookie` | `rustasea-http` (CORS + `SecurityConfig`) | **Partial** | No queued-cookie jar / cookie encryption layer yet. | | `Illuminate\Filesystem` | `rustasea-storage` (`Storage`, `StorageManager`, `LocalDisk`, `ObjectDisk`, `ReadThrough`) | **Adopted** | `object_store`-backed disks + read-through with path confinement. | | `Maatwebsite\Excel` | `rustasea-excel` (`Excel`, `ImportBuilder`, `ExportBuilder`, `ExportJob`) | **Partial** | Streaming CSV/xlsx import with row-level validation reports; chunked export to storage; queued `ExportJob` + signed download URLs (ADOPT-023). Formula/style/format parity absent. | @@ -85,8 +85,8 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | `Illuminate\Encryption` | — | **Planned** | No encrypter / key-rotation service. | | `Illuminate\Translation` | `rustasea-i18n` (`TranslationLoader`, `Translator`, `Message`, global `__`/`trans_choice`) + `lang:check` | **Adopted** | Loads `resources/lang/{locale}/*.toml`/`*.json` with dot-namespaced keys, active-locale-then-fallback resolution, interpolation, and pluralization (`crates/rustasea-i18n/src/{loader,translator,message}.rs`); global helpers in `crates/rustasea-i18n/src/global.rs`; `lang:check` reports missing/unused/duplicate entries (ADOPT-005; `crates/rustasea-cli/src/commands/langcheck.rs:106`). | | `Illuminate\View` | `rustasea-view` (`ViewEngine`, `ViewResponse`) | **Partial** | Engine-agnostic rendering with askama (default) and minijinja (`runtime-templates`), re-exported behind the `view` feature; the runnable app renders `resources/views` (`crates/rustasea-view/src/{askama_engine,minijinja_engine,response}.rs`). No Blade syntax or component system. | -| `Illuminate\Mail` | `rustasea-mail` (`Mailable`, `Mailer`, `ArrayMailer`, `LogMailer`, `SmtpMailer`, `QueuedNotification`) | **Partial** | Mailable/Mailer contracts + array/log transports and a feature-gated SMTP transport (`smtp`) with queued notifications are real (`crates/rustasea-mail/src/`); not yet re-exported from the `rustasea` umbrella. No Blade mail templates. | -| `Illuminate\Notifications` | `rustasea-queue` (`NotificationGuard`) | **Partial** | Missing-model skip guard only; no channel dispatcher. | +| `Illuminate\Mail` | `rustasea-mail` (`Mailable`, `Mailer`, `ArrayMailer`, `LogMailer`, `SmtpMailer`, `QueuedNotification`) | **Partial** | Mailable/Mailer contracts + array/log transports and a feature-gated SMTP transport (`smtp`) with queued notifications are real (`crates/rustasea-mail/src/`); re-exported from the umbrella as `rustasea::mail` with the `mail-smtp` / `mail-templates` features (`crates/rustasea/src/lib.rs:156`). Mailables render from minijinja templates behind the `templates` feature (`crates/rustasea-mail/src/template.rs:39`); no Markdown mail components. | +| `Illuminate\Notifications` | `rustasea-queue` (`NotificationGuard`), `rustasea-mail` (`MailNotification`, `QueuedNotification`) | **Partial** | Missing-model skip guard plus queued mail notifications (`crates/rustasea-mail/src/notification.rs:22`, `:41`); no multi-channel dispatcher. | | `Illuminate\Log` | `tracing` (workspace dependency) | **N-A** | Structured logging is handled by `tracing`, not a Laravel-style `Log` facade. | | `opcodesio/log-viewer` | `rustasea-logging` reader + `cargo artisan log:show` + `/_logs` dev viewer | **Partial** | On-disk log reader (`rustasea-logging::reader`: parse/filter/resolve/tail), `log:show` CLI (`--level`/`--since`/`--grep`/`--limit`/`--follow`/`--json`), and a dev-only `/_logs` web surface behind the `log-viewer` feature (ADOPT-014). Rotation-aware file resolution; no per-entry stack-trace grouping or multi-file index. | | `Illuminate\Redis` | `rustasea-cache` (`RedisStore`) | **Partial** | Real `deadpool-redis` store behind the opt-in `redis` feature (`GAP-004`; `crates/rustasea-cache/src/redis.rs:155`), built via `from_url`/`from_pool` (`:91`, `:105`); atomic `SET NX` insert-if-absent + Lua compare-and-delete. No general-purpose command/pub-sub surface. | @@ -97,7 +97,7 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | `pestphp/pest-plugin-browser` | `rustasea-testing` (`Browser`, `ServerHandle`, `BrowserError`) | **Partial** | Feature-gated WebDriver harness (feature `browser`, `fantoccini`) with Dusk-style `visit`/`fill`/`click`/`select`/`check`/`press`/`wait_for`/`assert_see` helpers, an ephemeral axum `ServerHandle`, and failure screenshots. Auto-skips when `WEBDRIVER_URL` is unreachable rather than failing the default run; `make:test --browser` scaffolds a test (ADOPT-029). No DevTools protocol, parallel browser pool, or Vite integration. | | `Illuminate\Image` | rustasea-image (Image, ImageBuilder, ImageTransformJob) | Partial | Fluent pipeline (resize/fit/cover/thumbnail/crop/rotate/watermark text+image), EXIF auto-orient, jpeg/png/webp/gif/bmp/tiff encode, storage round-trip + queued transforms (ADOPT-024). No GD/Imagick drivers or animated webp/gif transforms. | | `Illuminate\JsonSchema` | — | **Planned** | No JSON-schema contract. | -| AI SDK (`laravel/ai`, separate package) | `rustasea-ai` (`AiProvider`, `Agent`, `Tool`) | **Partial** | Provider-agnostic traits + agents real; real HTTP-backed OpenAI/Anthropic adapters plus a deterministic in-process provider kept for tests (feature `ai`); Gemini/Bedrock unsupported and embeddings default to a stub (`crates/rustasea-ai/src/providers/mod.rs:27`, `adapters.rs:50`, `crates/rustasea-search/src/embeddings.rs:97`). | +| AI SDK (`laravel/ai`, separate package) | `rustasea-ai` (`AiProvider`, `Agent`, `Tool`) | **Partial** | Provider-agnostic traits real; the agent runtime echoes the prompt and never calls a provider (`crates/rustasea-ai/src/agent.rs:247`); real HTTP-backed OpenAI-style and Anthropic adapters plus a deterministic in-process provider kept for tests (feature `ai`; `crates/rustasea-ai/src/providers/mod.rs:27`, `adapters.rs:50`). Gemini and Bedrock are served through their OpenAI-compatible endpoints (`crates/rustasea-ai/src/providers/client.rs:225`, `:376`); the provider-native APIs are not implemented. Provider-backed embeddings send a dedicated embedding model (`crates/rustasea-ai/src/embed.rs:18`, `providers/client.rs:246`); the engine-agnostic `rustasea-search::Str` keeps a deterministic stub fallback (`crates/rustasea-search/src/embeddings.rs:97`). | | `spatie/laravel-permission` | `rustasea-auth::rbac` (`Role`, `RbacRegistry`, `HasRoles`, `PermissionResolver`) | **Adopted** | Role/permission assignment with cached permission lookups and a `PermissionResolver` the ability `Gate` consults after its defined abilities (ADOPT-001; `crates/rustasea-auth/src/rbac/{mod,role,registry,has_roles}.rs`). | | `spatie/laravel-activitylog` | `rustasea-activitylog` (`ActivityLogger`, `ActivityEvent`) | **Adopted** | Model-change audit trail with JSON property diffs and an optional `batch_uuid`, built on the ORM `#[logs_activity]` seam and persisted to the `audit_log` table (ADOPT-002; `crates/rustasea-activitylog/src/{lib,recorder,model}.rs`). | | `rappasoft/laravel-authentication-log` | `rustasea-authlog` (`AuthenticationLogLogger`, `NewDeviceNotifier`) | **Adopted** | One row per login/failed/lockout/logout with client IP and `User-Agent`; an unknown-IP login triggers a queued new-device notification (ADOPT-003; `crates/rustasea-authlog/src/{lib,recorder,notifier}.rs`). | @@ -186,11 +186,11 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | `Illuminate\Contracts\Cache\Factory` | `rustasea-cache::CacheManager` | **Partial** | Manager selects stores; driver matrix incomplete. | | `Illuminate\Contracts\Queue\Queue` | `rustasea-queue::Queue` | **Adopted** | Push/dispatch surface real; sync + database + Redis drivers wired. | | `Illuminate\Contracts\Queue\Job` | `rustasea-queue::{Job, ErasedJob}` | **Adopted** | Job + erased-job traits real; worker loop real (`crates/rustasea-queue/src/driver/worker.rs:78`). | -| `Illuminate\Contracts\Queue\ShouldQueue` | `rustasea-queue::Job` | **Partial** | Implemented via trait; no queue-backed listener wiring. | -| `Illuminate\Contracts\Queue\ShouldBeUnique` | — | **Planned** | No unique-job locking. | +| `Illuminate\Contracts\Queue\ShouldQueue` | `rustasea-queue::Job` | **Adopted** | Implemented via trait; queue-enabled listeners enqueue a `ListenerJob` (`crates/rustasea-events/src/dispatcher.rs:145`). | +| `Illuminate\Contracts\Queue\ShouldBeUnique` | `rustasea-queue::ShouldBeUnique` | **Adopted** | Unique-job lease over a cache lock: `register_unique::()` at boot, lease acquired on dispatch and released on a terminal outcome (`crates/rustasea-queue/src/unique.rs:66`, `:169`, `:233`). Locking disengages when no cache store is installed. | | `Illuminate\Contracts\Queue\Factory` | `rustasea-queue::QueueRegistry` | **Partial** | Registry + routing real; connection factory thinner. | | `Illuminate\Queue\Connectors\ConnectorInterface` | `rustasea-queue::QueueDriver` | **Partial** | Driver trait real; database + Redis drivers implemented (`crates/rustasea-queue/src/driver/{database,redis}.rs`). | -| `Illuminate\Contracts\Events\Dispatcher` | `rustasea-events::Dispatcher` | **Partial** | Inline dispatch + `dispatchAfterResponse` real; queue path unwired. | +| `Illuminate\Contracts\Events\Dispatcher` | `rustasea-events::Dispatcher` | **Partial** | Inline dispatch real; queue-enabled listeners enqueue a `ListenerJob` (`crates/rustasea-events/src/dispatcher.rs:145`); `dispatchAfterResponse` buffers but is never flushed (`:254`). | | `Illuminate\Events\Dispatcher` (class) | `rustasea-events::Dispatcher` | **Partial** | Concrete dispatcher present with the same caveat. | ### Auth / Validation / Session @@ -198,22 +198,22 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | Laravel interface/trait | RustaSea equivalent | Status | Rationale | |---|---|---|---| | `Illuminate\Contracts\Auth\Guard` | `rustasea-auth::Guard` | **Adopted** | Guard trait + JWT implementation real. | -| `Illuminate\Contracts\Auth\StatefulGuard` | `rustasea-auth::SessionGuard` | **Partial** | `tower-sessions`-backed session guard real (`crates/rustasea-auth/src/session.rs:99`); default store is in-memory. | +| `Illuminate\Contracts\Auth\StatefulGuard` | `rustasea-auth::SessionGuard` | **Partial** | `tower-sessions`-backed session guard real (`crates/rustasea-auth/src/session.rs:99`); default store is in-memory, with a database store selectable by config (`crates/rustasea-auth/src/session/database.rs:74`). | | `Illuminate\Contracts\Auth\Authenticatable` | `rustasea-auth::AuthUser` | **Adopted** | User identity type implemented. | -| `Illuminate\Contracts\Auth\UserProvider` | `rustasea-auth::UserLookup` | **Partial** | Lookup trait real; DB/Eloquent providers thinner. | +| `Illuminate\Contracts\Auth\UserProvider` | `rustasea-auth::{UserProvider, UserLookup}` | **Adopted** | Async write+read `UserProvider` (`crates/rustasea-auth/src/users/provider.rs:110`) with a database implementation over the `users` table (`DatabaseUserProvider`, `crates/rustasea-auth/src/users/provider/database.rs:49`), an in-memory one, and a fail-closed default; the sync `UserLookup` remains for guard reads. The database provider is exercised on SQLite only. | | `Illuminate\Contracts\Auth\Factory` | `rustasea-auth::AuthManager` | **Adopted** | Named guard registration + `Auth::extend` real. | -| `Illuminate\Contracts\Auth\Access\Gate` | `rustasea-router::AuthorizeRegistry` | **Partial** | Record-level authorization enforced at dispatch: `#[authorize]` metadata resolves through `Router::authorize_meta` (`crates/rustasea-router/src/authorize.rs:216`) and `apply_authorize` fails closed on an unregistered resource (`crates/rustasea-router/src/dispatch.rs:135`). No general-purpose ability/`Gate::allows` surface yet. | +| `Illuminate\Contracts\Auth\Access\Gate` | `rustasea-router::AuthorizeRegistry` | **Partial** | Record-level authorization enforced at dispatch: `#[authorize]` metadata resolves through `Router::authorize_meta` (`crates/rustasea-router/src/authorize.rs:216`) and `apply_authorize` fails closed on an unregistered resource (`crates/rustasea-router/src/dispatch.rs:135`). A general-purpose ability `Gate` (named abilities with `before`/`after` hooks) lives in `rustasea-auth` (`crates/rustasea-auth/src/gate/mod.rs:176`). | | `Illuminate\Contracts\Auth\Access\Authorizable` | `rustasea-router::{AuthorizeRegistry, AuthorizeResource}` | **Partial** | `#[authorize]` metadata is enforced at runtime (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:135`); no `Authorizable` trait on models yet. | | `Illuminate\Contracts\Auth\CanResetPassword` | — | **Planned** | No password-reset broker. | -| `Illuminate\Contracts\Auth\MustVerifyEmail` | `rustasea-auth::EmailVerification` | **Partial** | Verification trait + memory impl real; mail transport absent. | -| `Illuminate\Contracts\Auth\PasswordBroker` | — | **Planned** | No token broker. | +| `Illuminate\Contracts\Auth\MustVerifyEmail` | `rustasea-auth::EmailVerification` | **Partial** | Verification trait + memory impl real; the runnable app delivers the verification mail through `rustasea-mail` (`crates/rustasea-app/src/routes/auth/verification.rs:165`). | +| `Illuminate\Contracts\Auth\PasswordBroker` | `rustasea-auth::PasswordResetStore` | **Partial** | Token-store seam with hashed-at-rest tokens, an in-memory store, and a fail-closed default (`crates/rustasea-auth/src/password_reset.rs:73`, `:135`, `:174`); no database-backed token table yet. | | `Illuminate\Auth\GuardHelpers` (trait) | `rustasea-auth::Guard` default methods | **Partial** | Shared guard defaults; surface smaller. | | `Illuminate\Contracts\Validation\Validator` | `rustasea-validation::Rules` | **Partial** | Rule engine real; contract breadth smaller. | | `Illuminate\Contracts\Validation\ValidatesWhenResolved` | `rustasea-validation::FormRequest` | **Adopted** | Form-request validation-on-resolve implemented. | | `Illuminate\Contracts\Validation\Rule` | `rustasea-validation::Rules` | **Partial** | Rule registration real; not a per-rule trait object. | | `Illuminate\Contracts\Validation\DataAwareRule` / `ValidatorAwareRule` | `rustasea-validation::Rules` | **Partial** | Data-aware validation exists; aware-rule contracts folded into `Rules`. | | `Illuminate\Validation\Concerns\ValidatesAttributes` (trait) | `rustasea-validation::rules` | **Partial** | Core rules implemented; full Laravel rule catalogue not ported. | -| `Illuminate\Contracts\Session\Session` | `rustasea-auth::SessionPolicy` | **Partial** | Policy/hardening real; store-backed session pending. | +| `Illuminate\Contracts\Session\Session` | `rustasea-auth::SessionPolicy` | **Partial** | Policy/hardening real; store-backed sessions through `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`). | | `google/auth` (`Google\Auth\Credentials\ServiceAccountCredentials`) | `rustasea-google` (`ServiceAccount`, `GoogleAuthClient`, `AssertionClaims`, `AccessToken`) | **Adopted** | Service-account JSON parse/validate, RS256 JWT assertion, token exchange + cached `AccessToken` (single-flight, 80% lifetime refresh); `GoogleCredentials` block in `config/services.toml`, feature `google` (ADOPT-026). | ### Support / Console / Filesystem / Advanced @@ -277,10 +277,10 @@ The dominant pattern: **RustaSea already has the shape of most Laravel surfaces | 1 | **M0** Bootstrap & Core | Contextual bindings + provider DAG + auto-construction; populate provider/command registries | `Contracts\Container\ContextualBindingBuilder`, `SelfBuilding`, `Contracts\Foundation\Application` | | 2 | **M1** Routing & HTTP | Add URL generation + implicit binding (`route:list` introspection is live; idle timeout now enforced) | `Contracts\Routing\Registrar`, `UrlGenerator`, `UrlRoutable`, `Contracts\Http\Kernel` | | 3 | **M2** ORM & Database | Attribute casts; reflect live DB column types in `show:model` (source-level `show:model` introspection landed) | `CastsAttributes`, `Castable` | -| 4 | **M3** Auth, Middleware & Validation | General-purpose `Gate`; store-backed session guard; password broker/reset (runtime `#[authorize]` enforcement landed) | `Contracts\Auth\Access\Gate`, `Authorizable`, `StatefulGuard`, `PasswordBroker` | -| 5 | **M4** Queue, Cache, Scheduling & Events | Cache/queue factory depth; `ShouldBeUnique`; lock owner/force-release surface | `Contracts\Queue\Factory`, `ShouldBeUnique`, `Contracts\Cache\Lock` | +| 4 | **M3** Auth, Middleware & Validation | Database-backed password-reset token store; database user provider wiring in the scaffold templates (general-purpose `Gate`, the database session store, the database user provider, and runtime `#[authorize]` enforcement landed) | `Contracts\Auth\Access\Gate`, `Authorizable`, `StatefulGuard`, `PasswordBroker` | +| 5 | **M4** Queue, Cache, Scheduling & Events | Scheduler dispatch through the queue and shared pause state; after-response event flush; cache/queue factory depth; lock owner/force-release surface (`ShouldBeUnique` landed) | `Contracts\Queue\Factory`, `ShouldBeUnique`, `Contracts\Cache\Lock` | | 6 | **M5** DX, CLI & Testing | `make:middleware`/`make:request`, `artisan new`, real cycle detection; DB refresh test traits | `Contracts\Console\Kernel`, `Foundation\Testing\RefreshDatabase`, `WithFaker` | -| 7 | **M6** Advanced | Real AI adapters; pgvector index; template engine; encryption/translation/mail surfaces | `rustasea-ai` adapters; `Illuminate\Encryption`, `Translation`, `View`, `Mail` analogues | +| 7 | **M6** Advanced | An agent loop that calls an `AiProvider`; provider-native Gemini/Bedrock adapters; encryption surface (real HTTP AI adapters, the view/template engine, translation, and mail landed) | `rustasea-ai` adapters; `Illuminate\Encryption`, `Translation`, `View`, `Mail` analogues | > The ordering above mirrors the P0–P5 gap program in [`docs/milestones.md`](milestones.md): foundation unblockers first (M0–M2), then security/async correctness (M3–M4), then DX and advanced surfaces (M5–M6). diff --git a/docs/milestones.md b/docs/milestones.md index 0187110..e44cab5 100644 --- a/docs/milestones.md +++ b/docs/milestones.md @@ -44,9 +44,9 @@ section records the reason. | **M1** | Routing & HTTP | **Partial** | Router DSL + controller dispatch real (`crates/rustasea-router/src/dispatch.rs:23`, `:62`); `route:list` renders the live 6-column table published at boot via `RouteSource` (`crates/rustasea-cli/src/routes.rs:19`, `:33`; `crates/rustasea-app/src/bootstrap/app.rs:57`; `crates/rustasea-cli/src/commands/inspect.rs:44`); `show:model` now parses `app/models/{snake}.rs` with `syn` for source-level metadata (`crates/rustasea-cli/src/model_inspect.rs:123`, `:217`; `crates/rustasea-cli/src/commands/inspect.rs:129`) and the HTTP client idle (inter-chunk) timeout is now enforced for streamed bodies (`crates/rustasea-http/src/idle.rs:23`, wired in `crates/rustasea-http/src/lib.rs:448`) | | **M2** | ORM & Database | **Done** | Real sqlx pool + async execution (`crates/rustasea-orm/src/db.rs:24`, `db/exec.rs:72`); model CRUD (`model_ops.rs:28`), transactions (`tx.rs:67`), custom `Migrator` (`migration.rs:131`, `:189`), eager loading (`eager.rs:59`), pgvector (`vector.rs:100`); `raw`/`raw_sql` remain display-only fragments (`execution.rs:239`, `:247`) | | **M3** | Auth, Middleware & Validation | **Partial** | JWT/CSRF/throttle/validation real; session guard now real via `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`, `impl Guard` `:291`, login `:296`, parse `:352`, refresh `:380`, logout `:408`); declarative attributes are consumed at runtime through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:109`) and `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:135`); store-backed options are real: `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`) and `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`); remaining: scaffolded apps do not wire the database user provider yet (see section) | -| **M4** | Queue, Cache, Scheduling & Events | **Done** | Database/Redis queue drivers + worker + persistent failed jobs real (`crates/rustasea-queue/src/driver/database.rs:36`, `driver/worker.rs:75`); `queue:work`/`queue:failed`/`queue:retry` CLI real (`crates/rustasea-cli/src/commands/queue.rs:18`, `ops.rs:21`, `:72`); Redis cache store real behind the `redis` feature (`crates/rustasea-cache/src/redis.rs:155`); async listeners enqueue (`crates/rustasea-events/src/dispatcher.rs:82`); declarative job attributes bind through `JobPolicy` at registration (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`); failed `sync` dispatches persist to `failed_jobs` through the registered `database` connection (`crates/rustasea-queue/src/driver.rs:192`) | +| **M4** | Queue, Cache, Scheduling & Events | **Partial** | Database/Redis queue drivers + worker + persistent failed jobs real (`crates/rustasea-queue/src/driver/database.rs:36`, `driver/worker.rs:75`); `queue:work`/`queue:failed`/`queue:retry` CLI real (`crates/rustasea-cli/src/commands/queue.rs:18`, `ops.rs:21`, `:72`); Redis cache store real behind the `redis` feature (`crates/rustasea-cache/src/redis.rs:155`); async listeners enqueue (`crates/rustasea-events/src/dispatcher.rs:82`); declarative job attributes bind through `JobPolicy` at registration (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`); failed `sync` dispatches persist to `failed_jobs` through the registered `database` connection (`crates/rustasea-queue/src/driver.rs:192`); remaining: the scheduler cannot dispatch a due command (`crates/rustasea-schedule/src/scheduler.rs:146`), schedule pause state is per-process, and after-response events are never flushed (`crates/rustasea-events/src/dispatcher.rs:254`) | | **M5** | DX, CLI & Testing | **Partial** | CLI + 17 `make:*` generators real (canonical `enum Kind`: `crates/rustasea-cli/src/generators/mod.rs:19-54`; registrations `crates/rustasea-cli/src/commands/mod.rs:17-31`); `cargo rustasea new --variant` real (`crates/rustasea/src/bin/cargo-rustasea.rs:46`); real `xtask` cycle detection (`xtask/src/cycles.rs:32`) and `xtask migrate` (`xtask/src/main.rs:37`); testcontainers-backed `PostgresTestDb` (`crates/rustasea-testing/src/fixtures.rs:49`) with a Docker-gated suite (`crates/rustasea/tests/feature/`); remaining: integration tests are opt-in and generated controllers still need manual route registration (`crates/rustasea-cli/src/generators/kinds/controller.rs:35`) | -| **M6** | Advanced (Broadcast, Search, FS, AI) | **Partial** | Broadcast WS/SSE, `object_store` storage + `config/storage.toml` facade, JSON:API, `rustasea-mail`, `rustasea-view`/`rustasea-inertia`/`rustasea-livewire`/`rustasea-scaffold`, real AI HTTP providers (`crates/rustasea-ai/src/providers/mod.rs:27`), AI queueing (`crates/rustasea-ai/src/queue.rs:41`), MCP client (`crates/rustasea-ai/src/mcp/client.rs:40`), and feature-gated pgvector (`crates/rustasea-search/src/pgvector.rs:24`) all real; Gemini/Bedrock served through their OpenAI-compatible endpoints (`crates/rustasea-ai/src/providers/client.rs:225`, `:376`); remaining: provider-native Gemini/Bedrock APIs, and `InProcessProvider` kept for deterministic tests | +| **M6** | Advanced (Broadcast, Search, FS, AI) | **Partial** | Broadcast WS/SSE, `object_store` storage + `config/storage.toml` facade, JSON:API, `rustasea-mail`, `rustasea-view`/`rustasea-inertia`/`rustasea-livewire`/`rustasea-scaffold`, real AI HTTP providers (`crates/rustasea-ai/src/providers/mod.rs:27`), AI queueing (`crates/rustasea-ai/src/queue.rs:41`), MCP client (`crates/rustasea-ai/src/mcp/client.rs:40`), and feature-gated pgvector (`crates/rustasea-search/src/pgvector.rs:24`) all real; Gemini/Bedrock served through their OpenAI-compatible endpoints (`crates/rustasea-ai/src/providers/client.rs:225`, `:376`); remaining: the agent runtime does not call a provider (`crates/rustasea-ai/src/agent.rs:247`), provider-native Gemini/Bedrock APIs, and `InProcessProvider` kept for deterministic tests | --- @@ -74,6 +74,7 @@ database, cache, or queue bindings are installed in the container at boot. **Partial (reason)** - The runnable app's `AppServiceProvider` binds only environment-derived defaults (environment name, password policy, destructive-command guard) — `crates/rustasea-app/src/bootstrap/providers.rs:124`; `AuthServiceProvider` installs the session guard (`:173`). - The config loader is mounted at boot (`crates/rustasea-foundation/src/lib.rs:309`, read back through `Application::config` `:299`), but no database pool, cache manager, or queue driver is bound in the container; features that need a pool connect on their own (the queue dashboard, and the database user provider — `crates/rustasea-app/src/bootstrap/auth.rs:320`). +- `graceful` waits for `SIGTERM`/`SIGINT` but ignores its timeout argument (`crates/rustasea-foundation/src/shutdown.rs:6`); the only enforced drain is axum's graceful shutdown, which has no timeout. - The root `bootstrap/` directory is an uncompiled skeleton mirror; its `AppServiceProvider` is a no-op (`bootstrap/providers.rs:17`). The compiled bootstrap is `crates/rustasea-app/src/bootstrap/`. **Missing** @@ -111,6 +112,7 @@ reflected. **Partial (reason)** - `show:model` reports declared source metadata only; live DB column types/constraints are not queried (the console has no pool handle). +- Domain routes are ordered ahead of non-domain routes (`crates/rustasea-router/src/router.rs:397`) but the request `Host` is never matched: the first route on a method+path wins (`crates/rustasea-router/src/dispatch.rs:57`), so a domain route answers for every host and a catch-all on the same path is unreachable. **Missing** - Live database column introspection for `show:model` (source metadata is implemented). @@ -147,6 +149,7 @@ Tracked by `GAP-001`, `GAP-010`–`GAP-013`. **Partial (reason)** - `raw` / `raw_sql` emit statement fragments for display only — `crates/rustasea-orm/src/execution.rs:239`, `:247`. +- `insert_or_ignore_returning` returns SQL text that nothing executes (`crates/rustasea-orm/src/model.rs:425`); there is no `find` shorthand (use `query().where_key(id).first(pool)`); `OrmError::MissingTable` is never constructed (`crates/rustasea-orm/src/error.rs:41`); `make:migration` has no `--create` flag. **Missing** - Compile-time `query!` macros (intentionally excluded: CI has no `DATABASE_URL`). @@ -188,6 +191,9 @@ configured, and scaffolded apps do not wire the database user provider yet. - The default session store is in-memory (`MemoryStore`). `driver = "database"` in `config/session.toml` selects the persistent `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`), built by `SessionGuard::from_config_database` (`crates/rustasea-auth/src/session.rs:155`); the `redis` driver is rejected at load time. - The guard's default synchronous lookup is the fail-closed `StaticLookup` (`crates/rustasea-auth/src/session.rs:194`). The database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`) covers registration, login, password reset, verification, and profile updates over the `users` table; the runnable app installs it at boot when the default guard's provider is ORM-backed and the table exists (`crates/rustasea-app/src/bootstrap/auth.rs:320`, called from `crates/rustasea-app/src/main.rs:32`). - `DatabaseUserProvider` is exercised on SQLite only (`crates/rustasea-auth/tests/database_user_provider.rs`); it has not been run against Postgres or MySQL. +- `JwtGuard::logout` is a no-op with no revocation or deny-list (`crates/rustasea-auth/src/jwt.rs:270`). +- The `in:` / `in_array:` rule parses each list item as JSON and drops what does not parse (`crates/rustasea-validation/src/rules/support.rs:134`), so a bare-word list such as `in:admin,editor` yields an empty allow-list and rejects every value; numbers and quoted strings work. +- The deserialization allow-list (`SessionPolicy::allow`) is defined but not called; `cache.serializable_classes` is parsed and unused (`crates/rustasea-cache/src/config.rs:191`). **Missing** - Database user provider wiring in the scaffold templates (`crates/rustasea-scaffold/src/templates/`), so generated apps get it without hand-wiring. @@ -206,13 +212,15 @@ configured, and scaffolded apps do not wire the database user provider yet. **Goal recap:** Async workloads, caching, scheduling, and event dispatch with observable queue metrics. -**Status: Done** — in-memory cache, the sync queue driver, inline events, and +**Status: Partial** — in-memory cache, the sync queue driver, inline events, and the scheduler exist; the gap-closure program added real `database`/`redis` queue drivers with a worker loop, persistent failed jobs, `queue:work`/ `queue:failed`/`queue:retry` CLI, a real feature-gated Redis cache store, queue-backed async listeners, and a runtime consumer for the declarative job attributes. A failed inline `sync` dispatch is persisted through the `database` -connection when one is registered. +connection when one is registered. Remaining: the scheduler cannot run a due +command, its pause state is not shared across processes, and events buffered by +`dispatchAfterResponse` are never delivered. **Done** - In-memory cache store (lock-guarded map; no `moka` dependency) — `crates/rustasea-cache/src/memory.rs:35`. @@ -229,15 +237,24 @@ connection when one is registered. - Broadcast fan-out (ADOPT-022): Pusher HTTP driver (HMAC-SHA256 request signing + MD5 body digest, `pusher`/`private-`/`presence-` channel auth) and a Redis Pub/Sub driver for cross-process fan-out behind the `pusher`/`redis` features (`crates/rustasea-broadcast/src/`, `crates/rustasea-app/src/routes/broadcasting.rs`). **Partial (reason)** -- None. Note: a failed `sync` dispatch is written to the `failed_jobs` table only when a `database` connection is registered (`dead_letter_sync`, `crates/rustasea-queue/src/driver.rs:192`; callers `crates/rustasea-queue/src/registry.rs:150`, `:186`). Without one, or when the insert fails, it falls back to the process-local list (`crates/rustasea-queue/src/driver.rs:174`), which does not survive the process. +- The scheduler cannot dispatch: `dispatch_command` returns `ScheduleError::Dispatch` for every due command because no queue dispatch path is wired (`crates/rustasea-schedule/src/scheduler.rs:146`), so a tick with a due command fails. `schedule:run` runs one tick and exits (`crates/rustasea-cli/src/commands/ops.rs:253`); the 60-second `tick_interval` (`crates/rustasea-schedule/src/scheduler.rs:168`) has no caller. +- Schedule pause state is a process-local `RwLock` (`crates/rustasea-schedule/src/pause.rs:28`), not stored in the cache or database, so `schedule:pause` in one process does not reach another. `on_one_server` records a flag and a `lock_key` (`crates/rustasea-schedule/src/command.rs:46`) but no lock is taken. +- `dispatchAfterResponse` only buffers into `EventSink` (`crates/rustasea-events/src/dispatcher.rs:254`); no non-test code drains it, so listeners for after-response events never run. `Dispatcher::dispatch` returns `EventError::Unhandled` when an event has no listener (`:244`), which also makes `schedule:pause` / `schedule:resume` report an error when nothing listens for `SchedulePaused` / `ScheduleResumed`. +- `Queue::chain` runs its jobs inline on the caller's task and never goes through a routed driver (`crates/rustasea-queue/src/registry.rs:175`). +- A failed `sync` dispatch is written to the `failed_jobs` table only when a `database` connection is registered (`dead_letter_sync`, `crates/rustasea-queue/src/driver.rs:192`; callers `crates/rustasea-queue/src/registry.rs:150`, `:186`). Without one, or when the insert fails, it falls back to the process-local list (`crates/rustasea-queue/src/driver.rs:174`), which does not survive the process. +- `JobAttempted` and `QueueBusy` are defined (`crates/rustasea-events/src/event.rs:32`, `:51`) but nothing emits them. **Missing** -- None. +- A queue dispatch path for due scheduled commands, and a long-running `schedule:run` loop. +- Shared (cache or database) schedule pause state and an `onOneServer` lock. +- A flush of the after-response event buffer from the HTTP layer. **Evidence:** `crates/rustasea-cache/src/{memory,redis}.rs`; `crates/rustasea-queue/src/driver.rs:115-197`; `crates/rustasea-queue/src/driver/{database,redis,worker}.rs`; `crates/rustasea-queue/src/policy.rs:21-55`; `crates/rustasea-queue/src/migrations.rs`; `crates/rustasea-events/src/dispatcher.rs:82-182`; `crates/rustasea-schedule/src/lib.rs:20`; `crates/rustasea-queue-dashboard/`; `crates/rustasea-broadcast/`; tasks `GAP-004`–`GAP-009`, `ADOPT-021`, `ADOPT-022`. **Next actions** -- None. +- Wire scheduled commands to the queue and run the scheduler tick on an interval. +- Persist schedule pause state and take the `onOneServer` lock through the cache `Lock`. +- Drain `EventSink` after the response is sent. --- @@ -310,8 +327,9 @@ TOML config facade, JSON:API, the mail crate, the presentation crates (view/Inertia/Livewire/scaffold), real HTTP-backed AI providers, AI queueing, and MCP are all real. Gemini and Bedrock are served through their OpenAI-compatible endpoints and provider-backed embeddings send a dedicated embedding model. -Remaining: the provider-native Gemini/Bedrock APIs are not implemented, and the -in-process AI provider is kept for tests. +Remaining: the agent runtime echoes the prompt instead of calling a provider, +the provider-native Gemini/Bedrock APIs are not implemented, and the in-process +AI provider is kept for tests. **Done** - Broadcasting: WebSocket (`axum/ws`, feature-gated default) + SSE + `ShouldBroadcast` — `crates/rustasea-broadcast/Cargo.toml:20`, `:22`; `crates/rustasea-broadcast/src/lib.rs:35`. @@ -339,13 +357,17 @@ in-process AI provider is kept for tests. - Gemini and Bedrock resolve to their OpenAI-compatible endpoints only (`crates/rustasea-ai/src/providers/client.rs:225`, `bedrock_from_env` `:376`): chat completions, streaming, and embeddings in the OpenAI wire format, with `GEMINI_API_KEY` / a Bedrock API key (`AWS_BEARER_TOKEN_BEDROCK`). The provider-native APIs (Gemini `generateContent`, Bedrock Converse with SigV4) are not implemented. Neither provider has been called against the live service from this repository. - Provider-backed embeddings are real: `StrToEmbeddings` (`crates/rustasea-ai/src/embed.rs:18`) calls `AiProvider::embeddings`, and the HTTP adapter sends the configured embedding model (`crates/rustasea-ai/src/providers/client.rs:246`, `:313`; `crates/rustasea-ai/src/providers/openai.rs:155`). The engine-agnostic `Str::to_embeddings` in `rustasea-search` still falls back to a deterministic hashing stub when its closure yields no vector (`crates/rustasea-search/src/embeddings.rs:97`). - `InProcessProvider` remains for deterministic tests — `crates/rustasea-ai/src/adapters.rs:50`. +- The agent runtime does not call a model: `Agent::run_inner` echoes the prompt and runs a tool only when the prompt literally contains `tool:name(args)` (`crates/rustasea-ai/src/agent.rs:247`), so `Agent::run`, `prompt_stream`, and the queued `AgentRunJob` never reach an `AiProvider` even though the HTTP providers are real. `provider_from_env` returns a boxed provider that `Ai::register` cannot take directly. +- Image, audio, rerank, and files exist only on the in-process stand-in; the HTTP adapters cover text, streaming, and (OpenAI-style only) embeddings. `AiProvider` has no `vector_stores` method. **Missing** - Provider-native Gemini and Bedrock adapters. +- An agent loop that sends the prompt and tool results to an `AiProvider`. **Evidence:** `crates/rustasea-broadcast/{Cargo.toml,src/lib.rs}`; `crates/rustasea-storage/{Cargo.toml,src/manager.rs:56-171,src/facade.rs}`; `config/storage.toml`; `crates/rustasea-jsonapi/src/wire.rs:7`; `crates/rustasea-mail/`; `crates/rustasea-view/`; `crates/rustasea-ai/src/{providers,queue.rs,mcp,adapters.rs}`; `crates/rustasea-search/{src/pgvector.rs,src/embeddings.rs}`; `crates/rustasea-google/`; `crates/rustasea-config/src/services.rs`; `crates/rustasea-i18n/`; `crates/rustasea-timezone/`; tasks `GAP-012`, `GAP-014`, `GAP-015`, `GAP-020`, `ADOPT-005`, `ADOPT-006`, `ADOPT-026`. **Next actions** +- Drive `Agent` through an `AiProvider` (prompt, tool calls, streaming). - Add provider-native Gemini/Bedrock adapters where the OpenAI-compatible surface is not enough. --- From e6eb62f2eaffee881e0c42ae15c1bad71074b7ae Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:41:57 +0700 Subject: [PATCH 12/14] docs: set as-built status on the planning documents The roadmap, sprint index, and sprint headers carry the as-built milestone status with a pointer to docs/milestones.md. The 110 implementation-task rows under application/modules were all still Todo; each was checked against the source tree (55 done, 53 partial, 2 not started) and every open row lists what is missing. Plan text is unchanged. --- .../modules/async-workloads/cache.md | 14 +++++++++---- .../modules/async-workloads/events.md | 14 +++++++++---- .../modules/async-workloads/queue.md | 16 +++++++++----- .../modules/async-workloads/schedule.md | 18 +++++++++++----- .../modules/data-orm/migrations.md | 14 +++++++++---- .../modules/data-orm/model-relations.md | 15 +++++++++---- .../modules/data-orm/query-builder.md | 17 ++++++++++----- .../application/modules/data-orm/vector.md | 13 ++++++++---- .../modules/developer-platform/cli.md | 15 +++++++++---- .../modules/developer-platform/generators.md | 19 +++++++++++------ .../developer-platform/testing-harness.md | 14 +++++++++---- .../application/modules/foundation/boot.md | 17 ++++++++++----- .../application/modules/foundation/config.md | 15 +++++++++---- .../modules/foundation/container.md | 12 ++++++++--- .../modules/http-routing/http-client.md | 13 ++++++++---- .../modules/http-routing/middleware.md | 14 +++++++++---- .../modules/http-routing/routing.md | 17 ++++++++++----- .../modules/identity-access/auth.md | 13 ++++++++---- .../modules/identity-access/csrf.md | 11 +++++++--- .../modules/identity-access/validation.md | 16 +++++++++----- .../intelligence-delivery/ai-agents.md | 21 ++++++++++++------- .../modules/intelligence-delivery/ai-sdk.md | 16 ++++++++++---- .../intelligence-delivery/broadcast.md | 13 ++++++++---- .../modules/intelligence-delivery/jsonapi.md | 11 +++++++--- .../modules/intelligence-delivery/storage.md | 13 ++++++++---- .agents/documents/tasks/roadmap.md | 18 +++++++++------- .agents/documents/tasks/sprints/manifest.md | 16 +++++++------- .agents/documents/tasks/sprints/sprint-01.md | 3 ++- .agents/documents/tasks/sprints/sprint-02.md | 3 ++- .agents/documents/tasks/sprints/sprint-03.md | 3 ++- .agents/documents/tasks/sprints/sprint-04.md | 3 ++- .agents/documents/tasks/sprints/sprint-05.md | 3 ++- .agents/documents/tasks/sprints/sprint-06.md | 2 +- .agents/documents/tasks/sprints/sprint-07.md | 2 +- 34 files changed, 294 insertions(+), 130 deletions(-) diff --git a/.agents/documents/application/modules/async-workloads/cache.md b/.agents/documents/application/modules/async-workloads/cache.md index b1c9c6a..edfd273 100644 --- a/.agents/documents/application/modules/async-workloads/cache.md +++ b/.agents/documents/application/modules/async-workloads/cache.md @@ -101,10 +101,16 @@ enum CacheError { StoreUnavailable, LockAlreadyHeld, TouchFailed } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M4-CACHE-01 | Store | Todo | `Store` + `Repository` + moka + redis | -| F-M4-CACHE-02 | touch | Todo | `EXPIRE`/TTL reset without value fetch → `bool` | -| F-M4-CACHE-03 | Lock | Todo | `SET NX EX` + `block` retries + lease expiry | -| F-M4-CACHE-04 | Tests | Todo | touch extends/missing `false`, Lock contention, store isolation | +| F-M4-CACHE-01 | Store | Partial | `Store` + `Repository` + moka + redis | +| F-M4-CACHE-02 | touch | Done | `EXPIRE`/TTL reset without value fetch → `bool` | +| F-M4-CACHE-03 | Lock | Done | `SET NX EX` + `block` retries + lease expiry | +| F-M4-CACHE-04 | Tests | Partial | touch extends/missing `false`, Lock contention, store isolation | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M4-CACHE-01` — `Store`, `Repository`, and `CacheManager` are real; the memory store is a lock-guarded map, not `moka` (`crates/rustasea-cache/src/memory.rs:35`), and the Redis store works only behind the non-default `redis` feature. +> - `F-M4-CACHE-04` — the touch and lock-contention tests exist but are `#[ignore]`d and need the `redis` feature plus a live Redis (`crates/rustasea-cache/src/redis/tests.rs`); there are no memory-store touch or lock tests and no store-isolation test. ## 10. Cross-References - API: [api-cache](../../api/async-workloads/api-cache.md) diff --git a/.agents/documents/application/modules/async-workloads/events.md b/.agents/documents/application/modules/async-workloads/events.md index b55f011..5351ee9 100644 --- a/.agents/documents/application/modules/async-workloads/events.md +++ b/.agents/documents/application/modules/async-workloads/events.md @@ -97,10 +97,16 @@ struct UserCreated { id: u64 } // example app-level | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M4-EVT-01 | Event/Listener | Todo | `Event`+`Listener` traits + `QUEUE` | -| F-M4-EVT-02 | Dispatcher | Todo | `dispatch` + `dispatchAfterResponse` buffered flush | -| F-M4-EVT-03 | Renames | Todo | `JobAttempted{exception}`/`QueueBusy{connectionName}` | -| F-M4-EVT-04 | Tests | Todo | async listener→Job, after-response spy, field names | +| F-M4-EVT-01 | Event/Listener | Done | `Event`+`Listener` traits + `QUEUE` | +| F-M4-EVT-02 | Dispatcher | Partial | `dispatch` + `dispatchAfterResponse` buffered flush | +| F-M4-EVT-03 | Renames | Done | `JobAttempted{exception}`/`QueueBusy{connectionName}` | +| F-M4-EVT-04 | Tests | Partial | async listener→Job, after-response spy, field names | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M4-EVT-02` — `dispatch` is real; `dispatch_after_response` only pushes into `EventSink` and no non-test code drains it, so after-response listeners never run (`crates/rustasea-events/src/dispatcher.rs:254`). +> - `F-M4-EVT-04` — the async listener → job → worker path is tested (`crates/rustasea-events/tests/queued_listener.rs`); there is no after-response spy test and no field-name test for `JobAttempted`/`QueueBusy`. ## 10. Cross-References - API: [api-events-schedule](../../api/async-workloads/api-events-schedule.md) — events section diff --git a/.agents/documents/application/modules/async-workloads/queue.md b/.agents/documents/application/modules/async-workloads/queue.md index 0c211ae..d7a5189 100644 --- a/.agents/documents/application/modules/async-workloads/queue.md +++ b/.agents/documents/application/modules/async-workloads/queue.md @@ -132,11 +132,17 @@ enum QueueError { DuplicateRoute{ type_name: &'static str }, UnknownConnection, | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M4-Q-01 | Job trait | Todo | `Job` + `#[tries]`/`#[backoff]`/`#[timeout]` | -| F-M4-Q-02 | Queue::route | Todo | `OnceLock` registry + `DuplicateRoute` | -| F-M4-Q-03 | Drivers | Todo | `sync`/`database`/`redis` BRPOP + `dispatch`/`chain`/`batch` | -| F-M4-Q-04 | failed_jobs | Todo | dead-letter + `queue:failed`/`retry` | -| F-M4-Q-05 | Tests | Todo | chain stop, batch BatchId, duplicate route, retry backoff | +| F-M4-Q-01 | Job trait | Done | `Job` + `#[tries]`/`#[backoff]`/`#[timeout]` | +| F-M4-Q-02 | Queue::route | Done | `OnceLock` registry + `DuplicateRoute` | +| F-M4-Q-03 | Drivers | Partial | `sync`/`database`/`redis` BRPOP + `dispatch`/`chain`/`batch` | +| F-M4-Q-04 | failed_jobs | Done | dead-letter + `queue:failed`/`retry` | +| F-M4-Q-05 | Tests | Partial | chain stop, batch BatchId, duplicate route, retry backoff | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M4-Q-03` — sync, database, and Redis drivers plus `dispatch` and `batch` are real (Redis behind the non-default `redis` feature); `Queue::chain` runs its jobs inline on the caller's task and never goes through a routed driver (`crates/rustasea-queue/src/registry.rs:175`). +> - `F-M4-Q-05` — retry backoff and the batch lifecycle are tested (`crates/rustasea-queue/tests/job_policy.rs`, `job_batches.rs`); there is no chain-stop test, no duplicate-route test, and no test of the `BatchId` returned by `Queue::batch`. ## 10. Cross-References - API: [api-queue](../../api/async-workloads/api-queue.md) diff --git a/.agents/documents/application/modules/async-workloads/schedule.md b/.agents/documents/application/modules/async-workloads/schedule.md index 574b900..3e8be8f 100644 --- a/.agents/documents/application/modules/async-workloads/schedule.md +++ b/.agents/documents/application/modules/async-workloads/schedule.md @@ -116,11 +116,19 @@ impl QueueRegistry { | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M4-SCH-01 | Schedule builder | Todo | `daily`/`cron`/`everyMinute`/`skipIfStillRunning`/`onOneServer` | -| F-M4-SCH-02 | Ticker | Todo | `schedule:run` 60s tick + `schedule:list` | -| F-M4-SCH-03 | Pause/Resume | Todo | flat cache/DB + `SchedulePaused`/`Resumed` events | -| F-M4-SCH-04 | Metrics | Todo | 4 metrics via `Queue` trait | -| F-M4-SCH-05 | Tests | Todo | pause→resume+skip+onOneServer+mid-exec+metrics | +| F-M4-SCH-01 | Schedule builder | Partial | `daily`/`cron`/`everyMinute`/`skipIfStillRunning`/`onOneServer` | +| F-M4-SCH-02 | Ticker | Partial | `schedule:run` 60s tick + `schedule:list` | +| F-M4-SCH-03 | Pause/Resume | Partial | flat cache/DB + `SchedulePaused`/`Resumed` events | +| F-M4-SCH-04 | Metrics | Done | 4 metrics via `Queue` trait | +| F-M4-SCH-05 | Tests | Partial | pause→resume+skip+onOneServer+mid-exec+metrics | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M4-SCH-01` — `daily`, `cron`, `every_minute`, and `skip_if_still_running` are real; `on_one_server` only sets a flag — its `lock_key` is computed but never read, so no distributed lock is taken (`crates/rustasea-schedule/src/command.rs:46`). +> - `F-M4-SCH-02` — `schedule:run` and `schedule:list` exist, but `schedule:run` runs one tick and exits (no 60s loop; `tick_interval` has no caller), and a due command cannot run: `dispatch_command` always returns `ScheduleError::Dispatch` because no queue dispatch path is wired (`crates/rustasea-schedule/src/scheduler.rs:146`). +> - `F-M4-SCH-03` — pause/resume flip a process-local `RwLock` and emit `SchedulePaused`/`ScheduleResumed`; the state is not stored in the cache or database (`crates/rustasea-schedule/src/pause.rs:28`), so a pause in one process does not reach another, and the emit fails with `Unhandled` when no listener is registered. +> - `F-M4-SCH-05` — only the queue metrics and schedule timezone handling are tested; there are no pause→resume, skip-if-running, onOneServer, or mid-execution tests. ## 10. Cross-References - API: [api-events-schedule](../../api/async-workloads/api-events-schedule.md) — schedule section diff --git a/.agents/documents/application/modules/data-orm/migrations.md b/.agents/documents/application/modules/data-orm/migrations.md index 9ef528a..6f03c01 100644 --- a/.agents/documents/application/modules/data-orm/migrations.md +++ b/.agents/documents/application/modules/data-orm/migrations.md @@ -94,10 +94,16 @@ enum MigrationError { AlreadyApplied, Irreversible { name: String }, ExtensionMi | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M2-MIG-01 | Migration scaffold | Todo | `make:migration --create` + versioned filename + up/down | -| F-M2-MIG-02 | migrate CLI | Todo | `migrate` idempotent + `migrate:fresh --seed` | -| F-M2-MIG-03 | Seeder/Factory | Todo | `Seeder::run` + `Factory` sequence + `state` + `Str` reset | -| F-M2-MIG-04 | Tests | Todo | migration exists, factory reset, MissingTable | +| F-M2-MIG-01 | Migration scaffold | Partial | `make:migration --create` + versioned filename + up/down | +| F-M2-MIG-02 | migrate CLI | Done | `migrate` idempotent + `migrate:fresh --seed` | +| F-M2-MIG-03 | Seeder/Factory | Done | `Seeder::run` + `Factory` sequence + `state` + `Str` reset | +| F-M2-MIG-04 | Tests | Partial | migration exists, factory reset, MissingTable | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M2-MIG-01` — versioned filenames and `up` / `down` are real (`crates/rustasea-cli/src/generators/kinds/migration.rs:62`); there is no `--create=` flag — the table is guessed from a `create_X_table` name and the template always emits `CREATE TABLE`. +> - `F-M2-MIG-04` — the generator output, the migration round trip, and the factory reset are tested; there is no missing-table test, and `OrmError::MissingTable` is never constructed outside tests (`crates/rustasea-orm/src/error.rs:41`). ## 10. Cross-References - API: [api-query-builder](../../api/data-orm/api-query-builder.md) — migration CLI adjacency diff --git a/.agents/documents/application/modules/data-orm/model-relations.md b/.agents/documents/application/modules/data-orm/model-relations.md index 99d51b6..53a6553 100644 --- a/.agents/documents/application/modules/data-orm/model-relations.md +++ b/.agents/documents/application/modules/data-orm/model-relations.md @@ -106,10 +106,17 @@ enum ModelError { MissingPrimaryKey, RelationNotFound { name: String } } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M2-MOD-01 | Derive macro | Todo | `id`/`timestamps`/`soft_delete`/table name/relations/serde | -| F-M2-MOD-02 | HasMany/BelongsTo | Todo | `with("posts")` eager load + `relation_loaded` | -| F-M2-MOD-03 | Soft delete | Todo | `deleted_at` partial index + `find(1)` without `withTrashed` → `None` | -| F-M2-MOD-04 | Tests | Todo | CRUD + serde round-trip (0/1/5) + depth cap | +| F-M2-MOD-01 | Derive macro | Partial | `id`/`timestamps`/`soft_delete`/table name/relations/serde | +| F-M2-MOD-02 | HasMany/BelongsTo | Done | `with("posts")` eager load + `relation_loaded` | +| F-M2-MOD-03 | Soft delete | Partial | `deleted_at` partial index + `find(1)` without `withTrashed` → `None` | +| F-M2-MOD-04 | Tests | Partial | CRUD + serde round-trip (0/1/5) + depth cap | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M2-MOD-01` — `#[derive(Model)]` handles the id, timestamps, soft deletes, and the table name (`crates/rustasea-macros/src/model.rs:178`); it cannot declare relations (a derived model has an empty `relations()` and callers pass `with_relations(...)` per query) and emits nothing for serde. +> - `F-M2-MOD-03` — the soft-delete global scope hides trashed rows (`crates/rustasea-orm/src/scopes.rs:72`); there is no `deleted_at` partial index (the schema builder has no partial-index DDL) and no `find` method. +> - `F-M2-MOD-04` — CRUD, soft delete, the depth cap, and a serde round trip with two related rows are tested; the 0/1/5 round-trip cases are not. ## 10. Cross-References - Design: `architecture.md BC-2` · `domain.md BC-2` · `tdd.md BC-2` · `database.md §2 (users/posts)` diff --git a/.agents/documents/application/modules/data-orm/query-builder.md b/.agents/documents/application/modules/data-orm/query-builder.md index 718a98d..50c3e21 100644 --- a/.agents/documents/application/modules/data-orm/query-builder.md +++ b/.agents/documents/application/modules/data-orm/query-builder.md @@ -117,11 +117,18 @@ struct UpsertResult { inserted: usize, updated: usize } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M2-BLD-01 | Builder core | Todo | `where`/`orWhere`/`find`/`firstOrFail`/`paginate` | -| F-M2-BLD-02 | Additions | Todo | `chunkBy`/`insertOrIgnoreReturning`/`saveOrIgnore`/`refreshForUpdate`/`StraightJoin` | -| F-M2-BLD-03 | Upsert/Delete | Todo | strict `uniqueBy` + MySQL DELETE JOIN | -| F-M2-BLD-04 | Locks/Tx | Todo | `forUpdate`/`sharedLock` + `db.transaction` | -| F-M2-BLD-05 | Tests | Todo | chunk 10k, upsert empty, MySQL delete join snapshot | +| F-M2-BLD-01 | Builder core | Partial | `where`/`orWhere`/`find`/`firstOrFail`/`paginate` | +| F-M2-BLD-02 | Additions | Partial | `chunkBy`/`insertOrIgnoreReturning`/`saveOrIgnore`/`refreshForUpdate`/`StraightJoin` | +| F-M2-BLD-03 | Upsert/Delete | Done | strict `uniqueBy` + MySQL DELETE JOIN | +| F-M2-BLD-04 | Locks/Tx | Done | `forUpdate`/`sharedLock` + `db.transaction` | +| F-M2-BLD-05 | Tests | Partial | chunk 10k, upsert empty, MySQL delete join snapshot | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M2-BLD-01` — `where_eq` / `or_where_eq` / `where_op`, `first_or_fail`, and `paginate` are real; there is no `find` method — the equivalent is `Model::query().where_key(id).first(pool)`. +> - `F-M2-BLD-02` — `chunk_by` and `refresh_for_update` run queries; `insert_or_ignore_returning` and `save_or_ignore_sql` only return SQL text that nothing executes (`crates/rustasea-orm/src/model.rs:425`), and `straight_join` depends on the compile-time dialect, not the live pool. +> - `F-M2-BLD-05` — the empty `uniqueBy` case is tested; the 10k test covers the window helper rather than the query-running `chunk_by`, and there is no MySQL `DELETE JOIN` snapshot test (`delete_join_sql` is called by no test). ## 10. Cross-References - API: [api-query-builder](../../api/data-orm/api-query-builder.md) diff --git a/.agents/documents/application/modules/data-orm/vector.md b/.agents/documents/application/modules/data-orm/vector.md index 06da449..a600e76 100644 --- a/.agents/documents/application/modules/data-orm/vector.md +++ b/.agents/documents/application/modules/data-orm/vector.md @@ -98,10 +98,15 @@ enum VectorError { ExtensionMissing { extension: &'static str, hint: String }, V | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M2-VEC-01 | Blueprint | Todo | `vector(n)` + `dropVectorIndex` DDL | -| F-M2-VEC-02 | Builder | Todo | `whereVectorSimilarTo` dispatch + dimension guard | -| F-M2-VEC-03 | Migration guard | Todo | `has_extension("vector")` → typed error | -| F-M2-VEC-04 | Tests | Todo | nearest-10, extension missing, dim mismatch | +| F-M2-VEC-01 | Blueprint | Done | `vector(n)` + `dropVectorIndex` DDL | +| F-M2-VEC-02 | Builder | Done | `whereVectorSimilarTo` dispatch + dimension guard | +| F-M2-VEC-03 | Migration guard | Done | `has_extension("vector")` → typed error | +| F-M2-VEC-04 | Tests | Partial | nearest-10, extension missing, dim mismatch | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M2-VEC-04` — nearest-10 is checked as SQL text only (`crates/rustasea-orm/tests/vector.rs`); the live round trip uses k=2 and is skipped without `DATABASE_URL` + pgvector; the missing-extension case runs through SQLite, not a Postgres without pgvector. ## 10. Cross-References - API: [api-query-builder](../../api/data-orm/api-query-builder.md) — vector section diff --git a/.agents/documents/application/modules/developer-platform/cli.md b/.agents/documents/application/modules/developer-platform/cli.md index 1bdb31f..98ee4c2 100644 --- a/.agents/documents/application/modules/developer-platform/cli.md +++ b/.agents/documents/application/modules/developer-platform/cli.md @@ -90,10 +90,17 @@ trait Shutdownable { async fn shutdown(&self, handle: ShutdownHandle) -> Result< | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M5-CLI-01 | CLI registry | Todo | `clap` derive + `list` + `#[usage]`/`#[help]`/`#[hidden]` | -| F-M5-CLI-02 | Prompts | Todo | `ask`/`secret`/`confirm`/`choice`/`multiSelect` + table/spinner | -| F-M5-CLI-03 | Artisan::call | Todo | in-process dispatch + `Shutdownable` | -| F-M5-CLI-04 | Tests | Todo | `list --json` entries, usage help, confirm abort, `did you mean?` | +| F-M5-CLI-01 | CLI registry | Partial | `clap` derive + `list` + `#[usage]`/`#[help]`/`#[hidden]` | +| F-M5-CLI-02 | Prompts | Done | `ask`/`secret`/`confirm`/`choice`/`multiSelect` + table/spinner | +| F-M5-CLI-03 | Artisan::call | Partial | in-process dispatch + `Shutdownable` | +| F-M5-CLI-04 | Tests | Partial | `list --json` entries, usage help, confirm abort, `did you mean?` | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M5-CLI-01` — the clap-derive CLI, the registry, and `list` are real; `list` reads usage/help/hidden from the `Command` trait methods (`crates/rustasea-cli/src/artisan.rs:71`), and the `#[usage]` / `#[help]` / `#[hidden]` attribute macros emit constants the registry never reads. +> - `F-M5-CLI-03` — `Artisan::call` dispatches in-process (`crates/rustasea-cli/src/artisan.rs:107`); `Shutdownable` has no implementation outside tests and `queue:work` does not use it or `drain_with_timeout`. +> - `F-M5-CLI-04` — "did you mean?" and hidden filtering are tested; no test runs `list --json` and checks the entries, none covers usage/help output, and none covers aborting on `confirm`. ## 10. Cross-References - API: [api-cli](../../api/developer-platform/api-cli.md) diff --git a/.agents/documents/application/modules/developer-platform/generators.md b/.agents/documents/application/modules/developer-platform/generators.md index 119e895..5ada14a 100644 --- a/.agents/documents/application/modules/developer-platform/generators.md +++ b/.agents/documents/application/modules/developer-platform/generators.md @@ -94,12 +94,19 @@ enum GeneratorError { AlreadyExists { path: String } } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M5-GEN-01 | make:crud | Todo | controller/model (+ `-m` migration) + `--force` | -| F-M5-GEN-02 | make:async | Todo | job/event/listener/observer/test/seeder | -| F-M5-GEN-03 | make:ai | Todo | agent/tool (M6 adjacency) | -| F-M5-GEN-04 | Attributes | Todo | `#[tries]`/`#[backoff]`/`#[timeout]`/… attrs | -| F-M5-GEN-05 | Lint | Todo | `rustfmt`+`clippy -D warnings` gate (C-04) | -| F-M5-GEN-06 | Tests | Todo | controller lint, model -m both artifacts, AlreadyExists, outline | +| F-M5-GEN-01 | make:crud | Done | controller/model (+ `-m` migration) + `--force` | +| F-M5-GEN-02 | make:async | Done | job/event/listener/observer/test/seeder | +| F-M5-GEN-03 | make:ai | Done | agent/tool (M6 adjacency) | +| F-M5-GEN-04 | Attributes | Partial | `#[tries]`/`#[backoff]`/`#[timeout]`/… attrs | +| F-M5-GEN-05 | Lint | Partial | `rustfmt`+`clippy -D warnings` gate (C-04) | +| F-M5-GEN-06 | Tests | Partial | controller lint, model -m both artifacts, AlreadyExists, outline | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M5-GEN-04` — every attribute exists as a proc-macro (snake_case names, e.g. `#[fail_on_timeout]`) but each only emits a `__RUSTASEA_*` constant; only tries/backoff/timeout have a runtime reader, and the app binds them by hand through `register_job_with_policy` (`crates/rustasea-queue/src/driver/worker.rs:68`). Nothing reads the fail-on-timeout, without-broadcasting, repair-tool-calls, usage, help, hidden, queue, or connection constants. +> - `F-M5-GEN-05` — the `fmt --check` + `clippy -D warnings` gate runs on the framework workspace (`cargo xtask ci`); nothing runs rustfmt or clippy on `make:*` output — only `make:module` output gets a real `cargo check` (`crates/rustasea-cli/tests/module_compiles.rs`). +> - `F-M5-GEN-06` — model `-m` writing both artifacts and a loop over every kind are tested (`crates/rustasea-cli/tests/make_generators/`); there is no lint test for controller output, and the already-exists test asserts only `is_err()`, not the `AlreadyExists` variant. ## 10. Cross-References - API: [api-cli](../../api/developer-platform/api-cli.md) — generators table diff --git a/.agents/documents/application/modules/developer-platform/testing-harness.md b/.agents/documents/application/modules/developer-platform/testing-harness.md index 4e166b9..ef9498d 100644 --- a/.agents/documents/application/modules/developer-platform/testing-harness.md +++ b/.agents/documents/application/modules/developer-platform/testing-harness.md @@ -87,10 +87,16 @@ enum TestError { ContainerTimeout, PaginatorMissing } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M5-HARN-01 | TestCase | Todo | `testcontainers` random port + migrate once per binary + teardown | -| F-M5-HARN-02 | Str reset | Todo | `Factory` sequence reset via hook + `state` sub-factory | -| F-M5-HARN-03 | Paginator | Todo | `bootstrap-3` view for `paginate(15)` | -| F-M5-HARN-04 | Tests | Todo | distinct ports parallel, Str reset, teardown clean | +| F-M5-HARN-01 | TestCase | Done | `testcontainers` random port + migrate once per binary + teardown | +| F-M5-HARN-02 | Str reset | Partial | `Factory` sequence reset via hook + `state` sub-factory | +| F-M5-HARN-03 | Paginator | Done | `bootstrap-3` view for `paginate(15)` | +| F-M5-HARN-04 | Tests | Partial | distinct ports parallel, Str reset, teardown clean | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M5-HARN-02` — the test hook resets only the testing crate's `StrFactory` sequences (`crates/rustasea-testing/src/test_case.rs:81`); the ORM `SequenceFactory`, which is the one with `state`, keeps its own counter outside that registry and needs a manual `reset()`. +> - `F-M5-HARN-04` — the `Str` reset is tested; no test checks that parallel runs get distinct ports, and teardown appears only in Docker-backed `#[ignore]`d tests with no assertion that the container is gone. ## 10. Cross-References - Tests: [test-cli](../../testing/developer-platform/test-cli.md) · BDD `@testing` · `testing/stubs/harness.stub.rs` diff --git a/.agents/documents/application/modules/foundation/boot.md b/.agents/documents/application/modules/foundation/boot.md index 8736b01..9e93774 100644 --- a/.agents/documents/application/modules/foundation/boot.md +++ b/.agents/documents/application/modules/foundation/boot.md @@ -120,12 +120,19 @@ CLI scaffold output tree (see `architecture.md §2` skeleton). No browser UI. | Task ID | Component | Status | Description | |---------|-----------|--------|-------------| -| F-M0-BOOT-01 | AppBuilder | Todo | `Application::configure()` + provider vec | -| F-M0-BOOT-02 | DAG validator | Todo | `depends_on` cycle detection + `BootError::Cycle` | +| F-M0-BOOT-01 | AppBuilder | Done | `Application::configure()` + provider vec | +| F-M0-BOOT-02 | DAG validator | Done | `depends_on` cycle detection + `BootError::Cycle` | | F-M0-BOOT-03 | Runner | Todo | `Runner` trait + HTTP/Queue/Schedule runners | -| F-M0-BOOT-04 | Shutdown | Todo | `tokio::signal` + drain with timeout | -| F-M0-BOOT-05 | Scaffold | Todo | `cargo rustasea new ` producing `bootstrap/app.rs` etc. | -| F-M0-BOOT-06 | Tests | Todo | DAG + shutdown drain + scaffold harness | +| F-M0-BOOT-04 | Shutdown | Partial | `tokio::signal` + drain with timeout | +| F-M0-BOOT-05 | Scaffold | Done | `cargo rustasea new ` producing `bootstrap/app.rs` etc. | +| F-M0-BOOT-06 | Tests | Partial | DAG + shutdown drain + scaffold harness | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M0-BOOT-03` — there is no `Runner` trait or HTTP/Queue/Schedule runner abstraction — only the separate `queue:work` / `schedule:run` commands and the axum serve in `crates/rustasea-app/src/main.rs`. +> - `F-M0-BOOT-04` — same as `F-M0-CFG-03`: the signal is caught, the timeout is ignored, and the drain is not enforced. +> - `F-M0-BOOT-06` — the provider DAG and the scaffold harness are tested (`crates/rustasea-foundation/tests/boot_dag.rs`, `crates/rustasea-scaffold/tests/`); there is no shutdown-drain test. ## 11. Cross-References - Design: `design/architecture.md §2-3` · `design/domain.md BC-0` · `tdd.md BC-0` · `api-contracts.md §1` diff --git a/.agents/documents/application/modules/foundation/config.md b/.agents/documents/application/modules/foundation/config.md index 32e33bd..e0f4149 100644 --- a/.agents/documents/application/modules/foundation/config.md +++ b/.agents/documents/application/modules/foundation/config.md @@ -94,10 +94,17 @@ impl ShutdownHandle { async fn drain(self, timeout: Duration) -> Result<(), Shut | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M0-CFG-01 | ConfigRegistry | Todo | layered merge + Deserialize | -| F-M0-CFG-02 | Diagnostics | Todo | `ConfigError::Parse { file,line,source }` | -| F-M0-CFG-03 | Shutdown | Todo | `tokio::signal` drain + timeout | -| F-M0-CFG-04 | Tests | Todo | layered precedence + invalid TOML line + drain | +| F-M0-CFG-01 | ConfigRegistry | Done | layered merge + Deserialize | +| F-M0-CFG-02 | Diagnostics | Partial | `ConfigError::Parse { file,line,source }` | +| F-M0-CFG-03 | Shutdown | Partial | `tokio::signal` drain + timeout | +| F-M0-CFG-04 | Tests | Partial | layered precedence + invalid TOML line + drain | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M0-CFG-02` — there is no typed `ConfigError::Parse { file, line, source }`; invalid TOML surfaces as the `config` crate's error turned into a string (`BootError::Config`, `crates/rustasea-foundation/src/lib.rs:211`). +> - `F-M0-CFG-03` — the signal is caught, but `graceful` ignores its timeout (`crates/rustasea-foundation/src/shutdown.rs:6`) and the CLI `drain_with_timeout` has no caller; the only real drain is axum's graceful shutdown, which has no timeout. +> - `F-M0-CFG-04` — layered precedence and bad value types are tested; there is no test for invalid TOML syntax with a line number and no drain test. ## 10. Cross-References - API: [api-bootstrap](../../api/foundation/api-bootstrap.md) diff --git a/.agents/documents/application/modules/foundation/container.md b/.agents/documents/application/modules/foundation/container.md index 254843a..e52a0ca 100644 --- a/.agents/documents/application/modules/foundation/container.md +++ b/.agents/documents/application/modules/foundation/container.md @@ -94,11 +94,17 @@ enum ContainerError { NotFound { type_name: &'static str }, AlreadyBound { type_ | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M0-CON-01 | Container | Todo | `Bind`/`Singleton`/`Instance`/`Make` | -| F-M0-CON-02 | Manager::extend | Todo | Closure bound to manager (`manager.prefix()`) | -| F-M0-CON-03 | Option | Todo | `Make> -> None` when unbound | +| F-M0-CON-01 | Container | Done | `Bind`/`Singleton`/`Instance`/`Make` | +| F-M0-CON-02 | Manager::extend | Partial | Closure bound to manager (`manager.prefix()`) | +| F-M0-CON-03 | Option | Done | `Make> -> None` when unbound | | F-M0-CON-04 | Tests | Todo | `ptr_eq` + NotFound + Manager::extend bound | +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M0-CON-02` — there is no generic `Manager` in the foundation crate; the only `extend` is `AuthManager::extend` (`crates/rustasea-auth/src/guard.rs:222`), whose factory receives no manager handle. +> - `F-M0-CON-04` — no container tests were found (`ptr_eq`, unbound resolution, `Manager::extend`); resolution returns `Option`, so a `NotFound` error does not exist. + ## 10. Cross-References - Design: `domain.md BC-0` · `tdd.md BC-0` · `architecture.md §3 DAG` · `api-contracts.md §1` - API: [api-bootstrap](../../api/foundation/api-bootstrap.md) diff --git a/.agents/documents/application/modules/http-routing/http-client.md b/.agents/documents/application/modules/http-routing/http-client.md index bb1313d..92e3156 100644 --- a/.agents/documents/application/modules/http-routing/http-client.md +++ b/.agents/documents/application/modules/http-routing/http-client.md @@ -100,10 +100,15 @@ struct ModelInspector { attributes: Vec, relations: Vec, casts: | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M1-HTTP-01 | Http client | Todo | `reqwest` wrapper + `throw` | -| F-M1-HTTP-02 | Timeouts | Todo | `Connect`/`Total`/`Idle` classification | -| F-M1-HTTP-03 | Introspection | Todo | `route:list --json` + `show:model` | -| F-M1-HTTP-04 | Tests | Todo | 500 throw, idle kind, route:list snapshot | +| F-M1-HTTP-01 | Http client | Done | `reqwest` wrapper + `throw` | +| F-M1-HTTP-02 | Timeouts | Done | `Connect`/`Total`/`Idle` classification | +| F-M1-HTTP-03 | Introspection | Done | `route:list --json` + `show:model` | +| F-M1-HTTP-04 | Tests | Partial | 500 throw, idle kind, route:list snapshot | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M1-HTTP-04` — the 500 `throw` and the idle timeout kind are tested (`crates/rustasea-http/tests/http_client.rs`, `idle_timeout.rs`); there is no `route:list` snapshot test. ## 10. Cross-References - API: [api-http-client](../../api/http-routing/api-http-client.md) diff --git a/.agents/documents/application/modules/http-routing/middleware.md b/.agents/documents/application/modules/http-routing/middleware.md index 1844633..135100e 100644 --- a/.agents/documents/application/modules/http-routing/middleware.md +++ b/.agents/documents/application/modules/http-routing/middleware.md @@ -119,10 +119,16 @@ CLI `route:list` shows middleware column per route as `["throttle:60,1","cors"]` | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M1-MW-01 | Throttle | Todo | `per_minute`/`by_*` + `429 Retry-After` + `trusted_proxies` | -| F-M1-MW-02 | Cors | Todo | `allow_origins` + `Access-Control-Allow-Origin` per allow-list | -| F-M1-MW-03 | Extractors+Valid | Todo | `Json`/`Path`/`Query` + `ErrorBag` 422 strict | -| F-M1-MW-04 | Tests | Todo | throttle 61st, CORS matrix, ErrorBag dual-field | +| F-M1-MW-01 | Throttle | Done | `per_minute`/`by_*` + `429 Retry-After` + `trusted_proxies` | +| F-M1-MW-02 | Cors | Done | `allow_origins` + `Access-Control-Allow-Origin` per allow-list | +| F-M1-MW-03 | Extractors+Valid | Partial | `Json`/`Path`/`Query` + `ErrorBag` 422 strict | +| F-M1-MW-04 | Tests | Partial | throttle 61st, CORS matrix, ErrorBag dual-field | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M1-MW-03` — `FormRequest` (JSON body) returns a 422 `ErrorBag` (`crates/rustasea-validation/src/form_request.rs:71`); `Json` / `Path` / `Query` are plain axum extractors whose rejections are axum's 400/415, and unknown fields are rejected only if the user's type sets `#[serde(deny_unknown_fields)]`. +> - `F-M1-MW-04` — the throttle is tested with a limit of 3 (4th rejected), not the 61st request; the multi-field `ErrorBag` is tested; the CORS test only proves the layer composes — there is no origin matrix. ## 11. Cross-References - Design: `domain.md BC-1` · `tdd.md BC-1` · `api-contracts.md §1` · [ADR-0003](../../../../../docs/adr/ADR-0003-axum-vs-actix.md) diff --git a/.agents/documents/application/modules/http-routing/routing.md b/.agents/documents/application/modules/http-routing/routing.md index 17623ec..4f172d2 100644 --- a/.agents/documents/application/modules/http-routing/routing.md +++ b/.agents/documents/application/modules/http-routing/routing.md @@ -127,11 +127,18 @@ CLI `route:list` human table columns: `METHOD | PATH | NAME | MIDDLEWARE`. | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M1-RTE-01 | RouteRegistry | Todo | method helpers + group + resource 7 routes | -| F-M1-RTE-02 | Domain dispatch | Todo | domain > non-domain split + Host extraction | -| F-M1-RTE-03 | Introspection | Todo | `route:list --json` binding_fields + snapshot | -| F-M1-RTE-04 | Proc-macro | Todo | `#[route]` | -| F-M1-RTE-05 | Tests | Todo | resource 7, group prefix, conflict, domain precedence | +| F-M1-RTE-01 | RouteRegistry | Done | method helpers + group + resource 7 routes | +| F-M1-RTE-02 | Domain dispatch | Partial | domain > non-domain split + Host extraction | +| F-M1-RTE-03 | Introspection | Partial | `route:list --json` binding_fields + snapshot | +| F-M1-RTE-04 | Proc-macro | Done | `#[route]` | +| F-M1-RTE-05 | Tests | Partial | resource 7, group prefix, conflict, domain precedence | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M1-RTE-02` — domain routes are sorted ahead of non-domain routes (`crates/rustasea-router/src/router.rs:397`), but the `Host` header is never read: the first route on a method+path wins (`crates/rustasea-router/src/dispatch.rs:57`), so a domain route answers for every host and a catch-all on the same path is unreachable. +> - `F-M1-RTE-03` — `route:list --json` with `binding_fields` is real (`crates/rustasea-cli/src/commands/inspect.rs:44`); no snapshot test compares the output with `route-list.json.snap` or the schema. +> - `F-M1-RTE-05` — the seven resource routes, domain ordering, and the group name prefix are tested; the group URI prefix and a conflicting/duplicate route have no test. ## 11. Cross-References - Design: `architecture.md BC-1` · `domain.md BC-1` · `tdd.md BC-1` · `api-contracts.md §1` · [ADR-0003](../../../../../docs/adr/ADR-0003-axum-vs-actix.md) diff --git a/.agents/documents/application/modules/identity-access/auth.md b/.agents/documents/application/modules/identity-access/auth.md index c9ede51..83ad2b3 100644 --- a/.agents/documents/application/modules/identity-access/auth.md +++ b/.agents/documents/application/modules/identity-access/auth.md @@ -125,10 +125,15 @@ enum AuthError { GuardMismatch{ expected:String, actual:String }, BadCredentials | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M3-AUTH-01 | JwtGuard | Todo | `jsonwebtoken` HS256 + `argon2` + `login`/`parse`/`refresh`/`logout` | -| F-M3-AUTH-02 | SessionGuard | Todo | `tower-sessions` store + cookie | -| F-M3-AUTH-03 | extend | Todo | `Auth::extend` + `GuardMismatch` | -| F-M3-AUTH-04 | Tests | Todo | login→parse, mismatch, BadCredentials/Expired/Malformed | +| F-M3-AUTH-01 | JwtGuard | Partial | `jsonwebtoken` HS256 + `argon2` + `login`/`parse`/`refresh`/`logout` | +| F-M3-AUTH-02 | SessionGuard | Done | `tower-sessions` store + cookie | +| F-M3-AUTH-03 | extend | Done | `Auth::extend` + `GuardMismatch` | +| F-M3-AUTH-04 | Tests | Done | login→parse, mismatch, BadCredentials/Expired/Malformed | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M3-AUTH-01` — `login`, `parse`, and `refresh` are real over `jsonwebtoken` HS256 + Argon2; `logout` is a no-op with no revocation or deny-list (`crates/rustasea-auth/src/jwt.rs:270`), and `refresh` does not invalidate the old token. The runnable app wires only `SessionGuard`. ## 10. Cross-References - API: [api-auth](../../api/identity-access/api-auth.md) diff --git a/.agents/documents/application/modules/identity-access/csrf.md b/.agents/documents/application/modules/identity-access/csrf.md index 8c9ca6e..45484aa 100644 --- a/.agents/documents/application/modules/identity-access/csrf.md +++ b/.agents/documents/application/modules/identity-access/csrf.md @@ -105,9 +105,14 @@ enum SerializationError { NotAllowed { type_name: String } } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M3-CSRF-01 | PreventRequestForgery | Todo | token-first + `Sec-Fetch-Site` matrix + safe-method exempt | -| F-M3-CSRF-02 | Hardening | Todo | JSON serialization default + hyphen prefix + allow-list gate | -| F-M3-CSRF-03 | Tests | Todo | CSRF matrix, NotAllowed, prefix -cache- | +| F-M3-CSRF-01 | PreventRequestForgery | Done | token-first + `Sec-Fetch-Site` matrix + safe-method exempt | +| F-M3-CSRF-02 | Hardening | Partial | JSON serialization default + hyphen prefix + allow-list gate | +| F-M3-CSRF-03 | Tests | Done | CSRF matrix, NotAllowed, prefix -cache- | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M3-CSRF-02` — the JSON serialization default and the `-session-` / `-cache-` prefixes are enforced; the allow-list gate (`SessionPolicy::allow`, `DeserializationAllowList`) exists but nothing calls it — the cache repository deserializes without a check and `cache.serializable_classes` is parsed but unused (`crates/rustasea-cache/src/config.rs:191`). ## 10. Cross-References - API: [api-auth](../../api/identity-access/api-auth.md) — CSRF decision table section diff --git a/.agents/documents/application/modules/identity-access/validation.md b/.agents/documents/application/modules/identity-access/validation.md index 5fbf5df..7c1efaf 100644 --- a/.agents/documents/application/modules/identity-access/validation.md +++ b/.agents/documents/application/modules/identity-access/validation.md @@ -110,11 +110,17 @@ struct ThrottleConfig { per_minute: u32, key_by: KeyBy } // ip|user|key(fn) | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M3-VAL-01 | Validate macro | Todo | `#[validate]` + `Validatable` + ErrorBag | -| F-M3-VAL-02 | Strict rules | Todo | `in_array`/`contains`/`doesnt_contain` strict (type+value) | -| F-M3-VAL-03 | Middleware attrs | Todo | `#[middleware]`/`#[authorize]` wiring | -| F-M3-VAL-04 | Throttle | Todo | `per_minute(3).by_ip` + 429 + `trusted_proxies` | -| F-M3-VAL-05 | Tests | Todo | dual-field ErrorBag, strict outline, 429, CORS adjacency | +| F-M3-VAL-01 | Validate macro | Done | `#[validate]` + `Validatable` + ErrorBag | +| F-M3-VAL-02 | Strict rules | Partial | `in_array`/`contains`/`doesnt_contain` strict (type+value) | +| F-M3-VAL-03 | Middleware attrs | Done | `#[middleware]`/`#[authorize]` wiring | +| F-M3-VAL-04 | Throttle | Done | `per_minute(3).by_ip` + 429 + `trusted_proxies` | +| F-M3-VAL-05 | Tests | Partial | dual-field ErrorBag, strict outline, 429, CORS adjacency | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M3-VAL-02` — type+value strict matching is real (`crates/rustasea-validation/src/strict.rs`), but the `in:` / `in_array:` arguments are parsed as JSON and anything that fails to parse is dropped (`crates/rustasea-validation/src/rules/support.rs:134`), so a bare-word list such as `in:admin,editor` yields an empty allow-list and rejects every value; only numbers or quoted strings work. +> - `F-M3-VAL-05` — the two-field `ErrorBag`, strict checks, and 429 are tested; CORS adjacency is a compile-level check only, and there are no outline/BDD tests (strict cases are plain assert lists). ## 10. Cross-References - API: [api-validation](../../api/identity-access/api-validation.md) · [api-auth](../../api/identity-access/api-auth.md) CSRF adjacency diff --git a/.agents/documents/application/modules/intelligence-delivery/ai-agents.md b/.agents/documents/application/modules/intelligence-delivery/ai-agents.md index 285f639..ba2f7b2 100644 --- a/.agents/documents/application/modules/intelligence-delivery/ai-agents.md +++ b/.agents/documents/application/modules/intelligence-delivery/ai-agents.md @@ -119,13 +119,20 @@ struct AiChunk { event: String, data: String } // event: token frames | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M6-AG-01 | Agent+Tool core | Todo | `Agent`/`Tool` traits + `#[derive(Agent)]` + anonymous `Ai::agent` | -| F-M6-AG-02 | Streaming/broadcast/queue | Todo | `Stream` WS + queued tools | -| F-M6-AG-03 | MCP + sub-agents | Todo | `feature="mcp"` discovery + sub-agents invoked as tools | -| F-M6-AG-04 | Deferred loaders | Todo | `SimilaritySearch`/`FileStorage`/`ToolSearch` | -| F-M6-AG-05 | Embedding+vector | Todo | `Str::toEmbeddings` + `dropVectorIndex` | -| F-M6-AG-06 | Generators | Todo | `make:agent`/`make:tool` | -| F-M6-AG-07 | Tests | Todo | stream, generator, sub-agent+middleware, deferred, MCP gate, WS broadcast, queued tools | +| F-M6-AG-01 | Agent+Tool core | Partial | `Agent`/`Tool` traits + `#[derive(Agent)]` + anonymous `Ai::agent` | +| F-M6-AG-02 | Streaming/broadcast/queue | Partial | `Stream` WS + queued tools | +| F-M6-AG-03 | MCP + sub-agents | Done | `feature="mcp"` discovery + sub-agents invoked as tools | +| F-M6-AG-04 | Deferred loaders | Done | `SimilaritySearch`/`FileStorage`/`ToolSearch` | +| F-M6-AG-05 | Embedding+vector | Done | `Str::toEmbeddings` + `dropVectorIndex` | +| F-M6-AG-06 | Generators | Done | `make:agent`/`make:tool` | +| F-M6-AG-07 | Tests | Partial | stream, generator, sub-agent+middleware, deferred, MCP gate, WS broadcast, queued tools | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M6-AG-01` — `Tool` is a trait and `Ai::agent` exists, but `Agent` is a struct, `#[derive(Agent)]` does not exist, and the agent runtime never calls an `AiProvider`: `Agent::run_inner` echoes the prompt and runs a tool only when the prompt literally contains `tool:name(args)` (`crates/rustasea-ai/src/agent.rs:247`). +> - `F-M6-AG-02` — `prompt_stream` returns a chunk stream and `AgentRunJob` queues a whole run (`crates/rustasea-ai/src/queue.rs:41`, behind the `queue` feature, which the umbrella crate does not forward), but the stream carries the echo output; the WebSocket path does not depend on `rustasea-ai`, and individual tool calls are not queued. +> - `F-M6-AG-07` — stream, sub-agent, deferred loaders, the MCP gate, queued runs, and the generators have tests; there is no WebSocket broadcast test of AI streaming, and middleware is tested only by calling its hooks directly, not through an agent run. ## 10. Cross-References - API: [api-ai](../../api/intelligence-delivery/api-ai.md) — Agents/streaming/broadcast/queue/MCP sections diff --git a/.agents/documents/application/modules/intelligence-delivery/ai-sdk.md b/.agents/documents/application/modules/intelligence-delivery/ai-sdk.md index bdfcab3..e6f8ce8 100644 --- a/.agents/documents/application/modules/intelligence-delivery/ai-sdk.md +++ b/.agents/documents/application/modules/intelligence-delivery/ai-sdk.md @@ -99,10 +99,18 @@ enum AiError { UnsupportedCapability { provider: String, capability: String }, P | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M6-AI-01 | AiProvider trait | Todo | 7 methods + UnsupportedCapability | -| F-M6-AI-02 | 12 adapters | Todo | per-provider feature flags + text/embeddings/… | -| F-M6-AI-03 | Degraded-mode | Todo | `rustasea-ai` optional; `cargo tree` probe | -| F-M6-AI-04 | Tests | Todo | switch provider preserves shape, unsupported capability outline, flag gate | +| F-M6-AI-01 | AiProvider trait | Partial | 7 methods + UnsupportedCapability | +| F-M6-AI-02 | 12 adapters | Partial | per-provider feature flags + text/embeddings/… | +| F-M6-AI-03 | Degraded-mode | Partial | `rustasea-ai` optional; `cargo tree` probe | +| F-M6-AI-04 | Tests | Partial | switch provider preserves shape, unsupported capability outline, flag gate | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M6-AI-01` — `AiProvider` has `text`, `stream_text`, `image`, `audio`, `embeddings`, `rerank`, and `files` plus `UnsupportedCapability`; there is no `vector_stores` method (only the `Capability::VectorStores` variant, `crates/rustasea-ai/src/provider.rs:51`). +> - `F-M6-AI-02` — all 12 names resolve to a real HTTP adapter (`crates/rustasea-ai/src/providers/client.rs:84`; 11 OpenAI-style including `gemini` and `bedrock` through their OpenAI-compatible endpoints, plus Anthropic), covering text, streaming, and — OpenAI-style only — embeddings. There are no per-provider Cargo features (`crates/rustasea-ai/Cargo.toml:25`), and image, audio, rerank, and files exist only in the in-process stand-in. +> - `F-M6-AI-03` — `rustasea-ai` is optional behind the umbrella `ai` feature (`crates/rustasea/Cargo.toml`), but no `cargo tree` degraded-mode probe exists in CI, `xtask`, or a test. +> - `F-M6-AI-04` — provider-switch shape is tested for openai/anthropic in-process only; unsupported capability is tested for two provider/capability pairs, not an outline over all 12; there is no flag-gate test because there are no per-provider flags. ## 10. Cross-References - API: [api-ai](../../api/intelligence-delivery/api-ai.md) — SDK section diff --git a/.agents/documents/application/modules/intelligence-delivery/broadcast.md b/.agents/documents/application/modules/intelligence-delivery/broadcast.md index dfdea2b..fc15e19 100644 --- a/.agents/documents/application/modules/intelligence-delivery/broadcast.md +++ b/.agents/documents/application/modules/intelligence-delivery/broadcast.md @@ -91,10 +91,15 @@ fn event_stream(stream: S) -> Response // Content-Type: text/event-stream (s. | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M6-BRD-01 | ShouldBroadcast | Todo | channels Private/Public/Presence + broadcastOn | -| F-M6-BRD-02 | WS + auth | Todo | `axum ws` + Authorize + close 4403 | -| F-M6-BRD-03 | SSE | Todo | `eventStream` `text/event-stream` frames + bounded mpsc | -| F-M6-BRD-04 | Tests | Todo | authorized receives, unauthorized 4403, SSE 2 frames, WS AI streaming | +| F-M6-BRD-01 | ShouldBroadcast | Done | channels Private/Public/Presence + broadcastOn | +| F-M6-BRD-02 | WS + auth | Done | `axum ws` + Authorize + close 4403 | +| F-M6-BRD-03 | SSE | Done | `eventStream` `text/event-stream` frames + bounded mpsc | +| F-M6-BRD-04 | Tests | Partial | authorized receives, unauthorized 4403, SSE 2 frames, WS AI streaming | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M6-BRD-04` — authorized receive and the two-frame SSE case are tested; the 4403 close is covered only as an error-to-code mapping (no live socket test), and WebSocket AI streaming has no test. ## 10. Cross-References - API: [api-broadcast](../../api/intelligence-delivery/api-broadcast.md) diff --git a/.agents/documents/application/modules/intelligence-delivery/jsonapi.md b/.agents/documents/application/modules/intelligence-delivery/jsonapi.md index 485ef87..298bc64 100644 --- a/.agents/documents/application/modules/intelligence-delivery/jsonapi.md +++ b/.agents/documents/application/modules/intelligence-delivery/jsonapi.md @@ -84,9 +84,14 @@ enum JsonApiError { RelationNotLoaded { relation: String } } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M6-JA-01 | Serializer | Todo | `JsonApiResource` sparse + include + links | -| F-M6-JA-02 | Guard | Todo | `RelationNotLoaded` when not eager | -| F-M6-JA-03 | Tests | Todo | fieldset+include happy, not-loaded, sparse outline | +| F-M6-JA-01 | Serializer | Done | `JsonApiResource` sparse + include + links | +| F-M6-JA-02 | Guard | Done | `RelationNotLoaded` when not eager | +| F-M6-JA-03 | Tests | Partial | fieldset+include happy, not-loaded, sparse outline | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M6-JA-03` — the fieldset + include happy path and sparse filtering are tested; no test asserts `RelationNotLoaded` (the fixture always reports its relation as loaded). ## 10. Cross-References - API: [api-jsonapi](../../api/intelligence-delivery/api-jsonapi.md) diff --git a/.agents/documents/application/modules/intelligence-delivery/storage.md b/.agents/documents/application/modules/intelligence-delivery/storage.md index 44bc6b1..4e17184 100644 --- a/.agents/documents/application/modules/intelligence-delivery/storage.md +++ b/.agents/documents/application/modules/intelligence-delivery/storage.md @@ -107,10 +107,15 @@ enum StorageError { NotFound, PathTraversal, StoreUnavailable } | ID | Component | Status | Description | |----|-----------|--------|-------------| -| F-M6-STO-01 | Read-through | Todo | primary→fallback + copy_back + NotFound uniform | -| F-M6-STO-02 | Path confinement | Todo | `path.starts_with(disk_root)` → `PathTraversal` | -| F-M6-STO-03 | Disks | Todo | `object_store` vs `tokio::fs` abstraction | -| F-M6-STO-04 | Tests | Todo | fallback read, PathTraversal corpus, copy_back, missing uniform | +| F-M6-STO-01 | Read-through | Done | primary→fallback + copy_back + NotFound uniform | +| F-M6-STO-02 | Path confinement | Done | `path.starts_with(disk_root)` → `PathTraversal` | +| F-M6-STO-03 | Disks | Done | `object_store` vs `tokio::fs` abstraction | +| F-M6-STO-04 | Tests | Partial | fallback read, PathTraversal corpus, copy_back, missing uniform | + +> **As-built note (2026-11-18):** the Status column was checked against the source tree on this date; the Component and Description columns are the original plan and are unchanged. `Done` means every element named in the row exists in reachable non-test code (for a Tests row: a test exists for each named case). Tests were read, not run. Live status: `docs/milestones.md`. +> +> Open items: +> - `F-M6-STO-04` — fallback read, copy-back, and uniform `NotFound` are tested (`crates/rustasea-storage/tests/storage_facade.rs` and the `manager`/`disk`/`path` unit tests); the path-traversal corpus is not — only `../../etc/passwd` and symlink escapes are covered, and `testing/fixtures/path-traversal.corpus.json` is loaded by no test. ## 10. Cross-References - API: [api-storage](../../api/intelligence-delivery/api-storage.md) diff --git a/.agents/documents/tasks/roadmap.md b/.agents/documents/tasks/roadmap.md index 49f8519..19a225a 100644 --- a/.agents/documents/tasks/roadmap.md +++ b/.agents/documents/tasks/roadmap.md @@ -11,14 +11,16 @@ | Milestone | Focus | Target | Depends On | Sprint | Status | |-----------|-------|--------|------------|--------|--------| -| **M0** | Bootstrap & Core | Q4 2026 (2026-10-01 → 2026-12-31) | — | Sprint 01 | Planned | -| **M1** | Routing & HTTP | Q4 2026 – Q1 2027 (2026-11-15 → 2027-02-15) | M0 | Sprint 02 | Planned | -| **M2** | ORM & Database | Q1 2027 (2027-01-01 → 2027-03-31) | M0, M1 | Sprint 03 | Planned | -| **M3** | Auth, Middleware & Validation | Q1 – Q2 2027 (2027-02-15 → 2027-05-15) | M1, M2 | Sprint 04 | Planned | -| **M4** | Queue, Cache, Scheduling & Events | Q2 2027 (2027-04-01 → 2027-06-30) | M0, M2, M3 | Sprint 05 | Planned | -| **M5** | DX, CLI & Testing | Q2 – Q3 2027 (2027-05-15 → 2027-08-31) | M0 – M4 | Sprint 06 | Planned | -| **M6** | Advanced (Broadcast, Search, FS, AI SDK, Real-time) | Q3 – Q4 2027 (2027-07-01 → 2027-12-31) | M1 – M5 | Sprint 07 | Planned | - +| **M0** | Bootstrap & Core | Q4 2026 (2026-10-01 → 2026-12-31) | — | Sprint 01 | Partial (as-built) | +| **M1** | Routing & HTTP | Q4 2026 – Q1 2027 (2026-11-15 → 2027-02-15) | M0 | Sprint 02 | Partial (as-built) | +| **M2** | ORM & Database | Q1 2027 (2027-01-01 → 2027-03-31) | M0, M1 | Sprint 03 | Done (as-built) | +| **M3** | Auth, Middleware & Validation | Q1 – Q2 2027 (2027-02-15 → 2027-05-15) | M1, M2 | Sprint 04 | Partial (as-built) | +| **M4** | Queue, Cache, Scheduling & Events | Q2 2027 (2027-04-01 → 2027-06-30) | M0, M2, M3 | Sprint 05 | Partial (as-built) | +| **M5** | DX, CLI & Testing | Q2 – Q3 2027 (2027-05-15 → 2027-08-31) | M0 – M4 | Sprint 06 | Partial (as-built) | +| **M6** | Advanced (Broadcast, Search, FS, AI SDK, Real-time) | Q3 – Q4 2027 (2027-07-01 → 2027-12-31) | M1 – M5 | Sprint 07 | Partial (as-built) | + +> **Planning vs as-built:** targets and sprint scope are the plan. The Status column is the as-built status on 2026-11-18, delivered ahead of the planned windows; the authoritative, evidence-backed source is [`docs/milestones.md`](../../../docs/milestones.md). +> > Timeline is aspirational; refined after M0 ships. Each milestone ships as a tagged release with migration notes (`CHANGELOG.md` at M0). ## 2. Dependency DAG (Delivery Order) diff --git a/.agents/documents/tasks/sprints/manifest.md b/.agents/documents/tasks/sprints/manifest.md index 4422142..9cf54c4 100644 --- a/.agents/documents/tasks/sprints/manifest.md +++ b/.agents/documents/tasks/sprints/manifest.md @@ -10,13 +10,15 @@ | Sprint | Milestone | Goal (one-liner) | Window | FRs | Crates | Status | |--------|-----------|------------------|--------|-----|--------|--------| -| **Sprint 01** | **M0** Bootstrap & Core | Bootable skeleton with config, container, providers, shutdown. | 2026-10-01 → 2026-12-31 | FR-000–FR-008 (9) | `rustasea`, `rustasea-foundation`, `rustasea-config`, `rustasea-macros` (scaffold) | Planned | -| **Sprint 02** | **M1** Routing & HTTP | Expressive HTTP layer with routing, middleware, introspection. | 2026-11-15 → 2027-02-15 | FR-100–FR-109 (10) | `rustasea-router`, `rustasea-http` | Planned | -| **Sprint 03** | **M2** ORM & Database | Fluent type-safe DB layer with migrations/factories/vector. | 2027-01-01 → 2027-03-31 | FR-200–FR-210 (11) | `rustasea-orm`, `rustasea-macros` (Model) | Planned | -| **Sprint 04** | **M3** Auth, Middleware & Validation | Hardened auth/validation at Laravel 13 defaults. | 2027-02-15 → 2027-05-15 | FR-300–FR-311 (12) | `rustasea-auth`, `rustasea-validation` | Planned | -| **Sprint 05** | **M4** Queue, Cache, Scheduling & Events | Observable async workloads. | 2027-04-01 → 2027-06-30 | FR-400–FR-410 (11) | `rustasea-queue`, `rustasea-cache`, `rustasea-events`, `rustasea-schedule` | Planned | -| **Sprint 06** | **M5** DX, CLI & Testing | Laravel-like DX loop: CLI, generators, testing. | 2027-05-15 → 2027-08-31 | FR-500–FR-509 (10) | `rustasea-cli`, `rustasea-macros`, `rustasea-testing` | Planned | -| **Sprint 07** | **M6** Advanced (AI/Broadcast/FS/JSON:API) | Differentiate: AI SDK, broadcast/SSE, storage, JSON:API. | 2027-07-01 → 2027-12-31 | FR-600–FR-612 (13) | `rustasea-broadcast`, `rustasea-storage`, `rustasea-search`, `rustasea-ai` | Planned | +| **Sprint 01** | **M0** Bootstrap & Core | Bootable skeleton with config, container, providers, shutdown. | 2026-10-01 → 2026-12-31 | FR-000–FR-008 (9) | `rustasea`, `rustasea-foundation`, `rustasea-config`, `rustasea-macros` (scaffold) | Partial (as-built) | +| **Sprint 02** | **M1** Routing & HTTP | Expressive HTTP layer with routing, middleware, introspection. | 2026-11-15 → 2027-02-15 | FR-100–FR-109 (10) | `rustasea-router`, `rustasea-http` | Partial (as-built) | +| **Sprint 03** | **M2** ORM & Database | Fluent type-safe DB layer with migrations/factories/vector. | 2027-01-01 → 2027-03-31 | FR-200–FR-210 (11) | `rustasea-orm`, `rustasea-macros` (Model) | Done (as-built) | +| **Sprint 04** | **M3** Auth, Middleware & Validation | Hardened auth/validation at Laravel 13 defaults. | 2027-02-15 → 2027-05-15 | FR-300–FR-311 (12) | `rustasea-auth`, `rustasea-validation` | Partial (as-built) | +| **Sprint 05** | **M4** Queue, Cache, Scheduling & Events | Observable async workloads. | 2027-04-01 → 2027-06-30 | FR-400–FR-410 (11) | `rustasea-queue`, `rustasea-cache`, `rustasea-events`, `rustasea-schedule` | Partial (as-built) | +| **Sprint 06** | **M5** DX, CLI & Testing | Laravel-like DX loop: CLI, generators, testing. | 2027-05-15 → 2027-08-31 | FR-500–FR-509 (10) | `rustasea-cli`, `rustasea-macros`, `rustasea-testing` | Partial (as-built) | +| **Sprint 07** | **M6** Advanced (AI/Broadcast/FS/JSON:API) | Differentiate: AI SDK, broadcast/SSE, storage, JSON:API. | 2027-07-01 → 2027-12-31 | FR-600–FR-612 (13) | `rustasea-broadcast`, `rustasea-storage`, `rustasea-search`, `rustasea-ai` | Partial (as-built) | + +> **Planning vs as-built:** windows and scope are the plan. The Status column is the as-built status on 2026-11-18; the authoritative, evidence-backed source is [`docs/milestones.md`](../../../../docs/milestones.md). **Total FRs:** 76 (M0 9 + M1 10 + M2 11 + M3 12 + M4 11 + M5 10 + M6 13) per `prd.md` §8. diff --git a/.agents/documents/tasks/sprints/sprint-01.md b/.agents/documents/tasks/sprints/sprint-01.md index e939504..25555e1 100644 --- a/.agents/documents/tasks/sprints/sprint-01.md +++ b/.agents/documents/tasks/sprints/sprint-01.md @@ -1,8 +1,9 @@ # Sprint 01 — M0 Bootstrap & Core -> **Milestone:** M0 · **Window:** 2026-10-01 → 2026-12-31 · **Status:** Planned +> **Milestone:** M0 · **Window:** 2026-10-01 → 2026-12-31 · **Status:** Partial as-built (2026-11-18) — container, provider DAG, config loader mounted at boot, graceful shutdown, and the scaffolder landed; no database/cache/queue container bindings at boot · Delivered ahead of the planned window > **Parents:** `../roadmap.md` · `prd.md` FR-000–FR-008 · `fsd.md` FS-M0-01–FS-M0-04 · `design/architecture.md` > **Crates:** `rustasea` (umbrella), `rustasea-foundation`, `rustasea-config`, `rustasea-macros` (scaffold) +> **Planning vs as-built:** Sprint scope/window is the plan. Live status: [`docs/milestones.md`](../../../../docs/milestones.md) — the authoritative as-built status source (TASK-003). --- diff --git a/.agents/documents/tasks/sprints/sprint-02.md b/.agents/documents/tasks/sprints/sprint-02.md index 7bc970c..7bea12c 100644 --- a/.agents/documents/tasks/sprints/sprint-02.md +++ b/.agents/documents/tasks/sprints/sprint-02.md @@ -1,9 +1,10 @@ # Sprint 02 — M1 Routing & HTTP -> **Milestone:** M1 · **Window:** 2026-11-15 → 2027-02-15 · **Status:** Planned +> **Milestone:** M1 · **Window:** 2026-11-15 → 2027-02-15 · **Status:** Partial as-built (2026-11-18) — router DSL, controller dispatch, `route:list`, and the HTTP client landed; `show:model` does not read live database columns · Delivered ahead of the planned window > **Parents:** `../roadmap.md` · `prd.md` FR-100–FR-109 · `fsd.md` FS-M1-01–FS-M1-06 · `design/architecture.md` > **Depends On:** M0 (Sprint 01) > **Crates:** `rustasea-router`, `rustasea-http` (uses `rustasea-foundation`, `rustasea-macros`) +> **Planning vs as-built:** Sprint scope/window is the plan. Live status: [`docs/milestones.md`](../../../../docs/milestones.md) — the authoritative as-built status source (TASK-003). --- diff --git a/.agents/documents/tasks/sprints/sprint-03.md b/.agents/documents/tasks/sprints/sprint-03.md index c162e35..19693bb 100644 --- a/.agents/documents/tasks/sprints/sprint-03.md +++ b/.agents/documents/tasks/sprints/sprint-03.md @@ -1,9 +1,10 @@ # Sprint 03 — M2 ORM & Database -> **Milestone:** M2 · **Window:** 2027-01-01 → 2027-03-31 · **Status:** Planned +> **Milestone:** M2 · **Window:** 2027-01-01 → 2027-03-31 · **Status:** Done as-built (2026-11-18) · Delivered ahead of the planned window > **Parents:** `../roadmap.md` · `prd.md` FR-200–FR-210 · `fsd.md` FS-M2-01–FS-M2-06 · `design/architecture.md` + `design/database.md` + `design/domain.md` > **Depends On:** M0 (S01), M1 (S02) > **Crates:** `rustasea-orm`, `rustasea-macros` (`#[derive(Model)]`) — `pgvector` behind `vector` feature +> **Planning vs as-built:** Sprint scope/window is the plan. Live status: [`docs/milestones.md`](../../../../docs/milestones.md) — the authoritative as-built status source (TASK-003). --- diff --git a/.agents/documents/tasks/sprints/sprint-04.md b/.agents/documents/tasks/sprints/sprint-04.md index fba8090..8e1f75b 100644 --- a/.agents/documents/tasks/sprints/sprint-04.md +++ b/.agents/documents/tasks/sprints/sprint-04.md @@ -1,9 +1,10 @@ # Sprint 04 — M3 Auth, Middleware & Validation -> **Milestone:** M3 · **Window:** 2027-02-15 → 2027-05-15 · **Status:** Planned +> **Milestone:** M3 · **Window:** 2027-02-15 → 2027-05-15 · **Status:** Partial as-built (2026-11-18) — JWT/session guards, CSRF, throttle, validation, a database session store, and a database user provider landed; scaffolded apps do not wire the database user provider yet · Delivered ahead of the planned window > **Parents:** `../roadmap.md` · `prd.md` FR-300–FR-311 · `fsd.md` FS-M3-01–FS-M3-06 · `design/architecture.md` > **Depends On:** M1 (S02), M2 (S03) > **Crates:** `rustasea-auth`, `rustasea-validation` +> **Planning vs as-built:** Sprint scope/window is the plan. Live status: [`docs/milestones.md`](../../../../docs/milestones.md) — the authoritative as-built status source (TASK-003). --- diff --git a/.agents/documents/tasks/sprints/sprint-05.md b/.agents/documents/tasks/sprints/sprint-05.md index c8a07aa..d01ae10 100644 --- a/.agents/documents/tasks/sprints/sprint-05.md +++ b/.agents/documents/tasks/sprints/sprint-05.md @@ -1,9 +1,10 @@ # Sprint 05 — M4 Queue, Cache, Scheduling & Events -> **Milestone:** M4 · **Window:** 2027-04-01 → 2027-06-30 · **Status:** Planned +> **Milestone:** M4 · **Window:** 2027-04-01 → 2027-06-30 · **Status:** Partial as-built (2026-11-18) — queue drivers, worker, failed jobs, cache stores, and queued listeners landed; the scheduler cannot dispatch a due command, schedule pause state is per-process, and after-response events are never flushed · Delivered ahead of the planned window > **Parents:** `../roadmap.md` · `prd.md` FR-400–FR-410 · `fsd.md` FS-M4-01–FS-M4-06 · `design/architecture.md` + `design/database.md` > **Depends On:** M0 (S01), M2 (S03), M3 (S04) > **Crates:** `rustasea-queue`, `rustasea-cache`, `rustasea-events`, `rustasea-schedule` +> **Planning vs as-built:** Sprint scope/window is the plan. Live status: [`docs/milestones.md`](../../../../docs/milestones.md) — the authoritative as-built status source (TASK-003). --- diff --git a/.agents/documents/tasks/sprints/sprint-06.md b/.agents/documents/tasks/sprints/sprint-06.md index 091bd3b..1df58ea 100644 --- a/.agents/documents/tasks/sprints/sprint-06.md +++ b/.agents/documents/tasks/sprints/sprint-06.md @@ -1,6 +1,6 @@ # Sprint 06 — M5 DX, CLI & Testing -> **Milestone:** M5 · **Window:** 2027-05-15 → 2027-08-31 · **Status:** In Progress — core surfaces landed (M5 generators, M6 broadcast/search/storage/ai), drivers/SDKs pending · Delivered ahead of 2027 window per 2026-09 automation (core landed 2026-09-09) +> **Milestone:** M5 · **Window:** 2027-05-15 → 2027-08-31 · **Status:** Partial as-built (2026-11-18) — CLI, the 17 `make:*` generators, the scaffolder, and the testing harness landed; generated controllers still need manual route registration · Delivered ahead of 2027 window per 2026-09 automation (core landed 2026-09-09) > **Parents:** `../roadmap.md` · `prd.md` FR-500–FR-509 · `fsd.md` FS-M5-01–FS-M5-07 · `design/architecture.md` > **Depends On:** M0–M4 (Sprints 01–05) > **Crates:** `rustasea-cli`, `rustasea-macros` (generators + attrs), `rustasea-testing` diff --git a/.agents/documents/tasks/sprints/sprint-07.md b/.agents/documents/tasks/sprints/sprint-07.md index 5be9c56..b74468a 100644 --- a/.agents/documents/tasks/sprints/sprint-07.md +++ b/.agents/documents/tasks/sprints/sprint-07.md @@ -1,6 +1,6 @@ # Sprint 07 — M6 Advanced (Broadcast, Search, Filesystem, AI SDK, Real-time) -> **Milestone:** M6 · **Window:** 2027-07-01 → 2027-12-31 · **Status:** In Progress — core surfaces landed (M5 generators, M6 broadcast/search/storage/ai), drivers/SDKs pending · Delivered ahead of 2027 window per 2026-09 automation (core landed 2026-09-09) +> **Milestone:** M6 · **Window:** 2027-07-01 → 2027-12-31 · **Status:** Partial as-built (2026-11-18) — broadcasting, storage, search, JSON:API, mail, the view/Inertia/Livewire layers, real HTTP AI providers (including Gemini and Bedrock through their OpenAI-compatible endpoints), AI queueing, and MCP landed; provider-native Gemini/Bedrock APIs are not implemented · Delivered ahead of 2027 window per 2026-09 automation (core landed 2026-09-09) > **Parents:** `../roadmap.md` · `prd.md` FR-600–FR-612 · `fsd.md` FS-M6-01–FS-M6-07 · `design/architecture.md` > **Depends On:** M1–M5 (Sprints 01–06) > **Crates:** `rustasea-broadcast`, `rustasea-storage`, `rustasea-search`, `rustasea-ai` (`optional` feature, provider adapters feature-flagged) From fea40185ae4a6569ec3318b82a4fcdef9b727e84 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:05:08 +0700 Subject: [PATCH 13/14] style(validation): address clippy 1.100 needless_bool in the unique check CI runs the latest stable (rustc 1.100.0), where clippy rejects the if-return-false / return-true pair under -D warnings and fails the lint job. Behaviour is unchanged. --- crates/rustasea-validation/src/context.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/rustasea-validation/src/context.rs b/crates/rustasea-validation/src/context.rs index 9362584..cf1aef8 100644 --- a/crates/rustasea-validation/src/context.rs +++ b/crates/rustasea-validation/src/context.rs @@ -156,10 +156,7 @@ impl ValidationContext for MemoryContext { // The only conflicting row is the caller's own row. return Some(ignore_id == Some(owner.as_str())); } - if self.taken.contains(&key) { - return Some(false); - } - Some(true) + Some(!self.taken.contains(&key)) } fn current_password_matches(&self, plaintext: &str) -> Option { From 9486603b624ae97908a41075e55dfc91a81320f1 Mon Sep 17 00:00:00 2001 From: gitfromwildan <201965665+gitfromwildan@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:38:39 +0700 Subject: [PATCH 14/14] chore(deps): replace the yanked clipboard-win 5.4.1 in the lockfile The generated-code tests (generated_module_compiles_in_workspace and generated_app_compiles_for_every_variant) compile a generated project offline, so they can only use the crates cargo fetch downloaded for the lockfile. With the yanked 5.4.1 pinned, both fail in CI to resolve rustyline's clipboard-win requirement. 5.4.3 replaces it. --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index afbbaa9..17f7005 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1072,9 +1072,9 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ]