diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..d26f2ec8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,13 @@ +# Once: protect one consequential operation + +Evaluate Once when an external write may be retried, its first outcome can be ambiguous, and duplicate effects matter. If native idempotency or a database constraint fully solves it, use that instead. Harmless repeatable work does not need Once. + +Start with `examples/first10/README.md`: run the refund fixture using published SDK 0.1.24, then read `examples/natural-placement/README.md` for a host-owned callback. Fixture PASS, installation, scanner findings, downloads and upstream fixes are not independent adoption. + +The developer owns stable logical identity and complete effect/account fields. Never silently infer or apply them. Keep identity across retries; genuine new intents need distinct IDs. Do not store Authorization credentials in effects. Route all writes through the reviewed boundary; opaque internal retries remain outside it. + +UNKNOWN means the original action may have succeeded. Never blindly redispatch, mint a new ID to escape uncertainty, bypass protection, or infer absence from a missing receipt. Reconcile only authoritative read-only provider truth. Preserve CONFIRMED replay, changed-effect CONFLICT, durable state and fail-closed unsupported shapes. Local SQLite needs Node 24.15+ and one persistent shared same-machine authority. + +FIRST 10 adds `once check [directory]` (read-only heuristic candidates) and `once prove` (controlled fixture only). Published 0.1.24 does not contain these commands. Preserve doctor and established APIs. Do not broaden frameworks for FIRST 10. + +Build SDK; run FIRST 10 regression and relevant local/wrapTool tests; regenerate proof assets and run source/site guards. Validate packed SDK and published SDK consumers in clean directories. Publication, deployment, release and outreach require owner approval of concrete changes. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f643080..fbf01d59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ Historical SDK change notes are recorded here. For current published versions an changes after the entries below, see the [public release history](https://github.com/stringsofthemind-oss/once/releases). Website-only changes do not alter SDK execution semantics. +## 0.1.25 - 2026-10-04 + +- Add `once prove`: account-free local HTTP refund fixture with separate provider journal, acknowledgement loss, fresh processes, replay, CONFLICT and authoritative recovery. It never invokes arbitrary application code. +- Add read-only `once check [directory]` using the existing heuristic scanner; no identity/effect inference or activation. Existing doctor and APIs remain available. +- Clarify UNKNOWN error wording without changing the safety engine, state schema, bindings or reconciliation authority. +- Add symptom-first onboarding and FIRST 10 evidence/retention guidance. See [release notes](docs/RELEASE_0_1_25.md). + ## 0.1.24 - 2026-10-03 - Add public `wrapTool(callback, semantics)` over `protectToolCall` and `protectLocal`; no new safety engine. diff --git a/README.md b/README.md index 59383dc7..641f3032 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,65 @@ +# Once: your agent sent the refund. The response disappeared. Should it try again? + +A provider can commit an action before the caller receives its response. Blind retry can refund twice. Once remembers one logical operation, replays confirmed results, and blocks another write while the original outcome is unknown. + +## See it happen in under five minutes + +Node.js **24.15+**. No account, API key, or financial transaction. The proof uses the published SDK and a controlled local HTTP provider with its own effect journal. + +From this checkout: + +```sh +npm install --no-save --package-lock=false @once-agent/sdk@0.1.24 +node examples/first10/prove.mjs +``` + +```text +WITHOUT ONCE: acknowledgement lost; fresh-process retry -> 2 provider writes +CONFIRMED: 1 provider write; restart replay; changed £50 -> £80: CONFLICT, 0 additional writes +RETRY BLOCKED — ORIGINAL OUTCOME UNKNOWN +The refund may already have succeeded. Once sent no second request. +LOST-ACK: 1 provider write; UNKNOWN -> CONFIRMED; recovered refund_1 +PASS +``` + +Every stage checks the separate provider's HTTP counter against its effect journal. Evidence is retained in the printed directory. This proves the controlled fixture, not a real payment provider. [Complete instructions, download path and recording recipe](examples/first10/README.md). + +## Protect one of your own operations + +Natural Placement: `wrapTool` replaces a host-owned async callback. You explicitly own identity and effect fields; no semantic decision is silently inferred. + +```js +import { wrapTool } from "@once-agent/sdk"; +const safeRefund = wrapTool(refundCustomer, { + operationId: x => `${x.tenantId}:refund:${x.refundIntentId}`, + effect: x => ({ tool: "payments:reviewed-account:refund", args: x }), + statePath: "./durable/operations.sqlite", + reconcile: lookupAuthoritativeRefund, +}); +``` + +The callback and lookup are your reviewed provider functions. Inspect every argument, bind full account/tenant authority and all effect-bearing fields, and exclude Authorization credentials. Route every write through the wrapper. Internal callback retries remain outside the boundary. The lookup returns `{status: "CONFIRMED", result}` only from authoritative provider truth, otherwise `{status: "UNKNOWN"}`. If unsupported, omit reconciliation and UNKNOWN remains blocked. + +Local SQLite requires a persistent shared file on **one machine**, Node 24.15+, and distinct IDs for genuine new intents. Multiple legitimate partial refunds need distinct refund-intent IDs. [Complete integration guide](examples/natural-placement/README.md). + +## When you need Once — and when you do not + +Evaluate Once when a consequential external write may be retried, its outcome can become ambiguous, and another effect would matter. Refunds, bookings, messages and tickets are examples, not automatic provider support. + +If a provider idempotency key completely solves your operation, use it. If a Postgres unique constraint completely solves it, use it. If repetition is harmless, you probably do not need Once. Keep native idempotency even with Once. Once does not replace your database, framework, queue, or Temporal and does not promise universal exactly-once execution. + +**UNKNOWN is protection:** the original action may have succeeded. Retain its identity and durable state; perform an authoritative read-only lookup. Never mint a new ID or bypass Once to force progress. Even an absence observation does not automatically permit local redispatch. + +## Find a candidate + +Published CLI: `once doctor` remains the detailed assessment path. This FIRST 10 branch adds read-only `once check [directory]` and `once prove` for the controlled refund fixture. The new commands need a build of this branch until SDK release; they are not in 0.1.24. Scan and installation do not activate protection; the fixture never executes your code. + +[Website](https://onceexec.com/) · [Quickstart](https://onceexec.com/quickstart/) · [Evidence](https://onceexec.com/evidence/) · [FIRST 10 plan and ledger](docs/FIRST10.md) + +--- + +## Deeper semantics, integrations, architecture and historical evidence + # @once-agent/sdk > **Natural Placement (SDK 0.1.24):** `wrapTool(callback, semantics)` protects a diff --git a/docs/FIRST10.md b/docs/FIRST10.md new file mode 100644 index 00000000..f1a87435 --- /dev/null +++ b/docs/FIRST10.md @@ -0,0 +1,44 @@ +# ONCE: FIRST 10 + +Objective: ten independent developers protect a meaningful real operation and retain Once. Owner/CI/demo activity, stars, clones, downloads and upstream fixes count as zero users. + +## Current-state audit — 2026-10-04 + +Base commit: d818f1eb346618dd9916dd666acc1d09fd2545e1. TypeScript 0.1.24 and MCP 0.1.5 were verified against npm. Python source and site say 0.1.1; registry verification is recorded in the execution report. Existing assets: browser simulation, installed-SDK ticket quickstart with separate journal, protectLocal, protectToolCall, wrapTool, doctor/scanner, reviewed routing and many framework labs. Main had just added Hermes; FIRST 10 adds no framework. Open issues: #267 independent testers; #280 and #284 disposable verification. Issue #267 includes one external self-reported completed Webhook.site evaluation on 2026-10-03 using SDK 0.1.22. The report claims replay/conflict/restart/reconciliation with no duplicates and 2m24s active time from fixture creation to first effect. This is reported evidence, not fresh provider verification, verified human independence, or retention. + +## Ranked plan + +| Priority | Work | Purpose | +| --- | --- | --- | +| P0 | Account-free refund proof with independent provider counter and restart | Experience the benefit first | +| P0 | Published-package cold run, README and homepage path | Reduce first-value friction | +| P0 | UNKNOWN explanation and explicit identity ownership | Explain stopping without weakening safety | +| P0 | Manual consent-based retention ledger | Measure the real objective | +| P1 | Read-only check, useful symptom page, agent guidance | Reach developers experiencing the problem | +| P1 | Independent cold run and own-operation integration | Find friction and demand | +| P2 | Real payment test mode, recording, further pages from user/search evidence | Follow demonstrated need | +| STOP | More framework adapters, broad launch, ads, monetisation, test-count marketing | Do not advance retention now | + +## Funnel + +Symptom page/homepage → refund proof using published SDK → understand UNKNOWN → review own identity and complete effect/account binding → wrap one callback → validate against disposable provider truth → record friction and consensual 7/30-day follow-up. + +`once prove` runs a fixture, not a certification of scanned operations. New branch commands remain unreleased; the standalone download works with SDK 0.1.24 after site publication. No telemetry is added. Do not claim an external user story before it exists. + +## Manual FIRST 10 ledger + +Use anonymous labels and consensual self-report. Never record credentials, payloads, customer data or unnecessary contact details. Blank means unknown. Delete notes if consent is withdrawn. Keep contact details separately only where necessary and consented. + +| User | Consent | Discovery source/date | Proof date | Meaningful operation/date | Stack/action | Identity difficulty | Minutes to first value | Friction | Day 7 useful/date | Day 30/date | Expanded | Recommended | Issue/PR | Why retained/removed | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| External-eval-01 | Voluntary research reply in #267; no attributed marketing quote permission assumed | GitHub #267 / 2026-10-03 | Self-reported 2026-10-03 | Disposable Webhook.site fixture; own workflow unverified | Node 24.19 / HTTP POST | Self-reported explicit IDs and complete effect | 2m24s active; earlier blocked time excluded | Initial credential/connector boundary; agreed anonymous fixture resolved | Unknown; earliest seven-day checkpoint 2026-10-10 | Unknown | Unknown | Unknown | [Public report](https://github.com/stringsofthemind-oss/once/issues/267#issuecomment-5966858930) | Would use again is intent, not demonstrated retention | + +**0 confirmed retained users recorded.** One external fixture evaluation is reported; confirmed independence, own-workflow use and retention remain unverified. No fresh Webhook.site verification was performed in FIRST 10. Count only independent developers who personally run Once, understand the operation, apply it to a meaningful write or realistic near-production equivalent, and retain it beyond the demo. Seven-day self-report is the early checkpoint; thirty days is stronger. Track proof-only and own-operation milestones separately. + +## Distribution and change signals + +Use existing opt-in issue #267 as a recruiting route. Do not add promotional comments to unrelated issues. Contributions should explain the failure and native-idempotency alternatives even without Once. No outreach has been sent in this phase. + +Change onboarding if more than half of cold users need help reaching proof. Change identity UX if semantics repeatedly block integration. Change positioning if users understand duplicates but find Once unnecessary. Revisit the beachhead after ten serious attempts with zero retention and evidence of pull elsewhere. Reassess the layer thesis against native capabilities and real retained-use evidence, not one negative response. + +**Next action:** one unrelated consenting developer runs the proof unaided, then protects one meaningful operation. Record elapsed time, first failure point and day-seven retention. Stop broadening until that feedback arrives. diff --git a/docs/RELEASE_0_1_25.md b/docs/RELEASE_0_1_25.md new file mode 100644 index 00000000..372796bd --- /dev/null +++ b/docs/RELEASE_0_1_25.md @@ -0,0 +1,13 @@ +# SDK 0.1.25 — FIRST 10 + +This patch adds `once prove` (a controlled local refund fixture) and `once check [directory]` (read-only heuristic candidate assessment). Existing doctor and SDK APIs remain unchanged. Node 24.15+ is required for the local SQLite proof; the package's other paths retain their existing runtime contracts. + +The proof starts a separate loopback HTTP provider with a flushed effect journal and starts a fresh caller process at each stage. It independently observes provider counts: two effects after an unprotected retry; one after protected replay, acknowledgement loss, blocked restarted retry, changed-effect conflict, unavailable/negative truth, authoritative reconciliation and recovered replay. + +The fixture demonstrates this controlled provider, not an arbitrary application or real financial integration. `once prove` never calls user application code. `once check` uploads no source, changes no application files and cannot establish complete semantics or safety from absence of findings. + +No state machine, durable schema, identity/fingerprint algorithm, provider authority or redispatch rule changed. UNKNOWN remains unresolved uncertainty. Only authoritative positive confirmation enables recovery; unavailable truth and absence do not permit local redispatch. Developers own identity and complete effect/account bindings. Preserve provider-native idempotency. No new framework adapter was added. + +Publication gates: complete release and Linux CI matrix, source/standalone parity, packed ESM/CommonJS/types and new CLI consumers, package-content inspection and matching tested tarball integrity. Website installation pins are synchronized only after registry verification. MCP and Python versions and historical evidence pins remain independent. + +FIRST 10 engineering readiness is not adoption: unaided independent proof, meaningful own-operation use and seven-day retention remain to be measured. diff --git a/docs/agent.md b/docs/agent.md index ec83b33e..2e616f84 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -304,3 +304,5 @@ Use https://onceexec.com/quickstart/ for a current-package, no-key local check. Its fake provider is not external-provider proof. Installing MCP alone is not protection; all effects must traverse the protected boundary. Local mode will not redispatch an ambiguous operation on an ABSENT observation. + +FIRST 10: Controlled refund proof: https://onceexec.com/first10/ . Standalone proof uses published SDK 0.1.24; the new once check/prove commands are branch-only until release. See repository examples/first10/README.md and docs/FIRST10.md. Native idempotency or a unique constraint should be used alone when sufficient. Identity/effect decisions require developer review; never infer them silently. diff --git a/docs/ambiguous-timeout/index.html b/docs/ambiguous-timeout/index.html index 724e997a..10f82f1c 100644 --- a/docs/ambiguous-timeout/index.html +++ b/docs/ambiguous-timeout/index.html @@ -22,5 +22,10 @@

