feat: SaaS foundation for CrowdSight

Elevate MiroFish/CrowdSight from single-container dev to a SaaS foundation:

- Local memory backend (Zep-compatible): memory services/models, local graph
  builder + updater, AgentActivity seam, import-boundary isolation; Zep stays
  default, local is opt-in behind MEMORY_BACKEND. Semantic parity not yet proven.
- Durable product persistence: projects/simulations/reports schema (migration
  0007) + tenant/owner-scoped ProductRepository + dual-write + scoped_project
  read-first + ArtifactStore abstraction; durable JobQueue + worker.py.
- SaaS hardening: durable RateLimiter (wired to login), UsageService (LLM
  accounting), redacted AuditService, idempotency, CORS allowlist, safe API
  errors, single-use PasswordResetService + endpoints (covers invite-pending).
- Exactly 3 roles (super_admin/admin/user) with tenant authz policy.
- Admin UI: GET/POST/PATCH /api/admin/users + GET/PUT /api/admin/settings
  (super-admin only, encrypted/masked); AdminView.vue + SettingsView.vue with
  admin/super-admin route guards, th/en i18n.
- Production deploy topology: multi-stage Dockerfile (frontend build + gunicorn
  wsgi + nginx SPA-proxy + supervisord worker), backend/wsgi.py, gunicorn dep.

Backend 197 passed; frontend 10 tests + build green. ruff unavailable (gap).
No commit of credentials; secrets handled via env/.env.example.
Deferred: Zep semantic A/B parity, object storage cutover, mobile QA, EasyPanel
container build of deploy topology.
This commit is contained in:
Kunthawat Greethong committed 2026-08-31 13:05:21 +07:00
1 parent 89d04e795b
commit 8b84378fe1
165 files changed
+15884 -4001

No files matched your search

