osuite 2.11.2 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,527 @@
1
+ # Matoi Controlled Transfers
2
+
3
+ **Unreleased candidate.** This entry is in the working SDK source, not the
4
+ already published `osuite@2.11.2`. Installing that registry version does not
5
+ provide these APIs. A versioned SDK release and matching server deployment must
6
+ be qualified together before customer rollout.
7
+
8
+ The additive ESM entry `osuite/controlled-transfers` speaks the
9
+ `matoi.controlled-transfer.v1` semantic profile to the resource-owned **controlled ledger**.
10
+ Its default full lease remains v1; this candidate also reads explicitly requested
11
+ compact `matoi.controlled-transfer.lease.v2` leases, as described below.
12
+ It requires **Node 24**. The ordinary SDK exports, Hook, runtime requirements,
13
+ installation settings and signing transport are unchanged.
14
+
15
+ Installing this package does **not** establish full-stack deployment protection.
16
+ The profile must be enabled and configured on the server, with actual native
17
+ Studio review and a resource-enforcing owner. This entry is not an external bank,
18
+ blockchain, arbitrary tool wrapper or local transfer callback. Deployment
19
+ qualification requires separate acceptance evidence; `not-qualified` and
20
+ `integrated-tested` are not `deployment-qualified`.
21
+
22
+ ## Resource Operator Setup
23
+
24
+ This is explicit operator configuration, not an automatic SDK installation
25
+ step. Use a test deployment and synthetic balances until deployment qualification
26
+ is complete. Initial ledger balances do not represent an actual bank deposit.
27
+
28
+ 1. Install the matching Studio server with its normal schema, authentication,
29
+ workspace membership, SDK/MCP enrollment and approval configuration. Use
30
+ `DASHCLAW_DB_DRIVER=postgres` and a writable interactive PostgreSQL connection.
31
+ The mock driver and Neon HTTP-only query adapter cannot provide this profile's
32
+ transaction boundary.
33
+ 2. Provision `OSUITE_MATOI_TRANSFER_ENABLED=true`, an explicit JSON array of
34
+ activated workspace IDs in `OSUITE_MATOI_TRANSFER_WORKSPACES`, and
35
+ `OSUITE_MATOI_ISSUER_PRIVATE_KEY_B64` (base64-encoded Ed25519 PKCS8 PEM) through
36
+ the server's secret management. Keep both the issuer private key and database
37
+ credentials away from agent hosts. Distribute the corresponding public key
38
+ through a trusted channel for client pinning. Missing, malformed, empty or
39
+ nonmatching workspace scope never enables new execution. Removing a workspace
40
+ from the scope leaves authenticated historical reads and administrator
41
+ revocation available; it does not erase receipts or grant a safe retry.
42
+ 3. From a current workspace owner/admin session, POST configuration to
43
+ `/api/matoi/transfers/configuration`. This endpoint does not accept an agent
44
+ API key as administrative approval. It validates membership and records the
45
+ mutation with its audit event. Browser requests must be same-origin.
46
+ 4. Initialize storage, provision source/destination accounts, then register a
47
+ finite grant for the actual enrolled agent/key. Initialization creates six
48
+ profile tables and authority-serialization triggers on existing Studio tables;
49
+ rehearse this migration and required database privileges before production.
50
+ Missing/disabled triggers or incomplete setup leave capability unavailable.
51
+ 5. Run the explicit doctor probe, prepare one allowed operation, complete its
52
+ real Studio review, execute and verify its receipt, then test rejection and
53
+ recovery. Doctor success reports configuration, not deployment certification.
54
+
55
+ Configuration requests have the following exact fields. Tenant and administrator
56
+ identity come from the authenticated session, never these JSON bodies.
57
+
58
+ | `kind` | Additional body fields | Purpose |
59
+ | --- | --- | --- |
60
+ | `initialize` | None | Create the profile's schema and workspace authority |
61
+ | `account` | `accountId`, `asset`, `network`, `decimals`, `balanceMinor`, `debitLimitMinor` | Provision a controlled account with exact integer-string amounts |
62
+ | `grant` | `agent_id`, `keyId`, `grantId`, `workflow`, `state`, `allowedEffects`, `budgetMinor`, `expiresAt` | Bind the enrolled principal, finite workflow, exact coupled effects, total budget and expiry |
63
+ | `authority` | `grantId`, `active`, and optionally `allowedEffects`, `budgetMinor` | Revoke/reactivate or update current authority without widening the original boundary |
64
+ | `state` | `grantId`, `state` | Update owner-controlled workflow state; relevant changes require reassessment |
65
+
66
+ The workflow grammar and exact effect example are in the
67
+ [implementation contract](../docs/superpowers/plans/2026-10-31-matoi-controlled-transfer-implementation.md).
68
+ Expiry is an integer Unix time in milliseconds, at most 24 hours ahead; prepared
69
+ leases last at most five minutes and cannot outlive the grant. An operator must
70
+ source each allowed `paymentId` from its business records, not let the agent mint
71
+ new authorized payments. A deployment must also prevent direct access to the
72
+ underlying ledger; this configuration API alone does not prove route coverage.
73
+
74
+ ## Configuration
75
+
76
+ ```js
77
+ import { createControlledTransfers } from 'osuite/controlled-transfers';
78
+
79
+ const transfers = createControlledTransfers({
80
+ config: {
81
+ baseUrl: process.env.OSUITE_BASE_URL,
82
+ apiKey: process.env.OSUITE_API_KEY,
83
+ privateKeyBase64: process.env.OSUITE_PRIVATE_KEY_BASE64,
84
+ orgId: process.env.OSUITE_ORG_ID,
85
+ agentId: process.env.OSUITE_AGENT_ID,
86
+ signatureMode: 'required',
87
+ guardFailureMode: 'block',
88
+ // Optional: pin the server's Ed25519 public key as SPKI PEM.
89
+ // issuerPublicKey: trustedIssuerPublicKey,
90
+ // Optional: explicit historical Ed25519 public roots, never private keys.
91
+ // trustedIssuerPublicKeys: [previousIssuerPublicKey],
92
+ // Optional: assert the authenticated credential's exact key ID.
93
+ // keyId: credentialKeyId,
94
+ timeoutMs: 2500,
95
+ },
96
+ });
97
+ ```
98
+
99
+ `baseUrl` uses the existing runtime configuration spelling. HTTPS or HTTP on
100
+ `localhost`, `127.0.0.1` or `[::1]` is required. Credentials in URLs, queries,
101
+ fragments, non-loopback HTTP, missing tenant/agent identity, missing or non-RSA
102
+ private keys, optional signing and fail-open modes are rejected before network
103
+ I/O. `allowInsecureHttp` cannot weaken this profile. `timeoutMs` is an integer
104
+ from 1 to 30000. There is no fetch override, raw execute callback, automatic
105
+ approval, timer-driven polling or mutation retry option.
106
+
107
+ The RSA PEM is base64 encoded for `privateKeyBase64`, as in the existing SDK.
108
+ All requests authenticate with `x-api-key`. POST requests use the unchanged
109
+ `runtime/protocol.mjs` client to attach an RSA `_signature` over canonical JSON.
110
+
111
+ For key rotation, provision up to eight previous Ed25519 SPKI public keys as the
112
+ server's `OSUITE_MATOI_TRUSTED_ISSUER_PUBLIC_KEYS_B64` (base64 of a JSON array of
113
+ PEM strings) and the client's `trustedIssuerPublicKeys`. The strict CLI accepts
114
+ the same environment field in its one selected credential bundle. Historical
115
+ keys verify original preparations and receipts during status recovery; fresh
116
+ prepare/execute authority still requires the current issuer. No key embedded in
117
+ a response is automatically accepted as a historical root. An existing client
118
+ pinned to the retired key must be reconfigured explicitly. Unknown or conflicting
119
+ history stays unknown and does not authorize a resend.
120
+
121
+ Historical signature verification alone does not fence an old writer or detect a
122
+ database rewind. Rotation/restore activation must also follow the tested resource
123
+ owner fencing and recovery procedure, preserving authoritative payment history.
124
+
125
+ `CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES`, exported by `osuite/controlled-transfers`,
126
+ is 1,048,576 (1 MiB). Only this profile's HTTP client, including the doctor probe,
127
+ overrides the existing transport's response limit. Ordinary SDK/Hook limits are
128
+ unchanged. Defensive snapshots allow at most 65,536 nodes, depth 24, and 1 MiB of
129
+ canonical JSON, covering a 64-effect status with its signed original preparation,
130
+ per-effect native passes and receipts. Over-limit responses remain unavailable or
131
+ `OUTCOME_UNKNOWN`, never proof of non-execution or permission to resend.
132
+
133
+ ## Workflow
134
+
135
+ ```js
136
+ const capability = await transfers.capabilities();
137
+ console.log(capability.qualification.status); // A server report, not an SDK guarantee.
138
+
139
+ // Retain the operation ID and preparation in your application's durable store.
140
+ const prepared = await transfers.prepare('invoice-batch-42', 'owner-grant-42');
141
+ console.log(prepared.state, prepared.actionId, prepared.reviewUrl);
142
+ ```
143
+
144
+ `capabilities()` performs one authenticated GET. It validates the profile,
145
+ scope and capability schema, but may report `configured: false` and
146
+ `issuerPublicKey: null`. Every new prepare or execute send requires a fresh
147
+ capability response with `installed`, `configured` and `resourceEnforced` true,
148
+ scope `controlled-ledger`, and a usable Ed25519 issuer key. Qualification remains
149
+ an independent server report, not a boolean inferred from installation.
150
+
151
+ `prepare(operationId, grantId)` performs at most one prepare POST per operation
152
+ in this client instance. It returns an immutable, verified preparation and the
153
+ existing Studio `actionId` and `reviewUrl`, with `retryAutomatically: false`.
154
+ `awaiting_approval` is **not** authorization. If the server is still `preparing`
155
+ with no action bound, the review URL is null; do not invent a review or resend
156
+ to create another one. Repeated/concurrent calls reuse the same preparation.
157
+ Changing the grant under an existing operation ID is a conflict. A native-policy
158
+ `denied` preparation remains a refusal and cannot be executed by this client.
159
+
160
+ ### Optional Compact Leases
161
+
162
+ Use only a newly qualified SDK/server pair supporting this option. Older JavaScript
163
+ clients can ignore an extra argument, so adding an option to an old installation
164
+ does not guarantee compact issuance. Default two-argument calls, MCP and CLI
165
+ callers continue requesting full leases; there is no automatic negotiation or
166
+ fallback to a different representation.
167
+
168
+ ```js
169
+ const prepared = await transfers.prepare('invoice-batch-43', 'owner-grant-43', {
170
+ leaseFormat: 'matoi.controlled-transfer.lease.v2',
171
+ });
172
+ ```
173
+
174
+ The new format signs an ordered commitment to every original Action Pass. At the
175
+ existing final gate, the owner reconstructs only the selected step and verifies
176
+ its complete pass hash, ID and action fingerprint. Issuance still builds the real
177
+ passes once. Current authority, native approval/quorum, expiry, monetary limits,
178
+ predecessors and atomic consumption are unchanged. Financial actions still use
179
+ the approved slow lane; compact storage is not permission to bypass review or a
180
+ claim of measured end-to-end speed.
181
+
182
+ An authenticated capability response adds `leaseFormats` with exact
183
+ `supported: ['matoi.controlled-transfer.v1', 'matoi.controlled-transfer.lease.v2']`,
184
+ `default: 'matoi.controlled-transfer.v1'` and a boolean `compactIssuanceEnabled`.
185
+ An absent `leaseFormats` object means legacy full-only support with compact
186
+ issuance disabled. A present object with missing or invalid members is rejected
187
+ as `INVALID_CAPABILITY`.
188
+ Support describes this reader, not current authorization or fleet readiness.
189
+
190
+ For operators, first qualify **all** owner, projection, status, SDK and evidence
191
+ readers with `OSUITE_MATOI_COMPACT_LEASE_ISSUANCE` absent or `0`. Only then enable
192
+ new compact issuance with exact `1`; any other value makes the owner unavailable.
193
+ The flag is not agent-controlled. Closing it prevents new compact preparations
194
+ but does not revoke existing leases, erase history or cancel transactions already
195
+ preparing. Verify/drain every writer rather than assuming the switch is atomic
196
+ across a fleet. Roll back to a qualified dual-reader build, never a full-only
197
+ reader while compact preparations or history remain. Use normal authority
198
+ revocation when existing admission must stop.
199
+
200
+ The format is immutable for an operation ID. Same-format calls return the original
201
+ preparation; a different format is `LEASE_FORMAT_CONFLICT`, not a replacement.
202
+ Before sending, a new compact request can fail with `LEASE_FORMAT_UNSUPPORTED`
203
+ or `COMPACT_LEASE_ISSUANCE_DISABLED`. After a POST, **any** non-2xx response or
204
+ invalid response binding retains `OUTCOME_UNKNOWN`, even if the HTTP response is
205
+ 400 or 409. Recover with `status(operationId)`, not another POST or a new ID.
206
+ A cold client seeking an existing compact record while issuance is off also uses
207
+ status. An old SDK encountering that record must be upgraded; do not strip fields
208
+ or present it as a full lease. Original v1 history remains readable.
209
+
210
+ ### Execute And Recover
211
+
212
+ Only after the actual Studio review, deliberately invoke:
213
+
214
+ ```js
215
+ const result = await transfers.execute(prepared, 0);
216
+ console.log(result.state, result.code, result.newlyCommitted);
217
+ ```
218
+
219
+ `execute(prepared, ordinal = 0)` sends a signed POST with the selected ordinal
220
+ and either the full signed `lease` or, when fresh capabilities advertise
221
+ `executionTransport: 'bound-reference-v1'`, the verified `preparationDigest`.
222
+ The server resolves that reference against the authenticated workspace, actor,
223
+ key and original operation, then verifies the stored signed lease. In either
224
+ transport, the SDK verifies the original preparation and any commitment receipt;
225
+ the server checks current authority and native Studio approval. The SDK never
226
+ runs a local side effect or executes remaining ordinals for you. An HTTP 200
227
+ `denied` decision, including `AWAITING_APPROVAL`, is returned unchanged with the
228
+ same review link; it is never treated as a commitment or automatically retried.
229
+ A deliberate later call after human review performs fresh capability checks.
230
+
231
+ A `committed` response is accepted only with a verified receipt matching the
232
+ current operation, action/fingerprint, preparation, epochs, evidence and exact
233
+ effect. `newlyCommitted: true` describes that acknowledged request only.
234
+ `already_committed` may return an earlier operation's receipt, including its
235
+ original ordinal, but its tenant, actor, grant and exact signed effect must
236
+ still match the current authorization. It always has `newlyCommitted: false`.
237
+ Re-reading an already verified result in this client never resends execution.
238
+
239
+ ### Derived Evidence Freshness
240
+
241
+ `execute()` results and every returned `status()` result include a separate,
242
+ immutable `projection` observation. MCP tool results expose the same normalized
243
+ public shape. Its profile is `matoi.controlled-transfer.projection.v1`, its scope
244
+ is always `derived-view`, and `authorizesExecution` is always `false`.
245
+
246
+ The view state is `current`, `pending_reconciliation`, `stale`, `failed`, or
247
+ `unavailable`. This is independent of the resource's `state`, signed receipt and
248
+ `newlyCommitted` flag. A pending, failed or unavailable view never invalidates a
249
+ verified `committed` or `already_committed` receipt and never permits a resend.
250
+ Even `current` is only a server-reported derived-view observation, not a new
251
+ authorization decision, independent proof validation or external settlement.
252
+
253
+ The remaining fields are always present, with missing optional values as null:
254
+
255
+ - `incarnation` and `artifactIncarnation`: lowercase UUID strings.
256
+ - `requestedGeneration`, `projectedGeneration`, and `artifactGeneration`:
257
+ canonical nonnegative decimal strings, at most PostgreSQL's signed bigint
258
+ maximum `9223372036854775807`. They never pass through JavaScript Number.
259
+ - `generatedAt` and `observedAt`: canonical 24-character UTC ISO timestamps.
260
+ - `lastError`: a machine code of at most 64 uppercase letters, digits or
261
+ underscores, starting with a letter, not arbitrary diagnostic text.
262
+
263
+ Absent legacy metadata, an unknown profile/scope/state, or malformed fields
264
+ produce `state: 'unavailable'` with null identities, generations, timestamps and
265
+ error. No observation time is invented. Arbitrary graph/debug extensions are
266
+ omitted. A known non-unavailable state requires an `observedAt` timestamp.
267
+ Additionally, `current` requires nonnull equal incarnation and artifact
268
+ incarnation, three equal positive generation strings, and nonnull canonical
269
+ timestamps with `generatedAt <= observedAt`. Inconsistent current claims become
270
+ unavailable before any cached downgrade to stale. These checks establish only
271
+ internal wire consistency, not cryptographic proof of server freshness.
272
+ Only this additive metadata is normalized; receipt signatures and the existing
273
+ unknown-outcome fences remain unchanged. The HTTP response limit and resource
274
+ snapshot limits remain unchanged, with the separately bounded projection
275
+ attached after resource snapshot validation.
276
+
277
+ A cached execute replay conservatively changes a previous `current` view to
278
+ `stale`, preserving its original `observedAt`, `generatedAt` and generations.
279
+ Other view states remain as previously observed. This does not trigger a GET or
280
+ POST. Explicit status reads, including GET-only recovery of an evicted receipt,
281
+ can return a new server observation; subsequent cached replays are stale again.
282
+
283
+ ## Unknown Outcomes And Recovery
284
+
285
+ A timeout, lost connection, unsuccessful HTTP response or malformed post-send
286
+ reply raises `ControlledTransferError` with `code: 'OUTCOME_UNKNOWN'`, the
287
+ original `operationId`, `retryAutomatically: false`, and `recovery.method:
288
+ 'status'`. A missing, invalid or substituted receipt is also unknown, **not**
289
+ proof that nothing executed. Even HTTP 400/401/503 after a POST is conservatively
290
+ unknown: a proxy or a lost response cannot prove the resource did not commit.
291
+
292
+ ```js
293
+ try {
294
+ await transfers.execute(prepared, 0);
295
+ } catch (error) {
296
+ if (error.code !== 'OUTCOME_UNKNOWN') throw error;
297
+ const observed = await transfers.status(error.operationId);
298
+ console.log(observed.state, observed.code);
299
+ // Stop here. Do not resend, generate another operation ID, or auto-approve.
300
+ }
301
+ ```
302
+
303
+ `status(operationId)` uses only authenticated GET requests with `operationId`
304
+ and `agent_id`. It never prepares, consumes approval or executes. It returns
305
+ `committed`, `partially_committed`, `denied`, `awaiting_approval`, `ready`, or `unknown`.
306
+ `ready` reports the owner's current native approval, not a local authorization
307
+ or an instruction to execute. Pending and denied native votes remain distinct.
308
+ All status results have `newlyCommitted: false`. Committed effects must carry
309
+ verified receipts; noncommitted observations are not permission to retry.
310
+ Outages, 404s, wrong scope, invalid receipts and malformed replies return
311
+ `state: 'unknown', code: 'OUTCOME_UNKNOWN'`, never a fabricated negative result.
312
+
313
+ An unknown outcome fences further mutations for that operation in this client,
314
+ even after a status read succeeds. The fence is **in memory**, not a durable
315
+ exactly-once claim. Applications must durably retain operation IDs, preparations
316
+ and uncertainty markers. After restart, recover through status, not by creating
317
+ a new client or ID to bypass uncertainty. A saved preparation may be supplied
318
+ to an intentional first execution; it is fully reverified before sending.
319
+
320
+ Each long-lived client keeps at most 16 hot operation payloads (preparations and
321
+ receipts), with active preparation, execution and recovery calls pinned against
322
+ eviction. Compact grant, preparation-binding, effect-count and receipt-digest
323
+ records, including every uncertainty fence, remain for up to 65,536 operation
324
+ IDs. A new ID at that limit, or a call needing a hot slot when all 16 are active,
325
+ fails with `CLIENT_CAPACITY_EXCEEDED` before sending a request; existing fences
326
+ are never evicted to admit new work. Preparing an evicted recorded ID recovers
327
+ its original preparation through authenticated GET, never another prepare POST.
328
+ Replaying an evicted locally acknowledged completion likewise verifies the
329
+ original preparation and receipt digests through GET and returns
330
+ `already_committed`, `newlyCommitted: false`, without an execution POST. Missing
331
+ or inconsistent history becomes `OUTCOME_UNKNOWN`; successful later status
332
+ reads do not clear that fence. Settled preparation promises and cold payloads
333
+ are released without resetting the client. These limits cover SDK-owned state,
334
+ not payloads retained by callers, and do not provide persistence across restart.
335
+
336
+ An optional `prepared` field in status is verified against the issuer, tenant,
337
+ actor/key, operation, grant, effect list and any retained preparation. Current
338
+ receipts must bind to that preparation. The verified immutable field exposes
339
+ the original lease and review link after restart or a lost preparation response,
340
+ without repeating approval creation. It does not clear an uncertainty fence.
341
+ Reading an expired original lease is permitted; sending it for execution is not.
342
+
343
+ With a retained or status-recovered preparation, status can also bind historical
344
+ payment receipts to its signed effect list. A cold client can verify receipts
345
+ for the requested current operation. A historical receipt without the current
346
+ preparation cannot prove the intended current effect and remains unknown. If no
347
+ issuer is pinned or previously learned, receipt/preparation-bearing status also
348
+ reads capabilities to obtain an authenticated key. A known/pinned key permits
349
+ status verification even when fresh action capabilities are unavailable.
350
+
351
+ ## Verification Contract
352
+
353
+ Lease and receipt signatures use Ed25519 over recursively sorted canonical JSON,
354
+ with canonical 86-character base64url signatures. `issuer` is SHA-256 of SPKI DER.
355
+ An explicit `issuerPublicKey` pin takes precedence; otherwise the authenticated
356
+ capability key is pinned for the lifetime of the client. A later key substitution
357
+ is rejected, not silently trusted.
358
+
359
+ Financial effects have exactly `operation`, `paymentId`, `sourceAccount`,
360
+ `destination`, `asset`, `network`, `amountMinor`, and `decimals`. Amounts are
361
+ positive canonical decimal integer strings of at most 38 digits; they never
362
+ pass through Number. Decimals are integers from 0 to 18. At most 64 effects are
363
+ accepted and payment IDs must be unique within the signed preparation.
364
+
365
+ The finance profile defines the effect digest as
366
+ `SHA256(canonicalJson(["matoi.controlled-transfer.v1", "effect", effect]))`.
367
+ The SDK uses this solely to verify the expected effect against the signed lease
368
+ at its ordinal and against a signed resource receipt. It does not produce
369
+ financial workflow evidence or substitute for the resource's independent check.
370
+ `preparationDigest` is SHA-256 of the canonical lease payload. The client allows
371
+ 30 seconds of forward clock skew for issuance/commitment timestamps; current
372
+ commitments must fall within their signed lease lifetime. Expired leases cannot
373
+ be used for a new send, but historical status remains verifiable.
374
+
375
+ Native approval fingerprints use `apfp_<64 lowercase hex>`; unprefixed fixture
376
+ fingerprints are also accepted. Exact values are compared, never normalized.
377
+ Optional per-effect `lease.payload.passes` remain signed CAVA/ZeroGate evidence,
378
+ not local execution permission. Financial actions stay high-risk and require
379
+ the slow-approved native review route; there is no fast-path latency promise.
380
+
381
+ For receipts bound to a compact source preparation, the signed `gate` is
382
+ mandatory; legacy full-source receipts without it remain accepted. When present,
383
+ it must use `lane: 'slow-approved'` and a canonical decimal-string
384
+ `admissionSequence`. Its actual ZeroGate receipt must retain the
385
+ `slow`/`review`/`risk_exceeds_fast_lane` result, correct hash, source ordinal and
386
+ timestamp. It binds to that original source preparation's pass commitment (or
387
+ full pass when available), not to a later operation's position for the payment.
388
+ The enclosing signed owner receipt, not that review receipt alone, acknowledges
389
+ commitment. If an earlier source preparation is unavailable, historical signature
390
+ and effect checks alone do not establish its pass commitment. Auxiliary
391
+ `projection` metadata is normalized separately by the client and is not financial
392
+ commitment evidence.
393
+
394
+ When its original source preparation is known, a receipt must also use that
395
+ source lease's issuer. Trusting both an old and a current public key does not
396
+ allow the current key to re-sign the old lease's receipt as if it were the
397
+ original. Valid old-key receipts remain verifiable after rotation; unknown
398
+ source history retains the narrower signature/effect-only guarantee above.
399
+
400
+ ## Doctor Integration
401
+
402
+ The doctor module exports these functions, with no import-time I/O:
403
+
404
+ ```js
405
+ import { probeMatoiStatus, formatMatoiStatus } from './matoiDoctor.mjs';
406
+
407
+ const status = await probeMatoiStatus({ config });
408
+ const output = formatMatoiStatus(status);
409
+ ```
410
+
411
+ The prober performs at most one capability GET and never mutates. It separates
412
+ `installed`, `localConfigured`, `configured`, `serverConfigured`,
413
+ `capabilityAvailable`, `resourceEnforced`, and the server's `qualification`.
414
+ Unavailable qualification is null and displays as unknown; valid qualifications
415
+ are explicitly labeled server-reported. Configuration failures are returned as
416
+ diagnostic codes without exposing credentials.
417
+
418
+ ```sh
419
+ osuite doctor --controlled-transfers
420
+ osuite doctor --require-controlled-transfers
421
+ osuite doctor --controlled-transfers --runtime mcp
422
+ ```
423
+
424
+ Both strict flags run only this diagnostic, not the ordinary health/Hook probes
425
+ or opt-in onboarding measurements. Exit zero requires strict local configuration
426
+ and authenticated, configured resource enforcement. It does not certify deployment
427
+ qualification; `not-qualified` remains visible. Ordinary `osuite doctor` adds a
428
+ non-gating Matoi diagnostic: lack of this optional profile does not fail an
429
+ otherwise healthy old SDK installation or change ordinary Hook behavior.
430
+
431
+ Strict commands select exactly one protected credential bundle: `.osuite/.env`
432
+ for SDK doctor, or `.osuite/mcp/.env` for MCP and `doctor --runtime mcp`. They never
433
+ load `.codex/.env`, `.claude/.env`, `.cursor/.env` or the project's root `.env`.
434
+ The bundle must provide `OSUITE_BASE_URL`, `OSUITE_API_KEY`,
435
+ `OSUITE_PRIVATE_KEY_BASE64`, `OSUITE_ORG_ID`, `OSUITE_AGENT_ID`,
436
+ `OSUITE_SIGNATURE_MODE=required`, `OSUITE_GUARD_FAILURE_MODE=block`, and the matching
437
+ `OSUITE_RUNTIME_ADAPTER_ID` (`sdk`, `framework_sdk`, `inline_sdk`, or `mcp` for MCP).
438
+ An optional `OSUITE_AGENT_KEY_ID` asserts the credential key identity.
439
+
440
+ A complete explicit shell configuration is usable when the selected bundle is
441
+ absent. With a bundle present, explicit shell configuration must agree with it;
442
+ partial bundles cannot borrow missing keys or identities from another source.
443
+ Conflicting `OSUITE_*`/`DASHCLAW_*` aliases and duplicate assignments are rejected.
444
+ Optional `OSUITE_MATOI_TIMEOUT_MS` sets the bounded request timeout;
445
+ `OSUITE_MATOI_ISSUER_PUBLIC_KEY_BASE64` pins base64-encoded Ed25519 SPKI PEM.
446
+
447
+ Unsafe, tracked, non-ignored, symlinked or non-owner-only credential files are
448
+ refused using the existing credential inspector. A selected connect journal or
449
+ lock, or any pending SDK/MCP migration marker, blocks strict commands. They do
450
+ not repair files, resume enrollment, merge identities, or print secrets.
451
+
452
+ ## Controlled MCP
453
+
454
+ ```js
455
+ import { createControlledTransferMcpServer } from 'osuite/controlled-transfers';
456
+
457
+ const server = createControlledTransferMcpServer(config);
458
+ const { tools } = server.listTools();
459
+ // The CLI uses server.handleRequest(jsonRpcRequest).
460
+ // Embedded callers may explicitly use server.callTool(name, argumentsObject).
461
+ ```
462
+
463
+ Only `osuite_transfer_prepare(operationId, grantId)`,
464
+ `osuite_transfer_execute(prepared, ordinal = 0)`, and
465
+ `osuite_transfer_status(operationId)` are exposed. They delegate to the real
466
+ client; there is no local payment function, automatic approval, or generic MCP
467
+ execution gateway. Tool arguments reject extra keys. Results preserve pending,
468
+ refusal and unknown states. `effect_executed` is true only for a newly verified
469
+ commitment, false for `already_committed`, pending, refusals and read-only known
470
+ observations, and null for unknown outcomes. Status never claims a new effect.
471
+ Results include only the bounded public freshness fields under `projection`,
472
+ not configuration, arbitrary server debug data or full projection graphs.
473
+
474
+ ```sh
475
+ osuite mcp --controlled-transfers
476
+ ```
477
+
478
+ This explicit lane uses `sdk/controlled-transfers-stdio.mjs`, not the ordinary
479
+ runtime MCP bridge. It accepts UTF-8 NDJSON, limits an input frame to 1 MiB and
480
+ buffered input to 2 MiB, and awaits each request and output before the next. The
481
+ frame limit uses `CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES`. Stdout contains
482
+ JSON-RPC only. Invalid JSON/UTF-8 or oversized framing emits a bounded protocol
483
+ error and stops rather than dispatching queued mutations. Initialization and
484
+ tool listing do not contact the server or change files. No arbitrary-MCP safety
485
+ or full-stack deployment protection is implied.
486
+
487
+ ## Local Contract Tests
488
+
489
+ Run with Node 24:
490
+
491
+ ```sh
492
+ node --test sdk/controlled-transfers/test/*.test.mjs
493
+ node node_modules/vitest/vitest.mjs run __tests__/unit/matoi-cli.test.js
494
+ ```
495
+
496
+ Tests use ephemeral loopback HTTP servers, real local RSA/Ed25519 signatures and
497
+ offline package inspection. Fixture receipts test client verification only;
498
+ they are not evidence of real financial writes, native Studio review, or
499
+ deployment qualification. Owner/PostgreSQL/live route acceptance is a separate
500
+ integration gate.
501
+
502
+ ## Transport And Rotation In The 2.12.0 Candidate
503
+
504
+ The `2.12.0` source candidate is not proof of registry publication or a qualified
505
+ server deployment. When fresh capabilities advertise
506
+ `executionTransport: 'bound-reference-v1'`, the execute POST sends the verified
507
+ `preparationDigest` instead of repeating the complete signed `lease`. The client
508
+ still verifies the original preparation, selected ordinal and returned receipt;
509
+ the reference is not a new approval or an unsigned local execution shortcut.
510
+ Without that advertisement, the existing full-lease request format is retained.
511
+ No timeout, transport fallback or oversized response authorizes a resend.
512
+
513
+ For rotation, explicitly pin the current Ed25519 issuer and retain only reviewed
514
+ previous public roots in `trustedIssuerPublicKeys`. Status may verify the
515
+ original historical preparation and receipt with those roots, without replacing
516
+ their signatures or making a POST. A retired issuer cannot authorize a fresh
517
+ preparation or execution, even when trusted for historical reads. Fence old
518
+ writers and preserve authoritative payment history before activating a rotated
519
+ or restored owner; missing history remains quarantine, not fresh spend capacity.
520
+
521
+ In the standalone public source export, run `npm run test:controlled-transfers`
522
+ on Node 24 for the transport, client contract, rotation, doctor, package and
523
+ strict CLI checks. The existing Node 24 `test:governed-tools` CI gate also runs
524
+ this command. The exported `source-manifest.json` records the five exact-name
525
+ private-owner test exclusions and their reason. The full repository commands
526
+ above retain those tests; no private owner implementation is exported. Ordinary
527
+ SDK compatibility remains a separate unchanged `npm run test:compat` gate.
package/cli.js CHANGED
@@ -145,7 +145,7 @@ function loadDotenvFile(relativePath) {
145
145
 
146
146
  function loadProjectEnvironment() {
147
147
  // Enrollment selects one whole runtime bundle, never a merged global env.
148
- if (process.argv[2] === 'connect') return;
148
+ if (process.argv[2] === 'connect' || CONTROLLED_TRANSFER_CLI) return;
149
149
  [...CLI_CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
150
150
  if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
151
151
  loadDotenvFile(relativePath);
@@ -174,6 +174,8 @@ function parseArgs(argv) {
174
174
 
175
175
  // Hooks run with the agent's environment, not the values this CLI loads from project .env files.
176
176
  const SHELL_ENV = { ...process.env };
177
+ const CONTROLLED_TRANSFER_CLI = ['doctor', 'mcp'].includes(process.argv[2])
178
+ && process.argv.slice(3).some(value => /^--(?:controlled-transfers|require-controlled-transfers)(?:=|$)/.test(value));
177
179
  loadProjectEnvironment();
178
180
 
179
181
  function envValue(name, fallback) {
@@ -729,6 +731,9 @@ function printHelp() {
729
731
  write('');
730
732
  write(c('Useful commands', ANSI.bold));
731
733
  write(' osuite doctor Check connection, then run the project hook with a sample call');
734
+ write(' osuite doctor --controlled-transfers Read strict profile capabilities only (Node 24; --runtime sdk|mcp)');
735
+ write(' --require-controlled-transfers is an alias; this does not certify deployment qualification');
736
+ write(' osuite mcp --controlled-transfers Three controlled-ledger tools over bounded NDJSON stdio (Node 24)');
732
737
  write(' osuite try Review one fixed, harmless terminal acknowledgement');
733
738
  write(' osuite status Ping Studio and show current workspace connection');
734
739
  write(' osuite explain "git push origin main" Explain how CAVA/Decision V2 will read a command');
@@ -1183,6 +1188,37 @@ function printExplanation(command) {
1183
1188
  }
1184
1189
  }
1185
1190
 
1191
+ async function controlledTransferDiagnosis({ strict = false, runtime = 'sdk' } = {}) {
1192
+ const { probeMatoiStatus, formatMatoiStatus } = await import('./matoiDoctor.mjs');
1193
+ const { loadControlledTransferCliConfig } = await import('./controlled-transfers/cli-config.mjs');
1194
+ let status;
1195
+ try {
1196
+ const config = loadControlledTransferCliConfig({ projectRoot: process.cwd(), shellEnv: SHELL_ENV, runtime });
1197
+ status = await probeMatoiStatus({ config });
1198
+ } catch (error) {
1199
+ status = { ...await probeMatoiStatus(), code: error.code || 'INVALID_CONFIGURATION' };
1200
+ }
1201
+ write(formatMatoiStatus(status));
1202
+ if (strict && !status.configured) process.exitCode = 1;
1203
+ return status.configured === true;
1204
+ }
1205
+
1206
+ async function controlledTransferCommand(command, args) {
1207
+ const { fail } = await import('./controlled-transfers/contract.mjs');
1208
+ const allowed = command === 'doctor' ? ['_', 'controlled-transfers', 'require-controlled-transfers', 'runtime'] : ['_', 'controlled-transfers'];
1209
+ if (args._.length || Object.keys(args).some(key => !allowed.includes(key))
1210
+ || ['controlled-transfers', 'require-controlled-transfers'].some(key => Object.hasOwn(args, key) && args[key] !== true)
1211
+ || (command === 'mcp' && args['controlled-transfers'] !== true)
1212
+ || (command === 'doctor' && args.runtime !== undefined && !['sdk', 'mcp'].includes(args.runtime))) {
1213
+ fail('INVALID_CONTROLLED_TRANSFER_OPTIONS');
1214
+ }
1215
+ if (command === 'doctor') return controlledTransferDiagnosis({ strict: true, runtime: args.runtime || 'sdk' });
1216
+ const { loadControlledTransferCliConfig } = await import('./controlled-transfers/cli-config.mjs');
1217
+ const { runControlledTransferStdio } = await import('./controlled-transfers-stdio.mjs');
1218
+ const config = loadControlledTransferCliConfig({ projectRoot: process.cwd(), shellEnv: SHELL_ENV, runtime: 'mcp' });
1219
+ if (!await runControlledTransferStdio(config)) process.exitCode = 1;
1220
+ }
1221
+
1186
1222
  async function doctor() {
1187
1223
  const config = readConfig();
1188
1224
  let ok = true;
@@ -1246,6 +1282,8 @@ async function doctor() {
1246
1282
  if (!hookChecks.length) writeCheckLine('miss', 'Agent hooks', 'none in this project (fine for SDK and MCP runtimes)');
1247
1283
  const hooksOk = hookChecks.every((check) => check.ok);
1248
1284
 
1285
+ write('');
1286
+ await controlledTransferDiagnosis();
1249
1287
  write('');
1250
1288
  if (!ok || !hooksOk) {
1251
1289
  write(c('Next step', ANSI.bold));
@@ -1775,6 +1813,7 @@ async function main() {
1775
1813
 
1776
1814
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1777
1815
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1816
+ if (CONTROLLED_TRANSFER_CLI) return controlledTransferCommand(command, args);
1778
1817
  if (command === 'doctor') return runDoctorWithMeasurement(doctor, { config: readConfig(), emit: write });
1779
1818
  if (command === 'try') return tryWalkthrough(args);
1780
1819
  if (command === 'status') return status();
@@ -1796,6 +1835,9 @@ async function main() {
1796
1835
  }
1797
1836
 
1798
1837
  main().catch((error) => {
1799
- process.stderr.write(`${error?.message || String(error)}\n`);
1838
+ const message = CONTROLLED_TRANSFER_CLI
1839
+ ? /^[A-Z][A-Z0-9_]{0,63}$/.test(error?.code) ? `Matoi ${error.code}` : 'Matoi CONTROLLED_TRANSFER_COMMAND_FAILED'
1840
+ : error?.message || String(error);
1841
+ process.stderr.write(`${message}\n`);
1800
1842
  process.exit(1);
1801
1843
  });