Why timeout handling matters

Transport failure tells you the caller did not receive a usable response. It does not tell you whether the provider committed the external effect.

Safer recovery

Keep the original logical-operation identity, inspect durable operation state and reconcile provider truth where supported. If safety cannot be established, preserve uncertainty instead of guessing.

Claim boundary: Once does not claim universal exactly-once execution. Safety depends on stable operation identity, durable Once state, the provider integration and sufficiently authoritative provider truth. When the outcome cannot be established safely, Once can preserve uncertainty rather than assume another external execution is safe.
-

Use Once for this failure mode

Once is the execution-safety layer between autonomous software and supported consequential real-world side effects.

npx -y @once-agent/mcp

Official MCP Registry identity: io.github.stringsofthemind-oss/once

Run the retry simulation · MCP package · Source

+

Run the failure yourself

Minimal failure: send one refund; the provider commits; lose the response; retry after restart. A new request without effective deduplication can create another refund.

// Unsafe when the first refund may already have committed:
+try { await refundCustomer(intent); }
+catch { await refundCustomer(intent); }
+

Use the runnable local refund proof: a separate HTTP provider records two unprotected effects versus one with Once, followed by UNKNOWN blocking, authoritative reconciliation and changed-amount CONFLICT. No financial account is required.

+

When an idempotency key solves it