@@ -0,0 +1,42 @@
# Architecture Study — MiroFish SaaS Migration
**Date:** 2026-08-23 (+07:00)
**Repository:** `/Users/kunthawat/Gitea/MiroFish`
**HEAD:** `89d04e7`
**Status:** complete — plan only; no production source changes
## Scope
Reviewed frontend i18n/rendering, backend API/entry points, Zep integration, LLM prompt paths, persistence, auth/security posture, role/tenant requirements and Docker runtime.
## Evidence
- Working tree was clean at start and after baseline verification.
- `npm run build` passed; Vite emitted chunk-size and `pendingUpload.js` import warnings.
- `python3 -m compileall -q backend/app backend/run.py backend/scripts` passed.
- `git diff --check` passed.
- Backend route inventory: 64 routes; no auth middleware found.
- Frontend locale inventory: `en` and `th` have matching 648 flattened keys; `zh` is still present and is the fallback/default path.
- Current built frontend still contains CJK code points in generated HTML/JS.
- Zep usage was traced through graph build, entity reader, search tools, graph memory updater, profile generation and ReportAgent.
- Current project/task/simulation/report state is mostly filesystem/in-memory scoped globally, not by user or organization.
- Independent SaaS audit confirmed additional risks: raw request-body logging, raw exception/path exposure, non-idempotent frontend retries, global history/debug routes, process-local pending uploads and a report-status HTTP method/body mismatch.
## Decisions captured in plan
- Use PostgreSQL as SaaS system of record; add tenant scope from v1.
- Use LLM for structured memory extraction/merge/summary/query reasoning, not for durable storage or unbounded search.
- Preserve internal memory result contracts while replacing Zep implementation.
- Use exactly `super_admin`, `admin`, `user` with backend-enforced policy.
- Default product locale recommendation: Thai, with English switcher.
- Move long-running work to durable workers before calling the system production SaaS-ready.
## Risks/open decisions
- Need user decision on whether user-uploaded Chinese content must also be translated/hidden.
- Need user decision on multi-organization scope, invite flow, Zep data migration and LLM settings scope.
- Python runtime on the current host is 3.14 while project metadata requires Python 3.11–3.12; compile success is not full runtime proof.
## Exact next action
Get M0 answers, then create PR-sized implementation batches starting with persistence/auth contracts and locale/API error contracts. Do not begin by deleting Zep files without first implementing the local memory interface and storage schema.
@@ -0,0 +1,28 @@
# Local Memory First Consumer — 2026-08-23
## Scope
Enabled the first explicit local-memory execution path without silently changing the existing Zep default.
## Changes
- Added `MEMORY_BACKEND=zep|local`; unknown values fail closed.
- Added per-request local entity-reader factory scoped by `organization_id` and `graph_id`.
- Added worker-owned SQLAlchemy session lifecycle for local readers.
- `SimulationManager` now accepts `entity_reader_factory` and uses it during preparation.
- `/api/simulation/entities/*` selects the configured reader and closes it after each request.
- `/api/simulation/prepare` uses the configured reader for preview and background preparation.
- `OasisProfileGenerator` supports `use_zep_context=False`; local mode does not initialize Zep context for profile enrichment.
- Default remains `MEMORY_BACKEND=zep` until remaining consumers and data migration are ready.
## Evidence
- Switch/route tests: 3 passed.
- Reader factory/entity parity/injection tests: passed.
- Full backend suite after this slice: **55 passed**.
- Frontend suite: **10 passed**.
- Build, compileall, and Alembic upgrade/check: passed.
## Boundary
This is not a full Zep removal. Profile generation still uses the legacy flow outside the explicit local preparation path, and graph tools/report consumers still need migration.
@@ -0,0 +1,32 @@
# Local Memory Foundation — 2026-08-23
## Scope
Started the Zep replacement without switching existing consumers yet. The goal of this slice is to separate LLM semantic extraction from durable storage, search, and authorization.
## Delivered
- SQLAlchemy memory tables: `memory_graphs`, `memory_episodes`, `memory_nodes`, `memory_edges`.
- Alembic revision `0003_memory` with SQLite upgrade/check parity.
- `SqlAlchemyMemoryRepository` constrained by `organization_id` + `graph_id`.
- Deterministic node normalization, confidence bounds, graph/node scope checks, and bounded search.
- Golden parity fixture and local adapters for entity filtering/context and quick search output shapes.
- Strict Pydantic extraction models with `extra="forbid"`.
- Bounded Thai/English extraction prompt builder.
- JSON/code-fence parser with validation.
- `MemoryExtractionService` that calls a JSON LLM client, validates output, resolves entity references deterministically, and persists only through the scoped repository.
## Evidence
- Memory repository tests: 2 passed.
- Extraction contract tests: 3 passed.
- Memory service test: 1 passed.
- Full backend suite: 47 passed.
- Frontend contract suite: 10 passed.
- Vite build: pass.
- Python compileall: pass.
- Alembic revisions `0001_identity` → `0003_memory` upgrade/check: pass.
## Deliberate non-change
Existing `GraphBuilderService`, `ZepEntityReader`, `ZepToolsService`, `OasisProfileGenerator`, and `ReportAgent` still use Zep. Consumer cutover is deferred until golden parity fixtures exist for entity reads, search, temporal edges, and simulation context.
@@ -0,0 +1,46 @@
# SaaS Foundation Continuation — 2026-08-23
## Scope
Continued implementation after reviewer delegation infrastructure failed to return a verdict.
## Changes
- Added blueprint-wide authentication and CSRF enforcement to simulation/report APIs.
- Added fail-closed resource helpers for project, graph, simulation, report, and task IDs.
- Scoped simulation/report listing and ownership checks to the authenticated actor.
- Added task metadata ownership for report-generation jobs and blocked cross-tenant task status reads.
- Added local `ApiError` handlers for simulation/report blueprints; removed the frozen exception behavior that caused `FrozenInstanceError` while unwinding a session context.
- Corrected frontend report-status method/body contract.
- Added cookie-session auth store, public login route, protected workspace router guard, and localized login view.
## Evidence
- Resource auth tests: 3 passed.
- Full backend suite: 41 passed.
- Frontend contract suite: 10 passed.
- Vite build: pass; existing chunk/import warnings remain.
- Python compileall: pass.
- Alembic SQLite upgrade/check: pass.
- Staged diff whitespace check: pass after staging the continuation changes.
## Prevention notes
- Any route that accepts a resource ID must pass through a shared scope helper before touching filesystem or in-memory state.
- Any task exposed through an API must carry `organization_id` and `owner_user_id`; legacy tasks without metadata fail closed.
- `ApiError` must remain a normal mutable exception class; frozen dataclasses cannot safely unwind through context managers because Python assigns traceback fields.
- Frontend API contract tests should assert HTTP method and request body against the backend route, not only function existence.
## Remaining blocker
Independent reviewer delegation exited before returning the required JSON verdict. This is recorded as `VERIFICATION BLOCKED`, not as an approval or security finding.
## Follow-up — local cutover and safe-error gate
- Added local graph activity updater coverage and graph → profile → report golden contract coverage.
- Replaced raw exception text in API response paths and persisted simulation/report/project/task/run state with generic localized errors; server logs retain only operation, identifier, exit code where needed, and exception type.
- Added `backend/tests/test_api_no_raw_exception_details.py` as a source-level regression gate.
- Verification: backend **67 passed**, frontend Node contract tests **10 passed**, Vite build **PASS**, Python compileall **PASS**, `git diff --check` **PASS**.
- `npm test` was attempted but the repository has no `test` script; the supported `node --test tests/*.mjs` command passed.
- Reviewer status remains `VERIFICATION BLOCKED` until the fresh independent reviewer returns a readable schema-valid terminal verdict.
- `deleg_289b16ce` also timed out without a terminal verdict after broad read-only inspection. Its intermediate targeted-test failure was not reproducible on the current tree: `tests/test_api_no_raw_exception_details.py` reran **1 passed**. Reviewer `deleg_e0e7bac1` was narrowed via steering and remains the active pending gate.
@@ -0,0 +1,35 @@
# Graph Scope Review — 2026-08-24
## Scope
Closed the two blockers from the earlier independent review:
1. Project deletion must be organization-scoped and owner-scoped for regular users.
2. Graph read/delete routes must use the local adapter when `MEMORY_BACKEND=local`, without constructing or silently falling back to Zep.
## Changes verified
- `backend/app/api/graph.py` resolves the authenticated actor and routes project/graph access through scoped helpers.
- `backend/app/models/project.py` requires organization scope for project deletion and applies the user-owner restriction where applicable.
- `backend/app/services/local_graph_builder.py` requires organization and project scope and passes graph operations to the tenant-scoped repository.
- `backend/tests/test_graph_backend_routes.py` covers backend dispatch, cross-tenant project/graph behavior, and local graph deletion with nodes and an edge.
## Verification evidence
- Focused regression set: **15 passed**.
- Full backend suite: **72 passed**.
- Frontend contract tests: **10 passed**.
- Frontend production build: **PASS**; existing chunk-size/dynamic-import warnings remain.
- Python `compileall`: **PASS**.
- Added-lines security scan: **0 findings** for hardcoded secrets, shell injection, eval/exec, unsafe pickle, and interpolated SQL patterns.
- `git diff --check`: **PASS**.
- `ruff`: unavailable in the current backend environment; no lint verdict claimed.
## Review gate
Independent review attempts before this entry did not return readable terminal JSON and therefore were fail-closed. Fresh narrow read-only reviewer `deleg_dec1c4b0` then returned the required exact five-key JSON with `passed=true`, empty `security_concerns`, and empty `logic_errors` after reviewing all seven target files. The bounded blocker gate is closed. This does not claim approval, parity completion, production readiness, or full Zep removal.
## Remaining work
- The bounded graph/project/local-memory review gate is closed; continue the staged local-memory consumer cutover and durable resource work.
- Broader migration review, parity, production hardening, and end-to-end tenant matrix remain open.
- No commit, push, or deploy was made during this verification.
@@ -0,0 +1,40 @@
# Local Memory Parity Slice — 2026-08-24
## Scope
Bounded local-memory compatibility work only:
- `LocalMemoryTools.panorama_search` now preserves the legacy all-graph inventory contract while relevance-ranking active and historical facts.
- `LocalMemoryTools.insight_forge` now derives entity insights and relationship chains from matching edges with the legacy-compatible output shape.
- `LocalEntityReader` rejects explicitly supplied graph IDs that differ from its repository-bound graph ID.
- `MEMORY_BACKEND=zep` remains the default compatibility path; this slice does not remove Zep or cut over ReportAgent/ProfileGenerator globally.
## TDD evidence
1. Added `backend/tests/fixtures/memory_parity/tools_fixture.json` with three entities, current and invalidated temporal edges, and one unrelated active edge.
2. Added `backend/tests/test_memory_parity.py` covering panorama inventory/temporal behavior, insight entity/relationship shape, and five conflicting graph-ID call forms.
3. Ran the new tests before the production change; the suite failed for the expected missing parity and scope behaviors.
4. Implemented the minimal adapter and reader changes.
5. Re-ran the focused parity suite: **8 passed**.
## Verification
- Focused consumer regression set: **17 passed**.
- Backend full suite: **81 passed**.
- Python `compileall`: **PASS**.
- `git diff --check`: **PASS**.
- Added-lines security scan: **0 findings**.
- `ruff`: unavailable in the backend environment; no lint pass is claimed.
- A probe run from repository root failed because that cwd cannot resolve the backend pytest executable; the same probe rerun from `backend/` passed 8/8. This is a command-location issue, not a test failure.
## Independent review gate
- The first bounded reviewer was stopped after exceeding the context/time budget; its silence was not treated as approval.
- Replacement reviewer: `deleg_73fac0de`.
- Required five-key JSON verdict: `passed=true`, `security_concerns=[]`, `logic_errors=[]`.
- Non-blocking suggestion: consider future LLM query decomposition for `insight_forge`; local `sub_queries=[query]` remains an explicit semantic gap outside this slice.
- This closes the review gate for this slice only. It is not approval of full semantic parity, the broader migration, or production readiness.
## Remaining boundary
This proves only the bounded panorama/insight/entity-reader contract. It does not prove semantic LLM parity (`sub_queries` remains local `[query]`), complete graph/profile/simulation/report E2E, all local consumer cutovers, migration parity, or production readiness.
@@ -0,0 +1,46 @@
# SaaS Foundation Verification — 2026-08-24
**Branch:** `feat/saas-foundation`
**Status:** in progress; not production-ready; no commit/push/deploy
## Milestone
Closed the confirmed TaskManager app-state leak and extended the durable-task tenant boundary. Added a deterministic local end-to-end regression covering graph → entity reader → profiles → simulation config → report tools → persisted report.
## Changes
- `TaskManager` now binds to the current Flask app's session factory at construction time instead of relying on app-factory global singleton state.
- In-memory TaskManager fallback remains test/legacy-only and isolated from app-bound managers; an app context without its configured factory now fails closed instead of using the class-global binding.
- Shared SQLite engine creation enables `PRAGMA foreign_keys=ON` for every connection, including migration/test engines.
- Durable `get_task()` and `list_tasks()` accept organization/owner filters and push predicates into SQLAlchemy queries.
- Scoped task lookup and graph task listing pass tenant/owner predicates before the defensive metadata check.
- Legacy asynchronous `GraphBuilderService` accepts session/tenant context and writes it into durable task metadata; authenticated graph build passes the captured context into the worker adapter.
- Added `test_local_graph_profile_simulation_report_is_persisted` and `test_graph_builder_async_task_keeps_organization_scope`.
## Verified evidence
- TDD regression sequence: app-context fallback, SQLite-FK, reused-manager, explicit-mismatch, prebound-manager, background-use, auxiliary API auth/CSRF/idempotency, cross-route idempotency, multipart-content, and local Zep-import-boundary tests were observed RED where applicable, then passed GREEN; the full backend suite passed afterward (**123 passed**, four Alembic deprecation warnings).
- Schema regression: **16 passed**, including migration round-trip/model alignment, SQLite foreign-key enforcement, invalid org/owner rejection, delete actions, cross-app TaskManager binding, and background use without Flask context.
- Auxiliary API regression: **8 passed**; all five routes are authenticated, LLM mutations enforce CSRF/idempotency, safe error responses are redacted, and completed mutation responses replay correctly.
- Idempotency regression: **5 passed**; the request fingerprint separates method/path/query/body and includes multipart file content hashes across repeated file fields.
- Local consumer-boundary regression: **5 fresh-import tests passed** plus the activity-dict boundary regression; fresh subprocess tests prove `app.services.local_graph_memory_updater`, `SimulationManager`, `SimulationRunner`, `ReportAgent`, and `GraphBuilderService` do not eagerly load `zep_cloud`, while activity conversion uses a neutral shared contract.
- Frontend contract tests: **10 passed**.
- `npm run build`: **passed**; existing Vite chunk/dynamic-import warnings remain.
- `PYTHONPATH= uv run python -m compileall -q app tests`: **passed**.
- Diff security scan over backend code: no `shell=True`, `eval/exec`, pickle loading, or hardcoded-secret assignment introduced.
- `ruff`: unavailable; not counted as a pass.
- Browser viewport capture at 320×568/500×768: **not verified** because Chrome requested an OS remote-debugging permission; no permission dialog was clicked.
## Risks / open boundaries
- The bounded local path is deterministic E2E; it does not prove semantic LLM parity or production worker durability.
- Zep remains the default and compatibility runtime; consumer cutover is not complete.
- Dockerfile still runs the development stack; no production WSGI/worker/object-storage topology has been verified.
- `ruff` and real browser viewport QA remain blocked/unavailable.
- Fresh independent bounded reviewer `deleg_fb0f80b0`: **PASS** (`passed=true`, empty `security_concerns` and `logic_errors`) after current-code app/factory mismatch probes for create/get/update/list paths, pooled and NullPool SQLite FK probes, migration round-trip, and ORM/migration parity. Suggestions are non-blocking and recorded in `HANDOFF.md`.
- Fresh independent auxiliary reviewer `deleg_d128494e`: **PASS** (`passed=true`, empty `security_concerns` and `logic_errors`) after verifying all five routes, decorator ordering, safe errors, and 8/8 targeted tests. Wider SaaS/Zep/deployment review remains open.
- Current-tree bounded local import-boundary reviewer `deleg_65bce3de`: **PASS** (`passed=true`, empty `security_concerns` and `logic_errors`) after running the focused boundary command (**6 passed**) and isolated probes for five fresh local imports, shared `AgentActivity`, explicit Zep paths, the `graph_builder.Zep` seam, and subprocess isolation. Suggestions are non-blocking; this closes only the import-boundary slice, not semantic parity or full consumer cutover.
## Next exact action
Inspect the non-blocking reviewer suggestions only if they are useful for the next test-hardening pass. The bounded schema/TaskManager slice is approved; keep the broader SaaS/Zep/deployment blockers explicit in `HANDOFF.md` and continue consumer cutover.
@@ -0,0 +1,53 @@
# Simulation Memory Fallback Hardening — 2026-08-24
## Scope
Close one local-memory safety gap without changing the migration decision:
- `MEMORY_BACKEND=zep` remains the default compatibility path.
- `MEMORY_BACKEND=local` must use an explicitly injected, request-scoped entity-reader factory.
- Local mode must not silently construct `ZepEntityReader` when the factory is absent.
## TDD evidence
1. Added `test_local_backend_refuses_unscoped_zep_reader_fallback` to
`backend/tests/test_simulation_memory_injection.py`.
2. The test failed against the pre-change fallback behavior.
3. `SimulationManager.create_entity_reader()` now raises the stable internal
sentinel `local_entity_reader_factory_required` in local mode when no
factory is injected.
4. Explicit factory injection remains unchanged.
## Verification
- Local-memory regression slice: **11 passed**.
- Backend full suite: **73 passed**.
- Frontend contract tests: **10 passed**.
- Frontend production build: **PASS**; existing chunk-size/dynamic-import warnings remain.
- Python `compileall`: **PASS**.
- `git diff --check`: **PASS**.
- Target-slice added-lines security scan: **0 findings**.
- Full-diff scan matched two password patterns in test-only fixtures; no production credential was identified by that scan.
- `ruff` is unavailable in the current backend environment; no lint pass is claimed.
## Independent review gate
- Fresh read-only reviewer: `deleg_029828b6`.
- Scope was limited to `SimulationManager.create_entity_reader()` and
`test_local_backend_refuses_unscoped_zep_reader_fallback()`.
- Required five-key verdict: `passed=true`, `security_concerns=[]`,
`logic_errors=[]`.
- Reviewer-reported runtime spy: local mode made **0** Zep constructor calls;
the default path made **1** Zep constructor call.
- Reviewer suggestions are non-blocking: add explicit constructor-spy
regression coverage for the local no-call path and the legacy/default path.
They are deferred to a later test-hardening pass; no production behavior gap
was found in this bounded slice.
- This closes the review gate for this slice only. It is not approval of the
full migration, semantic parity, or production readiness.
## Remaining migration boundary
This is a fail-closed guard, not Zep removal or semantic parity proof. Remaining
work includes complete local consumer cutover, parity fixtures, durable resource
persistence, production workers/object storage, and the full tenant E2E matrix.