# Changelog

All notable changes to `@syncropel/sdk` are documented here. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project uses [SemVer](https://semver.org/spec/v2.0.0.html).

The TypeScript SDK versions independently of the Syncropel server and the Python SDK.

## [0.10.0] — 2026-08-14

### Added

- **`client.members`** (kernel v0.158, ADR-194) — the membership surface:
  `list()` (the roster; admin sees all, others their own row), `adopt()`
  (retroactive principal creation for an existing actor or service-account
  holder), `revoke()` (offboarding as one revocation — every credential
  parented to the membership dies; optional `note` rides the signed
  revocation), `mintAgentGrant()` / `revokeAgentGrant()` (attenuated agent
  sub-grants that die with the member; scope-narrowing and caveat-tightening
  are door-enforced server-side).
- **Membership invites** — `invites.issue({ membership: { preset,
  ttlSeconds, caveats, label } })` makes the invite PRINCIPAL-CREATING;
  a pinned `label` naming an existing custodial member makes redemption a
  RENEWAL (same principal, fresh grant + bearer). `invites.redeem` accepts
  `memberLabel` + `custody` ("custodial" — "device" returns 501 honestly);
  `RedeemResult.membership` carries `{ member_did, master_did, grant_id }`;
  `InvitePreview.membership` exposes the signed envelope so clients can
  collect the member name before redeeming.
- HTTP transport gains `DELETE` (with optional JSON body) for the
  offboarding + sub-grant-revocation verbs.

## [0.9.1] — 2026-07-03

### Added

- `client.decisions.decide` speaks all three response shapes (SKL-2672):
  CHOOSE accepts any option id declared on the request (`approve`/`reject`
  remain the canonical pair — the client-side gate is gone; the daemon
  validates and returns 400 `BAD_OPTION`), PROVIDE sends `providedValue`
  (wire: `provided_value`, any JSON — 400 `PROVIDED_VALUE_REQUIRED` when
  missing), ACKNOWLEDGE needs no value. `Decision` widens to an open string
  with the canonical pair as well-known values (source-compatible).

## [0.9.0] — 2026-06-26

### Changed (breaking)

- **`client.aitl` → `client.decisions`** (ADR-139 — the protocol formerly
  "AITL", retired; hard cut, no alias). `ClientAitl` → `ClientDecisions`;
  `client.aitl.pending()` / `.decide()` → `client.decisions.pending()` /
  `.decide()`, now hitting `GET /v1/decisions` + `POST /v1/decisions/:id/decide`.
  Types `AitlPendingItem`/`AitlDecideOptions`/`AitlDecideResult`/`AitlDecision`
  → `PendingDecision`/`DecideOptions`/`DecideResult`/`Decision`; the generated
  `AitlDecisionRequest`/`AitlPending` → `DecisionDecideRequest`/`DecisionPending`.
  `PendingDecision` exposes the canonical decision_request view (question +
  `response_shape` + options + decider). The `expr` CEL context `"aitl"` →
  `"decision"`. Regenerated from the v0.107 kernel manifest.

## [0.8.1] — 2026-06-25

### Added

- **`Client.cancel({ thread, fulfills, reason? })`** (SKL-2661, ADR-UI-040 —
  cancel is an SDK method, not a raw route). Cancels an in-flight conversation
  Faculty response: POSTs `/v1/threads/{id}/cancel` with `fulfills` (the trigger
  — the user-message id whose running "thinking" node to cancel). The server
  emits `core.scribe.cancelled.v1`; the conversation fold renders a cancelled
  beat and suppresses a reply that lands after the cancel. Fail-open: a transport
  error resolves to `{ success: false }`, never throws. Additive — published as a
  patch so an existing `^0.8.0` range picks it up automatically.

## [0.8.0] — 2026-06-09

Adds the data plane to the client surface, and makes malformed read requests surface instead of silently returning empty.

### Added

#### `client.data.*` — the data plane (files, blobs, materials)

- **`client.data.write({ path, data, contentType?, expectedHash? })`** — one call for the three-step write (initiate → chunked upload → commit). Returns `{ contentHash, sizeBytes }`. Optimistic concurrency via `expectedHash`: omit for last-writer-wins, pass a hash for compare-and-swap, or pass `null` for create-only. A conflict throws `SyncropelDataError` with `isConflict === true` plus `expectedHash` / `currentHash` so you can drive a reload-or-overwrite UX.
- **`client.data.read(path)`** / **`client.data.readText(path)`** — resolve a path to its bytes (or UTF-8 text).
- **`client.data.readUrl(path)`** — resolve a path to a short-lived blob URL.
- **`client.data.list(path, { cursor?, limit? })`**, **`client.data.stat(path)`** — directory listing + per-node metadata (size, hash, content type, pin state, provenance).
- **`client.data.mkdir(path)`**, **`client.data.mv(from, to)`**, **`client.data.rm(path, { recursive? })`** — tree mutations.
- **`client.data.publish(path, { storageClass? })`** — promote a file to a content-addressed, durable artifact.
- **`client.data.materials({ q?, limit? })`** / **`client.data.node(path)`** — typed, byte-free views over files for pickers and previews.
- **`client.data.usage()`**, **`client.data.capabilities()`**, **`client.data.provenance({ … })`** — quota, self-describing limits, and the "made by" feed.
- Unlike the record read methods, the data plane **surfaces errors** (`SyncropelDataError`) rather than failing open — a dropped write never looks like a success.
- **New exports**: `ClientData`, `SyncropelDataError`, and the data-plane types (`WriteOptions`, `WriteResult`, `StatResult`, `ListResult`, `ListEntry`, `MaterialProvenance`, `ReadUrlResult`, `PublishResult`, `UsageResult`).

### Changed

#### Malformed (4xx) read requests now surface instead of being swallowed — **BREAKING**

- **`richQuery`, `query`, and `queryThread` now throw `SyncropelQueryError` when the daemon rejects a request as malformed (HTTP 4xx).** Previously a 4xx was silently collapsed into an empty result, making a *rejected* query indistinguishable from an *empty* one (e.g. a string `sort` like `'clock_desc'` instead of the object form `{ clock: -1 }` returned `400 sort must be an object`, which looked like zero records).
- **Fail-open is preserved for every other outcome** — transient `5xx`, `401`/`403`, and transport-down still return the empty sentinel so a UI never crashes on a briefly-unavailable daemon. Only a malformed request (a programmer error) throws — mirroring how the SDK already throws `SyncropelKindError` for an invalid `kind` at emit time.
- **New export**: `SyncropelQueryError` (carries `.detail`).
- **Migration**: wrap any read that may send a malformed filter/sort/path in `try/catch` for `SyncropelQueryError`; valid queries are unaffected. The canonical fix is the object sort form `{ clock: -1 }`.
- `EmitOptions.kind` remains top-level and authoritative; a body-supplied `kind` is overridden by the top-level value (unchanged).

## [0.7.0] — 2026-05-24

Generic fold reads, live thread watching, invitations, and graph helpers. Universal runtime throughout (Node 18+, Deno, Bun, Cloudflare Workers, modern browsers).

### Added

#### `client.folds.*` — the generic fold reader

- **`client.folds.resolve<V>(name, cacheKey?)`** — read any kernel fold through one typed method (the kernel dispatches by name, so new folds need no new SDK method). `cacheKey` is the thread id for per-thread folds; omit it for global folds. Returns `ResolvedFold { fold_name, cache_key, from_cache, watermark, value }`; fails open to an empty fold on transport error.
- **`client.folds.watermark(name, cacheKey)`** — the fold's current liveness watermark without computing the value, so a cache refetches only when it has actually moved.
- **New export**: `ResolvedFold<V>`.

#### `client.threads.watch()` — live thread streaming

- **`client.threads.watch(threadId, opts?)`** — an `AsyncIterable` over a thread's live event stream. Emits `record`, `scribe.delta`, `connected`, and `disconnected` events; auto-reconnects with exponential backoff and resume-from-clock so missed records replay; falls back to polling after repeated disconnects; cancellable via `AbortSignal`. Bearer-token auth works in every runtime (no `EventSource` dependency).
- The existing callback-based `client.subscribe(thread, cb, opts?)` is unchanged.
- **New exports**: `watchThread`, `ThreadWatchEvent`, `ThreadWatchOptions`.

#### `client.invites.*` — invitations

- Issue, list, preview, redeem, revoke, bulk-revoke, audit, and sign invitations; plus scope presets and reusable invite templates. Guest (browser-generated key) and federated (attested) redemption paths.
- **New exports**: `ClientInvites` + its option/result types.

#### Graph helpers

- **`GraphClient`** — a convenience client for graph-style search, traversal, and discovery against any instance configured for wide federation + indexing. Per-result provenance (`graph_node_did`, `graph_node_url`) and optional signed attestation receipts.
- **`client.federation.discoverPeers(predicate?)`** and **`client.federation.mergeResults(results[])`** (dedup by id, sort by trust).
- **`verifyManifestSignature(manifest, publicKey)`** — Ed25519 manifest verification via WebCrypto. Pure crypto, no transport, fail-closed.

## [0.4.0] — 2026-05-04

### Added

#### Type-generation pipeline (Phase 1A)

- **`scripts/gen-types.ts`** — generates `src/types-generated.ts` from the kernel capability manifest (`sdks/manifest.json`, output of `cargo run --bin export-manifest -p spl`). Uses `json-schema-to-typescript` to compile each `components.schemas` entry into a typed interface.
  - `npm run gen:types` regenerates the file in-place.
  - `npm run check:types` runs as a `prebuild` step — if the regenerated output differs from the committed `types-generated.ts`, the build fails with a diff.
- **`MANIFEST_VERSION` + `GENERATED_SCHEMA_NAMES` constants** — exported at the package root so consumers can detect drift between the SDK they shipped against and the daemon's served manifest version.
- **20 generated interfaces** — `Ack`, `AitlDecisionRequest`, `AitlPending`, `ApiError`, `DispatchRequest`, `DispatchResult`, `ExprEvalRequest`, `ExprEvalResponse`, `PairConfirmRequest`, `PairInitRequest`, `PairPollRequest`, `PairResponse`, `RecordList`, `ThreadList`, `ThreadSummary`, `TrustScore`, plus internal `Record` / `RichQueryRequest` / `RichQueryResult` / `Empty` (the latter four are intentionally not re-exported from the package root because the SDK ships hand-written ergonomic equivalents — `KernelRecord`, `RichQueryOptions`, `RichQueryResult` from `client.ts`).
- **`package.json` declares `"syncropel": { "manifest_version": "2" }`** — the manifest version this SDK build targets.

#### Method expansion (Phase 1B)

- **`client.threads`** — `.list(opts)`, `.records(threadId, opts)`, `.state(threadId)`, `.project(threadId, format)`. Wraps `GET /v1/threads`, `GET /v1/threads/:id/records`, `GET /v1/threads/:id/state`, `GET /v1/threads/:id/project`.
- **`client.aitl`** — `.pending()`, `.decide(proposalId, { decision, reason? })`. Wraps `GET /v1/aitl`, `POST /v1/aitl/:id/decide`.
- **`client.federation`** — `.peers()`, `.pair(peerUrlOrOpts)`, `.sync(threadId, peerDid?)`, `.relayPoll()`. Wraps `GET /v1/federation/pairs`, `POST /v1/federation/pair`, `POST /v1/sync/:thread`, `POST /v1/relay/poll` (ADR-063).
- **`client.namespaces`** — `.list()`, `.create({ id, description?, policy? })`. Wraps `GET /v1/namespaces`, `POST /v1/namespaces` (spec §08/04).
- **`client.expr`** — `.eval({ expression, context, record?, timeoutMs? })`. Wraps `POST /v1/expr/eval` (spec §10/20 — 7 evaluation contexts).
- **`client.graph`** — `.query({ start, edges?, depth?, limit?, filter? })`. Wraps `POST /v1/graph/query` (ADR-079 / ADR-080).
- **`client.records`** — `.create(emitOpts)` (alias for `client.emit`), `.get(recordId)`. Wraps `POST /v1/records`, `GET /v1/records/:id`.
- **Flat methods** — `client.do({ thread, description, ... })`, `client.know({ thread, observation, ... })`, `client.learn({ thread, insight, ... })` round out the act-emission surface alongside the existing `intend()` and `fulfill()` helpers. `client.capabilities()` reads `GET /v1/capabilities` returning the full manifest.
- **`ClientOptions.namespace`** — when set, every namespace-scoped request appends `?namespace=<id>` automatically (per ADR-UI-039). Per-call namespace arguments override the default. The active value is exposed on `client.namespace`.

### Fail-open contract

All new namespace methods follow the SDK's existing fail-open contract: transport errors and 4xx/5xx responses resolve to a typed empty shape (e.g. `{ records: [] }`, `[]`, `null`) rather than throwing — same model as `query()` / `richQuery()` / `search()`. Only argument validation (empty thread id, missing required field) and grammar errors (`SyncropelKindError`) throw before the request.

### Backwards compatibility

Every 0.3.0 surface — `emit`, `intend`, `fulfill`, `query`, `queryThread`, `richQuery`, `search`, `infer`, `subscribe`, `health`, the reserved-kind helpers — is unchanged. New methods are purely additive.

### Notes

- Consumers can bump `@syncropel/sdk` from `^0.3.0` to `^0.4.0` and start migrating hand-rolled fetches to typed SDK calls.
- The `ClientRecords.create()` alias is intentional — the existing `client.emit()` ergonomics also read as `client.records.create()` per the namespaced API expectation. Both work; both forward to the same code path.

## [0.3.0] — 2026-05-02

### Added

- **`Client.subscribe(thread, callback, options?)`** — live record subscription wrapping the kernel's `GET /v1/threads/{id}/watch` SSE endpoint. Returns a `Subscription` handle with `close()`, `cursor`, `closed`, and `transportName` properties.
  - **Reconnect**: automatic on transport failure with full-jitter exponential backoff (`reconnectBaseMs`, `reconnectMaxMs`, `maxReconnects`).
  - **Resume**: cursor (`Last-Event-ID`) is preserved across reconnects; the client picks up exactly where it left off without duplicate delivery (per the kernel's exactly-once subscribe semantics).
  - **Heartbeat watchdog**: if no event arrives within `heartbeatTimeoutMs` (default 60s), the SDK forces a reconnect. The kernel emits `event: heartbeat` every ~30s.
  - **Server shutdown**: `event: server_shutdown` honors the kernel's `retry_after_ms` hint.
  - **Hooks**: `onOpen`, `onError`, `onHeartbeat` for observability. The reconnect loop runs unconditionally; `onError` is informational, not control flow.
- **`Transport` interface + `SseTransport` class** exported from `@syncropel/sdk` — stable abstraction so a future WebSocket transport plugs in without altering `Client.subscribe`. Today the kernel exposes record subscribe via SSE only (WebSocket is reserved for `/v1/presence`); the abstraction is forward-looking.
- **`Subscription`, `SubscribeOptions`, `SubscribeError` types** exported from the public API.

### Notes

- Backwards compatible — every 0.2.0 surface (`emit`, `intend`, `fulfill`, `query`, `richQuery`, `search`, `infer`, `health`, the reserved-kind helpers) is unchanged.
- Universal runtime continues to hold: subscribe uses `fetch` + `ReadableStream` rather than the `EventSource` global, so it works in Node 18+, Deno, Bun, Cloudflare Workers, and modern browsers without polyfills.
- Closes downstream gates in [ADR-072 D6.1] (workspace orchestrator → substrate subscribe channel) and [ADR-073 D6] (profile sync from "read-on-mount" to "subscribe-and-update").

## [0.2.0] — 2026-04-28

### Added

- **`Client.query({ filter, sort?, limit?, fields? })`** — rich query helper wrapping `POST /v1/records/query`. Server-side filter AST + client-side `where` clauses with dotted paths.
- **`Client.search({ query, kinds?, namespaces?, limit?, threshold? })`** — semantic search over `POST /v1/records/search`. Returns ranked results with relevance scores; backend uses the daemon's embedder. Fail-open on transport errors.
- **`Client.infer(query, { wait?, pollIntervalMs?, timeoutMs? })`** — emits an `infer.query.v1` record and (when `wait: true`) polls until the response lands. Returns the response record or null on timeout.

### Notes

The existing 0.1.0 surface — `emit`, `intend`, `fulfill`, `queryThread`, `health`, and the reserved-kind helpers (`emitCorrection`, `emitErasure`, `emitAlias`, `emitScopeTransfer`, `emitScopeClaim`) — is unchanged.

## [0.1.0] — 2026-04-19

Initial release.

### Features

- **`Client` class** — async emit + query surface.
  - `emit({ act, kind, body, thread, refs?, parents?, dataType?, clock? })` — validates kind, builds the record envelope, retries on 5xx / network errors with exponential backoff. Returns `Promise<EmitResult>`. Never rejects on transport failures.
  - `intend({ goal, thread?, ... })` — open a thread with an `INTEND` record. Generates a random 64-hex thread id if none supplied; returns it on `result.thread`.
  - `fulfill({ thread, summary, fulfills?, ... })` — close a thread with a `KNOW` record. `fulfills` accepts a single record id or list.
  - `queryThread({ thread, limit?, since? })` — fail-open thread query.
  - `query({ kind?, actor?, thread?, ... })` — filtered query. Server-side filters: `thread`, `actor`. Client-side: `kind` and `where` clauses (dotted paths).
  - `health()` — fail-open health probe.
  - `onEmit` hook fires on every success and failure; hook exceptions are swallowed with `console.warn`.
  - `apiKey` option forwards as `x-api-key` header.
  - `fetch` option accepts a custom transport — useful for tests, proxies, observability wrappers.
  - Uses `AbortController` for request timeouts (`timeoutMs` defaults to 30s).

- **Auto-clock fill** — when `clock` is omitted, the client supplies wall-clock milliseconds with a per-thread monotonic floor so back-to-back emits within the same millisecond never collide on `DuplicateClock`. Adapters that need deterministic clocks (replay, golden fixtures) pass `clock: N` explicitly to bypass auto-fill.

- **Grammar validation** (`validateKind`, `validateScope`, `hasExplicitVersion`, `SyncropelKindError`) — enforces the `scope.category.entity[.version]` grammar before any network call. Two-segment kinds accepted only for `core` scope and `@<community>` scopes.

- **11 canonical reference constructors** on the `Ref` namespace: `musicTrack`, `codeFile`, `opsIncident`, `calEvent`, `socialPerson`, `mediaPhoto`, `mediaVideo`, `docText`, `finTransaction`, `researchPaper`, `coreThread`. Each returns `{ kind, id }`. `mergeRefs(body, refs)` is exposed for adapters that compose bodies in pieces.

- **`Identity` class** with `Identity.static(did)` available today and `Identity.key(...)` / `Identity.federated(...)` reserved as named stubs for upcoming releases.

- **5 reserved-kind helpers** on `Client`: `emitCorrection`, `emitErasure`, `emitAlias`, `emitScopeTransfer`, `emitScopeClaim`. Each validates body shape, defaults identity fields to the configured actor, and defaults `effectiveAt` / `since` to UTC ISO-8601 now.

- **`MockKernel`** at the `@syncropel/sdk/testing` subpath — in-memory stand-in for the Syncropel server. Implements POST `/v1/records`, GET `/v1/records`, GET `/v1/threads/:id/records`, GET `/health`. Computes record ids via SHA-256 of canonical JSON so mock ids match production ids. Inspection: `recordsIn(thread)`, `recordsByKind(kind)`, `recordsByActor(actor)`, `count()`, `clear()`. Failure injection: `failNextPostCall(n)`, `failNextGetCall(n)`. Mirrors the server's `DuplicateClock` constraint.

- **`canonicalJson` / `canonicalValue`** — exposed for adapters that want to pre-hash records or debug on-the-wire bytes. Produces byte-identical canonical JSON across every Syncropel implementation.

- **`EmitResult`** with `success`, `recordId`, `clock`, `error`, `retried`, `kind`, `act`, `thread` fields.

### Runtime targets

- Node.js 18+ (built-in `fetch` + `AbortController`)
- Deno 1.30+
- Bun 1.0+
- Cloudflare Workers
- Modern browsers

### Dependencies

Zero runtime dependencies. Dev-only: `typescript`, `@types/node`, `tsx`.

### Tests

179 unit tests + 4 integration tests (gated on a Syncropel server binary). Strict `tsc --noEmit` passes (ES2022, NodeNext modules, `noUncheckedIndexedAccess`, `strict: true`).