If the provider key binds the complete intended operation for your full retry horizon, use it. Once does not replace that guarantee. A local result table cannot make an arbitrary external write atomic with a database commit; preserve uncertainty when no trustworthy result exists.

+

Limits and next action

The controlled proof is not a real payment integration. Your developer must explicitly choose a stable, tenant-scoped refund-intent ID and complete effect/account fields. Use distinct IDs for genuine new partial refunds. UNKNOWN stays blocked when truth is unavailable; absence alone does not authorize local redispatch. Local SQLite is limited to one machine.

Run the proof and apply the wrapper pattern →

\ No newline at end of file diff --git a/docs/duplicate-refund-timeout/index.html b/docs/duplicate-refund-timeout/index.html index 549feccd..10398f72 100644 --- a/docs/duplicate-refund-timeout/index.html +++ b/docs/duplicate-refund-timeout/index.html @@ -22,5 +22,10 @@

The duplicate-refund failure mode

The provider may commit the refund before the response reaches the agent. The caller sees a timeout and retries. Without stable logical identity or reconciliation, the second attempt can look like a brand-new refund.

Recovery sequence

  1. Reuse the same logical operation identity.
  2. Read durable operation state.
  3. Reconcile authoritative provider truth where supported.
  4. Replay stored results when already confirmed.
  5. Block another external execution if the outcome remains unsafe to determine.
Claim boundary: Once does not claim universal exactly-once execution. Safety depends on stable operation identity, durable Once state, the provider integration and sufficiently authoritative provider truth. When the outcome cannot be established safely, Once can preserve uncertainty rather than assume another external execution is safe.
-

Use Once for this failure mode

Once is the execution-safety layer between autonomous software and supported consequential real-world side effects.

npx -y @once-agent/mcp

Official MCP Registry identity: io.github.stringsofthemind-oss/once

Run the retry simulation · MCP package · Source

+

Run the failure yourself

Minimal failure: send one refund; the provider commits; lose the response; retry after restart. A new request without effective deduplication can create another refund.

