duroxide-node
Copilot instructions36 starsChanged 57 days agoMITView on GitHub
π¨ STOP: DO NOT git commit OR git push WITHOUT EXPLICIT USER PERMISSION π¨ Always ask before committing or pushing. Never assume. When making changes to this SDK, always check ../duroxide-python for symmetry: 1. Bug fixes: If you fix a bug here, apply the same fix in duroxide-python (and vice versa) 2. API parity: Every public API in one SDK must have an equivalent in the other (adjusted for language idioms β camelCase in JS, snake_case in Python) 3. Testβ¦
- Reads credentials
- Commits and pushes
In this repository3 other files it gives its agents.
- duroxide-node-orchestrationsSkill
- napi-interopSkill
- release-preparationSkill
The file
Show its rules and text
We split this copilot-instructions.md into the rules it gives an agent
16 rules. About 0 are common, 3 are distinctive, and 13 are very specific to this project.
β0
Common Β· estimate
Many files like this have a rule of this kind.
β3
Distinctive Β· estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 9
When making changes to this SDK, always check ../duroxide-python for symmetry:
- Distinctive: line 10
Bug fixes: If you fix a bug here, apply the same fix in duroxide-python (and vice versa)
- Distinctive: line 11
API parity: Every public API in one SDK must have an equivalent in the other (adjusted for language idioms β camelCase in JS, snake_case in β¦
- Distinctive: line 12
Test parity: Every test in one SDK must have a corresponding test in the other
- Very specific: line 45
Orchestrations: use function* (generators) and yield for all durable operations
- Very specific: line 46
Activities: use async function and await (normal async)
- Very specific: line 95
Important: After any Rust code change (src/*.rs), you MUST run npx napi build --platform before running tests.
- Very specific: line 184
After adding features: update docs/user-guide.md, relevant skills in .agents/skills/, and the ScheduledTask table above.
- Very specific: line 187
Add variant to ScheduledTask enum in src/types.rs
- Very specific: line 188
Add execution branch in execute_task() in src/handlers.rs
- Very specific: line 189
Add JS method to OrchestrationContext class in lib/duroxide.js
- Very specific: line 190
Add TypeScript type to index.d.ts
- Very specific: line 191
Add test in __tests__/e2e.test.js
- Very specific: line 194
Add #[napi] function in src/lib.rs (or relevant module)
- Very specific: line 195
Import in lib/duroxide.js from the napi binding
- Very specific: line 203
All JS callbacks run on the Node.js main thread (single-threaded)
β βCommonβ is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. βVery specificβ is our guess from the words: it names a file, a command, a setting or the project itself.
Files
duroxide-node β AI Coding Assistant Instructions
π¨ STOP: DO NOT
git commitORgit pushWITHOUT EXPLICIT USER PERMISSION π¨Always ask before committing or pushing. Never assume.
β οΈ SDK Symmetry β duroxide-node & duroxide-python MUST stay in sync
When making changes to this SDK, always check ../duroxide-python for symmetry:
- Bug fixes: If you fix a bug here, apply the same fix in duroxide-python (and vice versa)
- API parity: Every public API in one SDK must have an equivalent in the other (adjusted for language idioms β camelCase in JS, snake_case in Python)
- Test parity: Every test in one SDK must have a corresponding test in the other
- Feature parity: New duroxide features exposed in one SDK must be exposed in both
- Rust handler code (
src/handlers.rs): Both SDKs share the same interop architecture βexecute_task,make_select_future,make_join_futureshould be kept structurally identical
Project Overview
duroxide-node is a Node.js/TypeScript SDK for the Duroxide durable execution runtime. It wraps the Rust runtime via napi-rs, exposing generator-based orchestrations and async activities to JavaScript.
Key docs: docs/architecture.md, docs/user-guide.md.
Architecture
lib/duroxide.js β JS wrapper: generator driver, OrchestrationContext, ActivityContext
src/lib.rs β napi entry point, trace functions
src/handlers.rs β Core interop: orchestration handler loop, activity invocation,
global context maps, select/race/join, activity cancellation
src/types.rs β ScheduledTask enum (activity, timer, wait, orchestration, etc.)
src/runtime.rs β JsRuntime (wraps duroxide::Runtime)
src/client.rs β JsClient (wraps duroxide::Client, including admin/management APIs)
src/provider.rs β JsSqliteProvider
src/pg_provider.rs β JsPostgresProvider
__tests__/e2e.test.js β PostgreSQL e2e tests (24 tests + 1 SQLite smoketest)
__tests__/races.test.js β ctx.all() and ctx.race() with mixed task types + cancellation (7 tests)
__tests__/admin_api.test.js β Admin/management API tests (14 tests)
__tests__/sessions.test.js β Session support tests (6 tests, SQLite in-memory)
__tests__/scenarios/ β Scenario tests modeling real-world patterns (toygres, 6 tests)β οΈ Critical: Yield vs Await
This is the most important design constraint. Get this wrong and replay breaks.
- Orchestrations use
function*(generators) andyieldfor all durable operations - Activities use
async functionandawait(normal async) - Tracing methods (
ctx.traceInfo()etc.) are fire-and-forget β no yield needed
// β
Orchestration: generator, yield for durable operations
runtime.registerOrchestration('MyWorkflow', function* (ctx, input) {
ctx.traceInfo('starting'); // no yield β fire-and-forget
const result = yield ctx.scheduleActivity('Work', input); // yield β durable
return result;
});
// β
Activity: async function, await for I/O
runtime.registerActivity('Work', async (ctx, input) => {
ctx.traceInfo(`processing ${input}`);
const data = await fetch(input.url);
return data;
});Why generators? The Rust replay engine needs full control over each step β it calls poll_once() on DurableFutures and feeds cached results during replay. await would yield control to the JS event loop, breaking the replay engine's synchronous step-by-step model. See docs/architecture.md for the full explanation.
β οΈ Critical: Tracing Delegates to Rust
Tracing in both orchestrations and activities delegates to Rust contexts via global HashMaps. Do NOT reimplement tracing in JS.
- Orchestration tracing:
orchestrationTraceLog(ctxToken, level, message)β looks upOrchestrationContextfromORCHESTRATION_CTXSmap β callsctx.trace()which handlesis_replayingsuppression - Activity tracing:
activityTraceLog(token, level, message)β looks upActivityContextfromACTIVITY_CTXSmap β callsctx.trace_info()etc. with full structured fields
The is_replaying guard lives entirely on the Rust side. JS never knows about replay state.
Build & Test
# Build (MUST use napi build, not cargo build, for the .node binary)
npx napi build --platform # Debug build
npx napi build --platform --release # Release build
# Tests
npm test # PostgreSQL e2e (24 tests + 1 SQLite smoketest, needs DATABASE_URL in .env)
npm run test:races # Race/join composition tests (7 tests, needs DATABASE_URL)
npm run test:admin # Admin API tests (14 tests, needs DATABASE_URL)
npm run test:scenarios # Scenario tests (6 tests, needs DATABASE_URL)
npm run test:sessions # Session tests (6 tests, SQLite in-memory)
npm run test:all # Everything (58 tests)
# Lint the Rust side
cargo clippy --all-targetsImportant: After any Rust code change (src/*.rs), you MUST run npx napi build --platform before running tests. The JS side loads a compiled .node binary, not Rust source.
Interop Model
The orchestration handler loop in src/handlers.rs:
- Rust calls JS
createGenerator(payload)viaThreadsafeFunction(blocked withblock_in_place) - JS creates a generator, calls
gen.next(), returns the first yieldedScheduledTaskdescriptor - Rust executes the task via
OrchestrationContext(real execution or replay) - Rust calls JS
nextStep(result)β feeds result back to generator - Repeat until generator returns or throws
Activities are simpler: Rust calls JS async function via call_async, awaits the Promise.
block_in_place is required because the replay engine's poll_once() drops the handler future after one poll. A regular call_async future would be dropped before the JS callback fires.
ScheduledTask Protocol
The JS generator yields plain objects that map to Rust ScheduledTask variants:
| JS Descriptor | Rust Variant | Notes |
{ type: 'activity', name, input } | Activity | Runs an activity |
{ type: 'activity', name, input, sessionId } | Activity | Runs an activity on a session |
{ type: 'activityWithRetry', name, input, retryPolicy } | ActivityWithRetry | With retry policy |
{ type: 'timer', delayMs } | Timer | Durable delay |
{ type: 'wait', eventName } | WaitEvent | Wait for external event |
{ type: 'subOrchestration', name, input } | SubOrchestration | Await child workflow |
{ type: 'orchestration', name, instanceId, input } | Orchestration | Fire-and-forget |
{ type: 'all', tasks } | All | Parallel execution |
{ type: 'race', task1, task2 } | Race | First-to-complete |
{ type: 'utcNow' } | UtcNow | Deterministic timestamp |
{ type: 'newGuid' } | NewGuid | Deterministic GUID |
{ type: 'continueAsNew', input } | ContinueAsNew | Restart orchestration |
{ type: 'continueAsNewVersioned', input, version } | ContinueAsNewVersioned | Restart as specific version |
Key Patterns
Provider polymorphism β napi-rs can't use trait objects in constructors, so JsRuntime has a factory method:
// JS wrapper detects provider._type and calls the right constructor
if (provider._type === 'postgres') {
this._native = JsRuntime.fromPostgres(provider._native, options);
} else {
this._native = new JsRuntime(provider._native, options);
}Global context maps for cross-thread tracing:
ACTIVITY_CTXS: HashMap<String, ActivityContext>β keyed by atomic token (act-0,act-1, ...)ORCHESTRATION_CTXS: HashMap<String, OrchestrationContext>β keyed by atomic token (orch-0,orch-1, ...), one per invocation. Never key it byinstance_id: two replays of one instance can be alive in the same process, and each must only reach its own context. JS gets the token inctxInfo._ctxToken.- Contexts are inserted before calling JS, removed after completion
select/race uses make_select_future() which returns Pin<Box<dyn Future<Output = Result<String, String>>>> to handle all task types uniformly. select_result() returns { index, value } for a winner that succeeded, and the winner's own error for one that failed, so the yield throws.
join/all uses make_join_future() β similar to make_select_future() but normalizes output to {ok:v}/{err:e} JSON. Supports all task types: activities, timers, waits, sub-orchestrations (all variants).
Nested join/select rejection β Join and Select handlers reject nested Join/Select tasks to avoid recursive async issues.
Activity cancellation β ctx.isCancelled() checks the Rust CancellationToken via ACTIVITY_CTXS map. Cancellation is detected via lock renewal failure (latency = workerLockTimeoutMs / 2). A missing map entry also means cancelled: the runtime removes the entry when it gives up on a cancelled activity after the grace period, while the JS function is still running.
Activity client access β ctx.getClient() calls activityGetClient(token) napi function β looks up ActivityContext in ACTIVITY_CTXS map β calls ctx.get_client() β wraps result as JsClient. Activities can use this to start orchestrations, raise events, etc.
Metrics snapshot β runtime.metricsSnapshot() returns a JsMetricsSnapshot with 17 counters (orch starts/completions/failures, activity results, dispatcher stats, provider errors). Returns null if observability is not enabled.
Observability options β JsRuntimeOptions includes logFormat, logLevel, serviceName, serviceVersion which map to duroxide::ObservabilityConfig.
Determinism Rules
Orchestration generators must be deterministic (same rules as Rust duroxide):
- β
Use:
yield ctx.utcNow(),yield ctx.newGuid(),ctx.traceInfo() - β Avoid:
Date.now(),Math.random(),crypto.randomUUID(),console.log(), I/O,fetch()
Activities have no restrictions β they run once, result is cached.
Crate Version Alignment
Release manifests must resolve duroxide and duroxide-pg from crates.io:
duroxide = { version = "0.1.30", features = ["sqlite"] }
duroxide-pg = "0.1.35"Temporary local [patch.crates-io] sections or inline path = overrides are
acceptable during cross-repository development, but remove them before release
validation so CI and published packages use registry crates.
Adding Features
After adding features: update docs/user-guide.md, relevant skills in .agents/skills/, and the ScheduledTask table above.
New ScheduledTask type:
- Add variant to
ScheduledTaskenum insrc/types.rs - Add execution branch in
execute_task()insrc/handlers.rs - Add JS method to
OrchestrationContextclass inlib/duroxide.js - Add TypeScript type to
index.d.ts - Add test in
__tests__/e2e.test.js
New napi function:
- Add
#[napi]function insrc/lib.rs(or relevant module) - Import in
lib/duroxide.jsfrom the napi binding - Rebuild:
npx napi build --platform
Limitations
ctx.race()supports exactly 2 tasks (maps to Rustselect2)ctx.all()supports all task types: activities, timers, waits, sub-orchestrations (all variants). Nestedall()/race()is rejected.ctx.race()supports all task types. Nestedall()/race()is rejected.- All JS callbacks run on the Node.js main thread (single-threaded)
- No
async function*generators β breaks replay model - SQLite may hit "database is locked" under concurrency (retried automatically)
Runtime.shutdown(timeoutMs)waits the full timeout (no short-circuit)- Platform-specific
.nodebinary β cross-platform needs per-platform builds - Activity cancellation detection latency depends on
workerLockTimeoutMs(default 30s β ~15s detection)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

