diff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.yml index f0f73433..8775a0ee 100644 --- a/.github/workflows/sdk-ci.yml +++ b/.github/workflows/sdk-ci.yml @@ -8,6 +8,16 @@ on: - "sdk/python/**" - "mcp/**" - "conformance/**" + - "README.md" + - "docs/START_HERE.md" + - "docs/GUARANTEES.md" + - "docs/IDENTITY_AND_EFFECT.md" + - "docs/UNKNOWN_PLAYBOOK.md" + - "docs/PRODUCTION_OPERATION.md" + - "docs/published-versions.json" + - "scripts/check-current-onboarding.mjs" + - "scripts/test-current-onboarding.mjs" + - "scripts/test-openai-plugin-line-endings.mjs" - ".github/workflows/sdk-ci.yml" push: branches: @@ -18,12 +28,84 @@ on: - "sdk/python/**" - "mcp/**" - "conformance/**" + - "README.md" + - "docs/START_HERE.md" + - "docs/GUARANTEES.md" + - "docs/IDENTITY_AND_EFFECT.md" + - "docs/UNKNOWN_PLAYBOOK.md" + - "docs/PRODUCTION_OPERATION.md" + - "docs/published-versions.json" + - "scripts/check-current-onboarding.mjs" + - "scripts/test-current-onboarding.mjs" + - "scripts/test-openai-plugin-line-endings.mjs" - ".github/workflows/sdk-ci.yml" permissions: contents: read jobs: + legacy-runtime-boundary: + runs-on: ubuntu-latest + strategy: + matrix: + node: ['18', '20'] + defaults: + run: + working-directory: sdk/typescript + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + cache-dependency-path: sdk/typescript/package-lock.json + - run: npm ci + - run: npm run build + - name: Hosted compatibility and unsupported local admission + run: node --test ./test/connect/*.test.mjs ./test/unsupported-runtime.test.mjs + + onboarding-portability: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + node: ['24.15.0'] + include: + - os: ubuntu-latest + node: '24.x' + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + defaults: + run: + working-directory: sdk/typescript + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + cache-dependency-path: sdk/typescript/package-lock.json + - run: npm ci + - run: npm run build + - name: Local and connected execution contracts + run: node --test ./test/local.test.mjs ./test/local-session.test.mjs ./test/connect/*.test.mjs ./test/first-action.test.mjs + - name: Isolated packed first-action proof + run: npm run test:first-action-package + - name: Retained authority and explicit loss boundary + run: npm run test:authority-continuity + - name: Exact authority state and independent provider forensic evidence + run: npm run test:authority-forensics + - name: Current onboarding release references + run: node ../../scripts/check-site-surface.mjs + - name: Onboarding drift regressions + run: node ../../scripts/test-current-onboarding.mjs + - name: Plugin frontmatter portability + run: node ../../scripts/test-openai-plugin-line-endings.mjs + test-release: runs-on: ubuntu-latest timeout-minutes: 20 @@ -99,8 +181,8 @@ jobs: - name: Run materialized reviewed companion execution proof run: node ./scripts/materialized-companion-proof-regression.mjs - - name: Run persistent local state regressions - run: node --test ./test/local-session.test.mjs + - name: Run packed first-action proof + run: npm run test:first-action-package - name: Run MCP boundary mutation regressions run: node --test ./test/connect/mcp-execution-boundary-mutation.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index e7ce6d91..36010a51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 0.1.23 — release candidate, NOT PUBLISHED + +- Put the existing credential-free synthetic proof first in documentation and CLI help. +- Add one package-included simulated example covering identity, effect conflict, + UNKNOWN, exact-evidence recovery and fresh-process replay. +- Clarify identity ownership, UNKNOWN operations and local/hosted guarantee boundaries. +- Fix Windows session fixture cleanup and verify open-file locking explicitly. +- Align current public SDK references with independently verified 0.1.22; retain historical pins. +- Add cross-platform local CI and current-surface release checks. +- Update the MCP source dependency to SDK 0.1.22, subject to integration regressions. + +These are review-branch changes. No release, merge or deployment is implied. + +- Add a disposable cross-process authority-continuity regression and document + measured redispatch after complete state loss or stale backup restoration. +- Prepare SDK package metadata for 0.1.23. Current public registry remains 0.1.22. +- Scope SQLite tests to Node 24.15+ and add a pre-dispatch rejection regression + for unsupported local runtimes; add Node 18/20 compatibility CI. + All notable changes to the Once SDK are documented here. ## 0.1.12 - 2026-09-25 diff --git a/README.md b/README.md index bcf1add5..86d40d7a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,26 @@ # @once-agent/sdk -> **Automatic Connect:** `@once-agent/sdk@0.1.18` publishes the tested +## Start with one protected action + +Current public TypeScript SDK: **@once-agent/sdk@0.1.22**. +For a credential-free controlled proof on Node.js 24.15+: + +```sh +npm install @once-agent/sdk@0.1.22 +npx once prove +``` + +This simulates a lost acknowledgement, blocked retry, recovery and replay. +It does not protect your project's tools merely by being run. +Your application owns persisted intent and complete effect binding. + +[Start here](https://github.com/stringsofthemind-oss/once/blob/main/docs/START_HERE.md) +· [Identity and effect](https://github.com/stringsofthemind-oss/once/blob/main/docs/IDENTITY_AND_EFFECT.md) +· [UNKNOWN playbook](https://github.com/stringsofthemind-oss/once/blob/main/docs/UNKNOWN_PLAYBOOK.md) +· [Guarantees](https://github.com/stringsofthemind-oss/once/blob/main/docs/GUARANTEES.md) + + +> **Automatic Connect:** `@once-agent/sdk@0.1.22` publishes the tested > `@once-agent/sdk/connect` path for classifying supported agent tools as > `BYPASS`, `PROTECT`, or fail-closed `UNKNOWN`, then wiring whole local tool > registries with trusted logical identity and effect binding. It also includes @@ -23,7 +43,7 @@ Once helps protect supported refunds, bookings, payments and other externally vi - Automatic Connect guide: [`docs/CONNECT_AUTO.md`](./docs/CONNECT_AUTO.md) - MCP idempotency guide: https://onceexec.com/mcp-idempotency/ - AI agent retry safety: https://onceexec.com/ai-agent-retry-safety/ -- TypeScript SDK: [`@once-agent/sdk@0.1.18`](https://www.npmjs.com/package/@once-agent/sdk) +- TypeScript SDK: [`@once-agent/sdk@0.1.22`](https://www.npmjs.com/package/@once-agent/sdk) - Python SDK: [`once-agent-sdk==0.1.1`](https://pypi.org/project/once-agent-sdk/) - MCP package: `@once-agent/mcp@0.1.5` - MCP Registry: `io.github.stringsofthemind-oss/once` @@ -212,7 +232,7 @@ ONCE_API_KEY=your_api_key Do not commit API keys to source control. -## 60-second quick start +## Hosted quick start (provider setup required) First configure a provider with `once setup .`, or use a provider alias already registered with your Once account. diff --git a/docs/AUTHORITY_CONTINUITY.md b/docs/AUTHORITY_CONTINUITY.md new file mode 100644 index 00000000..b4e33fd6 --- /dev/null +++ b/docs/AUTHORITY_CONTINUITY.md @@ -0,0 +1,65 @@ +# Authority continuity: measured local boundary + +The TypeScript local path requires retained durable authority. It cannot +distinguish a new installation from total loss of an old database after restart. +A missing row does not establish provider absence. + +## Controlled experiment, 2026-10-01 + +Run `node sdk/typescript/scripts/authority-continuity-regression.mjs` after +building. Set `ONCE_PRIOR_IMPLEMENTATION` to the absolute public 0.1.22 +`dist/index.js` to include upgrade/rollback evidence. The harness owns fresh +temporary directories and deletes only those fixtures. Provider effects live +in a separate file ledger: **simulated, not external provider evidence**. +Each invocation is a fresh process. + +| Scenario | Expected contract | Observed on Windows, Node 24.19 | Effects | +|---|---|---|---| +| Normal restart | Replay retained receipt | Original receipt | 1 | +| SQLite current snapshot restore | Replay retained receipt | Original receipt | 1 | +| Public 0.1.22 to review candidate | Retained schema/effect stays replayable | Original receipt | 1 | +| Candidate rollback to 0.1.22, retained state | Same unchanged authority | Original receipt | 1 | +| Closed-process complete state loss | No cross-restart loss detection promised | New database, redispatch | **2** | +| Pre-effect snapshot restored after commit | Stale authority cannot remember missing effect | Redispatch | **2** | +| Process death after provider commit | Reconcile abandoned claim after lease | Original receipt, no write | 1 | +| Recovery interrupted | Read-only recovery can resume | UNKNOWN while unavailable, then receipt | 1 | +| Provider truth unavailable | Block | UNKNOWN | 1 | +| ABSENT assertion after known commit | No local redispatch | UNKNOWN | 1 | + +These are demonstrated limitations of the retained-authority contract, not a +new bug introduced by the optimization. They disprove a broader claim that +local restart protection survives arbitrary state loss or stale restore. +Live-session file checks do not close the cross-restart gap. This harness does +not certify multi-host coordination, arbitrary-version migrations, positive +contradictory receipts or an untrusted reconcile callback. + +## Operational gate + +Stop provider writes after suspected authority loss or stale restore. Retain +business intents independently, identify the affected interval and verify +provider truth before resuming. Do not point the wrapper at an empty file to +escape STATE_UNAVAILABLE or UNKNOWN. Current backup used SQLite `VACUUM INTO` +after calls completed; this is not a hot-backup load test. + +A cross-restart authority-loss guarantee requires an independently retained +admission/authority contract and a reviewed migration/bootstrap flow. A sentinel +beside the database can disappear with it and cannot prove freshness after +rollback. Adding one without resolving this boundary gives false confidence. +No such kernel change is included in this candidate. + +## Forensic confirmation + +`npm run test:authority-forensics` records exact inputs, SQLite rows/schema, +fingerprints, receipt envelopes, independent provider contents, child process +IDs and UTC snapshot/restore boundaries. A stale but valid snapshot retains an +older confirmed B while omitting later committed A; retry A produces its second +effect. Complete authority-directory loss does likewise. A current snapshot +replays A. In all these cases the supplied reconcile callback is never invoked: +missing rows take first-admission, while confirmed rows replay directly. + +The harness also models an atomic provider-native identity/effect deduplication +contract surviving local loss. Once dispatches again, but that simulated +provider returns its existing receipt without another effect. This is a +mechanism illustration, not a real-provider or unlimited-retention guarantee. +The provider store is independent of Once loss, and must remain so for that +stronger boundary. No production execution code or storage schema changes. diff --git a/docs/FOUNDING_PRODUCTION_PACKAGE.md b/docs/FOUNDING_PRODUCTION_PACKAGE.md new file mode 100644 index 00000000..f8aa19f7 --- /dev/null +++ b/docs/FOUNDING_PRODUCTION_PACKAGE.md @@ -0,0 +1,79 @@ +# Founding production package — proposal for validation + +**Internal commercial experiment; not an available production service or an +approved price list.** Repository hosted-readiness gates remain in force. No +live billing, release or deployment is authorized by this document. + +## Smallest product worth paying for + +One supported consequential workflow with managed durable coordination, a +maintained provider recovery adapter and an owner for unresolved outcomes. +Do not select the first workflow because an adapter already exists. +Stripe refunds are an integration candidate, but native idempotency is a +strong substitute. Qualify for recurring recovery/operational work, not merely +a missing idempotency header. Research agent-created orders, bookings and +account mutations where native protections or recovery are inadequate. +GitHub issue creation is a safe research effect, not a validated paid wedge. +No initial commercial workflow has yet been selected by cold-user evidence. + +Hypothesis: **£200/month excluding VAT**, one production project plus staging, +one agreed workflow, two users, inspectable operation history, UNKNOWN alerts, +bounded recovery assistance and onboarding. These contents are acceptance +requirements to validate; not all are implemented or live. Choose operation +allowance, retention and support limits from measured costs before selling. + +The local SDK remains useful and free. Charge for operating safety, not for +the ability to block an unsafe retry. Meter unique admitted logical operations; +do not bill each replay, reconciliation or retry. Existing recovery must remain +accessible when new-effect admission is blocked by quotas or subscriptions. +Resolve orphaned meter reservations in the billing policy before live charging. + +## Three design partners first + +Target small B2B teams deploying support/commerce agents within 60 days, with +consequential writes, retrying workers and a named engineering owner. Trigger: +production launch, a real retry incident or repeated manual recovery work. +Start through one framework/tool integration and a provider sandbox proof. + +Pilot acceptance: + +1. Trusted code persists intent before dispatch and binds the actual effect. +2. Actual runtime/tool invocation goes through Once; no equivalent raw tool is exposed. +3. First execution/replay/conflict and lost-ack recovery pass in the provider sandbox. +4. Provider effects are independently counted; unresolved truth remains blocked. +5. State continuity, deployed service version and adapter assumptions are reviewed. +6. Operator ownership, support scope and recurring payment acceptance are agreed. + +Production delivery still requires explicit owner approval of the actual +deployment/live-provider change. A local fixture or sandbox checkout is not MRR. + +## Measurable acquisition funnel + +Track organizations, qualified conversations, pilots started, independently +verified protected actions, paid recurring accounts and 30/60/90-day retention. +Measure UNKNOWN age/resolution, onboarding time and support hours. No opt-in +telemetry is introduced by this document. + +Working target: approach 20 relevant organizations/week, hold about three +qualified conversations, and start at most one pilot/week while keeping at most +two new integrations active. Founder outreach is an activity plan, not an +assumed conversion rate. No messages are sent by this implementation. + +Revenue alternatives: + +| Model | Accounts for £2,000 MRR | Early tradeoff | +|---|---:|---| +| £200/month | 10 | Requires real operated value; support must be bounded | +| £100/month | 20 | More acquisition and support; useful if teams self-onboard | +| £50/month | 40 | High account burden before onboarding is repeatable | + +Use £200 as the first paid-pilot hypothesis. Seek three recurring commitments +before adding tiers. If at least 15 qualified conversations and five completed +pilots produce fewer than two paying customers, revise the workflow/segment +before adding integrations or discounting. Conversion, retention and time to +£2,000 MRR remain unknown; calculate a forecast only after collecting cohorts. + +Retention reason: production execution and uncertain-outcome recovery are +operationally useful every month. Expansion follows additional proven workflows +or volume, not extra agents. If Stripe alone is enough for the cohort, choose +one repeated non-native provider need rather than claiming broader safety. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md new file mode 100644 index 00000000..2a3d0f6d --- /dev/null +++ b/docs/GUARANTEES.md @@ -0,0 +1,50 @@ +# Execution-safety boundaries + +Current public TypeScript SDK: **0.1.22**. This matrix describes the inspected +implementation, not certification of every deployment or provider. Once does +not claim universal exactly-once execution or atomicity with arbitrary external +systems. Approval, correctness of the business action and access control are +separate responsibilities. + +| Behavior | Supported? | Guarantee on the local path | Requires / boundary | +|---|---|---|---| +| Confirmed replay | Yes | Returns the stored replayable receipt without another wrapper dispatch | Same ID, effect and retained SQLite file | +| Changed effect | Yes | CONFLICT prevents a second wrapper dispatch | Complete explicit effect binding | +| Same payload, new intent | Yes | Separate intended action may execute | Application-owned distinct identity | +| Uncertain outcome | Yes | UNKNOWN blocks blind redispatch | Every call stays behind wrapper | +| Provider recovery | Conditional | Valid CONFIRMED evidence can persist original receipt | Authoritative read-only lookup and safe receipt | +| Absence after ambiguity | No local redispatch | Even ABSENT evidence does not authorize another local write | Provider-native guarantee needed for other recovery models | +| Restart replay | Yes, bounded | Retained confirmed state replays; abandoned claim blocks/reconciles | Same persistent authority; early retry can be IN_FLIGHT | +| Same-process concurrency | Yes, bounded | One cooperating claimant dispatches | Shared file and supported filesystem | +| Multiple processes | Yes, bounded | SQLite coordinates cooperating callers sharing one file | One machine, SQLite WAL/locking support | +| Multiple hosts | Not via local SQLite | Separate files do not coordinate | Review a supported shared hosted/backend contract | +| Unreplayable receipt | Blocks | No blind retry after an effect may have occurred | Reconcile to JSON-safe result | +| Provider-internal retries | Not generically | Wrapper controls its dispatch, not every provider SDK attempt | Adapter review/native idempotency | +| Ledger loss/old backup | Not covered; measured redispatch | Complete loss and stale restore each produced two controlled effects | Stop writes; [continuity evidence](AUTHORITY_CONTINUITY.md) | +| Wrong identity / omitted effect | Not automatically repairable | Declared semantics are trusted | Application review against actual request | + +## Deployment distinctions + +- **TypeScript local:** Node.js 24.15+, persistent same-machine SQLite. No API key + or provider registration needed to wrap an existing function. +- **Python reference core:** a separate capability-aware reference backend. + Its provider-idempotency/fencing recovery contract is not identical to + TypeScript `protectLocal`; see `sdk/python/src/once_agent/core.py`. +- **Existing hosted client/runtime:** requires authentication and supported + provider setup. A public endpoint does not prove the new gateway gates are on. +- **New hosted gateway:** repository contracts record isolated Stripe-sandbox + staging evidence. The production-readiness document explicitly says the new + path is not deployed or wired to production. Verify active version and flags + before claiming otherwise. +- **MCP discovery/setup:** helps integrate protection. It does not intercept + every external action simply because it is installed. A reviewed runtime + proxy/connected tool boundary is a separate path. + +Runtime tests using the local SQLite harness do not model Cloudflare output +gates or scheduling. Framework fixtures and real-provider experiments support +their tested failure models; neither establishes universal behavior. + +See [hosted contract](GATEWAY_HOSTED_TRANSPORT_V1.md), +[readiness](GATEWAY_HOSTED_PRODUCTION_READINESS_V1.md), +[local details](../examples/local-function/README.md) and +[production operation](PRODUCTION_OPERATION.md). diff --git a/docs/IDENTITY_AND_EFFECT.md b/docs/IDENTITY_AND_EFFECT.md new file mode 100644 index 00000000..9d4abf78 --- /dev/null +++ b/docs/IDENTITY_AND_EFFECT.md @@ -0,0 +1,51 @@ +# Own the identity; bind the effect + +Before integration, answer: **what durable application record represents one +intended action?** Once cannot decide this from the text of a model response. + +Persist a new intent before the first provider request. A random UUID generated +once and stored is valid. Generating it inside each retry is not. A deterministic +ID is only correct if its business semantics are correct. + +| Situation | Identity | Effect | +|---|---|---| +| Retry after timeout/restart | Original intent | Original bound inputs | +| Two separate identical orders | Different persisted intents | May be identical | +| Correcting amount under existing intent | Original intent | Changed amount produces CONFLICT | +| Second legitimate partial refund | Separate refund-request intent | Separately authorized amount | + +An order ID alone cannot distinguish multiple legitimate refunds for that order. +Scope identities by environment, tenant/provider account and operation type. +Do not change that scope to escape an unresolved action. Framework call IDs, +timestamps and freshly generated request IDs identify attempts, not intentions. + +## Effect review + +Review the actual outbound mutation and include every value that changes it: + +- Provider account/tenant and destination resource. +- Amount and currency, quantity, product or reservation details. +- Message recipient, content, attachments and relevant delivery options. +- Operation type, behavior-changing API version/defaults and configuration. + +Exclude attempt-only tracing fields and fault-injection flags only after checking +they cannot change the real effect. Do not solve omissions by silently hashing +all inputs. Conversely, conservative full-input binding can conflict when +volatile metadata changes; explicit reviewed selectors avoid that problem. + +Ordinary arguments are snapshotted. Opaque handles, credentials, closures and +dynamic receivers remain trusted application code; the wrapper does not prove +that the function uses only declared fields. Prefer constructing the provider +request directly from bound data. A declared account must match the account +selected by the provider credential. + +Keep identity encoding and effect semantics stable across retries, deployment, +upgrade and rollback. Versioning a tool name or operation namespace can make an +old retry look like a new action. Review migration before changing it. + +For agents, persist and inject intent in trusted application code. A tool input +called `intentId` is not automatically trustworthy if the model invents it each +time. Do not expose an unwrapped equivalent tool alongside the protected one. + +See [UNKNOWN](UNKNOWN_PLAYBOOK.md) for blocked actions and +[production operation](PRODUCTION_OPERATION.md) for state continuity. diff --git a/docs/OPTIMIZATION_PLAN_2026-10-01.md b/docs/OPTIMIZATION_PLAN_2026-10-01.md new file mode 100644 index 00000000..f7fdf013 --- /dev/null +++ b/docs/OPTIMIZATION_PLAN_2026-10-01.md @@ -0,0 +1,65 @@ +# Optimization decision record — 1 October 2026 + +Owner-authorized branch work; no merge, release or production deployment. + +## Product thesis + +The smallest paid product is one supported consequential workflow with managed +durable authority, inspectable outcomes and provider-truth recovery assistance. +The free local kernel remains useful. Optimize adoption and trust before breadth. + +## Ranked P0/P1 plan + +| Rank | Priority | Change | Status / evidence | +|---|---|---|---| +| 1 | P0 | Make current guarantees and deployment boundaries explicit | Implemented: GUARANTEES and production runbook | +| 2 | P0 | Give developers one credential-free first-action entry point | Implemented: existing once prove promoted; canonical source/packed example | +| 3 | P0 | Preserve identity ownership and make UNKNOWN operable | Implemented guidance; no new inspection/recovery service claimed | +| 4 | P1 | Eliminate current-version drift and prevent recurrence | Implemented source-surface guard, drift regressions and registry verification | +| 5 | P1 | Fix platform-specific test defects and gate portability | Implemented fixtures, plugin line-ending checks and CI matrix; non-Windows execution pending | +| 6 | P1 | Align MCP with reviewed SDK and verify the runtime boundary | Implemented 0.1.22 pin/lockfile; smoke and boundary/stdio/replay/persistence checks | +| 7 | P1 | Define one sellable package and measurable pilot acceptance | Implemented internal commercial experiment; price/adoption unvalidated | +| 8 | P0 | Establish deployed hosted production safety and authority continuity | Deferred: requires actual deployed-version evidence, operator decisions and separate owner approval; no speculative redesign | + +## Truth audit + +| Public claim | Evidence | Status | Confidence / boundary | +|---|---|---|---| +| Current SDK is 0.1.22 | npm metadata; source package; inspected artifact | PROVEN as published-version identity | High; branch additions are unreleased | +| Same ID/effect replays | local/Connect regressions; durable receipt code | SUPPORTED BUT BOUNDED | High on tested same-file local paths | +| Changed effect conflicts | binding and execution regressions | SUPPORTED BUT BOUNDED | Depends on complete trusted selectors | +| UNKNOWN blocks blind local retry | source transitions; lost-ack/crash tests | SUPPORTED BUT BOUNDED | Does not imply eventual completion | +| Local absence permits redispatch | local source explicitly refuses it | FALSE if stated generically | Guide now distinguishes local/adapter models | +| Recovery needs no saved issue number | marker lookup implementation and controlled tests | PARTIALLY PROVEN | Live issue counts owner-reported; mutable trusted repository assumptions | +| Restart preserves protection | retained-file replay and crash tests | SUPPORTED BUT BOUNDED | Ledger deletion/rollback not covered | +| Same-machine multiple processes coordinate | SQLite claim and process tests | SUPPORTED BUT BOUNDED | Same persistent file; no network filesystem | +| Local wrappers coordinate hosts | No shared authority for separate files | FALSE | Explicitly unsupported | +| MCP install protects all calls | discovery/setup separate from runtime | FALSE | Connected proxy/tool path must be configured | +| OpenAI FunctionTool boundary is supported | structural invoke adapter and tests | SUPPORTED BUT BOUNDED | Trusted identity/effect; no certification of every framework version | +| New hosted path is production-ready | readiness document says not deployed | UNVERIFIED | No production changes or live proof performed | +| 60-second first integration | no full human onboarding measurement | UNVERIFIED | Removed from current surfaces | +| Security/compliance/availability guarantees | no deployed-service audit in this work | UNVERIFIED | No new such claims added | +| Hosted retention/billing prevents safety-state deletion | source contract and runtime regressions | SUPPORTED BUT BOUNDED | Deployment/configuration remains separate | +| £200 package has buyers | no paid customer cohort | UNVERIFIED | Internal experiment only | + +## Audit coverage + +The source inspection covered repository layout and public docs; both SDK +metadata/client/core/storage surfaces; MCP server/proxy and package pins; +CLI/scanner/protect/apply and HTTP/local transformer boundaries; local state, +identity/payload, reconciliation contracts; Connect/Gateway/OpenAI adapters; +monitor/discovery/observation surfaces; examples and regression scripts; +website/static/dynamic versions; CI, package contents and release references; +hosted transport, credentials, metering/retention and production-readiness records. +Tests exercise specific contracts. This is not exhaustive line-by-line review +of every source file or certification of all provider/deployment behavior. + +## Limits retained intentionally + +No kernel state transition, storage schema or identity algorithm changed. +No model-owned identity, UNKNOWN expiry, unsafe fallback, arbitrary interception +or public service readiness claim was introduced. Authority-loss recovery, +multi-host storage changes and new outcome APIs need separately scoped design. +Historical evidence pins remain frozen; incomplete historical changelog entries +were not fabricated. Existing commands remain compatible while their first-user +presentation is simplified. diff --git a/docs/PRODUCTION_OPERATION.md b/docs/PRODUCTION_OPERATION.md new file mode 100644 index 00000000..52a8e779 --- /dev/null +++ b/docs/PRODUCTION_OPERATION.md @@ -0,0 +1,57 @@ +# Operate one protected workflow + +Choose a supported workflow and adapter before promising production protection. +Name an owner for unresolved operations. A successful synthetic proof is a useful +start, not production readiness. + +## Before real provider writes + +1. Review persisted intent, namespace and complete effect against actual outbound + requests; confirm native provider idempotency and its retention window. +2. Ensure every caller uses the protected boundary. Review internal SDK retries, + redirects and functions containing multiple effects. +3. Select persistent authority for the topology. Local SQLite does not coordinate + separate hosts or isolated containers, and network filesystems are unsupported. +4. Exercise first execution, replay, conflict, lost acknowledgement, process death + and read-only recovery against the provider sandbox. Count provider effects. +5. Validate receipt serialization and version compatibility before deployment. +6. Document UNKNOWN escalation, provider-read limits and alert ownership. Check + subscription/quota changes preserve access to existing replay/reconciliation. + +## State continuity, upgrade and rollback + +Keep the state location and semantic identity stable across deployments. Back up +SQLite with a SQLite-compatible procedure that accounts for WAL; a copied main +file alone may be incomplete. Test recovery in an isolated sandbox. + +An old backup may omit already-committed effects. Do not restore it and resume +writes on the assumption that missing rows prove absence. Stop writes, investigate +provider truth for the affected interval and retain unresolved intents. Live +session file checks cannot prove all cross-restart continuity or backup freshness. + +The [continuity experiment](AUTHORITY_CONTINUITY.md) measured this boundary: +complete state loss and a stale pre-effect snapshot each allowed a second +controlled effect after restart. Treat this as an operational write-stop gate. + +Do not change an identity algorithm, tool name, provider account, effect schema +or receipt format without testing existing confirmed and uncertain operations. +Rehearse upgrade and rollback with retained state. This branch does not introduce +a new storage schema or guarantee transparent arbitrary-version rollback. + +## Hosted service + +Inspect the [hosted readiness record](GATEWAY_HOSTED_PRODUCTION_READINESS_V1.md) +for deployment, credential, entitlement, retention and billing decisions. It is +not authorization to turn on production gates. Verify the deployed artifact, +route and configuration separately, including tenant isolation and durability +before provider dispatch. + +Publish actual data handling, credential encryption/rotation, retention and +service support behavior before making security, compliance or availability +promises. An operation record is safety authority, not a disposable cache; do +not couple its deletion to a short audit-log or subscription retention policy. + +Measure UNKNOWN count/age, recovery time, unreplayable receipts, conflicts, +contention, replay latency and manual operator effort. Keep payloads and secrets +out of telemetry by default. Downloads and scanner counts do not measure protected +production actions. diff --git a/docs/RELEASE_0_1_23.md b/docs/RELEASE_0_1_23.md new file mode 100644 index 00000000..33da1e8a --- /dev/null +++ b/docs/RELEASE_0_1_23.md @@ -0,0 +1,45 @@ +# SDK 0.1.23 candidate — not published + +Public registry remains **0.1.22**. Source package and lockfile prepare +**0.1.23**. Public onboarding pins and `published-versions.json` intentionally +remain 0.1.22 until registry publication is verified. MCP source still depends +on public 0.1.22; no MCP release is included. + +## Release notes + +This patch improves the first protected-action journey and operational clarity. +It includes a credential-free simulated first-action example in the package, +promotes the existing `once prove` command, clarifies identity/effect ownership +and UNKNOWN recovery, and improves Windows persistence test reliability. +It adds portability CI, current-onboarding consistency checks and a controlled +authority-continuity investigation. No execution-kernel or storage-schema +change is included. No new exactly-once, multi-host, backup freshness, security +or hosted availability guarantee is introduced. + +**Measured limitation:** losing complete local authority or restoring a +pre-effect snapshot after commit allowed a second controlled effect. The +same-machine retained-state contract remains essential. Stop writes after +suspected authority loss and investigate provider truth. See +[continuity evidence](AUTHORITY_CONTINUITY.md). + +## Gate + +Status: **NOT READY for owner publication approval** until candidate verification +is attached and required portability CI has passed. Local Windows evidence is +not Linux/macOS evidence. Release preparation does not authorize publishing. + +- [x] Review scoped source diff and unchanged kernel/schema. +- [x] Rebuild 0.1.23 ESM/CommonJS and inspect packed metadata and contents. +- [x] Full release, local, SDK, runtime, Python and MCP checks on Windows. +- [x] Packed first-action, Connect and Gateway protection checks. +- [x] Authority continuity with public 0.1.22 and candidate; simulated provider. +- [ ] Windows/Linux/macOS Node 24.15 portability CI; other supported Node gates. +- [x] Confirm guidance conspicuously excludes state loss/stale restore/multi-host. +- [ ] Owner reviews acceptance of operational limitations and release notes. +- [ ] Owner approves merge and npm publication separately. +- [ ] After approval only: publish exact reviewed tarball, verify npm integrity, + update public pins/site metadata and MCP source dependency deliberately. +- [ ] Deploy documentation only with owner approval; verify deployed surfaces. + +Five-minute/30-minute onboarding targets and £200/month packaging remain +unvalidated. Recruitment results are separate from release-test results. diff --git a/docs/START_HERE.md b/docs/START_HERE.md new file mode 100644 index 00000000..f5caca8f --- /dev/null +++ b/docs/START_HERE.md @@ -0,0 +1,114 @@ +# Start with one protected action + +Once wraps consequential application functions and agent tools so retries use +durable knowledge of the original action. You define the intended action's +identity and the inputs that determine its effect. Once replays confirmed +receipts, rejects changed effects and blocks uncertain outcomes. + +Use Once when an external write can be retried, its acknowledgement can be lost, +and duplication matters. Provider-native idempotency may already cover a simple +integration. Use it where available; Once does not replace the provider's +guarantees or your application's authorization checks. + +## First controlled proof + +The currently published TypeScript SDK is **0.1.22**. Local execution needs +**Node.js 24.15+**; the hosted HTTP client has a different runtime boundary. + +In a throwaway directory, these commands work in PowerShell and POSIX shells: + +```sh +npm init -y +npm install @once-agent/sdk@0.1.22 +npx once prove +``` + +No Once API key or provider credentials are required. The proof uses a simulated +provider and isolated temporary state. It demonstrates a committed effect with +a lost acknowledgement, a blocked retry, recovery and confirmed replay. It does +not establish that your application's tools are protected or that a real +provider can reconcile. Five minutes is an onboarding target, not a measured +human completion-time guarantee. + +## Protect your existing function + +```ts +import { Once, protectLocal } from "@once-agent/sdk"; + +const createOrder = protectLocal( + async (input) => provider.createOrder({ + account: input.account, + sku: input.sku, + quantity: input.quantity, + }), + { + // Persist intentId BEFORE dispatch. Reuse it for every retry/restart. + // A separate intended order gets a separate intent, even for the same SKU. + id: (input) => Once.id("production", input.account, "create-order", input.intentId), + payload: (input) => ({ + account: input.account, + sku: input.sku, + quantity: input.quantity, + }), + statePath: "/persistent/local/path/operations.sqlite", + }, +); +``` + +Replace the state path with a persistent absolute path on your machine; on +Windows, for example, use `C:/your-project/.once/operations.sqlite`. All +cooperating processes must use the same file. The provider account/configuration +must correspond to the bound account and remain stable during a call. + +Return a JSON-safe receipt that represents the provider outcome you intend to +confirm. Do not return an SDK response object, stream or credential. An accepted +queued job is not proof of the job's final effect. Route all calls through the +wrapper; internal provider retries and multiple effects inside one function need +their own reviewed provider semantics. + +The [canonical source example](../sdk/typescript/examples/first-action/verify.mjs) +counts simulated effects for first execution, replay, changed-effect conflict, +distinct intent with identical effect, lost acknowledgement, unavailable truth, +recovery and fresh-process replay. Run it from a built source checkout using +`node examples/local-function/verify.mjs`. That source example and its package +inclusion are branch changes; public 0.1.22 consumers can use `once prove` now. + +## Choose your path + +- Existing function on one machine: [local function guide](../examples/local-function/README.md). +- Agent tool registry or OpenAI function tools: [Connect](CONNECT_AUTO.md). + Give the agent only the connected tools. Trusted application code supplies + the persisted intent; a model-generated call ID is not business identity. +- MCP: [MCP guide](../mcp/README.md). Setup/discovery is separate from runtime + enforcement; installation alone does not protect arbitrary tool calls. +- Existing project discovery: `npx once doctor .`, then review `npx once protect .`. + Applying a supported patch is an explicit separate step. Never reshape an + action's business meaning to satisfy a transformer. +- Multiple hosts: inspect [guarantees](GUARANTEES.md) and + [production operation](PRODUCTION_OPERATION.md) before choosing a backend. + +## Documentation map + +1. What is Once? This guide's introduction. +2. Why does it exist? Ambiguous external writes, described above. +3. Five-minute target: [controlled proof](#first-controlled-proof); human timing unverified. +4. Identity: [application ownership](IDENTITY_AND_EFFECT.md). +5. Effect binding: [effect review](IDENTITY_AND_EFFECT.md#effect-review). +6. Replay: [local execution contract](../examples/local-function/README.md). +7. Conflict: [caller outcomes](UNKNOWN_PLAYBOOK.md#safe-application-response). +8. UNKNOWN: [playbook](UNKNOWN_PLAYBOOK.md). +9. Recovery: [original receipt](UNKNOWN_PLAYBOOK.md#recover-the-original-receipt). +10. Provider adapters: [reconciliation contract](../sdk/typescript/src/reconciliation/CONTRACT.md). +11. Agent integration: [Connect](CONNECT_AUTO.md). +12. MCP: [MCP guide](../mcp/README.md). +13. CLI: [CLI reference](../sdk/typescript/README.md#cli-workflow). +14. Guarantees: [matrix](GUARANTEES.md). +15. Limitations: [authority continuity](AUTHORITY_CONTINUITY.md) and guarantee boundaries. +16. Production operation: [runbook](PRODUCTION_OPERATION.md). +17. API reference: [TypeScript SDK](../sdk/typescript/README.md#api-overview) and [Python SDK](../sdk/python/README.md). +18. Architecture: [local boundary](../examples/local-function/README.md), + [hosted contract](GATEWAY_HOSTED_TRANSPORT_V1.md) and + [hosted readiness](GATEWAY_HOSTED_PRODUCTION_READINESS_V1.md). + +Historical evidence and phase records remain available for reproducibility. +They do not override current adapter or deployed-service boundaries. diff --git a/docs/UNKNOWN_PLAYBOOK.md b/docs/UNKNOWN_PLAYBOOK.md new file mode 100644 index 00000000..9728df1f --- /dev/null +++ b/docs/UNKNOWN_PLAYBOOK.md @@ -0,0 +1,57 @@ +# UNKNOWN: the action may already have happened + +UNKNOWN means Once cannot safely establish the external outcome. A timeout, +crash, lost response or unusable receipt does not prove failure. Your application +must stop blind mutation retries and preserve the original intent and state. + +## Safe application response + +Tell the user the outcome is being checked. Keep the business action unresolved. +Record a correlation ID and machine-readable error code without logging secrets. +For local wrappers, use `LocalProtectionError.code`; errors are not permission +to invoke the provider directly. + +| Outcome | Next safe step | +|---|---| +| Receipt | Record the original result; replay is not a live object refresh | +| `IN_FLIGHT` | Wait with a bounded retry budget and reuse the same intent/file | +| `UNKNOWN` | Read provider truth under the original intent, or escalate | +| `CONFLICT` | Investigate changed effect fields; do not generate a replacement ID automatically | +| `UNREPLAYABLE_RESULT` | The effect may exist; recover a JSON-safe receipt | +| `EXECUTION_RIGHT_LOST` | Treat completion as uncertain; reconcile | +| `STATE_UNAVAILABLE` | Restore access to existing authority; do not create an empty substitute | + +## Recover the original receipt + +Supply a read-only `reconcile({ id, payload })` callback to `protectLocal` or +Connect. It must validate that provider evidence matches the exact intended +action and complete effect. Return `{ state: "CONFIRMED", result: receipt }` +only with authoritative evidence and a replayable receipt. A retry through the +same wrapper can then recover and persist it; later retries replay it. + +A timeout, rate limit, edited object, ambiguous match or search miss remains +UNKNOWN. Local mode **does not redispatch after ambiguity even if reconciliation +returns ABSENT**: an old request might still commit. A hosted/provider integration +can have different capability requirements; inspect its contract before relying +on re-execution. + +For the hosted client, `once.truth(operationId)` inspects the supported service +status; that is not a generic local-file inspection API. The local path uses the +original protected call and reconciliation callback. Do not imply these APIs +are interchangeable. + +The [GitHub recovery example](../sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md) +demonstrates correlation without retaining a lost issue number, under explicit +trusted-repository assumptions. It is not a universal GitHub exactly-once adapter. + +## If truth stays unavailable + +Escalate to a named operator with the original intent, expected effect, provider +account and last safe evidence. Keep the operation blocked. A retry budget +expiring does not make another write safe. Do not clear the database, expire the +identity, change the account or expose an unwrapped fallback. + +A genuinely new business action needs separate authorization and intent. If the +original is unresolved, explicitly account for the possibility that it occurred; +a new ID is not a recovery mechanism. Compensation is a separate consequential +operation and needs its own identity and provider semantics. diff --git a/docs/agent.md b/docs/agent.md index 92e4d2aa..7ed53455 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -1,6 +1,12 @@ # Once — Agent-Readable Product Guide -> **Automatic Connect:** `@once-agent/sdk@0.1.14` publishes the tested +Start: https://github.com/stringsofthemind-oss/once/blob/main/docs/START_HERE.md + +Recovery: https://github.com/stringsofthemind-oss/once/blob/main/docs/UNKNOWN_PLAYBOOK.md + +Guarantees: https://github.com/stringsofthemind-oss/once/blob/main/docs/GUARANTEES.md + +> **Automatic Connect:** `@once-agent/sdk@0.1.22` publishes the tested > `@once-agent/sdk/connect` toolset integration path. It can classify supported > agent tools as `BYPASS`, `PROTECT`, or fail-closed `UNKNOWN`, bind trusted > logical intent identity and effect payload, and return a connected local tool @@ -24,7 +30,7 @@ Canonical site: https://onceexec.com/ Repository: https://github.com/stringsofthemind-oss/once -TypeScript SDK: `@once-agent/sdk@0.1.14` +TypeScript SDK: `@once-agent/sdk@0.1.22` npm: https://www.npmjs.com/package/@once-agent/sdk diff --git a/docs/index.html b/docs/index.html index be4d87ab..05ac734c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -46,7 +46,7 @@ "@type": "SoftwareApplication", "name": "Once", "applicationCategory": "DeveloperApplication", - "softwareVersion": "0.1.10", + "softwareVersion": "0.1.22", "url": "https://onceexec.com/", "downloadUrl": "https://www.npmjs.com/package/@once-agent/sdk", "codeRepository": "https://github.com/stringsofthemind-oss/once", @@ -309,7 +309,7 @@ - TS SDK 0.1.10 · PY SDK 0.1.0 · MCP 0.1.2 + TS SDK 0.1.22 · PY SDK 0.1.1 · MCP 0.1.5 @@ -659,7 +659,7 @@

- Run 60s quickstart + Run controlled proof - @once-agent/sdk 0.1.10 + @once-agent/sdk 0.1.22
@@ -2613,6 +2613,17 @@

+
+ $ + npx --yes --package=@once-agent/sdk@0.1.22 once prove +
+ +

Start with an isolated simulated provider on Node.js 24.15+. + No credentials or real provider writes. This proof does not wire your application's tools.

+

Protect one action + · UNKNOWN playbook + · Guarantees and limits

+
$ npx --yes --package=@once-agent/sdk once doctor . @@ -2912,7 +2923,7 @@

- TS SDK 0.1.10 · PY SDK 0.1.0 · MCP 0.1.2 + TS SDK 0.1.22 · PY SDK 0.1.1 · MCP 0.1.5 diff --git a/docs/llms.txt b/docs/llms.txt index ebd8e87b..69be517f 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -24,7 +24,7 @@ https://onceexec.com/ Repository: https://github.com/stringsofthemind-oss/once -TYPESCRIPT SDK: @once-agent/sdk@0.1.14 +TYPESCRIPT SDK: @once-agent/sdk@0.1.22 Install: npm install @once-agent/sdk npm: https://www.npmjs.com/package/@once-agent/sdk @@ -32,7 +32,7 @@ PYTHON SDK: once-agent-sdk==0.1.1 Install: pip install once-agent-sdk PyPI: https://pypi.org/project/once-agent-sdk/ -AUTOMATIC CONNECT: published in @once-agent/sdk@0.1.14. It can classify supported agent-tool descriptors as BYPASS, PROTECT, or fail-closed UNKNOWN; plan and connect whole local tool registries; resolve trusted intent/idempotency identity; bind effect payload; and structurally wrap OpenAI Agents FunctionTools. Automatic protected local execution requires Node 24.15+ and shared same-machine SQLite state. It is not a multi-host or universal exactly-once guarantee. +AUTOMATIC CONNECT: published in @once-agent/sdk@0.1.22. It can classify supported agent-tool descriptors as BYPASS, PROTECT, or fail-closed UNKNOWN; plan and connect whole local tool registries; resolve trusted intent/idempotency identity; bind effect payload; and structurally wrap OpenAI Agents FunctionTools. Automatic protected local execution requires Node 24.15+ and shared same-machine SQLite state. It is not a multi-host or universal exactly-once guarantee. LOCAL PROTECTION: protectLocal(existingAsyncFunction, {id, payload}) keeps the call shape and receiver, snapshots ordinary data arguments, and uses durable same-machine SQLite on Node 24.15+. It validates a narrow plain-data domain. UNKNOWN and CONFLICT block; do not infer ABSENT from a timeout. See examples/local-function/README.md in the repository. For separate hosts use a supported distributed Once integration. MCP package: @once-agent/mcp@0.1.5 MCP Registry: io.github.stringsofthemind-oss/once diff --git a/docs/page-analytics.js b/docs/page-analytics.js index 1f042c6b..f01dc204 100644 --- a/docs/page-analytics.js +++ b/docs/page-analytics.js @@ -4,7 +4,7 @@ // Kept in lockstep with package metadata by // scripts/check-site-surface.mjs. const SITE_VERSIONS = Object.freeze({ - ts: "0.1.18", + ts: "0.1.22", python: "0.1.1", mcp: "0.1.5" }); diff --git a/docs/published-versions.json b/docs/published-versions.json index cdb857d7..484bf553 100644 --- a/docs/published-versions.json +++ b/docs/published-versions.json @@ -1,4 +1,4 @@ { - "ts": "0.1.18", + "ts": "0.1.22", "mcp": "0.1.5" } diff --git a/examples/local-function/README.md b/examples/local-function/README.md index 2ac87961..f0e5e6ed 100644 --- a/examples/local-function/README.md +++ b/examples/local-function/README.md @@ -102,32 +102,32 @@ To verify, use a test provider that counts actual external effects. Invoke **2**, with the last call raising `CONFLICT`. Also commit an effect then drop its response: a retry must remain blocked until provider truth confirms it. -The runnable [`verify.mjs`](./verify.mjs) is a controlled first proof using a -fake provider. It does not call a real payment or order API. The reproduction -commands below are intentionally frozen to the historical v0.1.9 proof; that -version pin is reproducibility evidence, not a statement that v0.1.9 is the -current SDK. With Node.js 24.15+ installed, run it in a new throwaway directory: - -```bash -mkdir once-local-proof && cd once-local-proof -npm init -y -npm install @once-agent/sdk@0.1.9 -curl -fsSL https://raw.githubusercontent.com/stringsofthemind-oss/once/v0.1.9/examples/local-function/verify.mjs -o verify.mjs -node verify.mjs -``` +## Run the canonical source proof -For PowerShell: +From a source checkout with Node.js 24.15+: -```powershell -New-Item -ItemType Directory -Path once-local-proof | Out-Null -Set-Location once-local-proof -npm init -y -npm install @once-agent/sdk@0.1.9 -Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/stringsofthemind-oss/once/v0.1.9/examples/local-function/verify.mjs' -OutFile verify.mjs -node verify.mjs +```sh +cd sdk/typescript +npm ci +npm run build +cd ../.. +node examples/local-function/verify.mjs ``` -The expected result is `2 effects`: the retry -reuses the first result, a separate order executes, and a changed payload -with the first order ID raises `CONFLICT`. The proof writes a local effect log -and `.once/operations.sqlite` inside this throwaway directory. +The entry point delegates to one canonical SDK example. It persists simulated +intent before dispatch, counts first execution/replay and conflict, permits a +separate intent with identical effect, blocks UNKNOWN when truth is unavailable, +recovers by exact provider evidence, then replays from a fresh process. +Expected final count: **3 simulated effects** for three distinct intents. +The proof uses a new isolated temporary directory and removes only that fixture. +It calls no real provider and modifies no application project files. + +For the **currently published 0.1.22 package**, use the existing +`npx once prove` command after installation. The expanded source example is a +review-branch addition; its inclusion in a future package requires release approval. +Historical v0.1.9 proofs remain reproducible from the v0.1.9 tag. + +See [Start here](../../docs/START_HERE.md), +[identity/effect](../../docs/IDENTITY_AND_EFFECT.md), +[UNKNOWN](../../docs/UNKNOWN_PLAYBOOK.md) and +[guarantees](../../docs/GUARANTEES.md). diff --git a/examples/local-function/verify.mjs b/examples/local-function/verify.mjs index fb056519..ccd3ce7a 100644 --- a/examples/local-function/verify.mjs +++ b/examples/local-function/verify.mjs @@ -1,31 +1,2 @@ -import assert from "node:assert/strict"; -import { randomUUID } from "node:crypto"; -import { appendFileSync, readFileSync } from "node:fs"; -import path from "node:path"; -import { protectLocal } from "@once-agent/sdk"; - -// This fake provider writes to a separate durable effect log, not the Once -// ledger. For a real integration, count effects in the provider's sandbox. -const session = randomUUID(); -const effectsPath = path.resolve(`effects-${session}.jsonl`); -const createOrder = protectLocal( - async ({ orderId, amountCents }) => { - appendFileSync(effectsPath, JSON.stringify({ orderId, amountCents }) + "\n"); - return { orderId, amountCents }; - }, - { - id: ({ orderId }) => `create-order:${orderId}`, - payload: ({ orderId, amountCents }) => ({ orderId, amountCents }), - }, -); - -const a = { orderId: `A-${session}`, amountCents: 100 }; -const b = { orderId: `B-${session}`, amountCents: 100 }; -assert.deepEqual(await createOrder(a), await createOrder(a)); -await createOrder(b); -await assert.rejects( - createOrder({ orderId: a.orderId, amountCents: 125 }), - { code: "CONFLICT" }, -); -assert.equal(readFileSync(effectsPath, "utf8").trim().split("\n").length, 2); -console.log("Verified: A/100 + retry, B/100, A/125 conflict => 2 effects"); +// One canonical example; it imports the public SDK export from the source package. +import "../../sdk/typescript/examples/first-action/verify.mjs"; diff --git a/mcp/package-lock.json b/mcp/package-lock.json index 167cc253..3cc7894b 100644 --- a/mcp/package-lock.json +++ b/mcp/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@modelcontextprotocol/client": "2.0.0", "@modelcontextprotocol/server": "2.0.0", - "@once-agent/sdk": "0.1.14", + "@once-agent/sdk": "0.1.22", "zod": "4.6.5" }, "bin": { @@ -512,15 +512,15 @@ } }, "node_modules/@once-agent/sdk": { - "version": "0.1.14", - "resolved": "https://registry.npmjs.org/@once-agent/sdk/-/sdk-0.1.14.tgz", - "integrity": "sha512-e1VtyshV+9RVFnEJydqYz+5pKlsodaEylERfcUoteHFa/uYUbsL4/MBHFmazpcMsf3uinv1i9uFIbyjp2o31ZA==", + "version": "0.1.22", + "resolved": "https://registry.npmjs.org/@once-agent/sdk/-/sdk-0.1.22.tgz", + "integrity": "sha512-1xSA2QutzzAcgoM0RURGbR/08ywRO+Q2n/Djrwk8VN/J3emkV7lWmmJSzAi/sMpY6lPpxhJkeIIV27Tm2ew+jg==", "license": "MIT", "dependencies": { "typescript": "^5.9.0" }, "bin": { - "once": "dist/cli.js", + "once": "dist/once-cli.js", "once-dataset": "dist/dataset-cli.js", "once-monitor": "dist/monitor-cli.js" }, diff --git a/mcp/package.json b/mcp/package.json index 2395000e..33164b76 100644 --- a/mcp/package.json +++ b/mcp/package.json @@ -52,7 +52,7 @@ "dependencies": { "@modelcontextprotocol/client": "2.0.0", "@modelcontextprotocol/server": "2.0.0", - "@once-agent/sdk": "0.1.14", + "@once-agent/sdk": "0.1.22", "zod": "4.6.5" }, "devDependencies": { diff --git a/mcp/scripts/phase13c-persistent-state-e2e.mjs b/mcp/scripts/phase13c-persistent-state-e2e.mjs index bbe4d7dd..9d389564 100644 --- a/mcp/scripts/phase13c-persistent-state-e2e.mjs +++ b/mcp/scripts/phase13c-persistent-state-e2e.mjs @@ -83,13 +83,15 @@ async function sample(fn, n = 25) { return summarize(values); } +let proxy; +let client; try { // The SDK CI lane installs the freshly packed branch SDK into this MCP workspace, // so this test uses the same package import path that customers will use. const primary = configFor("primary"); - let proxy = await connectStdioProxy(primary.config); + proxy = await connectStdioProxy(primary.config); assert.equal(proxy.persistentLocalState, true); - let client = await attach(proxy, "persistent-primary"); + client = await attach(proxy, "persistent-primary"); const firstCall = { name: "create_order", arguments: { operation_id: "p-1", sku: "one", quantity: 1 }, @@ -177,8 +179,26 @@ try { arguments: { operation_id: "p-loss-1", sku: "safe", quantity: 1 }, }); assert.equal(count(lost.effectsPath), 1); + if (process.platform === "win32") { + // Windows refuses live deletion. Keep the replay assertion, then test + // corrupted replacement authority on reconnect after closing the handle. + assert.throws(() => unlinkSync(lost.statePath), error => + error.code === "EBUSY" || error.code === "EPERM"); + await client.callTool({ + name: "create_order", + arguments: { operation_id: "p-loss-1", sku: "safe", quantity: 1 }, + }); + assert.equal(count(lost.effectsPath), 1); + await closePair(client, proxy); + client = undefined; + proxy = undefined; + } unlinkSync(lost.statePath); writeFileSync(lost.statePath, "replacement-state-file"); + if (process.platform === "win32") { + proxy = await connectStdioProxy(lost.config); + client = await attach(proxy, "persistent-corrupt-restart"); + } await assert.rejects(client.callTool({ name: "create_order", arguments: { operation_id: "p-loss-2", sku: "must-not-run", quantity: 1 }, @@ -226,5 +246,9 @@ try { rmSync(primary.dir, { recursive: true, force: true }); console.log("ONCE PHASE 13C PERSISTENT STATE: PASS"); } finally { - rmSync(root, { recursive: true, force: true }); + try { + await closePair(client, proxy); + } finally { + rmSync(root, { recursive: true, force: true }); + } } diff --git a/plugins/openai/once/skills/protect-consequential-writes/SKILL.md b/plugins/openai/once/skills/protect-consequential-writes/SKILL.md index 20dc103e..4513a3d0 100644 --- a/plugins/openai/once/skills/protect-consequential-writes/SKILL.md +++ b/plugins/openai/once/skills/protect-consequential-writes/SKILL.md @@ -42,15 +42,15 @@ Never make an operation ID unique by adding a timestamp, random retry token, age 1. **Assess after the gate passes** — once a qualifying external-write candidate has already been identified, call `once_assess_project` with the absolute project path. If MCP is unavailable, run the pinned CLI fallback: - `npx --yes --package=@once-agent/sdk@0.1.18 once scan ` + `npx --yes --package=@once-agent/sdk@0.1.22 once scan ` 2. **Explain applicability** — for each high-signal candidate, verify the four routing conditions. Use `once_explain_risk` when helpful. Do not equate every POST, write, retry loop, or MCP action with a Once requirement. 3. **Plan before mutation** — call `once_plan_setup` and/or `once_plan_protection`. If using the CLI, prefer read-only planning commands such as: - - `npx --yes --package=@once-agent/sdk@0.1.18 once setup --plan` - - `npx --yes --package=@once-agent/sdk@0.1.18 once protect ` - - `npx --yes --package=@once-agent/sdk@0.1.18 once protect --all --patch` + - `npx --yes --package=@once-agent/sdk@0.1.22 once setup --plan` + - `npx --yes --package=@once-agent/sdk@0.1.22 once protect ` + - `npx --yes --package=@once-agent/sdk@0.1.22 once protect --all --patch` 4. **Show the plan** — identify the exact operation, why it qualifies, the stable identity inputs, the provider/reconciliation assumption, and the files or callsites that would change. @@ -60,7 +60,7 @@ Never make an operation ID unique by adding a timestamp, random retry token, age 7. **Verify** — run `once_verify_connection` when Cloud verification is relevant, or use: - `npx --yes --package=@once-agent/sdk@0.1.18 once doctor` + `npx --yes --package=@once-agent/sdk@0.1.22 once doctor` Do not expose `ONCE_API_KEY` in output, source code, patches, logs, or committed configuration. diff --git a/scripts/check-current-onboarding.mjs b/scripts/check-current-onboarding.mjs new file mode 100644 index 00000000..c97786b9 --- /dev/null +++ b/scripts/check-current-onboarding.mjs @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +const read = file => readFileSync(new URL(`../${file}`, import.meta.url), "utf8"); +export function currentOnboardingSurfaces() { + return { + version: JSON.parse(read("docs/published-versions.json")).ts, + rootReadme: read("README.md"), + sdkReadme: read("sdk/typescript/README.md"), + agentGuide: read("docs/agent.md"), + llms: read("docs/llms.txt"), + html: read("docs/index.html"), + start: read("docs/START_HERE.md"), + recovery: read("sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md"), + mcpDependency: JSON.parse(read("mcp/package.json")).dependencies["@once-agent/sdk"], + }; +} + +export function validateCurrentOnboarding(surface) { + const { version } = surface; + assert.match(version, /^\d+\.\d+\.\d+$/); + for (const name of ["rootReadme", "sdkReadme", "agentGuide", "llms"]) { + // Only inspect the current introduction. Frozen lab/version evidence further + // down may legitimately retain its historical pin. + const firstPin = surface[name].match(/@once-agent\/sdk@(\d+\.\d+\.\d+)/)?.[1]; + assert.equal(firstPin, version, `${name}: current SDK introduction is stale`); + } + assert.equal(surface.html.match(/"softwareVersion":\s*"([^"]+)"/)?.[1], version, + "static homepage metadata must match the published SDK"); + assert.ok(surface.html.includes(`@once-agent/sdk ${version}`), "static CLI badge is stale"); + assert.ok(surface.html.includes(`@once-agent/sdk@${version} once prove`), "first proof pin is stale"); + assert.ok(surface.start.includes(`@once-agent/sdk@${version}`), "start guide is stale"); + assert.ok(surface.recovery.includes(`install \`@once-agent/sdk@${version}\``), "recovery install is stale"); + assert.equal(surface.mcpDependency, version, "reviewed MCP source must pin the current SDK"); + for (const name of ["rootReadme", "sdkReadme", "html"]) { + assert.doesNotMatch(surface[name], /60[- ]second quick start|Run 60s quickstart/i, + `${name}: unsupported human onboarding time claim`); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + validateCurrentOnboarding(currentOnboardingSurfaces()); + console.log("Current onboarding surfaces: PASS (historical evidence pins preserved)"); +} diff --git a/scripts/check-site-surface.mjs b/scripts/check-site-surface.mjs index 6c099ca5..6d9484a3 100644 --- a/scripts/check-site-surface.mjs +++ b/scripts/check-site-surface.mjs @@ -1,5 +1,8 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; +import { currentOnboardingSurfaces, validateCurrentOnboarding } from "./check-current-onboarding.mjs"; + +validateCurrentOnboarding(currentOnboardingSurfaces()); function read(path) { return readFileSync(new URL(`../${path}`, import.meta.url), "utf8"); diff --git a/scripts/test-current-onboarding.mjs b/scripts/test-current-onboarding.mjs new file mode 100644 index 00000000..2678d0fd --- /dev/null +++ b/scripts/test-current-onboarding.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert/strict"; +import { currentOnboardingSurfaces, validateCurrentOnboarding } from "./check-current-onboarding.mjs"; + +const original = currentOnboardingSurfaces(); +validateCurrentOnboarding(original); +for (const name of ["rootReadme", "sdkReadme", "agentGuide", "llms", "html", "start", "recovery"]) { + const stale = { ...original, [name]: original[name].replaceAll(original.version, "0.0.0") }; + assert.throws(() => validateCurrentOnboarding(stale), undefined, `${name} drift must fail`); +} +assert.throws(() => validateCurrentOnboarding({ ...original, mcpDependency: "0.0.0" })); +for (const name of ["rootReadme", "sdkReadme", "html"]) { + assert.throws(() => validateCurrentOnboarding({ ...original, [name]: original[name] + "\nRun 60s quickstart" })); +} +validateCurrentOnboarding({ ...original, rootReadme: original.rootReadme + "\nHistorical lab: @once-agent/sdk@0.1.9" }); +console.log("Current onboarding regressions: 13 checks passed"); diff --git a/scripts/test-openai-plugin-line-endings.mjs b/scripts/test-openai-plugin-line-endings.mjs new file mode 100644 index 00000000..08daa6e3 --- /dev/null +++ b/scripts/test-openai-plugin-line-endings.mjs @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const repo = fileURLToPath(new URL("../", import.meta.url)); +const temp = mkdtempSync(path.join(os.tmpdir(), "once-plugin-endings-")); +try { + for (const file of [".agents/plugins/marketplace.json", "docs/published-versions.json"]) { + mkdirSync(path.dirname(path.join(temp, file)), { recursive: true }); + cpSync(path.join(repo, file), path.join(temp, file)); + } + cpSync(path.join(repo, "plugins/openai/once"), path.join(temp, "plugins/openai/once"), { recursive: true }); + const skillPath = path.join(temp, "plugins/openai/once/skills/protect-consequential-writes/SKILL.md"); + const skill = readFileSync(skillPath, "utf8").replaceAll("\r\n", "\n"); + for (const ending of ["\n", "\r\n"]) { + writeFileSync(skillPath, skill.replaceAll("\n", ending)); + const result = spawnSync(process.execPath, [path.join(repo, "scripts/validate-openai-plugin.mjs")], + { cwd: temp, encoding: "utf8", windowsHide: true, timeout: 30_000 }); + assert.equal(result.status, 0, result.stderr); + } + writeFileSync(skillPath, skill.replace(/^---/, "missing-frontmatter")); + const rejected = spawnSync(process.execPath, [path.join(repo, "scripts/validate-openai-plugin.mjs")], + { cwd: temp, encoding: "utf8", windowsHide: true, timeout: 30_000 }); + assert.notEqual(rejected.status, 0); + assert.match(rejected.stderr, /Skill must start with YAML frontmatter/); + console.log("Plugin frontmatter: LF + CRLF accepted; malformed frontmatter rejected"); +} finally { + rmSync(temp, { recursive: true, force: true }); +} diff --git a/scripts/validate-openai-plugin.mjs b/scripts/validate-openai-plugin.mjs index 31d86b85..1020e681 100644 --- a/scripts/validate-openai-plugin.mjs +++ b/scripts/validate-openai-plugin.mjs @@ -96,8 +96,8 @@ assert( `Codex plugin README must describe published @once-agent/mcp@${published.mcp}` ); -assert(skill.startsWith("---\n"), "Skill must start with YAML frontmatter"); -assert(/\nname:\s*protect-consequential-writes\n/.test(skill), "Skill frontmatter name is incorrect"); +assert(/^---\r?\n/.test(skill), "Skill must start with YAML frontmatter"); +assert(/\nname:\s*protect-consequential-writes\r?\n/.test(skill), "Skill frontmatter name is incorrect"); assert(/\ndescription:\s*/.test(skill), "Skill frontmatter description is required"); for (const phrase of [ "change external state", diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index a5a6d2af..7ed692e2 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -1,6 +1,30 @@ # @once-agent/sdk -> **Automatic Connect in 0.1.12:** this SDK version includes the +This checkout prepares **0.1.23 (unpublished)**. Current public SDK: +**0.1.22**. Public install pins below remain deliberate. The included +first-action example is a candidate improvement; it is not in public 0.1.22. + +## Start with one protected action + +Current public TypeScript SDK: **@once-agent/sdk@0.1.22**. +For a credential-free controlled proof on Node.js 24.15+: + +```sh +npm install @once-agent/sdk@0.1.22 +npx once prove +``` + +This simulates a lost acknowledgement, blocked retry, recovery and replay. +It does not protect your project's tools merely by being run. +Your application owns persisted intent and complete effect binding. + +[Start here](https://github.com/stringsofthemind-oss/once/blob/main/docs/START_HERE.md) +· [Identity and effect](https://github.com/stringsofthemind-oss/once/blob/main/docs/IDENTITY_AND_EFFECT.md) +· [UNKNOWN playbook](https://github.com/stringsofthemind-oss/once/blob/main/docs/UNKNOWN_PLAYBOOK.md) +· [Guarantees](https://github.com/stringsofthemind-oss/once/blob/main/docs/GUARANTEES.md) + + +> **Current Connect surface in 0.1.22:** this SDK version includes the > `@once-agent/sdk/connect` public surface for automatic tool classification, > whole-toolset wiring, trusted intent identity, conservative effect binding, > and OpenAI Agents FunctionTool wrapping. It has passed source, packed-package, @@ -141,7 +165,7 @@ ONCE_API_KEY=your_api_key Do not commit API keys to source control. -## 60-second quick start +## Hosted quick start (provider setup required) ### Runtime HTTP protection diff --git a/sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md b/sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md index 3ec72133..962bd191 100644 --- a/sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md +++ b/sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md @@ -24,7 +24,7 @@ export ONCE_STATE_PATH="$PWD/.once/github-issues.sqlite" ``` For an installed-package consumer, copy `github-issue-recovery.mjs` into your -own project and install `@once-agent/sdk@0.1.21`. It imports the public package +own project and install `@once-agent/sdk@0.1.22`. It imports the public package by name; no private source imports or extra runtime dependencies are needed. Persist this input as `intent.json` **before** the first call: diff --git a/sdk/typescript/examples/first-action/verify.mjs b/sdk/typescript/examples/first-action/verify.mjs new file mode 100644 index 00000000..5b9094af --- /dev/null +++ b/sdk/typescript/examples/first-action/verify.mjs @@ -0,0 +1,95 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { Once, protectLocal } from "@once-agent/sdk"; + +// A controlled provider ledger, separate from Once's state. No network, real +// orders, payment credentials or project files are involved. +const freshProcess = process.argv[2] === "--replay-child"; +const directory = freshProcess ? process.argv[3] : mkdtempSync(path.join(os.tmpdir(), "once-first-action-")); +const effectsPath = path.join(directory, "provider-effects.json"); +const intentPath = path.join(directory, "persisted-intent.json"); +const statePath = path.join(directory, "operations.sqlite"); +const effects = () => JSON.parse(readFileSync(effectsPath, "utf8")); +const effect = ({ account, sku, quantity }) => ({ account, sku, quantity }); +const identity = ({ account, intentId }) => Once.id("sandbox", account, "create-order", intentId); +let loseAcknowledgement = false; // Transport fault, not business identity. +let truthAvailable = false; + +const createOrder = protectLocal(async input => { + const rows = effects(); + const receipt = { orderId: `order-${rows.length + 1}`, ...effect(input) }; + rows.push({ id: identity(input), effect: effect(input), receipt }); + writeFileSync(effectsPath, JSON.stringify(rows)); + if (loseAcknowledgement) throw new Error("Provider committed; acknowledgement lost"); + return receipt; +}, { + statePath, + id: identity, + payload: effect, + reconcile({ id, payload }) { + if (!truthAvailable) return { state: "UNKNOWN" }; + const matches = effects().filter(row => row.id === id); + if (matches.length !== 1) return { state: "UNKNOWN" }; + assert.deepEqual(matches[0].effect, payload); + return { state: "CONFIRMED", result: matches[0].receipt }; + }, +}); + +if (freshProcess) { + // If redispatched, this provider would append another effect. + const persisted = JSON.parse(readFileSync(intentPath, "utf8")); + assert.deepEqual(await createOrder(persisted), effects()[2].receipt); + assert.equal(effects().length, 3); + console.log("Fresh process: original receipt replayed, 3 effects retained"); +} else { + try { + writeFileSync(effectsPath, "[]"); + const first = { intentId: "checkout-1042", account: "shop-1", sku: "widget", quantity: 1 }; + // Durable business requests, not generated model/framework call IDs. + writeFileSync(intentPath, JSON.stringify(first)); + const receipt = await createOrder(first); + assert.deepEqual(await createOrder(first), receipt); + assert.equal(effects().length, 1); + console.log("First execution + replay: 1 effect"); + + await assert.rejects(createOrder({ ...first, quantity: 2 }), { code: "CONFLICT" }); + assert.equal(effects().length, 1); + console.log("Changed effect under original intent: CONFLICT, no write"); + + const second = { ...first, intentId: "checkout-1043" }; + writeFileSync(intentPath, JSON.stringify(second)); + await createOrder(second); + assert.equal(effects().length, 2); + console.log("Separate intent, identical effect: 2 effects"); + + const uncertain = { ...first, intentId: "checkout-1044" }; + writeFileSync(intentPath, JSON.stringify(uncertain)); + loseAcknowledgement = true; + await assert.rejects(createOrder(uncertain), { code: "UNKNOWN" }); + loseAcknowledgement = false; + await assert.rejects(createOrder(uncertain), { code: "UNKNOWN" }); + assert.equal(effects().length, 3); + console.log("Lost acknowledgement + unavailable truth: UNKNOWN, 3 effects"); + + truthAvailable = true; + assert.deepEqual(await createOrder(uncertain), effects()[2].receipt); + assert.deepEqual(await createOrder(uncertain), effects()[2].receipt); + assert.equal(effects().length, 3); + console.log("Read-only provider truth: recovered original receipt, no redispatch"); + + const restarted = spawnSync(process.execPath, + [fileURLToPath(import.meta.url), "--replay-child", directory], + { encoding: "utf8", windowsHide: true, timeout: 30_000 }); + assert.equal(restarted.status, 0, restarted.error?.message ?? restarted.stderr); + assert.equal(effects().length, 3); + console.log(restarted.stdout.trim()); + console.log("FIRST ACTION PROOF: PASS (simulated provider; same-machine SQLite only)"); + } finally { + // Delete only the fresh disposable fixture. Never clear production state. + rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/sdk/typescript/package-lock.json b/sdk/typescript/package-lock.json index aa543833..1c0115ab 100644 --- a/sdk/typescript/package-lock.json +++ b/sdk/typescript/package-lock.json @@ -1,12 +1,12 @@ { "name": "@once-agent/sdk", - "version": "0.1.22", + "version": "0.1.23", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@once-agent/sdk", - "version": "0.1.22", + "version": "0.1.23", "license": "MIT", "dependencies": { "typescript": "^5.9.0" diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json index f9754fa1..c75727e5 100644 --- a/sdk/typescript/package.json +++ b/sdk/typescript/package.json @@ -1,6 +1,6 @@ { "name": "@once-agent/sdk", - "version": "0.1.22", + "version": "0.1.23", "description": "Execution safety for side-effecting AI agent tools.", "type": "module", "main": "./dist/index.js", @@ -45,7 +45,8 @@ "files": [ "dist", "README.md", - "dist-cjs" + "dist-cjs", + "examples/first-action/verify.mjs" ], "scripts": { "benchmark:http-autoprotection": "node ./scripts/http-autoprotection-coverage.mjs", @@ -80,7 +81,7 @@ "test:routing-conformance": "node ./scripts/agent-routing-conformance-regression.mjs", "test:contract": "npm run build && tsc --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext --strict --types node ./scripts/sdk-contract-types.ts && node ./scripts/sdk-contract-runtime.mjs", "test:release": "npm run benchmark:scan && npm run benchmark:local-function-bridge && npm run test:local-function-transformer && npm run test:local-function-bridge-plan && npm run test:reviewed-local-semantics && npm run test:reviewed-local-caller-inventory && npm run test:reviewed-local-routing-preview && npm run test:reviewed-local-routing-review && npm run test:reviewed-local-routing-apply && npm run test:benchmark && npm run test:trace && npm run test:dataset-seal && npm run test:dataset-progress && npm run test:agent-discovery && npm run test:doctor && npm run test:monitor && npm run test:tool-discovery && npm run test:gateway && npm run test:reconciliation && npm run test:reconciliation-package && npm run test:routing-conformance && npm run test:scanner-declarations && npm run test:contract && npm run test:protect && npm run test:capabilities && npm run test:transformer && npm run test:binding && npm run test:patch-planner && npm run test:transformer-protect && npm run test:apply && npm run test:route-proof && npm run test:id-conformance && npm run test:consumer && npm run test:connect-package && npm run test:discovery-package && npm run test:gateway-package && npm run test:activation && npm run test:package && npm run test:runtime-setup && npm run test:connect", - "test:local": "npm run build && node --test ./test/local.test.mjs ./test/connect/github-issue-recovery.test.mjs ./test/connect/local-agent-tool.test.mjs ./test/connect/mcp-execution-boundary.test.mjs ./test/gateway/local-gateway-toolset.test.mjs ./test/gateway/openai-function-tools-gateway.test.mjs && node ./scripts/synthetic-proof-regression.mjs && node ./scripts/local-function-bridge-apply-regression.mjs && npm run test:reviewed-local-caller-inventory && npm run test:reviewed-local-routing-preview && npm run test:reviewed-local-routing-review && npm run test:reviewed-local-routing-apply && npm run test:reviewed-local-routed-application-proof && npm run test:local-function-bridge-cli && npm run test:reviewed-local-cli", + "test:local": "npm run build && node --test ./test/local.test.mjs ./test/local-session.test.mjs ./test/first-action.test.mjs ./test/connect/github-issue-recovery.test.mjs ./test/connect/local-agent-tool.test.mjs ./test/connect/mcp-execution-boundary.test.mjs ./test/gateway/local-gateway-toolset.test.mjs ./test/gateway/openai-function-tools-gateway.test.mjs && node ./scripts/synthetic-proof-regression.mjs && node ./scripts/local-function-bridge-apply-regression.mjs && npm run test:reviewed-local-caller-inventory && npm run test:reviewed-local-routing-preview && npm run test:reviewed-local-routing-review && npm run test:reviewed-local-routing-apply && npm run test:reviewed-local-routed-application-proof && npm run test:local-function-bridge-cli && npm run test:reviewed-local-cli", "test:connect": "npm run build && node --test ./test/connect/*.test.mjs", "test:connect-package": "node ./scripts/connect-package-regression.mjs", "test:discovery-package": "node ./scripts/runtime-discovery-package-regression.mjs && node ./scripts/execution-discovery-package-regression.mjs", @@ -104,7 +105,11 @@ "test:runtime-setup": "npm run build && node ./scripts/runtime-setup-regression.mjs", "test:activation": "npm run build && node ./scripts/activation-regression.mjs", "test:setup-persistence": "npm run build && node ./scripts/setup-persistence-regression.mjs", - "prepack": "npm run build" + "prepack": "npm run build", + "test:first-action": "npm run build && node --test ./test/first-action.test.mjs", + "test:first-action-package": "node ./scripts/first-action-package-regression.mjs", + "test:authority-continuity": "node ./scripts/authority-continuity-regression.mjs", + "test:authority-forensics": "node ./scripts/authority-forensics.mjs" }, "keywords": [ "ai", diff --git a/sdk/typescript/scripts/authority-continuity-regression.mjs b/sdk/typescript/scripts/authority-continuity-regression.mjs new file mode 100644 index 00000000..2662db8c --- /dev/null +++ b/sdk/typescript/scripts/authority-continuity-regression.mjs @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, rmSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { pathToFileURL, fileURLToPath } from 'node:url'; + +// Disposable provider ledger is independent of SQLite authority. This is +// controlled evidence, never a claim about a real external provider. +const script = fileURLToPath(import.meta.url); +if (process.argv[2] === '--child') { + const [directory, mode, implementation] = process.argv.slice(3); + const { protectLocal } = await import(pathToFileURL(implementation).href); + const ledger = join(directory, 'provider.json'); + const rows = () => JSON.parse(readFileSync(ledger, 'utf8')); + const run = protectLocal(async input => { + const records = rows(); const result = { receipt: records.length + 1 }; + records.push({ id: input.id, amount: input.amount, result }); + writeFileSync(ledger, JSON.stringify(records)); + if (mode === 'lost') throw Error('acknowledgement lost after commit'); + if (mode === 'crash') process.exit(73); + return result; + }, { statePath: join(directory, 'state.sqlite'), leaseMs: 1, + id: input => input.id, payload: input => ({ amount: input.amount }), + reconcile({ id, payload }) { + if (mode === 'interrupt-recovery') process.exit(74); + if (mode === 'unavailable') throw Error('provider unavailable'); + if (mode === 'absent') return { state: 'ABSENT' }; + const matches = rows().filter(row => row.id === id && row.amount === payload.amount); + return matches.length === 1 ? { state: 'CONFIRMED', result: matches[0].result } : { state: 'UNKNOWN' }; + }, + }); + try { console.log(JSON.stringify({ outcome: 'CONFIRMED', result: await run({ id: 'persisted-intent-A', amount: 100 }) })); } + catch (error) { console.log(JSON.stringify({ outcome: error.code ?? 'ERROR' })); } +} else { + const implementation = fileURLToPath(new URL('../dist/index.js', import.meta.url)); + const prior = process.env.ONCE_PRIOR_IMPLEMENTATION; + const root = mkdtempSync(join(tmpdir(), 'once-continuity-')); + const evidence = []; + const fixture = name => { const directory = join(root, name); mkdirSync(directory); writeFileSync(join(directory, 'provider.json'), '[]'); return directory; }; + const count = directory => JSON.parse(readFileSync(join(directory, 'provider.json'), 'utf8')).length; + function call(directory, mode = 'normal', source = implementation) { + const child = spawnSync(process.execPath, [script, '--child', directory, mode, source], { encoding: 'utf8', windowsHide: true, timeout: 30000 }); + if (mode === 'crash' || mode === 'interrupt-recovery') { assert.equal(child.status, mode === 'crash' ? 73 : 74, child.stderr); return { outcome: 'PROCESS_EXIT', exit: child.status }; } + assert.equal(child.status, 0, child.error?.message ?? child.stderr); + return JSON.parse(child.stdout.trim()); + } + function record(scenario, directory, result, expectedCount, classification) { + assert.equal(count(directory), expectedCount); + evidence.push({ scenario, observed: result, providerLedgerEffects: count(directory), classification, provider: 'controlled independent file ledger; NOT real external provider' }); + } + try { + const normal = fixture('normal'); const first = call(normal); + assert.deepEqual(call(normal), first); record('A restart', normal, first, 1, 'SUPPORTED BUT BOUNDED'); + // Calls close their database before backup. VACUUM INTO uses SQLite's + // snapshot mechanism, rather than a potentially incomplete WAL main copy. + const { DatabaseSync } = await import('node:sqlite'); + const snapshot = directory => { const db = new DatabaseSync(join(directory, 'state.sqlite')); const backup = join(directory, 'backup.sqlite'); db.prepare('VACUUM INTO ?').run(backup); db.close(); return backup; }; + const removeState = directory => { for (const suffix of ['', '-wal', '-shm']) { const file = join(directory, `state.sqlite${suffix}`); if (existsSync(file)) rmSync(file); } }; + const backup = snapshot(normal); removeState(normal); copyFileSync(backup, join(normal, 'state.sqlite')); + assert.deepEqual(call(normal), first); record('B current SQLite snapshot restore', normal, first, 1, 'SUPPORTED BUT BOUNDED'); + if (prior) { + const upgrade = fixture('upgrade'); const old = call(upgrade, 'normal', prior); + assert.deepEqual(call(upgrade), old); record('E public 0.1.22 to candidate upgrade', upgrade, old, 1, 'SUPPORTED BUT BOUNDED'); + assert.deepEqual(call(upgrade, 'normal', prior), old); record('C rollback retaining authority', upgrade, old, 1, 'SUPPORTED BUT BOUNDED'); + } else evidence.push({ scenario: 'C/E upgrade and rollback', classification: 'NOT EXECUTED — prior implementation unavailable' }); + const loss = fixture('loss'); call(loss); removeState(loss); + record('D closed-process complete authority loss', loss, call(loss), 2, 'DEMONSTRATED LIMITATION: recreated authority redispatches'); + const stale = fixture('stale'); const empty = new DatabaseSync(join(stale, 'state.sqlite')); empty.exec('PRAGMA user_version=0'); empty.close(); + const staleBackup = snapshot(stale); call(stale); removeState(stale); copyFileSync(staleBackup, join(stale, 'state.sqlite')); + record('B stale pre-effect snapshot restore', stale, call(stale), 2, 'DEMONSTRATED LIMITATION: rollback omits committed effect'); + const recovery = fixture('recovery'); assert.equal(call(recovery, 'lost').outcome, 'UNKNOWN'); + call(recovery, 'interrupt-recovery'); assert.equal(call(recovery, 'unavailable').outcome, 'UNKNOWN'); + record('F interrupted read-only recovery; G unavailable truth', recovery, { outcome: 'UNKNOWN' }, 1, 'SUPPORTED BUT BOUNDED'); + assert.equal(call(recovery, 'absent').outcome, 'UNKNOWN'); + record('H ABSENT assertion after known commit', recovery, { outcome: 'UNKNOWN' }, 1, 'SUPPORTED BUT BOUNDED: ABSENT never authorizes local redispatch'); + assert.equal(call(recovery).outcome, 'CONFIRMED'); record('G restored truth recovery', recovery, call(recovery), 1, 'SUPPORTED BUT BOUNDED'); + const crash = fixture('crash'); call(crash, 'crash'); assert.equal(call(crash).outcome, 'CONFIRMED'); + record('process death after controlled provider commit', crash, call(crash), 1, 'SUPPORTED BUT BOUNDED'); + console.log(JSON.stringify({ node: process.version, os: process.platform, evidence }, null, 2)); + } finally { rmSync(root, { recursive: true, force: true }); } +} diff --git a/sdk/typescript/scripts/authority-forensics.mjs b/sdk/typescript/scripts/authority-forensics.mjs new file mode 100644 index 00000000..cb5d204c --- /dev/null +++ b/sdk/typescript/scripts/authority-forensics.mjs @@ -0,0 +1,120 @@ +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, rmSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve, dirname } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { DatabaseSync } from 'node:sqlite'; + +// A provider simulator, not a replacement Once implementation. Real Once +// executes every action. Independent provider files survive authority loss. +const script = fileURLToPath(import.meta.url); +const sdk = fileURLToPath(new URL('../dist/index.js', import.meta.url)); +const read = file => JSON.parse(readFileSync(file, 'utf8')); +const now = () => new Date().toISOString(); +function inspect(file) { + if (!existsSync(file)) return { exists: false, rows: [] }; + const db = new DatabaseSync(file, { readOnly: true }); + try { + const tables = db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table'").all(); + return { exists: true, userVersion: db.prepare('PRAGMA user_version').get(), tables, + rows: tables.some(table => table.name === 'local_operations') + ? db.prepare('SELECT * FROM local_operations ORDER BY id').all() : [] }; + } finally { db.close(); } +} +if (process.argv[2] === '--child') { + const [directory, identity, native] = process.argv.slice(3); + const { protectLocal } = await import(pathToFileURL(sdk).href); + const statePath = join(directory, 'authority', 'state.sqlite'); + const providerFile = join(directory, 'provider.json'); + const traceFile = join(directory, 'calls.json'); + const trace = event => { const rows = read(traceFile); rows.push({ ...event, pid: process.pid, utc: now() }); writeFileSync(traceFile, JSON.stringify(rows)); }; + const payload = { account: 'sandbox-account', amount: 100, currency: 'GBP' }; + const run = protectLocal(async input => { + trace({ type: 'provider-dispatch', identity, payload }); + const rows = read(providerFile); + if (native === 'native') { + const existing = rows.find(row => row.identity === input.identity); + if (existing) { assert.deepEqual(existing.payload, payload); return existing.receipt; } + } + const receipt = { effectNumber: rows.length + 1 }; + rows.push({ identity: input.identity, payload, receipt, committedUtc: now(), pid: process.pid }); + writeFileSync(providerFile, JSON.stringify(rows)); + return receipt; + }, { statePath, id: input => input.identity, payload: () => payload, + reconcile({ id, payload: effect }) { + trace({ type: 'reconciliation-read', identity: id }); + const matches = read(providerFile).filter(row => row.identity === id); + return matches.length === 1 && JSON.stringify(matches[0].payload) === JSON.stringify(effect) + ? { state: 'CONFIRMED', result: matches[0].receipt } : { state: 'UNKNOWN' }; + }, + }); + const before = inspect(statePath); + const startedUtc = now(); + const result = await run({ identity }); + console.log(JSON.stringify({ pid: process.pid, identity, payload, startedUtc, endedUtc: now(), before, result, after: inspect(statePath) })); +} else { + const root = mkdtempSync(join(tmpdir(), 'once-authority-forensics-')); + const scenarios = []; + function fixture(name) { + const dir = join(root, name); mkdirSync(join(dir, 'authority'), { recursive: true }); + writeFileSync(join(dir, 'provider.json'), '[]'); writeFileSync(join(dir, 'calls.json'), '[]'); + return dir; + } + function call(dir, id = 'persisted-intent-A', native = '') { + const r = spawnSync(process.execPath, [script, '--child', dir, id, native], { encoding: 'utf8', windowsHide: true, timeout: 30000 }); + assert.equal(r.status, 0, r.error?.message ?? r.stderr); + return JSON.parse(r.stdout.trim()); + } + function snapshot(dir) { + const target = join(dir, 'snapshot.sqlite'); const startedUtc = now(); + const db = new DatabaseSync(join(dir, 'authority', 'state.sqlite')); + try { db.prepare('VACUUM INTO ?').run(target); } finally { db.close(); } + return { startedUtc, endedUtc: now(), content: inspect(target) }; + } + function lose(dir, restore = false) { + const authority = resolve(dir, 'authority'); + assert.equal(dirname(authority), resolve(dir)); + const before = inspect(join(authority, 'state.sqlite')); const startedUtc = now(); + rmSync(authority, { recursive: true, force: true }); mkdirSync(authority); + if (restore) copyFileSync(join(dir, 'snapshot.sqlite'), join(authority, 'state.sqlite')); + return { before, startedUtc, endedUtc: now(), after: inspect(join(authority, 'state.sqlite')) }; + } + try { + for (const mode of ['stale', 'loss', 'current', 'native-loss']) { + const dir = fixture(mode); const initial = { utc: now(), authority: inspect(join(dir, 'authority', 'state.sqlite')), provider: read(join(dir, 'provider.json')) }; + let olderAction; let backup; + if (mode === 'stale') { + // Historically correct retained B makes the snapshot valid, yet stale + // with respect to subsequent A. It is not corruption or an empty fake. + olderAction = call(dir, 'persisted-intent-B'); backup = snapshot(dir); + } + const first = call(dir, 'persisted-intent-A', mode === 'native-loss' ? 'native' : ''); + assert.equal(first.after.rows.find(row => row.id === 'persisted-intent-A').state, 'CONFIRMED'); + if (mode === 'current') backup = snapshot(dir); + const providerBeforeRestore = read(join(dir, 'provider.json')); + const restoration = lose(dir, mode === 'stale' || mode === 'current'); + const retry = call(dir, 'persisted-intent-A', mode === 'native-loss' ? 'native' : ''); + const providerFinal = read(join(dir, 'provider.json')); const calls = read(join(dir, 'calls.json')); + const actionEffects = providerFinal.filter(row => row.identity === 'persisted-intent-A'); + const duplicate = mode === 'stale' || mode === 'loss'; + assert.equal(actionEffects.length, duplicate ? 2 : 1); + assert.equal(calls.filter(row => row.type === 'reconciliation-read').length, 0, + 'Missing rows and CONFIRMED replay do not invoke recovery'); + assert.deepEqual(actionEffects.map(row => row.payload), Array(actionEffects.length).fill(first.payload)); + if (duplicate) assert.notDeepEqual(retry.result, first.result); + else assert.deepEqual(retry.result, first.result); + if (mode === 'stale') { + assert.ok(restoration.after.rows.some(row => row.id === 'persisted-intent-B')); + assert.ok(!restoration.after.rows.some(row => row.id === 'persisted-intent-A')); + } + scenarios.push({ mode, initial, olderAction, snapshot: backup ?? null, + first, providerBeforeRestore, restoration, retry, providerFinal, calls, + targetEffectCount: actionEffects.length, reconciliationReads: 0, + guarantee: mode === 'native-loss' ? 'SIMULATED atomic provider dedup survives local loss; not a real-provider certification' : 'current retained-authority boundary' }); + } + console.log(JSON.stringify({ node: process.version, os: process.platform, + sdkVersion: read(fileURLToPath(new URL('../package.json', import.meta.url))).version, + provider: 'independent disposable simulated provider; no external writes', scenarios }, null, 2)); + } finally { rmSync(root, { recursive: true, force: true }); } +} diff --git a/sdk/typescript/scripts/first-action-package-regression.mjs b/sdk/typescript/scripts/first-action-package-regression.mjs new file mode 100644 index 00000000..0aa0eca5 --- /dev/null +++ b/sdk/typescript/scripts/first-action-package-regression.mjs @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, existsSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; + +// npm run supplies the CLI path; spawning Node avoids Windows .cmd quoting. +assert.ok(process.env.npm_execpath, "Run via npm run test:first-action-package"); +const fixture = mkdtempSync(path.join(os.tmpdir(), "once-first-package-")); +const run = (program, args, options = {}) => { + const result = spawnSync(program, args, { encoding: "utf8", windowsHide: true, + timeout: 60_000, ...options }); + assert.equal(result.status, 0, result.error?.message ?? result.stderr); + return result.stdout; +}; +try { + const packed = JSON.parse(run(process.execPath, + [process.env.npm_execpath, "pack", "--ignore-scripts", "--json", "--pack-destination", fixture, + "--cache", path.join(fixture, "npm-cache")])); + const entry = packed[0]; + assert.ok(entry.files.some(file => file.path === "examples/first-action/verify.mjs"), + "The canonical proof must reach npm consumers"); + const unpack = path.join(fixture, "consumer"); + mkdirSync(unpack); + run("tar", ["-xf", path.join(fixture, entry.filename), "-C", unpack]); + const packageRoot = path.join(unpack, "package"); + assert.equal(existsSync(path.join(packageRoot, "node_modules")), false); + const started = performance.now(); + const output = run(process.execPath, + [path.join(packageRoot, "examples", "first-action", "verify.mjs")], { cwd: unpack }); + assert.match(output, /FIRST ACTION PROOF: PASS/); + assert.match(output, /Fresh process: original receipt replayed, 3 effects retained/); + const metadata = JSON.parse(readFileSync(path.join(packageRoot, "package.json"), "utf8")); + console.log(`Packed first-action proof: PASS; SDK ${metadata.version}; ${(performance.now() - started).toFixed(1)} ms (machine execution only)`); +} finally { + rmSync(fixture, { recursive: true, force: true }); +} diff --git a/sdk/typescript/scripts/zero-friction-cli-regression.mjs b/sdk/typescript/scripts/zero-friction-cli-regression.mjs index b9a4b7f8..6c5679d5 100644 --- a/sdk/typescript/scripts/zero-friction-cli-regression.mjs +++ b/sdk/typescript/scripts/zero-friction-cli-regression.mjs @@ -75,6 +75,8 @@ try { assert.equal(explicit.status, 0); assert.match(explicit.stdout, /^\s*Once\s*$/m); assert.match(explicit.stdout, /once doctor/); + assert.match(explicit.stdout, /Start with one action: once prove/); + assert.match(explicit.stdout, /Identity belongs to your application/); assert.doesNotMatch(explicit.stdout, /AUTOPROTECTION METRICS/); console.log("zero-friction CLI regression: PASS"); diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts index 1723fd50..53eb191c 100644 --- a/sdk/typescript/src/cli.ts +++ b/sdk/typescript/src/cli.ts @@ -53,6 +53,10 @@ import { } from "./mcp-tool-refresh-report.js"; function printHelp(): void { + console.log("Start with one action: once prove (isolated simulation, Node.js 24.15+)."); + console.log("Then assess -> protect -> verify the actual provider boundary."); + console.log("Identity belongs to your application; UNKNOWN never permits blind retry."); + console.log("Guide: https://github.com/stringsofthemind-oss/once/blob/main/docs/START_HERE.md"); console.log(""); console.log("Once"); console.log("----"); diff --git a/sdk/typescript/test/first-action.test.mjs b/sdk/typescript/test/first-action.test.mjs new file mode 100644 index 00000000..78eda649 --- /dev/null +++ b/sdk/typescript/test/first-action.test.mjs @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +const [major, minor] = process.versions.node.split('.').map(Number); +const localReady = major > 24 || (major === 24 && minor >= 15); + +test("canonical proof exercises intent, conflict, uncertainty and restart without touching the caller project", { skip: localReady ? false : 'Local SQLite requires Node 24.15+' }, t => { + const project = mkdtempSync(path.join(os.tmpdir(), "once-proof-project-")); + t.after(() => rmSync(project, { recursive: true, force: true })); + writeFileSync(path.join(project, "keep.txt"), "original project"); + const result = spawnSync(process.execPath, + [fileURLToPath(new URL("../examples/first-action/verify.mjs", import.meta.url))], + { cwd: project, encoding: "utf8", windowsHide: true, timeout: 30_000, + env: { ...process.env, ONCE_API_KEY: "unused-fixture-key" } }); + assert.equal(result.status, 0, result.error?.message ?? result.stderr); + assert.match(result.stdout, /First execution \+ replay: 1 effect/); + assert.match(result.stdout, /CONFLICT, no write/); + assert.match(result.stdout, /Separate intent, identical effect: 2 effects/); + assert.match(result.stdout, /unavailable truth: UNKNOWN, 3 effects/); + assert.match(result.stdout, /recovered original receipt, no redispatch/); + assert.match(result.stdout, /Fresh process: original receipt replayed, 3 effects retained/); + assert.match(result.stdout, /simulated provider; same-machine SQLite only/); + assert.deepEqual(readdirSync(project), ["keep.txt"]); + assert.equal(readFileSync(path.join(project, "keep.txt"), "utf8"), "original project"); +}); + +test("CLI help starts with the existing safe proof and makes ownership explicit", () => { + const result = spawnSync(process.execPath, + [fileURLToPath(new URL("../dist/once-cli.js", import.meta.url)), "--help"], + { encoding: "utf8", windowsHide: true, timeout: 30_000 }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /Start with one action: once prove/); + assert.match(result.stdout, /Identity belongs to your application/); + assert.match(result.stdout, /UNKNOWN never permits blind retry/); + assert.match(result.stdout, /docs\/START_HERE.md/); +}); diff --git a/sdk/typescript/test/gateway/local-gateway-toolset.test.mjs b/sdk/typescript/test/gateway/local-gateway-toolset.test.mjs index 12fb72b5..1b618073 100644 --- a/sdk/typescript/test/gateway/local-gateway-toolset.test.mjs +++ b/sdk/typescript/test/gateway/local-gateway-toolset.test.mjs @@ -3,12 +3,14 @@ import { mkdtemp, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; +const [major, minor] = process.versions.node.split('.').map(Number); +const localReady = major > 24 || (major === 24 && minor >= 15); import { connectLocalGatewayToolsetAuto, } from "../../dist/gateway/index.js"; -test("gateway keeps direct tools direct and protected retries single-effect", async () => { +test("gateway keeps direct tools direct and protected retries single-effect", { skip: localReady ? false : 'Local SQLite requires Node 24.15+' }, async () => { const directory = await mkdtemp(path.join(os.tmpdir(), "once-gateway-local-")); const statePath = path.join(directory, "operations.sqlite"); diff --git a/sdk/typescript/test/gateway/openai-function-tools-gateway.test.mjs b/sdk/typescript/test/gateway/openai-function-tools-gateway.test.mjs index 89ca2336..fdfd132b 100644 --- a/sdk/typescript/test/gateway/openai-function-tools-gateway.test.mjs +++ b/sdk/typescript/test/gateway/openai-function-tools-gateway.test.mjs @@ -3,12 +3,14 @@ import { mkdtemp, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; +const [major, minor] = process.versions.node.split('.').map(Number); +const localReady = major > 24 || (major === 24 && minor >= 15); import { connectOpenAIAgentsFunctionToolsGatewayAuto, } from "../../dist/gateway/index.js"; -test("OpenAI Gateway ignores transport call ID for protected logical retry", async () => { +test("OpenAI Gateway ignores transport call ID for protected logical retry", { skip: localReady ? false : 'Local SQLite requires Node 24.15+' }, async () => { const directory = await mkdtemp(path.join(os.tmpdir(), "once-openai-gateway-")); const statePath = path.join(directory, "operations.sqlite"); diff --git a/sdk/typescript/test/local-session.test.mjs b/sdk/typescript/test/local-session.test.mjs index 6626e059..a351e5bb 100644 --- a/sdk/typescript/test/local-session.test.mjs +++ b/sdk/typescript/test/local-session.test.mjs @@ -2,7 +2,10 @@ import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; -import test from "node:test"; +import nodeTest from "node:test"; +const [major, minor] = process.versions.node.split('.').map(Number); +const localReady = major > 24 || (major === 24 && minor >= 15); +const test = (name, fn) => nodeTest(name, { skip: localReady ? false : 'Local SQLite requires Node 24.15+' }, fn); import { createLocalProtectionSession, withLocalProtectionSession, @@ -17,8 +20,21 @@ function fixture(t) { const statePath = path.join(dir, "state.sqlite"); const effectsPath = path.join(dir, "effects.json"); writeFileSync(effectsPath, "[]"); - t.after(() => rmSync(dir, { recursive: true, force: true })); - return { dir, statePath, effectsPath }; + const sessions = []; + // Node after hooks run in registration order. Close handles before removing + // the fixture: Windows cannot remove an open SQLite database. + t.after(() => { + for (const session of sessions) session.close(); + rmSync(dir, { recursive: true, force: true }); + }); + return { + dir, statePath, effectsPath, + session(pathname = statePath) { + const session = createLocalProtectionSession(pathname); + sessions.push(session); + return session; + }, + }; } function count(pathname) { @@ -48,8 +64,7 @@ async function settle(callback) { test("scoped persistent state preserves replay and conflict semantics", async t => { const f = fixture(t); - const session = createLocalProtectionSession(f.statePath); - t.after(() => session.close()); + const session = f.session(); const run = createRun(f); const first = await withLocalProtectionSession(session, @@ -65,16 +80,24 @@ test("scoped persistent state preserves replay and conflict semantics", async t assert.equal(count(f.effectsPath), 1); }); -test("scoped session fails closed when its durable state path disappears", async t => { +test("live path disappearance or Windows open-file locking cannot permit another effect", async t => { const f = fixture(t); - const session = createLocalProtectionSession(f.statePath); - t.after(() => session.close()); + const session = f.session(); const run = createRun(f); await withLocalProtectionSession(session, () => run({ id: "A", amount: 100 })); assert.equal(count(f.effectsPath), 1); + if (process.platform === "win32") { + // Windows prevents live deletion itself; replay must remain protected. + assert.throws(() => unlinkSync(f.statePath), error => + error.code === "EBUSY" || error.code === "EPERM"); + assert.deepEqual(await withLocalProtectionSession(session, + () => run({ id: "A", amount: 100 })), { receipt: "r-1" }); + assert.equal(count(f.effectsPath), 1); + session.close(); + } unlinkSync(f.statePath); await assert.rejects( withLocalProtectionSession(session, @@ -96,7 +119,7 @@ test("scoped session fails closed when its durable state path disappears", async test("same-inode main-file damage cannot lose a confirmed effect across restart", async t => { const f = fixture(t); - const session = createLocalProtectionSession(f.statePath); + const session = f.session(); const run = createRun(f); await withLocalProtectionSession(session, @@ -109,8 +132,7 @@ test("same-inode main-file damage cannot lose a confirmed effect across restart" writeFileSync(f.statePath, "not-a-sqlite-database"); session.close(); - const restarted = createLocalProtectionSession(f.statePath); - t.after(() => restarted.close()); + const restarted = f.session(); await settle(() => withLocalProtectionSession(restarted, () => run({ id: "A", amount: 100 }))); assert.equal(count(f.effectsPath), 1); @@ -118,7 +140,7 @@ test("same-inode main-file damage cannot lose a confirmed effect across restart" test("damage after an external effect cannot cause a blind redispatch after restart", async t => { const f = fixture(t); - const session = createLocalProtectionSession(f.statePath); + const session = f.session(); const run = protectLocal(async input => { addEffect(f.effectsPath, input.amount); // Damage the same live main database file after the effect but before Once @@ -137,8 +159,7 @@ test("damage after an external effect cannot cause a blind redispatch after rest assert.equal(count(f.effectsPath), 1); session.close(); - const restarted = createLocalProtectionSession(f.statePath); - t.after(() => restarted.close()); + const restarted = f.session(); await settle(() => withLocalProtectionSession(restarted, () => run({ id: "A", amount: 100 }))); assert.equal(count(f.effectsPath), 1); @@ -147,11 +168,23 @@ test("damage after an external effect cannot cause a blind redispatch after rest test("an unrelated scoped session cannot change a protectLocal state path", async t => { const f = fixture(t); const other = path.join(f.dir, "other.sqlite"); - const session = createLocalProtectionSession(other); - t.after(() => session.close()); + const session = f.session(other); const run = createRun(f); assert.deepEqual(await withLocalProtectionSession(session, () => run({ id: "A", amount: 100 })), { receipt: "r-1" }); assert.equal(count(f.effectsPath), 1); }); + +test("a closed session never silently creates replacement authority", async t => { + const f = fixture(t); + const session = f.session(); + const run = createRun(f); + await withLocalProtectionSession(session, () => run({ id: "A", amount: 100 })); + session.close(); + await assert.rejects( + withLocalProtectionSession(session, () => run({ id: "B", amount: 200 })), + error => error instanceof LocalProtectionError && error.code === "STATE_UNAVAILABLE", + ); + assert.equal(count(f.effectsPath), 1); +}); diff --git a/sdk/typescript/test/local.test.mjs b/sdk/typescript/test/local.test.mjs index b964a7ab..1b1ec7ab 100644 --- a/sdk/typescript/test/local.test.mjs +++ b/sdk/typescript/test/local.test.mjs @@ -3,7 +3,10 @@ import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import test from "node:test"; +import nodeTest from "node:test"; +const [major, minor] = process.versions.node.split('.').map(Number); +const localReady = major > 24 || (major === 24 && minor >= 15); +const test = (name, fn) => nodeTest(name, { skip: localReady ? false : 'Local SQLite requires Node 24.15+' }, fn); import { protectLocal, LocalProtectionError } from "../dist/index.js"; const root = path.dirname(fileURLToPath(import.meta.url)); diff --git a/sdk/typescript/test/unsupported-runtime.test.mjs b/sdk/typescript/test/unsupported-runtime.test.mjs new file mode 100644 index 00000000..d2869fc5 --- /dev/null +++ b/sdk/typescript/test/unsupported-runtime.test.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { mkdtempSync, readdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { protectLocal } from '../dist/index.js'; +const [major, minor] = process.versions.node.split('.').map(Number); +const localReady = major > 24 || (major === 24 && minor >= 15); + +test('unsupported local runtime rejects before dispatch or authority creation', { + skip: localReady ? 'Unsupported-runtime contract runs on Node 18/20' : false, +}, async t => { + const dir = mkdtempSync(join(tmpdir(), 'once-unsupported-runtime-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + let effects = 0; + const run = protectLocal(async () => { effects++; return { receipt: 'unsafe' }; }, { + statePath: join(dir, 'state.sqlite'), id: () => 'persisted-intent', payload: () => ({ amount: 100 }), + }); + await assert.rejects(run(), { code: 'UNSUPPORTED_RUNTIME' }); + assert.equal(effects, 0); + assert.deepEqual(readdirSync(dir), []); +});