// Unsafe when the first refund may already have committed:
+try { await refundCustomer(intent); }
+catch { await refundCustomer(intent); }
+

Use the runnable local refund proof: a separate HTTP provider records two unprotected effects versus one with Once, followed by UNKNOWN blocking, authoritative reconciliation and changed-amount CONFLICT. No financial account is required.

+

When an idempotency key solves it

If the provider key binds the complete intended operation for your full retry horizon, use it. Once does not replace that guarantee. A local result table cannot make an arbitrary external write atomic with a database commit; preserve uncertainty when no trustworthy result exists.

+

Limits and next action

The controlled proof is not a real payment integration. Your developer must explicitly choose a stable, tenant-scoped refund-intent ID and complete effect/account fields. Use distinct IDs for genuine new partial refunds. UNKNOWN stays blocked when truth is unavailable; absence alone does not authorize local redispatch. Local SQLite is limited to one machine.

Run the proof and apply the wrapper pattern →

\ No newline at end of file diff --git a/docs/first10/index.html b/docs/first10/index.html new file mode 100644 index 00000000..1a881e26 --- /dev/null +++ b/docs/first10/index.html @@ -0,0 +1,37 @@ + + +Prevent a duplicate refund after process restart — Once + + +
+
+

Local refund proof · no account · no money movement

Your agent sent the refund. The response disappeared. Should it try again?

+

The provider can succeed before its response reaches you. Blind retry can send a second refund. Once keeps that uncertainty and blocks another write until authoritative truth confirms the original result.

+

Run locally now

Without Once: 2 effects

Refund commits → acknowledgement lost → caller restarts → blind retry → another refund.

With Once: 1 effect

Refund commits → UNKNOWN → restarted retry blocked → read-only reconciliation → original receipt recovered.

+

Run the actual SDK

Node.js 24.15+. An independent local HTTP provider keeps a separate effect journal. No cloud account, keys or payment account.

+
npm install @once-agent/sdk@0.1.24
+curl -fsSLo prove.mjs https://onceexec.com/first10/prove.mjs
+node prove.mjs
+

PowerShell download: Invoke-WebRequest https://onceexec.com/first10/prove.mjs -OutFile prove.mjs.

+

Prefer a checkout? See the complete source and instructions. The ticket quickstart provides another installed-SDK example.

+
WITHOUT ONCE: 2 provider writes
+CONFIRMED: first execution, restart replay, 1 provider write
+RETRY BLOCKED — ORIGINAL OUTCOME UNKNOWN
+Changed £50 → £80: CONFLICT, 0 additional writes
+UNKNOWN → CONFIRMED: recovered refund_1
+PASS
+

Actual output also prints the evidence directory and measured runtime. Each stage independently reads provider truth and compares its journal; a failing assertion exits nonzero. The proof includes unavailable truth and NOT_FOUND remaining blocked.

+

Fixture PASS proves this controlled provider only. It does not certify your operation, a real financial provider, or power-loss durability. Every caller stage starts a fresh process. Inspect the runnable source.

+

Why an idempotency key may be enough

If the provider's key covers the complete operation, retry horizon and effect inputs, use it. If a database unique constraint completely solves the operation, use it. If repetition is harmless, you probably do not need Once.

Once is relevant when the caller cannot safely establish whether another dispatch creates another consequence. Keep native idempotency; Once does not make arbitrary external effects atomic or replace your framework, queue or database.

+

Protect your own refund function

Choose a durable, tenant-scoped refund-intent ID. Multiple legitimate partial refunds need distinct intent IDs; a transport request ID is not the business operation. Review all effect inputs and provider/account authority explicitly.

+
import { wrapTool } from "@once-agent/sdk";
+const safeRefund = wrapTool(refundCustomer, {
+  operationId: x => `${x.tenantId}:refund:${x.refundIntentId}`,
+  effect: x => ({ tool: "payments:reviewed-account:refund", args: x }),
+  statePath: "./durable/operations.sqlite",
+  reconcile: lookupAuthoritativeRefund,
+});
+

Your callback and lookup need reviewed provider semantics. Bind every effect field; exclude Authorization credentials. Route every write through the wrapper. Internal callback retries remain outside the boundary. Persistent shared SQLite covers one machine only.

+

UNKNOWN is protection. Retain the same identity and state. Reconcile authoritative read-only truth; unavailable truth stays blocked. Do not invent a new ID or bypass protection to force progress. Absence alone does not permit local redispatch.

+Apply the complete wrapper pattern

Existing installed-SDK quickstart · Evidence and limits

