fortistate
v3.0.0
Published
๐ A powerful state management library with collaborative inspector, real-time debugging, store snapshots, and IDE integration. Features include share snapshots, locate stores in code, and team collaboration tools.
Maintainers
Readme
fortistate
Version 3.0 - Collaborative Inspector Edition ๐ฅ
A powerful state management library with collaborative inspector, real-time debugging, and IDE integration. Share snapshots ๐ธ, locate stores in code ๐, and collaborate with your team in real-time!
๏ฟฝ What's New in v3.0!
Collaborative Inspector Features
๐ธ Share Store Snapshots
- One-click shareable URLs with encoded state
- Export as JSON, CSV, Email, or Tweet
- Perfect for bug reports and team collaboration
๐ Locate Store in Code
- Automatically opens store files in VS Code
- Intelligent search pattern generation
- Works with VS Code, WebStorm, and GitHub
๐ฅ Invite Team to Inspector
- Share inspector session URLs
- QR code for mobile access
- Real-time collaboration and debugging
๐จ Aurora White Theme
- Beautiful, professional interface
- Improved readability and UX
- Modern glassmorphism design
See full v3.0 release notes โ
๐ Quick Start
Installation
npm install fortistateCreate a Store
import { createStore } from 'fortistate'
const counterStore = createStore('counter', { count: 0 })Start the Inspector
npx fortistate inspectOpen http://localhost:4000 and enjoy the new collaboration features!
Use New v3.0 Features
- Click ๐ธ on any store to share snapshots
- Click ๐ to locate store in your code (auto-opens VS Code!)
- Click ๐ฅ Invite to share with your team
๐ฏ Advanced Features (v2.0 - Cosmogenesis Engine)
From Cosmogenesis Engine โ Substrate of Possibility โ Evolution into "Figma for State Management" with quantum mechanics and relativity built-in.
๐ Meta-Laws Engine is live! Compose laws with conflict resolution:
Week 7-8: Meta-Laws Engine โ๏ธ
- ๐ Law composition: AND/OR/IMPLIES/SEQUENCE/PARALLEL operators
- โก Conflict resolution: 7 strategies (priority, voting, frame-dependent, etc.)
- ๐งฉ Dynamic mutation: Add/remove laws at runtime
- ๐จ Helper functions:
and(),or(),implies(),sequence() - ๐ฏ 157/161 tests passing (97.5% - core functionality 100%)
Meta-laws docs โ | Progress tracker โ
Week 5-6: Relativistic Substrate ๐
- ๐ Observer frames: Multiple perspectives with relative velocities
- โฑ๏ธ Causal ordering: Light cone constraints, no time paradoxes
- ๐ Lorentz transformations: Time dilation for distributed systems
- ๐ 29 new tests: 133/133 v3.0 tests passing (100%)
Week 3-4: Quantum Substrate โ๏ธ
- ๐ Superposition: States exist in multiple possibilities simultaneously
- ๐ Entanglement: Spooky action between entities
- ๐๏ธ Observer: Collapse superpositions via measurement (Born rule)
- ๐ 37 new tests: 104/104 v3.0 tests passing (100%)
Week 1-2: Possibility Algebra ๐ค
- ๐๏ธ Entity primitive: Type-safe entity definitions
- ๐ Constraint primitive: Validation with auto-repair
- โ๏ธ Law primitive: Universal rules governing behavior
- ๐ 67 tests: Foundation complete
๐ v3.0 Quick Start
Meta-Law Composition
import { defineMetaLaw, defineLaw, and } from '@fortistate/possibility'
// Define individual laws
const creditCheck = defineLaw({
name: 'credit-check',
inputs: ['customer'],
output: 'approved',
enforce: (c) => c.creditScore > 650
})
const inventoryCheck = defineLaw({
name: 'inventory-check',
inputs: ['product'],
output: 'available',
enforce: (p) => p.stock > 0
})
const fraudCheck = defineLaw({
name: 'fraud-check',
inputs: ['transaction'],
output: 'safe',
enforce: (t) => !t.flagged && t.amount < 10000
})
// Compose into meta-law (ALL must pass)
const orderApproval = and('order-approval', [
creditCheck,
inventoryCheck,
fraudCheck
], {
conflictResolution: 'error',
context: { mode: 'strict' }
})
// Execute
const result = orderApproval.execute([customer, product, transaction])
if (result.success) {
console.log('Order approved! โ
')
} else {
console.log('Order denied:', result.error)
console.log('Failed checks:',
Array.from(result.lawResults.entries())
.filter(([_, r]) => !r.success)
.map(([name, _]) => name)
)
}๐ What's New in v2.0 (Phase 3D Complete!)
๐ Physics Simulations are live! Latest achievements:
Phase 3D: Physics Simulations ๏ฟฝ
- โ๏ธ Classical mechanics substrate: Gravity, friction, momentum, energy
- ๐ฅ Collision detection & resolution: Elastic collisions with conservation laws
- ๐ Vector mathematics: 2D physics operations and utilities
- ๐ Constraint enforcement: Mass positivity, velocity limits, position bounds
- ๐ Energy tracking: Kinetic, potential, and total energy calculations
- ๐ฎ Example simulations: Bouncing ball, multi-body collisions
Physics guide โ | Examples โ
Phase 3C: Performance Harness โก
- ๐ Statistical benchmarking: P95/P99 analysis with warmup
- ๐ฏ Result: 5.6ms average (3x better than 15ms target!)
- ๐พ Memory tracking: ~38MB for 10k events
- ๐ Scalability testing: Constraint overhead, repairs, cross-store laws
Phase 3B: Universe Manager ๐
- ๐ Universe orchestration: Manage multiple causal stores as unified realities
- ๐ Lifecycle management: Start, pause, resume, destroy universes
- ๐ธ Snapshots & time travel: Capture and restore complete universe state
- ๐ฟ Universe forking: Create alternate timelines with divergent state
- ๐ Multiverse coordination: Manage multiple universes simultaneously
Universe docs โ | Quick reference โ | Full roadmap โ
Phase 1 (Temporal Foundation):
- โฐ Time travel: Jump to any state in history
- ๐ฟ Universe branching: Create parallel timelines
- ๐ Entropy measurement: Quantify state complexity
- ๐ Existence constraints: Define "laws of nature"
Phase 1 summary โ | Migration guide โ
Quick install & getting started
npm install fortistateBasic Usage (v1.x compatible)
import { createStore, useStore } from 'fortistate'
const counter = createStore({ value: 0 })
function Counter() {
const [state, setState] = useStore(counter)
return <button onClick={() => setState(s => ({ value: s.value + 1 }))}>
{state.value}
</button>
}New: Temporal State & Universe Management (v2.0+)
import { createUniverse } from 'fortistate'
// Define laws of physics for your universe
const substrate = {
id: 'my-app',
name: 'Application Rules',
constraints: new Map([...]),
laws: new Map([...]),
}
// Create a universe with multiple stores
const universe = createUniverse({
id: 'my-app',
substrate,
})
// Create stores within the universe
const counter = universe.createStore('counter', 0)
const user = universe.createStore('user', { name: 'Alice' })
// Time travel
const pastState = counter.at(Date.now() - 5000) // 5 seconds ago
// Snapshots
const checkpoint = universe.snapshot()
universe.restore(checkpoint) // Rollback to checkpoint
// Forking (create parallel realities)
const fork = universe.fork('experiment-a')
fork.getStore('counter')?.set(999) // Changes don't affect original
// Multiverse coordination
import { Multiverse } from 'fortistate'
const multiverse = new Multiverse()
multiverse.add(universe1)
multiverse.add(universe2)
multiverse.pauseAll() // Freeze all universesFull Universe Manager guide โ
Quickstarts
React (hooks)
import React from 'react'
import { createStore, useStore } from 'fortistate'
const counter = createStore({ value: 0 })
function Counter(){
const [state, setState] = useStore(counter)
return <button onClick={() => setState(s => ({ value: s.value + 1 }))}>{state.value}</button>
}
export default CounterVue (composition)
import { createStore, useStore } from 'fortistate'
import { ref } from 'vue'
const counter = createStore({ value: 0 })
export default {
setup(){
const [state, setState] = useStore(counter)
return { state, inc: () => setState(s => ({ value: s.value + 1 })) }
}
}Next.js (auto-register example)
See examples/my-nextjs-app for a full Next.js example that auto-registers stores on the client and demonstrates the inspector integration.
Zero-config inspector
Start a local inspector for your project (zero-config):
npm run inspect
# or
npx fortistate inspectBy default the inspector runs an HTTP server that serves a small UI and a WebSocket endpoint. Browser agents (examples included) auto-register client stores and stream updates to the inspector. Use --token and --allow-origin flags to control access in shared environments.
CLI / Inspector flags
The CLI exposes a few useful flags when running npx fortistate inspect or npm run inspect:
--port <n>: specify the inspector port (default 4000).--token <token>: provide a legacy shared token (backward compatibility only โ use session-based auth for production).--allow-origin <origin>: add an allowed origin for CORS.--quiet: reduce debug logs in tests or CI.FORTISTATE_REQUIRE_SESSIONS=1: require issued sessions for write operations; combine withFORTISTATE_ALLOW_ANON_SESSIONS=1to keep anonymous read-only access during local testing.
New: Session management via CLI
# Create editor session
fortistate session create --role editor --label "Alice" --ttl 24h
# List active sessions (requires admin token)
fortistate session list --port 4000 --token <admin-token>
# Revoke session
fortistate session revoke <session-id> --token <admin-token>Run fortistate help for complete command reference and environment variable documentation.
Example:
npx fortistate inspect --port 3333 --allow-origin http://localhost:3000For comprehensive session workflows, see docs/SESSION_WORKFLOWS.md.
Config-driven presets & plugins
- The inspector now looks for
fortistate.config.{js,cjs,mjs}in its working directory and automatically loads any declared presets or plugins. - Presets that return additional plugins are resolved before plugin execution, matching the RFC roadmap for a Tailwind-like ecosystem.
- Config changes (or updates to string-referenced presets/plugins) trigger a reload via
chokidar; the inspector refreshes registered stores in-place and broadcasts updates to connected clients. - Use the environment variable
FORTISTATE_DISABLE_CONFIG_WATCH=1to disable file watching when running in environments where filesystem watchers are not desirable. - When a plugin/preset is removed from the config, the associated stores are cleaned up from the inspector's remote view so the UI stays in sync with the source of truth.
Developer experience (DX)
- One-line install and small runtime make adoption trivial.
- Hooks for React/Vue and an example Next.js app make getting started fast.
- Inspector provides live remote inspection, persisted registrations across restarts, and simple token/origin controls for basic security.
CI and stability
There is a small CI workflow that runs tests and builds on push and pull requests; it helps keep the package stable. See .github/workflows/ci.yml for details.
Examples and templates
Look in examples/ for working integrations (Next.js example and a small inspector client). Contributing templates and migration recipes are planned to make adoption even easier.
Contributing
See CONTRIBUTING.md for contribution guidelines and release notes.
Small utility-first state library and tooling.
Testing
- Tests are run with Vitest. There is a global
testTimeoutconfigured invitest.config.tsset to 20000ms to allow network/socket tests (inspector) to be stable in CI. - The inspector integration test opens a local WebSocket, requests a snapshot and verifies that stores are included. The test runs quietly in CI by default (the inspector server is created with
quiet: true).
Run tests locally:
npm ci
npm run build
npm testInspector (dev tooling)
Fortistate ships a lightweight inspector that runs an HTTP + WebSocket server (default port 4000, examples use 4555).
Start the inspector:
# from the fortistate package root
node dist/cli.js inspect 4555Options:
- --token โ require requests to include header x-fortistate-token for /register and /change
- --allow-origin โ set Access-Control-Allow-Origin for CORS (useful for browser clients)
Dev helper:
- GET /set-token โ small HTML form to set a token for local dev
- POST /set-token โ accepts JSON or form-encoded token and saves
.fortistate-inspector-tokenin working dir (dev only)
Snapshots and persistence:
- Remote registrations are stored in
.fortistate-remote-stores.jsonand loaded at inspector startup.
Collaboration & security:
- Set
FORTISTATE_REQUIRE_SESSIONS=1to require session tokens for write endpoints and WebSocket connections. Create sessions viaPOST /session/create(roles:observer,editor,admin). - The inspector issues JWT-based sessions by default; provide
FORTISTATE_SESSION_SECRETto persist tokens across restarts (otherwise ephemeral secret is generated). - Audit entries are appended to
.fortistate-audit.log(JSON Lines). Admin sessions can retrieve recent entries viaGET /audit/log?limit=<n>&format=<json|csv|plain>. Logs rotate automatically by size (default: 1 MB) or age (default: 30 days); configure withFORTISTATE_AUDIT_MAX_SIZE(bytes) andFORTISTATE_AUDIT_ROTATE_DAYS. - Admins can clean up access with
POST /session/revoke, passing either asessionIdortokento invalidate. - New: Role-based middleware simplifies endpoint guards. See
docs/AUTHENTICATION.mdfor comprehensive auth documentation and security best practices.
Release notes โ v1.0.1
- Inspector: added persistence for remote-registered stores, token support, CORS/allow-origin support, and a small dev token setter UI.
- CLI: added
--tokenand--allow-originflags forinspectcommand. - Example: Next.js example auto-registers demo counter to the inspector for easier testing.
What's new (latest)
- Embedded inspector client: safer event wiring (no inline onclick code), modernized UI, and a new store filter input for easier navigation.
- Auto-swap detection: the inspector can now heuristically detect the host app's active store key (URL param, data-active-key, or common names) and swap stores without manual key entry.
- Presets & CSS: apply presets remotely; installer helper can optionally write a preset's CSS into the project. The inspector UI now has clearer apply / install CSS buttons.
- Favicon support: inspector serves
/favicon.icofrom the project root if present (or a packaged fallback), so you can set a custom icon. - Example fixes: Next.js demo now reflects the selected store in the header and actions (inc/dec/reset) operate on the selected store.
Publishing a release (npm + GitHub)
- Bump the package version in
package.json(semver). Example to set v1.0.2:
npm version patch -m "release: v%s"- Build the package and run tests:
npm run build
npm test- Dry-run publish to check packaged files:
npm publish --dry-run- Publish to npm and push a git tag (example using npm to publish):
npm publish
git push origin --follow-tags- Create a GitHub release (optional) and attach the changelog/notes. If you want, I can automatically create a release for you after publishing.
Notes:
- If your project uses a CI workflow to publish from tags (recommended), consider adding a GitHub Actions workflow to publish on semantic version tags. I can add a sample workflow if you'd like.
