gemstone-nexus · Phase 6
DOC03 — Product Requirements Document
Metadata
| id | doc_id | title | category | source_path | summary | content_hash | indexed_at |
|---|---|---|---|---|---|---|---|
| 21 | DOC03 | DOC03 — Product Requirements Document | prd | DevResources/docs/DOC03-PRD.md | ``` class SecurityTier(str, Enum): HIGH_SECURITY = "high_security" # numeric value 0 (most restrictive) STANDARD = "standard" # numeric value 1 OPEN_MODE = "open_mode" # numeric value 2 (least restrictive) | b1d8320af00bbd5acfe3807ae8422f30e94a40d9 | 2026-07-22 18:33:18 |
Content
# DOC03 — Product Requirements Document
*Schemas, API contracts, state machines, and full functional/non-functional requirements*
**Initiative:** GemStone · **Version:** v2.0 (Rewrite) · **Status:** Approved for Build · **Date:** July 17, 2026
## 1. Core Data Model
```
class SecurityTier(str, Enum):
HIGH_SECURITY = "high_security" # numeric value 0 (most restrictive)
STANDARD = "standard" # numeric value 1
OPEN_MODE = "open_mode" # numeric value 2 (least restrictive)
class Session(SQLModel, table=True):
__tablename__ = "sessions"
id: UUID = Field(default_factory=uuid4, primary_key=True)
org_id: UUID = Field(index=True)
practitioner_id: UUID = Field(index=True)
tier: SecurityTier = Field(index=True) # immutable after insert; enforced by DB trigger + TierGuard
mode: str # "field" | "extended"
notebook_ids: list[UUID] = Field(default_factory=list, sa_column=Column(JSON))
started_at: datetime
last_activity_at: datetime
ended_at: Optional[datetime] = None
interruption_snapshot: Optional[dict] = Field(default=None, sa_column=Column(JSON))
class DomainPack(SQLModel, table=True):
__tablename__ = "domain_packs"
id: UUID = Field(default_factory=uuid4, primary_key=True)
name: str = Field(unique=True)
version: str
system_prompt_extension: str
terminology: dict = Field(sa_column=Column(JSON))
methodology_templates: list[dict] = Field(sa_column=Column(JSON))
knowledge_doc_refs: list[str] = Field(sa_column=Column(JSON)) # MCP document IDs
class PackInstallation(SQLModel, table=True):
__tablename__ = "pack_installations"
practitioner_id: UUID = Field(foreign_key="practitioners.id", primary_key=True)
pack_id: UUID = Field(foreign_key="domain_packs.id", primary_key=True)
installed_at: datetime
active: bool = Field(default=True)
class Notebook(SQLModel, table=True):
__tablename__ = "notebooks"
id: UUID = Field(default_factory=uuid4, primary_key=True)
practitioner_id: UUID = Field(index=True)
name: str
created_at: datetime
# Recents is never a table; it is always the live query below, so Notebook
# membership can NEVER cause a session to disappear from it:
# SELECT * FROM sessions WHERE practitioner_id = :pid ORDER BY last_activity_at DESC
```
## 2. Voice Provider Abstraction
```
class STTProvider(ABC):
@abstractmethod
async def stream_transcribe(self, audio_chunk: bytes) -> TranscriptSegment: ...
@abstractmethod
def supports_streaming(self) -> bool: ...
class TTSProvider(ABC):
@abstractmethod
async def stream_synthesize(self, text: str) -> AsyncIterator[bytes]: ...
class WhisperSTTProvider(STTProvider): # self-hosted default, all tiers
...
class PiperTTSProvider(TTSProvider): # self-hosted default, all tiers
...
class AzureSpeechSTTProvider(STTProvider): # cloud, Standard/Open Mode only
...
class DeepgramSTTProvider(STTProvider): # cloud, Standard/Open Mode only
...
class VoiceProviderFactory:
def get_stt(self, tier: SecurityTier, preference: Optional[str]) -> STTProvider:
if tier == SecurityTier.HIGH_SECURITY:
return WhisperSTTProvider() # cloud providers never permitted at High Security
return PROVIDER_REGISTRY.get(preference, WhisperSTTProvider())
class StreamingAdapter:
"""Wraps a non-streaming provider to emit synthetic partial chunks."""
...
```
## 3. HUME AI: Formal Review Status
| Consideration | Assessment |
| --- | --- |
| Status | Pending Review, not integrated, no code path exists for it |
| Risk | Behavioral profiling risk; HUME infers emotional/behavioral state from voice beyond transcription |
| Minimum tier if approved | Open Mode only, never Standard or High Security, regardless of any Data Processing Agreement |
| Resolution path | A NEXTECH principal must review and approve HUME data handling terms in writing, with all Critical/High risk items resolved, before any integration work begins |
## 4. REST and WebSocket API Contract
| Method | Path | Request | Response |
| --- | --- | --- | --- |
| WS | /ws/session/{session_id} | Binary audio frames + JSON control messages | Streamed transcript segments, streamed TTS audio, control acks |
| POST | /api/sessions | {practitioner_id, tier, mode} | {session_id, tier, started_at} |
| GET | /api/sessions/{id} | - | Full session object including interruption_snapshot if paused |
| POST | /api/sessions/{id}/resume | {} | {restored: bool, last_turn: object} |
| POST | /api/notebooks | {practitioner_id, name} | {notebook_id} |
| POST | /api/notebooks/{id}/link | {session_id} | {linked: true} — additive only, never removes from Recents |
| POST | /api/search/inferenced | {practitioner_id, query} | {results: [{session_id, snippet, relevance}]} |
| POST | /api/domain-packs/{id}/install | {practitioner_id} | {installed_at, active: true} |
| DELETE | /api/domain-packs/{id}/install | {practitioner_id} | {active: false} |
| POST | /api/didymus/tasks | {requested_by, target_worker, task_type, payload} | {task_id, status: "PENDING"} |
| POST | /api/didymus/tasks/{id}/approve | {approved_by} | {status: "APPROVED", approved_at} |
## 5. Session Lifecycle State Machine
```
CREATED --(tier assigned, immutable)--> ACTIVE
ACTIVE --(OS audio focus loss incl. incoming call | network drop | app background)--> PAUSED
PAUSED --(interruption_snapshot written: token state, audio buffer, context)--> PAUSED
PAUSED --(session-ready chime fires)--> RESUMABLE
RESUMABLE --(one tap OR app reopen)--> ACTIVE [restores from interruption_snapshot via Atlas Vault]
ACTIVE --(explicit end OR extended timeout with confirmation)--> ENDED
# Three interruption causes share this path: OS audio focus loss (incl. incoming call),
# network drop, and app backgrounding. Extended timeout is ENDED, not RESUMABLE.
```
## 6. Didymus Task State Machine (GemStone-Facing View)
```
PENDING --(human sets approved_by + approved_at)--> APPROVED
# PENDING -> RUNNING is not a legal transition; the schema constraint blocks it.
APPROVED --(worker leases task, atomic UPDATE)--> RUNNING
RUNNING --(worker reports result)--> COMPLETED | FAILED
COMPLETED --(GemStone or worker verifies output)--> VERIFIED
# This state machine is IDENTICAL regardless of whether requested_by is
# a human user_id or the string "GemStone". Source never changes the path.
```
## 7. RBAC Permission Matrix
Auth0 is the identity provider. Roles SuperAdmin, Org Admin, Practitioner, and GemStone Agent are provisioned in the Auth0 tenant (DOC02 Phase 0). Social connections Google, Facebook, and LinkedIn are enabled for practitioner-facing login; role claims still come from Auth0 authorization, not from the social IdP alone.
| Action | SuperAdmin | Org Admin | Practitioner | GemStone Agent |
| --- | --- | --- | --- | --- |
| Create/modify org-level Domain Pack availability | Yes | Yes (own org) | No | No |
| Install/uninstall a Domain Pack for self | Yes | Yes | Yes | No |
| View another practitioner's session content | Yes (support only, audited) | No | No | No |
| Approve a Didymus task | Yes | Yes (own org scope) | Yes (own tasks) | No, never |
| Submit a Didymus task | Yes | Yes | Yes | Yes (as a proposer only) |
| Change a session's tier mid-session | No, nobody can, tier is immutable | No | No | No |
## 8. External Research Agent
The Research Agent performs Query Isolation and Entity Scrubbing (spaCy en_core_web_lg, self-hosted NER) on any query before it leaves the platform. Approved web search providers are Brave Search and Perplexity; approved synthesis providers are Claude API and Gemini API. Every external query generates an audit token logged to the Project Ledger. An Open Mode scrubbing toggle exists for practitioners who explicitly accept reduced scrubbing in that tier.
## 9. Three-Tier Security Model
Tier cascade evaluates as the minimum numeric value across the chain (Horizon IQ, Atlas, GemStone, Practitioner), so no layer can grant more access than the most restrictive layer above it. TierGuard is the single enforcement point; a secondary tier check anywhere else in the codebase is a defect. Session transcripts are never transmitted externally, in any tier, without exception.
```
def resolve_effective_tier(iq_tier: int, atlas_tier: int, gemstone_tier: int, practitioner_tier: int) -> int:
return min(iq_tier, atlas_tier, gemstone_tier, practitioner_tier)
class TierGuard:
"""The ONLY place tier-gated behavior is checked. Do not duplicate this logic."""
def enforce(self, session: Session, action: str) -> None:
if action in RESTRICTED_ACTIONS[session.tier]:
raise TierViolation(session.id, action, session.tier)
```
## 10. Domain Pack System
| Pack Component | Description |
| --- | --- |
| System Prompt Extension | Domain-specific behavioral instructions extending the base personality |
| Terminology Dictionary | Domain vocabulary GemStone uses fluently in conversation and documents |
| Methodology Templates | Pre-built methodology node templates seeded into Atlas Vault |
| Knowledge Documents | Curated reference material indexed in MCP for retrieval |
| Tool Integrations | Optional domain-specific tool connections |
## 11. First-Party Domain Packs, Phase 1
| Pack Name | Target Practitioner | Key Specializations |
| --- | --- | --- |
| PE Operating Partner | PE operating partners, portfolio company executives | Deal structuring, EBITDA optimization, board reporting, 100-day plans |
| Healthcare Executive | CMOs, CNOs, hospital administrators | Clinical operations, HIPAA/CMS compliance, value-based care |
| FinTech / Capital Markets | Fintech founders, investment managers | SEC/FINRA landscape, product structuring, risk frameworks |
| Management Consulting | Independent and firm-affiliated consultants | Engagement frameworks, change management, org design |
| Construction / Real Estate | Developers, owner-builders, construction managers | Project management, permitting, cost control |
| Manufacturing Operations | COOs, plant managers | Lean/Six Sigma, supply chain, production optimization |
## 12. Didymus Orchestration
GemStone is the single, universal presentation, approval, and orchestration surface for all build task suggestions, regardless of originating tool. Didymus captures full context/rationale for every suggestion and feeds a distilled version into Atlas Vault. No task, from any source, executes without human approval, at any platform maturity level.
## 13. GemStone Mobility Layer
Field Mode: foreground tap-to-talk via standard Capacitor WebView audio. Extended Sessions: native background audio (iOS AVAudioSession + UIBackgroundModes: audio; Android foreground service with FOREGROUND_SERVICE_TYPE_MICROPHONE), periodic mic-open cue, longer timeout with confirmation. Wake-word: configurable multi-phrase list; Android foreground-service on-device model; iOS Siri Shortcuts. Full detail in GS-MOB-01.
## 14. Non-Functional Requirements
- AES-256 at rest; TLS 1.3 in transit; no audio data to external APIs.
- Raw audio discarded immediately after transcription/indexing/vectorization into Atlas Vault.
- Failed vectorization holds audio in chunks, flags in-app and system log.
- OWASP Top 10 compliance; penetration testing at Phase 5.
- Session state survives Redis restart with AOF persistence enabled.
---
NEXTECH Business Technology Management LLC · nex-tech.biz · (941) 499-5505