+
diff --git a/docs/first10/prove.mjs b/docs/first10/prove.mjs new file mode 100644 index 00000000..3afee6d5 --- /dev/null +++ b/docs/first10/prove.mjs @@ -0,0 +1,174 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { wrapTool } from "@once-agent/sdk"; +const input = { refundId: "invoice_456", customerId: "customer_123", amount: 5000, currency: "GBP" }; +const rows = (directory) => readFileSync(path.join(directory, "provider.jsonl"), "utf8").split("\n").filter(Boolean).map(line => JSON.parse(line)); +async function worker(mode, directory, origin) { + const dispatch = async (args) => { + const response = await fetch(`${origin}/refund`, { method: "POST", body: JSON.stringify(args), signal: AbortSignal.timeout(5000) }); + if (!response.ok) + throw new Error(`Provider HTTP ${response.status}`); + return await response.json(); + }; + if (mode === "naive") { + await assert.rejects(dispatch(input)); + return; + } + const refund = wrapTool(dispatch, { + operationId: args => `demo-tenant:refund:${args.refundId}`, + effect: args => ({ tool: "local-demo-provider:demo-account:refund", args }), + statePath: path.join(directory, "operations.sqlite"), + ...(mode === "reconcile" || mode === "replay" || mode === "unavailable" || mode === "absent" ? { reconcile: async () => { + if (mode === "absent") + return { status: "NOT_FOUND" }; + if (mode === "unavailable") + return { status: "UNKNOWN" }; + const response = await fetch(`${origin}/truth`, { signal: AbortSignal.timeout(5000) }); + if (!response.ok) + return { status: "UNKNOWN" }; + const receipts = await response.json(); + const matches = receipts.filter(row => JSON.stringify(row.input) === JSON.stringify(input)); + return matches.length === 1 ? { status: "CONFIRMED", result: matches[0] } : { status: "UNKNOWN" }; + } } : {}), + }); + if (["lost", "blocked", "unavailable", "absent"].includes(mode)) + await assert.rejects(refund(input), { code: "UNKNOWN" }); + else if (mode === "conflict") + await assert.rejects(refund({ ...input, amount: 8000 }), { code: "CONFLICT" }); + else { + const receipt = await refund(input); + assert.ok(receipt); + assert.equal(receipt.receipt, "refund_1"); + assert.deepEqual(receipt.input, input); + } +} +async function provider(directory, loseAck) { + writeFileSync(path.join(directory, "provider.jsonl"), ""); + const server = createServer(async (request, response) => { + if (request.method === "GET" && request.url === "/truth") { + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(rows(directory))); + return; + } + if (request.method !== "POST" || request.url !== "/refund") { + response.writeHead(404).end(); + return; + } + const chunks = []; + for await (const chunk of request) + chunks.push(Buffer.from(chunk)); + const args = JSON.parse(Buffer.concat(chunks).toString()); + const receipt = { receipt: `refund_${rows(directory).length + 1}`, input: args }; + appendFileSync(path.join(directory, "provider.jsonl"), JSON.stringify(receipt) + "\n", { flush: true }); + if (loseAck) { + response.destroy(); + return; + } + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(receipt)); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (address && typeof address !== "string") + process.send?.(`http://127.0.0.1:${address.port}`); + }); +} +const modulePath = fileURLToPath(import.meta.url); +async function runWorker(mode, directory, origin) { + await new Promise((resolve, reject) => { + const child = spawn(process.execPath, [modulePath, "worker", mode, directory, origin], { stdio: ["ignore", "pipe", "pipe"] }); + let errors = ""; + child.stderr.on("data", chunk => { errors += String(chunk); }); + child.on("error", reject); + const timer = setTimeout(() => { child.kill(); reject(new Error(`Worker ${mode} timed out`)); }, 15000); + child.on("exit", code => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error(`Worker ${mode} failed: ${errors}`)); }); + }); +} +export async function runFirst10Proof() { + const [major, minor] = process.versions.node.split(".").map(Number); + if (major < 24 || (major === 24 && minor < 15)) + throw new Error("once prove requires Node.js 24.15+ for durable local SQLite."); + const started = performance.now(); + const root = mkdtempSync(path.join(tmpdir(), "once-refund-proof-")); + console.log("ONCE REFUND PROOF\nControlled local HTTP provider. No account, API key or money movement."); + console.log(`Evidence: ${root}`); + const report = {}; + for (const scenario of ["without-once", "confirmed", "lost-ack"]) { + const directory = path.join(root, scenario); + mkdirSync(directory); + const observedCounts = []; + const child = spawn(process.execPath, [modulePath, "provider", directory, String(scenario !== "confirmed")], { stdio: ["ignore", "ignore", "pipe", "ipc"] }); + try { + const origin = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("Provider startup timed out")), 10000); + child.once("message", value => { clearTimeout(timer); resolve(String(value)); }); + child.once("error", error => { clearTimeout(timer); reject(error); }); + child.once("exit", code => { clearTimeout(timer); reject(new Error(`Provider exited: ${code}`)); }); + }); + const count = async () => { + const response = await fetch(`${origin}/truth`, { signal: AbortSignal.timeout(5000) }); + assert.equal(response.status, 200); + const observed = await response.json(); + assert.deepEqual(observed, rows(directory)); + observedCounts.push(observed.length); + return observed.length; + }; + assert.equal(await count(), 0); + if (scenario === "without-once") { + await runWorker("naive", directory, origin); + assert.equal(await count(), 1); + await runWorker("naive", directory, origin); + assert.equal(await count(), 2); + console.log("WITHOUT ONCE: acknowledgement lost; fresh-process retry -> 2 provider writes"); + report[scenario] = { writes: 2, observedCounts }; + } + else { + const lost = scenario === "lost-ack"; + await runWorker(lost ? "lost" : "first", directory, origin); + assert.equal(await count(), 1); + await runWorker(lost ? "blocked" : "replay", directory, origin); + assert.equal(await count(), 1); + await runWorker("conflict", directory, origin); + assert.equal(await count(), 1); + if (lost) { + await runWorker("unavailable", directory, origin); + assert.equal(await count(), 1); + await runWorker("absent", directory, origin); + assert.equal(await count(), 1); + console.log("RETRY BLOCKED — ORIGINAL OUTCOME UNKNOWN\nThe refund may already have succeeded. Once sent no second request.\nNext action: read authoritative provider truth (demonstrated next)."); + await runWorker("reconcile", directory, origin); + assert.equal(await count(), 1); + await runWorker("replay", directory, origin); + assert.equal(await count(), 1); + } + console.log(`${scenario.toUpperCase()}: 1 provider write; restart replay; changed £50 -> £80: CONFLICT, 0 additional writes${lost ? "; UNKNOWN -> CONFIRMED; recovered refund_1" : ""}`); + report[scenario] = { writes: 1, observedCounts, conflictAdditionalWrites: 0, restart: true, ...(lost ? { initialStatus: "UNKNOWN", finalStatus: "CONFIRMED", unsafeRedispatches: 0, receipt: "refund_1" } : { replay: true }) }; + } + } + finally { + if (child.exitCode === null) { + const stopped = new Promise(resolve => child.once("exit", () => resolve())); + child.kill(); + await stopped; + } + } + } + const seconds = Number(((performance.now() - started) / 1000).toFixed(2)); + writeFileSync(path.join(root, "report.json"), JSON.stringify({ scope: "controlled-local-http-provider", seconds, scenarios: report }, null, 2)); + console.log(`PASS (${seconds}s). Local proof only; this does not certify a real payment provider or your operation.\nApply the pattern: https://onceexec.com/quickstart/`); + return { root, seconds, scenarios: report }; +} +if (process.argv[1] && path.resolve(process.argv[1]) === modulePath) { + const [, , role, a, b, c] = process.argv; + if (role === "provider") + await provider(a, b === "true"); + else if (role === "worker") + await worker(a, b, c); + else + await runFirst10Proof(); +} diff --git a/docs/index.html b/docs/index.html index 2bfc5ebd..fe6d19fe 100644 --- a/docs/index.html +++ b/docs/index.html @@ -4,7 +4,7 @@ - Once — safe retry decisions for agent and application actions + Once — prevent duplicate actions after a lost response - + How it worksQuickstartEvidenceDocsGitHubRun the retry demo + >Run the refund proof @@ -55,31 +55,29 @@

