@hotmeshio/hotmesh 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,52 +1,135 @@
1
1
  # HotMesh
2
2
 
3
- **Workflow That Remembers**
3
+ **Durable Memory + Coordinated Execution**
4
4
 
5
- ![beta release](https://img.shields.io/badge/release-beta-blue.svg) ![made with typescript](https://img.shields.io/badge/built%20with-typescript-lightblue.svg)
5
+ ![beta release](https://img.shields.io/badge/release-beta-blue.svg) ![made with typescript](https://img.shields.io/badge/built%20with-typescript-lightblue.svg)
6
6
 
7
- HotMesh brings a **memory model** to durable functions. Built on PostgreSQL, it treats your database as the runtime hub for agents, pipelines, and long-lived processes.
7
+ HotMesh removes the repetitive glue of building durable agents, pipelines, and long‑running workflows. Instead of you designing queues, schedulers, cache layers, and ad‑hoc state stores for each agent or pipeline, HotMesh standardizes the pattern:
8
8
 
9
- Use HotMesh to:
9
+ * **Entity (Core Memory)**: The authoritative JSONB document + its indexable “surface” fields.
10
+ * **Hooks (Durable Units of Work)**: Re‑entrant, idempotent functions that *maintain* the entity over time.
11
+ * **Workflow (Coordinator)**: The thin orchestration entry that seeds state, spawns hooks, and optionally synthesizes results.
12
+ * **Commands (State Mutation API)**: Atomic `set / merge / append / increment / tag / signal` updates with optimistic invariants handled by Postgres transactions.
10
13
 
11
- * **Store Evolving State** Retain memory/state between executions
12
- * **Coordinate Distributed Work** – Safely allow multiple workers to act on shared state
13
- * **Track and Replay** – Full audit history and replay support by default
14
+ You focus on *what should change in memory*; HotMesh handles *how it changes safely and durably.*
15
+
16
+ ---
17
+
18
+ ## Why It’s Easier with HotMesh
19
+
20
+ | Problem You Usually Solve Manually | HotMesh Built‑In | Impact |
21
+ | --------------------------------------------------- | ----------------------------------------- | ---------------------------------------------- |
22
+ | Designing per‑agent persistence and caches | Unified JSONB entity + typed accessors | One memory model across agents/pipelines |
23
+ | Preventing race conditions on shared state | Transactional hook writes | Safe parallel maintenance |
24
+ | Coordinating multi-perspective / multi-step work | Hook spawning + signals | Decomposed work without orchestration glue |
25
+ | Schema evolution / optional fields | Flexible JSONB + selective indexes | Add / adapt state incrementally |
26
+ | Querying live pipeline / agent status | SQL over materialized surfaces | Operational observability using standard tools |
27
+ | Avoiding duplicate side-effects during retry/replay | Deterministic re‑entry + idempotent hooks | Simplifies error handling |
28
+ | Per‑tenant isolation | Schema (or prefix) scoping | Clean multi‑tenant boundary |
29
+ | Background progression / fan‑out | `execHook` + signals | Natural concurrency without queue plumbing |
30
+
31
+ ---
32
+
33
+ ## Core Abstractions
34
+
35
+ ### 1. Entities
36
+
37
+ Durable JSONB documents representing *process memory*. Each entity:
38
+
39
+ * Has a stable identity (`workflowId` / logical key).
40
+ * Evolves via atomic commands.
41
+ * Is versioned implicitly by transactional history.
42
+ * Can be partially indexed for targeted query performance.
43
+
44
+ > **Design Note:** Treat entity shape as *contractual surface* + *freeform interior*. Index only the minimal surface required for lookups or dashboards.
45
+
46
+ ### 2. Hooks
47
+
48
+ Re‑entrant, idempotent, interruptible units of work that *maintain* an entity. Hooks can:
49
+
50
+ * Start, stop, or be re‑invoked without corrupting state.
51
+ * Run concurrently (Postgres ensures isolation on write).
52
+ * Emit signals to let coordinators or sibling hooks know a perspective / phase completed.
53
+
54
+ ### 3. Workflow Coordinators
55
+
56
+ Thin entrypoints that:
57
+
58
+ * Seed initial entity state.
59
+ * Fan out perspective / phase hooks.
60
+ * Optionally synthesize or finalize.
61
+ * Return a snapshot (often the final entity state) — *the workflow result is just memory*.
62
+
63
+ ### 4. Commands (Entity Mutation Primitives)
64
+
65
+ | Command | Purpose | Example |
66
+ | ----------- | ----------------------------------------- | ------------------------------------------------ |
67
+ | `set` | Replace full value (first write or reset) | `await e.set({ user: { id: 123, name: "John" } })` |
68
+ | `merge` | Deep JSON merge | `await e.merge({ user: { email: "john@example.com" } })` |
69
+ | `append` | Append to an array field | `await e.append('items', { id: 1, name: "New Item" })` |
70
+ | `prepend` | Add to start of array field | `await e.prepend('items', { id: 0, name: "First Item" })` |
71
+ | `remove` | Remove item from array by index | `await e.remove('items', 0)` |
72
+ | `increment` | Numeric counters / progress | `await e.increment('counter', 5)` |
73
+ | `toggle` | Toggle boolean value | `await e.toggle('settings.enabled')` |
74
+ | `setIfNotExists` | Set value only if path doesn't exist | `await e.setIfNotExists('user.id', 123)` |
75
+ | `delete` | Remove field at specified path | `await e.delete('user.email')` |
76
+ | `get` | Read value at path (or full entity) | `await e.get('user.email')` |
77
+ | `signal` | Mark hook milestone / unlock waiters | `await MemFlow.workflow.signal('phase-x', data)` |
78
+
79
+ The Entity module also provides static methods for cross-entity querying:
80
+
81
+ ```typescript
82
+ // Find entities matching conditions
83
+ const activeUsers = await Entity.find('user', {
84
+ status: 'active',
85
+ country: 'US'
86
+ });
87
+
88
+ // Find by specific field condition
89
+ const highValueOrders = await Entity.findByCondition(
90
+ 'order',
91
+ 'total_amount',
92
+ 1000,
93
+ '>=',
94
+ hotMeshClient
95
+ );
96
+
97
+ // Find single entity by ID
98
+ const user = await Entity.findById('user', 'user123', hotMeshClient);
99
+
100
+ // Create optimized index for queries
101
+ await Entity.createIndex('user', 'email', hotMeshClient);
102
+ ```
14
103
 
15
104
  ---
16
105
 
17
106
  ## Table of Contents
18
107
 
19
108
  1. [Quick Start](#quick-start)
20
- 2. [Permanent Memory Architecture](#permanent-memory-architecture)
109
+ 2. [Memory Architecture](#memory-architecture)
21
110
  3. [Durable AI Agents](#durable-ai-agents)
22
- 4. [Building Pipelines with State](#building-pipelines-with-state)
23
- 5. [Documentation & Links](#documentation--links)
111
+ 4. [Stateful Pipelines](#stateful-pipelines)
112
+ 5. [Indexing Strategy](#indexing-strategy)
113
+ 6. [Operational Notes](#operational-notes)
114
+ 7. [Documentation & Links](#documentation--links)
24
115
 
25
116
  ---
26
117
 
27
118
  ## Quick Start
28
119
 
29
- ### Prerequisites
30
-
31
- * PostgreSQL (or Supabase)
32
- * Node.js 16+
33
-
34
120
  ### Install
35
121
 
36
122
  ```bash
37
123
  npm install @hotmeshio/hotmesh
38
124
  ```
39
125
 
40
- ### Connect to a Database
41
-
42
- HotMesh leverages Temporal.io's developer-friendly syntax for authoring workers, workflows, and clients. The `init` and `start` methods should look familiar.
43
-
126
+ ### Minimal Setup
44
127
  ```ts
45
128
  import { MemFlow } from '@hotmeshio/hotmesh';
46
129
  import { Client as Postgres } from 'pg';
47
130
 
48
131
  async function main() {
49
- // MemFlow will auto-provision the database upon init
132
+ // Auto-provisions required tables/index scaffolding on first run
50
133
  const mf = await MemFlow.init({
51
134
  appId: 'my-app',
52
135
  engine: {
@@ -57,157 +140,129 @@ async function main() {
57
140
  }
58
141
  });
59
142
 
60
- // Start a workflow with an assigned ID and arguments
143
+ // Start a durable research agent (entity-backed workflow)
61
144
  const handle = await mf.workflow.start({
62
145
  entity: 'research-agent',
63
146
  workflowName: 'researchAgent',
64
147
  workflowId: 'agent-session-jane-001',
65
- args: ['What are the long-term impacts of renewable energy subsidies?'],
148
+ args: ['Long-term impacts of renewable energy subsidies'],
66
149
  taskQueue: 'agents'
67
150
  });
68
151
 
69
- console.log('Result:', await handle.result());
152
+ console.log('Final Memory Snapshot:', await handle.result());
70
153
  }
71
154
 
72
155
  main().catch(console.error);
73
156
  ```
74
157
 
75
- ### System Benefits
76
-
77
- * **No Setup Required** – Tables and indexes are provisioned automatically
78
- * **Shared State** – Every worker shares access to the same entity memory
79
- * **Coordination by Design** PostgreSQL handles consistency and isolation
80
- * **Tenant Isolation** – Each app maintains its own schema
81
- * **Scalable Defaults** – Partitioned tables and index support included
158
+ ### Value Checklist (What You Did *Not* Have To Do)
159
+ - Create tables / migrations
160
+ - Define per-agent caches
161
+ - Implement optimistic locking
162
+ - Build a queue fan‑out mechanism
163
+ - Hand-roll replay protection
82
164
 
83
165
  ---
84
166
 
85
- ## Permanent Memory Architecture
167
+ ## Memory Architecture
168
+ Each workflow = **1 durable entity**. Hooks are stateless functions *shaped by* that entity's evolving JSON. You can inspect or modify it at any time using ordinary SQL or the provided API.
86
169
 
87
- Every workflow in HotMesh is backed by an "entity": a versioned, JSONB record that tracks its memory and state transitions.
88
-
89
- * **Entities** Represent long-lived state for a workflow or agent
90
- * **Commands** Modify state with methods like `set`, `merge`, `append`, `increment`
91
- * **Consistency** – All updates are transactional with Postgres
92
- * **Replay Safety** Protects against duplicated side effects during re-execution
93
- * **Partial Indexing** Optimized querying of fields within large JSON structures
94
-
95
- ### Example: Partial Index for Premium Users
170
+ ### Programmatic Indexing
171
+ ```ts
172
+ // Create index for premium research agents
173
+ await MemFlow.Entity.createIndex('research-agent', 'isPremium', hotMeshClient);
174
+
175
+ // Find premium agents needing verification
176
+ const agents = await MemFlow.Entity.find('research-agent', {
177
+ isPremium: true,
178
+ needsVerification: true
179
+ }, hotMeshClient);
180
+ ```
96
181
 
182
+ ### Direct SQL Access
97
183
  ```sql
98
- -- Index only those user entities that are marked as premium
99
- CREATE INDEX idx_user_premium ON your_app.jobs (id)
100
- WHERE entity = 'user' AND (context->>'isPremium')::boolean = true;
184
+ -- Same index via SQL (more control over index type/conditions)
185
+ CREATE INDEX idx_research_agents_premium ON my_app.jobs (id)
186
+ WHERE entity = 'research-agent' AND (context->>'isPremium')::boolean = true;
187
+
188
+ -- Ad hoc query example
189
+ SELECT id, context->>'status' as status, context->>'confidence' as confidence
190
+ FROM my_app.jobs
191
+ WHERE entity = 'research-agent'
192
+ AND (context->>'isPremium')::boolean = true
193
+ AND (context->>'confidence')::numeric > 0.8;
101
194
  ```
102
195
 
103
- This index improves performance for filtered queries while reducing index size.
196
+ **Guidelines:**
197
+ 1. *Model intent, not mechanics.* Keep ephemeral calculation artifacts minimal; store derived values only if reused.
198
+ 2. *Index sparingly.* Each index is a write amplification cost. Start with 1–2 selective partial indexes.
199
+ 3. *Keep arrays append‑only where possible.* Supports audit and replay semantics cheaply.
200
+ 4. *Choose your tool:* Use Entity methods for standard queries, raw SQL for complex analytics or custom indexes.
104
201
 
105
202
  ---
106
203
 
107
204
  ## Durable AI Agents
205
+ Agents become simpler: the *agent* is the memory record; hooks supply perspectives, verification, enrichment, or lifecycle progression.
108
206
 
109
- Agents often require memory—context that persists between invocations, spans multiple perspectives, or outlives a single process.
110
-
111
- The following example builds a "research agent" that executes hooks with different perspectives and then synthesizes. The data-first approach sets up initial state and then uses temporary hook functions to augment over the lifecycle of the entity record.
112
-
113
- ### Research Agent Example
114
-
115
- #### Main Coordinator Agent
116
-
207
+ ### Coordinator (Research Agent)
117
208
  ```ts
118
- export async function researchAgent(query: string): Promise<any> {
119
- const agent = await MemFlow.workflow.entity();
209
+ export async function researchAgent(query: string) {
210
+ const entity = await MemFlow.workflow.entity();
120
211
 
121
- // Set up shared memory for this agent session
122
- const initialState = {
212
+ const initial = {
123
213
  query,
124
214
  findings: [],
125
215
  perspectives: {},
126
216
  confidence: 0,
127
217
  verification: {},
128
218
  status: 'researching',
129
- startTime: new Date().toISOString(),
130
- }
131
- await agent.set<typeof initialState>(initialState);
132
-
133
- // Launch perspective hooks
134
- await MemFlow.workflow.execHook({
135
- taskQueue: 'agents',
136
- workflowName: 'optimisticPerspective',
137
- args: [query],
138
- signalId: 'optimistic-complete'
139
- });
140
-
141
- await MemFlow.workflow.execHook({
142
- taskQueue: 'agents',
143
- workflowName: 'skepticalPerspective',
144
- args: [query],
145
- signalId: 'skeptical-complete'
146
- });
147
-
148
- await MemFlow.workflow.execHook({
149
- taskQueue: 'agents',
150
- workflowName: 'verificationHook',
151
- args: [query],
152
- signalId: 'verification-complete'
153
- });
219
+ startTime: new Date().toISOString()
220
+ };
221
+ await entity.set<typeof initial>(initial);
154
222
 
155
- await MemFlow.workflow.execHook({
156
- taskQueue: 'perspectives',
157
- workflowName: 'synthesizePerspectives',
158
- args: [],
159
- signalId: 'synthesis-complete',
160
- });
223
+ // Fan-out perspectives
224
+ await MemFlow.workflow.execHook({ taskQueue: 'agents', workflowName: 'optimisticPerspective', args: [query], signalId: 'optimistic-complete' });
225
+ await MemFlow.workflow.execHook({ taskQueue: 'agents', workflowName: 'skepticalPerspective', args: [query], signalId: 'skeptical-complete' });
226
+ await MemFlow.workflow.execHook({ taskQueue: 'agents', workflowName: 'verificationHook', args: [query], signalId: 'verification-complete' });
227
+ await MemFlow.workflow.execHook({ taskQueue: 'agents', workflowName: 'synthesizePerspectives', args: [], signalId: 'synthesis-complete' });
161
228
 
162
- // return analysis, verification, and synthesis
163
- return await agent.get();
229
+ return await entity.get();
164
230
  }
165
231
  ```
166
232
 
167
-
168
- Let's look at one of these hooks in detail - the synthesis hook that combines all perspectives into a final assessment:
169
-
170
- #### Synthesis Hook
171
-
233
+ ### Synthesis Hook
172
234
  ```ts
173
- // Synthesis hook aggregates different viewpoints
174
- export async function synthesizePerspectives(config: {signal: string}): Promise<void> {
175
- const entity = await MemFlow.workflow.entity();
176
- const context = await entity.get();
177
-
178
- const result = await analyzePerspectives(context.perspectives);
235
+ export async function synthesizePerspectives({ signal }: { signal: string }) {
236
+ const e = await MemFlow.workflow.entity();
237
+ const ctx = await e.get();
179
238
 
180
- await entity.merge({
239
+ const synthesized = await analyzePerspectives(ctx.perspectives);
240
+ await e.merge({
181
241
  perspectives: {
182
242
  synthesis: {
183
- finalAssessment: result,
184
- confidence: calculateConfidence(context.perspectives)
243
+ finalAssessment: synthesized,
244
+ confidence: calculateConfidence(ctx.perspectives)
185
245
  }
186
246
  },
187
247
  status: 'completed'
188
248
  });
189
- await MemFlow.workflow.signal(config.signal, {});
249
+ await MemFlow.workflow.signal(signal, {});
190
250
  }
191
-
192
- //other hooks...
193
251
  ```
194
252
 
195
- > 💡 A complete implementation of this Research Agent example with tests, OpenAI integration, and multi-perspective analysis can be found in the [agent test suite](https://github.com/hotmeshio/sdk-typescript/tree/main/tests/memflow/agent).
253
+ > **Pattern:** Fan-out hooks that write *adjacent* subtrees (e.g., `perspectives.optimistic`, `perspectives.skeptical`). A final hook merges a compact synthesis object. Avoid cross-hook mutation of the same nested branch.
196
254
 
197
255
  ---
198
256
 
199
- ## Building Pipelines with State
200
-
201
- HotMesh treats pipelines as long-lived records. Every pipeline run is stateful, resumable, and traceable. Hooks can be re-run at any time, and can be invoked by external callers. Sleep and run on a cadence to keep the pipeline up to date.
202
-
203
- ### Setup a Data Pipeline
257
+ ## Stateful Pipelines
258
+ Pipelines are identical in structure to agents: a coordinator seeds memory; phase hooks advance state; the entity is the audit trail.
204
259
 
260
+ ### Document Processing Pipeline (Coordinator)
205
261
  ```ts
206
- export async function documentProcessingPipeline(): Promise<any> {
262
+ export async function documentProcessingPipeline() {
207
263
  const pipeline = await MemFlow.workflow.entity();
208
264
 
209
- // Initialize pipeline state with empty arrays
210
- const initialState = {
265
+ const initial = {
211
266
  documentId: `doc-${Date.now()}`,
212
267
  status: 'started',
213
268
  startTime: new Date().toISOString(),
@@ -219,73 +274,54 @@ export async function documentProcessingPipeline(): Promise<any> {
219
274
  errors: [],
220
275
  pageSignals: {}
221
276
  };
222
-
223
- await pipeline.set<typeof initialState>(initialState);
277
+ await pipeline.set<typeof initial>(initial);
224
278
 
225
- // Step 1: Get list of image file references
226
- await pipeline.merge({status: 'loading-images'});
279
+ await pipeline.merge({ status: 'loading-images' });
227
280
  await pipeline.append('processingSteps', 'image-load-started');
228
281
  const imageRefs = await activities.loadImagePages();
229
- if (!imageRefs || imageRefs.length === 0) {
230
- throw new Error('No image references found');
231
- }
232
- await pipeline.merge({imageRefs});
282
+ if (!imageRefs?.length) throw new Error('No image references found');
283
+ await pipeline.merge({ imageRefs });
233
284
  await pipeline.append('processingSteps', 'image-load-completed');
234
285
 
235
- // Step 2: Launch processing hooks for each page
236
- for (const [index, imageRef] of imageRefs.entries()) {
237
- const pageNumber = index + 1;
238
-
286
+ // Page hooks
287
+ for (const [i, ref] of imageRefs.entries()) {
288
+ const page = i + 1;
239
289
  await MemFlow.workflow.execHook({
240
290
  taskQueue: 'pipeline',
241
291
  workflowName: 'pageProcessingHook',
242
- args: [imageRef, pageNumber, initialState.documentId],
243
- signalId: `page-${pageNumber}-complete`
292
+ args: [ref, page, initial.documentId],
293
+ signalId: `page-${page}-complete`
244
294
  });
245
- };
246
-
247
- // Step 3: Launch validation hook
248
- await MemFlow.workflow.execHook({
249
- taskQueue: 'pipeline',
250
- workflowName: 'validationHook',
251
- args: [initialState.documentId],
252
- signalId: 'validation-complete'
253
- });
254
-
255
- // Step 4: Launch approval hook
256
- await MemFlow.workflow.execHook({
257
- taskQueue: 'pipeline',
258
- workflowName: 'approvalHook',
259
- args: [initialState.documentId],
260
- signalId: 'approval-complete',
261
- });
295
+ }
262
296
 
263
- // Step 5: Launch notification hook
264
- await MemFlow.workflow.execHook({
265
- taskQueue: 'pipeline',
266
- workflowName: 'notificationHook',
267
- args: [initialState.documentId],
268
- signalId: 'processing-complete',
269
- });
297
+ // Validation
298
+ await MemFlow.workflow.execHook({ taskQueue: 'pipeline', workflowName: 'validationHook', args: [initial.documentId], signalId: 'validation-complete' });
299
+ // Approval
300
+ await MemFlow.workflow.execHook({ taskQueue: 'pipeline', workflowName: 'approvalHook', args: [initial.documentId], signalId: 'approval-complete' });
301
+ // Notification
302
+ await MemFlow.workflow.execHook({ taskQueue: 'pipeline', workflowName: 'notificationHook', args: [initial.documentId], signalId: 'processing-complete' });
270
303
 
271
- // Step 6: Return final state
272
- await pipeline.merge({status: 'completed', completedAt: new Date().toISOString()});
304
+ await pipeline.merge({ status: 'completed', completedAt: new Date().toISOString() });
273
305
  await pipeline.append('processingSteps', 'pipeline-completed');
274
306
  return await pipeline.get();
275
307
  }
276
308
  ```
277
309
 
278
- > 💡 A complete implementation of this Pipeline example with OpenAI Vision integration, processing hooks, and document workflow automation can be found in the [pipeline test suite](https://github.com/hotmeshio/sdk-typescript/tree/main/tests/memflow/pipeline).
310
+ **Operational Characteristics:**
311
+ - *Replay Friendly*: Each hook can be retried; pipeline memory records invariant progress markers (`processingSteps`).
312
+ - *Parallelizable*: Pages fan out naturally without manual queue wiring.
313
+ - *Auditable*: Entire lifecycle captured in a single evolving JSON record.
279
314
 
280
315
  ---
281
316
 
282
317
  ## Documentation & Links
283
-
284
- * SDK Reference[hotmeshio.github.io/sdk-typescript](https://hotmeshio.github.io/sdk-typescript)
285
- * Examples[github.com/hotmeshio/samples-typescript](https://github.com/hotmeshio/samples-typescript)
318
+ * **SDK Reference** – https://hotmeshio.github.io/sdk-typescript
319
+ * **Agent Example Tests** – https://github.com/hotmeshio/sdk-typescript/tree/main/tests/memflow/agent
320
+ * **Pipeline Example Tests** https://github.com/hotmeshio/sdk-typescript/tree/main/tests/memflow/pipeline
321
+ * **Sample Projects** – https://github.com/hotmeshio/samples-typescript
286
322
 
287
323
  ---
288
324
 
289
325
  ## License
290
-
291
- Apache 2.0 with commercial restrictions See `LICENSE` for details.
326
+ Apache 2.0 with commercial restrictions* – see `LICENSE`.
327
+ >*NOTE: It's open source with one commercial exception: Build, sell, and share solutions made with HotMesh. But don't white-label the orchestration core and repackage it as your own workflow-as-a-service.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Permanent-Memory Workflows & AI Agents",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Permanent-Memory Workflows & AI Agents",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",