Retry safety for agent tools and applications

-

The same action should only happen once.

-

- A payment, booking or ticket can succeed even when the response is lost. Once helps supported integrations reuse confirmed - results and block uncertain retries instead of blindly repeating the action. -

+

Your agent sent the refund.
The response disappeared.
Should it try again?

+

Once remembers the logical operation, reuses confirmed results, and blocks unsafe repetition when the original outcome is uncertain. Reconciliation needs authoritative provider truth.

-

Try the simulation without an account or checkout.
Then verify the SDK locally without a Once API key.

+

Run the local refund proof without an account or API key.
Run the retry demo in your browser.

Inspect the code and failure tests →
-
+

When you do not need Once

If a provider idempotency key completely solves your operation, use it. If a database unique constraint solves it, use it. Harmless repeated actions do not need Once.

Use Once when a consequential operation may already have happened, you cannot safely establish its outcome, and repeating it could create another effect. Keep native idempotency wherever available.

See two unprotected refunds versus one protected refund →
+

What Once changes

Your caller can retry.
The write needs a safe decision.

diff --git a/docs/llms.txt b/docs/llms.txt index 9b06fb31..a7cd1c75 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -162,3 +162,5 @@ MCP idempotency; MCP retry safety; MCP safe retries; MCP duplicate tool calls; s - [Interactive simulation](https://onceexec.com/demo/): no account or checkout; not an SDK execution proof. - [Local quickstart](https://onceexec.com/quickstart/): actual SDK with controlled fake provider, restart and UNKNOWN checks; Node 24.15+, same-machine durability. - [Evidence](https://onceexec.com/evidence/): scoped reproductions and current release history. + +FIRST 10: Controlled refund proof: https://onceexec.com/first10/ . Standalone proof uses published SDK 0.1.24; the new once check/prove commands are branch-only until release. See repository examples/first10/README.md and docs/FIRST10.md. Native idempotency or a unique constraint should be used alone when sufficient. Identity/effect decisions require developer review; never infer them silently. diff --git a/docs/quickstart/index.html b/docs/quickstart/index.html index 9bc5caa3..29d801ff 100644 --- a/docs/quickstart/index.html +++ b/docs/quickstart/index.html @@ -38,7 +38,7 @@
-

Local first-action quickstart

+

Local first-action quickstart

Want the refund failure in one run? Run the account-free refund proof, then return here for the step-by-step ticket integration.

One action. Retry it. Verify one effect.

Use the actual Once SDK without a Once API key. This controlled example writes a fake ticket provider’s receipt to a separate local diff --git a/docs/sitemap.xml b/docs/sitemap.xml index 30b5a8a9..17dc9c0d 100644 --- a/docs/sitemap.xml +++ b/docs/sitemap.xml @@ -23,4 +23,5 @@ https://onceexec.com/quickstart/2026-10-02weekly0.9 https://onceexec.com/evidence/2026-10-02weekly0.9 https://onceexec.com/retry-exposure/2026-10-02weekly0.9 + https://onceexec.com/first10/2026-10-04weekly0.9 diff --git a/examples/first10/README.md b/examples/first10/README.md new file mode 100644 index 00000000..597bba33 --- /dev/null +++ b/examples/first10/README.md @@ -0,0 +1,76 @@ +# Prevent a duplicate refund after acknowledgement loss and process restart + +The canonical FIRST 10 proof uses published SDK 0.1.24, Node 24.15+, and built-in Node modules. No account, API key, or money movement. + +From a checkout: + +```sh +npm install --no-save --package-lock=false @once-agent/sdk@0.1.24 +node examples/first10/prove.mjs +``` + +From an empty directory, **after site publication**: + +```sh +npm install @once-agent/sdk@0.1.24 +curl -fsSLo prove.mjs https://onceexec.com/first10/prove.mjs +node prove.mjs +``` + +PowerShell download: `Invoke-WebRequest https://onceexec.com/first10/prove.mjs -OutFile prove.mjs`. The hosted file is pending deployment; the checkout route works now. + +## What happens + +Caller child process → loopback HTTP refund provider → separate flushed effect journal. +Once keeps a separate SQLite file. Each caller stage starts a fresh process. The provider deliberately has no native deduplication and drops its HTTP connection **after** journaling the refund. The parent observes provider truth over HTTP and checks it against the journal at every stage. + +1. Without Once: commit, lost acknowledgement, fresh-process blind retry → **2 writes**. +2. Confirmed path: first write, fresh-process replay, changed £50 to £80 → **1 write**, CONFLICT adds **0**. +3. Lost acknowledgement: first write → UNKNOWN; fresh-process retry blocked → **1 write**. +4. Unavailable truth and NOT_FOUND both remain blocked → **1 write**. +5. Read-only reconciliation retrieves `refund_1`; fresh-process replay returns it → **1 write**. + +Expected output: + +```text +WITHOUT ONCE: acknowledgement lost; fresh-process retry -> 2 provider writes +CONFIRMED: 1 provider write; restart replay; changed £50 -> £80: CONFLICT, 0 additional writes +RETRY BLOCKED — ORIGINAL OUTCOME UNKNOWN +The refund may already have succeeded. Once sent no second request. +LOST-ACK: 1 provider write; restart replay; changed £50 -> £80: CONFLICT, 0 additional writes; UNKNOWN -> CONFIRMED; recovered refund_1 +PASS +``` + +A failing assertion exits nonzero. The printed evidence directory contains journals, SQLite state and `report.json`. Every run uses fresh state; never delete production state to make a proof pass. + +## Protect your own operation + +Natural Placement wraps a host-owned unary async callback. The developer explicitly chooses identity and effect fields: + +```js +import { wrapTool } from "@once-agent/sdk"; +const safeRefund = wrapTool(refundCustomer, { + operationId: x => `${x.tenantId}:refund:${x.refundIntentId}`, + effect: x => ({ tool: "payments:reviewed-account:refund", args: x }), + statePath: "./durable/operations.sqlite", + reconcile: lookupAuthoritativeRefund, +}); +``` + +`refundCustomer` and `lookupAuthoritativeRefund` are your reviewed provider functions, not built-ins. Inspect every argument; include all effect-bearing fields and account/tenant authority. Exclude Authorization credentials. A refund intent is not always the invoice: legitimate partial refunds need distinct intent IDs. Keep identity stable across transport retries. Route all writes through `safeRefund`; opaque retries inside the callback remain outside the boundary. + +`lookupAuthoritativeRefund({operationId, effect})` returns `{status: "CONFIRMED", result}` only from authoritative provider truth, otherwise `{status: "UNKNOWN"}`. Omit reconciliation if unsupported: UNKNOWN remains blocked. See [the complete integration guide](../natural-placement/README.md). + +## When you do not need Once + +Use provider-native idempotency or a database constraint alone when it fully solves the operation. Harmless repeated reads do not need this protection. Retain native idempotency alongside Once where available. + +## Limits + +This is a controlled provider, not Stripe, an independent user, or production certification. It exercises acknowledgement loss and fresh-process restart, not power loss or every crash point. The fake journal defines authoritative truth only for this fixture. Real providers need reviewed lookup, authority, concurrency and idempotency contracts. Local SQLite covers cooperating callers on one machine only. UNKNOWN can block indefinitely. No untrusted application code is invoked. + +## Record a 60–90 second walkthrough + +Show the failure scenario; run `node examples/first10/prove.mjs`; pause on UNKNOWN; open the printed `report.json`; end with the wrapper and provider-idempotency boundary. Output completes quickly; narration supplies context. A recording is not included. + +Maintainers: build the SDK, then regenerate the standalone assets with `node scripts/generate-first10-proof.mjs`. Validate with `--check`. diff --git a/examples/first10/prove.mjs b/examples/first10/prove.mjs new file mode 100644 index 00000000..3afee6d5 --- /dev/null +++ b/examples/first10/prove.mjs @@ -0,0 +1,174 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { wrapTool } from "@once-agent/sdk"; +const input = { refundId: "invoice_456", customerId: "customer_123", amount: 5000, currency: "GBP" }; +const rows = (directory) => readFileSync(path.join(directory, "provider.jsonl"), "utf8").split("\n").filter(Boolean).map(line => JSON.parse(line)); +async function worker(mode, directory, origin) { + const dispatch = async (args) => { + const response = await fetch(`${origin}/refund`, { method: "POST", body: JSON.stringify(args), signal: AbortSignal.timeout(5000) }); + if (!response.ok) + throw new Error(`Provider HTTP ${response.status}`); + return await response.json(); + }; + if (mode === "naive") { + await assert.rejects(dispatch(input)); + return; + } + const refund = wrapTool(dispatch, { + operationId: args => `demo-tenant:refund:${args.refundId}`, + effect: args => ({ tool: "local-demo-provider:demo-account:refund", args }), + statePath: path.join(directory, "operations.sqlite"), + ...(mode === "reconcile" || mode === "replay" || mode === "unavailable" || mode === "absent" ? { reconcile: async () => { + if (mode === "absent") + return { status: "NOT_FOUND" }; + if (mode === "unavailable") + return { status: "UNKNOWN" }; + const response = await fetch(`${origin}/truth`, { signal: AbortSignal.timeout(5000) }); + if (!response.ok) + return { status: "UNKNOWN" }; + const receipts = await response.json(); + const matches = receipts.filter(row => JSON.stringify(row.input) === JSON.stringify(input)); + return matches.length === 1 ? { status: "CONFIRMED", result: matches[0] } : { status: "UNKNOWN" }; + } } : {}), + }); + if (["lost", "blocked", "unavailable", "absent"].includes(mode)) + await assert.rejects(refund(input), { code: "UNKNOWN" }); + else if (mode === "conflict") + await assert.rejects(refund({ ...input, amount: 8000 }), { code: "CONFLICT" }); + else { + const receipt = await refund(input); + assert.ok(receipt); + assert.equal(receipt.receipt, "refund_1"); + assert.deepEqual(receipt.input, input); + } +} +async function provider(directory, loseAck) { + writeFileSync(path.join(directory, "provider.jsonl"), ""); + const server = createServer(async (request, response) => { + if (request.method === "GET" && request.url === "/truth") { + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(rows(directory))); + return; + } + if (request.method !== "POST" || request.url !== "/refund") { + response.writeHead(404).end(); + return; + } + const chunks = []; + for await (const chunk of request) + chunks.push(Buffer.from(chunk)); + const args = JSON.parse(Buffer.concat(chunks).toString()); + const receipt = { receipt: `refund_${rows(directory).length + 1}`, input: args }; + appendFileSync(path.join(directory, "provider.jsonl"), JSON.stringify(receipt) + "\n", { flush: true }); + if (loseAck) { + response.destroy(); + return; + } + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(receipt)); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (address && typeof address !== "string") + process.send?.(`http://127.0.0.1:${address.port}`); + }); +} +const modulePath = fileURLToPath(import.meta.url); +async function runWorker(mode, directory, origin) { + await new Promise((resolve, reject) => { + const child = spawn(process.execPath, [modulePath, "worker", mode, directory, origin], { stdio: ["ignore", "pipe", "pipe"] }); + let errors = ""; + child.stderr.on("data", chunk => { errors += String(chunk); }); + child.on("error", reject); + const timer = setTimeout(() => { child.kill(); reject(new Error(`Worker ${mode} timed out`)); }, 15000); + child.on("exit", code => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error(`Worker ${mode} failed: ${errors}`)); }); + }); +} +export async function runFirst10Proof() { + const [major, minor] = process.versions.node.split(".").map(Number); + if (major < 24 || (major === 24 && minor < 15)) + throw new Error("once prove requires Node.js 24.15+ for durable local SQLite."); + const started = performance.now(); + const root = mkdtempSync(path.join(tmpdir(), "once-refund-proof-")); + console.log("ONCE REFUND PROOF\nControlled local HTTP provider. No account, API key or money movement."); + console.log(`Evidence: ${root}`); + const report = {}; + for (const scenario of ["without-once", "confirmed", "lost-ack"]) { + const directory = path.join(root, scenario); + mkdirSync(directory); + const observedCounts = []; + const child = spawn(process.execPath, [modulePath, "provider", directory, String(scenario !== "confirmed")], { stdio: ["ignore", "ignore", "pipe", "ipc"] }); + try { + const origin = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("Provider startup timed out")), 10000); + child.once("message", value => { clearTimeout(timer); resolve(String(value)); }); + child.once("error", error => { clearTimeout(timer); reject(error); }); + child.once("exit", code => { clearTimeout(timer); reject(new Error(`Provider exited: ${code}`)); }); + }); + const count = async () => { + const response = await fetch(`${origin}/truth`, { signal: AbortSignal.timeout(5000) }); + assert.equal(response.status, 200); + const observed = await response.json(); + assert.deepEqual(observed, rows(directory)); + observedCounts.push(observed.length); + return observed.length; + }; + assert.equal(await count(), 0); + if (scenario === "without-once") { + await runWorker("naive", directory, origin); + assert.equal(await count(), 1); + await runWorker("naive", directory, origin); + assert.equal(await count(), 2); + console.log("WITHOUT ONCE: acknowledgement lost; fresh-process retry -> 2 provider writes"); + report[scenario] = { writes: 2, observedCounts }; + } + else { + const lost = scenario === "lost-ack"; + await runWorker(lost ? "lost" : "first", directory, origin); + assert.equal(await count(), 1); + await runWorker(lost ? "blocked" : "replay", directory, origin); + assert.equal(await count(), 1); + await runWorker("conflict", directory, origin); + assert.equal(await count(), 1); + if (lost) { + await runWorker("unavailable", directory, origin); + assert.equal(await count(), 1); + await runWorker("absent", directory, origin); + assert.equal(await count(), 1); + console.log("RETRY BLOCKED — ORIGINAL OUTCOME UNKNOWN\nThe refund may already have succeeded. Once sent no second request.\nNext action: read authoritative provider truth (demonstrated next)."); + await runWorker("reconcile", directory, origin); + assert.equal(await count(), 1); + await runWorker("replay", directory, origin); + assert.equal(await count(), 1); + } + console.log(`${scenario.toUpperCase()}: 1 provider write; restart replay; changed £50 -> £80: CONFLICT, 0 additional writes${lost ? "; UNKNOWN -> CONFIRMED; recovered refund_1" : ""}`); + report[scenario] = { writes: 1, observedCounts, conflictAdditionalWrites: 0, restart: true, ...(lost ? { initialStatus: "UNKNOWN", finalStatus: "CONFIRMED", unsafeRedispatches: 0, receipt: "refund_1" } : { replay: true }) }; + } + } + finally { + if (child.exitCode === null) { + const stopped = new Promise(resolve => child.once("exit", () => resolve())); + child.kill(); + await stopped; + } + } + } + const seconds = Number(((performance.now() - started) / 1000).toFixed(2)); + writeFileSync(path.join(root, "report.json"), JSON.stringify({ scope: "controlled-local-http-provider", seconds, scenarios: report }, null, 2)); + console.log(`PASS (${seconds}s). Local proof only; this does not certify a real payment provider or your operation.\nApply the pattern: https://onceexec.com/quickstart/`); + return { root, seconds, scenarios: report }; +} +if (process.argv[1] && path.resolve(process.argv[1]) === modulePath) { + const [, , role, a, b, c] = process.argv; + if (role === "provider") + await provider(a, b === "true"); + else if (role === "worker") + await worker(a, b, c); + else + await runFirst10Proof(); +} diff --git a/scripts/check-site-surface.mjs b/scripts/check-site-surface.mjs index 23e0a246..b8fb30eb 100644 --- a/scripts/check-site-surface.mjs +++ b/scripts/check-site-surface.mjs @@ -92,7 +92,7 @@ assert.match(homepage, /Run the retry demo/, "homepage must lead to the ungated assert.doesNotMatch(homepage, /once-network|Open live proof|Test Once at your scale/, "obsolete proof/funnel claims must stay removed"); const schema = JSON.parse(homepage.match(/