@ultimat3/action 23.0.0 → 25.0.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.
@@ -79,10 +79,25 @@ interface Refusals {
79
79
  readonly unauthorizedHeaders?: Record<string, unknown>;
80
80
  }
81
81
 
82
+ /**
83
+ * An ACTION's limit is spent inside `invoke`, so its route carries no bucket to read; the operation
84
+ * itself publishes the declaration (`x-ultimate.rateLimit`, `null` when none). A query's route
85
+ * still does, hence both reads above.
86
+ */
87
+ function declaresRateLimit(operation: Operation): boolean {
88
+ const extensions = operation['x-ultimate'];
89
+ if (typeof extensions !== 'object' || extensions === null) return false;
90
+ const declared = (extensions as Record<string, unknown>)['rateLimit'];
91
+ return declared !== undefined && declared !== null;
92
+ }
93
+
82
94
  /** One operation, with its route's refusals and security added. Never mutates `operation`. */
83
95
  function completeOperation(operation: Operation, route: Route | undefined, refusals: Refusals) {
84
96
  const authenticated = route?.meta.auth === 'required';
85
- const limited = refusals.everyOpLimited || route?.meta.rateLimitBucket !== undefined;
97
+ const limited =
98
+ refusals.everyOpLimited ||
99
+ route?.meta.rateLimitBucket !== undefined ||
100
+ declaresRateLimit(operation);
86
101
  if (!authenticated && !limited) return operation;
87
102
  const responses = { ...(operation['responses'] as Record<string, unknown>) };
88
103
  if (limited) {
package/src/openapi.ts CHANGED
@@ -76,7 +76,12 @@ function compareByName(a: AnyAction, b: AnyAction): number {
76
76
  return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
77
77
  }
78
78
 
79
- /** RFC 9457 + the Ultimate error contract (code / cause / fix / docs). */
79
+ /**
80
+ * RFC 9457 + the Ultimate error contract, member for member what `@ultimat3/http`'s `toProblem`
81
+ * serves (`openapi-problem.test.ts` compares the two). `code` carries no `pattern`: `factsOf`
82
+ * serves whatever string an app's own throwable holds, and a published pattern the server breaks
83
+ * makes a generated client reject the very document it was written to read.
84
+ */
80
85
  const PROBLEM_SCHEMA: JsonSchemaObject = {
81
86
  type: 'object',
82
87
  required: ['type', 'title', 'status', 'code'],
@@ -85,9 +90,27 @@ const PROBLEM_SCHEMA: JsonSchemaObject = {
85
90
  title: { type: 'string' },
86
91
  status: { type: 'integer' },
87
92
  detail: { type: 'string' },
88
- code: { type: 'string', pattern: '^X_[A-Z0-9_]+$' },
93
+ instance: { type: 'string' },
94
+ code: { type: 'string' },
89
95
  cause: { type: 'string' },
90
96
  fix: { type: 'string' },
91
97
  docs: { type: 'string', format: 'uri' },
98
+ requestId: { type: 'string' },
99
+ // Absent when the failure produced none — never `[]`, which would claim "validated clean".
100
+ issues: {
101
+ type: 'array',
102
+ items: {
103
+ type: 'object',
104
+ required: ['path', 'expected', 'received', 'message'],
105
+ properties: {
106
+ path: { type: 'string' },
107
+ expected: { type: 'string' },
108
+ received: { type: 'string' },
109
+ message: { type: 'string' },
110
+ },
111
+ },
112
+ },
113
+ // Only the keys the code declared through `registerProblemMeta`; its shape is per code.
114
+ meta: { type: 'object' },
92
115
  },
93
116
  };
@@ -1,18 +1,13 @@
1
1
  /**
2
2
  * The single point of contact with @ultimat3/policy. Every surface (HTTP, MCP,
3
- * job, direct server call) reaches authz through `guard()` — there is no second
3
+ * job, direct server call) reaches authz through `guardAction()` — there is no second
4
4
  * code path, which is what makes "one authz system" true rather than aspirational.
5
5
  */
6
6
 
7
7
  import type { Actor, Ctx } from '@ultimat3/core';
8
- import { assertNever, isAnonymous } from '@ultimat3/core';
8
+ import { assertNever } from '@ultimat3/core';
9
9
  import type { Policy, Surface as PolicySurface } from '@ultimat3/policy';
10
- import {
11
- enforce,
12
- enforceBeforeInput,
13
- policyPermissions as flattenedPermissions,
14
- admitsAnonymous as policyAdmitsAnonymous,
15
- } from '@ultimat3/policy';
10
+ import { enforce, enforceBeforeInput } from '@ultimat3/policy';
16
11
  import { ActionDeniedError } from './errors';
17
12
 
18
13
  /**
@@ -45,7 +40,7 @@ export interface PolicySubject {
45
40
  * object for every surface, so an actor denied over HTTP is denied over MCP with
46
41
  * the same reason and the same code.
47
42
  */
48
- export function guard(policy: ActionPolicy, subject: PolicySubject, surface: Surface): void {
43
+ export function guardAction(policy: ActionPolicy, subject: PolicySubject, surface: Surface): void {
49
44
  const denial = enforce(policySurface(surface), policy, {
50
45
  input: subject.input,
51
46
  actor: subject.actor,
@@ -58,13 +53,13 @@ export function guard(policy: ActionPolicy, subject: PolicySubject, surface: Sur
58
53
  }
59
54
 
60
55
  /**
61
- * The actor-only half of `guard`, run BEFORE the input is parsed: a caller the policy refuses
56
+ * The actor-only half of `guardAction`, run BEFORE the input is parsed: a caller the policy refuses
62
57
  * whatever they send gets the 403 (or 401) here, and never the 400 whose issue list describes
63
58
  * the input schema of an operation they may not call. Undecided — a predicate that reads the input
64
- * or the row — passes, and `guard` decides after the parse exactly as before. Same denial class,
65
- * same code, same surface rendering as `guard`'s.
59
+ * or the row — passes, and `guardAction` decides after the parse exactly as before. Same denial
60
+ * class, same code, same surface rendering as `guardAction`'s.
66
61
  */
67
- export function guardBeforeInput(
62
+ export function guardActionBeforeInput(
68
63
  policy: ActionPolicy,
69
64
  subject: Omit<PolicySubject, 'input' | 'row'>,
70
65
  surface: Surface,
@@ -90,41 +85,3 @@ function policySurface(surface: Surface): PolicySurface {
90
85
  return assertNever(surface);
91
86
  }
92
87
  }
93
-
94
- /**
95
- * Core models "nobody" as an anonymous actor; policy models it as `null`, which is
96
- * what turns a missing session into `X_UNAUTHENTICATED` instead of a bare denial.
97
- */
98
- export function actorOf(ctx: Ctx): Actor | null {
99
- return isAnonymous(ctx.actor) ? null : ctx.actor;
100
- }
101
-
102
- /** The capability an action requires, for manifests and OpenAPI metadata. A DISPLAY label. */
103
- export function policyCapability(policy: ActionPolicy): string {
104
- return policy.label;
105
- }
106
-
107
- /**
108
- * Every permission the policy tree references, flattened and deduped — and the only field a
109
- * compliance report may match a grant against. `label` renders a composite as
110
- * `and(post:publish, org:administer)`, which is a sentence and never equals a permission string,
111
- * so matching on it reported every action guarded by a composite as enforcing nothing: `x policy
112
- * list` showed real grants as dead. The two are kept side by side rather than one replacing the
113
- * other — the label is what a human reads, this is what a machine compares.
114
- */
115
- export function policyPermissions(policy: ActionPolicy): readonly string[] {
116
- return flattenedPermissions(policy);
117
- }
118
-
119
- /**
120
- * Whether a policy admits an ANONYMOUS caller — `@ultimat3/policy`'s answer, re-exported here so
121
- * `http.ts` reads it through this file like every other authz question. `toRoute` derives
122
- * `meta.auth` from it, never from `policy.kind === 'allow'`: that read looked at the ROOT
123
- * combinator only, so `or(allow(), can('x:y'))` was 401'd by the pipeline before `invoke` ran
124
- * while the MCP tool and the job handle allowed it. `true` is not "unguarded" — `invoke` still
125
- * evaluates the policy for every call. Declared once in `policy.ts`, exactly as
126
- * `policyPermissions` is: the answer is a property of the combinators it walks.
127
- */
128
- export function admitsAnonymous(policy: ActionPolicy): boolean {
129
- return policyAdmitsAnonymous(policy);
130
- }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Where a declared `rateLimit:` is spent: once, inside `invoke`, so HTTP, MCP, the in-app agent
3
+ * tool and `.job()` draw on ONE bucket. The store is `@ultimat3/http`'s installed one — the slot
4
+ * `@ultimat3/query` spends from too, filled at boot with the instance `httpServer` is handed.
5
+ */
6
+
7
+ import type { Ctx } from '@ultimat3/core';
8
+ import { asyncContext, isAnonymous } from '@ultimat3/core';
9
+ import type { RateLimitDecision } from '@ultimat3/http';
10
+ // The bucket maths, the subject precedence and the refusal are all `@ultimat3/http`'s (tier 2):
11
+ // a copy here would be a second answer to "what does this limit mean" and "whose bucket is it".
12
+ import { installedRateLimitStore, rateLimited, rateLimitSpends, toBucket } from '@ultimat3/http';
13
+ import type { ActionRateLimit } from './action';
14
+ import type { Surface } from './policy-gate';
15
+
16
+ /**
17
+ * Who a call chain started from: the address of the request, or the fact that it is a job run.
18
+ * An `agent()` is an action whose handler calls its tools through `invoke` with no address of its
19
+ * own, so without this every anonymous visitor's tool calls shared one `ip:unknown` bucket and one
20
+ * visitor could exhaust it for all. Opened by `invoke`; read by every nested call that has none.
21
+ */
22
+ interface CallerFrame {
23
+ readonly address: string | null;
24
+ /** Inside a job run: nested calls are the job's, never a visitor's. */
25
+ readonly job: boolean;
26
+ }
27
+
28
+ const callerFrame = asyncContext<CallerFrame>('the caller frame');
29
+
30
+ /** Run `fn` with `address` as the inherited caller address; an absent one changes nothing. */
31
+ export function withCallerAddress<T>(address: string | null | undefined, fn: () => T): T {
32
+ return typeof address === 'string' && address !== ''
33
+ ? callerFrame.run({ address, job: false }, fn)
34
+ : fn();
35
+ }
36
+
37
+ /**
38
+ * Run `fn` as a job: no inherited address, and every nested call unattributed unless it has an
39
+ * actor or an org of its own. A FRESH frame, not a read of the current one — a worker loop re-armed
40
+ * by `setTimeout` inside a request carries that request's frame, and a tenantless job charged to
41
+ * whichever visitor happened to start the loop is the leak this closes.
42
+ */
43
+ export function withJobFrame<T>(fn: () => T): T {
44
+ return callerFrame.run({ address: null, job: true }, fn);
45
+ }
46
+
47
+ /**
48
+ * The subject of a job run nobody attributed — no actor, no tenant. Its own population: sharing
49
+ * `ip:unknown` let a flood of unaddressed anonymous requests park every tenantless job, and the
50
+ * reverse. Still ONE bucket for all such runs, deliberately: unlimited is the abuse this exists for.
51
+ */
52
+ const UNATTRIBUTED_JOB = 'job:unattributed';
53
+
54
+ /**
55
+ * Namespaced, never the bare action name: the HTTP pipeline still spends its `default` bucket
56
+ * under `<route name>|<subject>`, and one key taken against two bucket shapes in one store would
57
+ * corrupt both counters.
58
+ */
59
+ const ACTION_SCOPE = 'action';
60
+
61
+ export interface RateLimitSpendOptions {
62
+ readonly surface: Surface;
63
+ /** The connection address — the only subject an anonymous caller has. */
64
+ readonly clientAddress?: string | null | undefined;
65
+ /** The decision, before a refusal is thrown: how HTTP puts `RateLimit-*` on the answer. */
66
+ readonly onRateLimit?: ((decision: RateLimitDecision) => void) | undefined;
67
+ }
68
+
69
+ /**
70
+ * Spend one token of `limit` for this caller, or throw `X_RATE_LIMITED` — the code, the cause and
71
+ * the `Retry-After` seconds every limit in the framework answers with.
72
+ *
73
+ * `surface: 'server'` spends nothing: that is app code calling its own action in-process (a
74
+ * service composing two, a seed, a test), not a caller arriving from outside. A refused attempt
75
+ * spends nothing either — the token bucket only decrements on an admission — so a job retried
76
+ * into a refusal is not charged for it.
77
+ */
78
+ export async function spendActionLimit(
79
+ name: string,
80
+ limit: ActionRateLimit | undefined,
81
+ ctx: Ctx,
82
+ options: RateLimitSpendOptions,
83
+ ): Promise<void> {
84
+ if (limit === undefined || options.surface === 'server') return;
85
+ const frame = callerFrame.get();
86
+ // A job run, or any call nested inside one (an `agent()` run as a job calling its tools as
87
+ // `'mcp'`): never a visitor's address, and the unattributed bucket rather than `ip:unknown`.
88
+ const inJob = options.surface === 'job' || frame?.job === true;
89
+ const spends = rateLimitSpends(
90
+ {
91
+ actorId: isAnonymous(ctx.actor) ? null : ctx.actor.id,
92
+ // Read off an anonymous actor too: a job run IS the worker's anonymous identity carrying the
93
+ // job's org (`jobRunActor`), and that org is who the run is — charging every tenant's runs
94
+ // to one `ip:unknown` key let one tenant's backlog refuse everyone's.
95
+ orgId: ctx.actor.orgId ?? null,
96
+ ip: options.clientAddress ?? (inJob ? null : (frame?.address ?? null)),
97
+ routeName: `${ACTION_SCOPE}:${name}`,
98
+ ...(inJob ? { unattributed: UNATTRIBUTED_JOB } : {}),
99
+ },
100
+ // The tenant allowance is the HTTP pipeline's (it spends it for every route, a handler-limited
101
+ // one included); counting it here too would charge an HTTP call against the tenant twice.
102
+ { route: name, tenant: null },
103
+ );
104
+ for (const spend of spends) {
105
+ const decision = await installedRateLimitStore().take(
106
+ spend.key,
107
+ toBucket(name, limit),
108
+ 1,
109
+ ctx.now().getTime(),
110
+ );
111
+ options.onRateLimit?.(decision);
112
+ if (!decision.allowed) throw rateLimited(spend.key, decision.retryAfterSeconds);
113
+ }
114
+ }
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { encodeRecordEnvelope, RECORDS_HEADER } from '@ultimat3/core';
8
8
  import { hasEntityRows, rowsOf } from '@ultimat3/entity';
9
- import { json } from '@ultimat3/http';
9
+ import { jsonResponse } from '@ultimat3/http';
10
10
  import type { StandardSchemaV1 } from '@ultimat3/schema';
11
11
 
12
12
  /** The header value that says "this body is an envelope". Presence alone is not enough. */
@@ -26,7 +26,7 @@ export function carriesRecords(output: StandardSchemaV1): boolean {
26
26
 
27
27
  /** The 200 for an action that carries records: the envelope, and the header that names it. */
28
28
  export function recordResponse(output: StandardSchemaV1, result: unknown): Response {
29
- const response = json(encodeRecordEnvelope(result, rowsOf(output, result)));
29
+ const response = jsonResponse(encodeRecordEnvelope(result, rowsOf(output, result)));
30
30
  response.headers.set(RECORDS_HEADER, ENVELOPED);
31
31
  return response;
32
32
  }
package/src/registry.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import type { ActionPathStyle } from '@ultimat3/core';
8
- import { SchemaUnsupportedError } from '@ultimat3/schema';
8
+ import { SchemaUnsupportedError, toWireSchema } from '@ultimat3/schema';
9
9
  import type { ActionDescriptor, AnyAction } from './action';
10
10
  import { isAction, nameAction } from './action';
11
11
  import { resetApiDeclaration } from './api-declaration';
@@ -19,7 +19,7 @@ import {
19
19
  } from './http-path';
20
20
  import { assertIdempotencyScope } from './idempotency';
21
21
  import { defOf } from './invoke';
22
- import { jsonSchemaOf, mcpSchemaOf } from './json-schema';
22
+ import { jsonSchemaOf } from './json-schema';
23
23
  import type { ActionPath } from './naming';
24
24
  import { seatedActions } from './registry-store';
25
25
 
@@ -111,7 +111,8 @@ function assertProjectable(name: string, target: AnyAction): void {
111
111
  for (const field of ['input', 'output'] as const) {
112
112
  try {
113
113
  jsonSchemaOf(target[field]);
114
- mcpSchemaOf(target[field]);
114
+ // The schema `tools/list` publishes — the one an MCP client reads.
115
+ toWireSchema(target[field]);
115
116
  } catch {
116
117
  // The thrown value is deliberately not rendered into the cause: it is the provider's, of
117
118
  // unknown shape, and this package's own two facts — which action, which field — are the
@@ -153,7 +154,7 @@ export function describeActions(): readonly ActionDescriptor[] {
153
154
  }
154
155
 
155
156
  /** Test-only. Production registers once at boot and never unregisters. */
156
- export function resetRegistry(): void {
157
+ export function resetActions(): void {
157
158
  registry.clear();
158
159
  paths.clear();
159
160
  resetActionPathStyle();
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The app's request deadline — how long an idempotency record bound to a transaction may stay in
3
+ * flight before a retry takes the key. Read from `@ultimat3/http`'s own declaration and resolved
4
+ * by its own `defineHttpConfig`, so the default and its screen are never restated here.
5
+ */
6
+ import { configuredHttp, defineHttpConfig } from '@ultimat3/http';
7
+
8
+ let resolved: { readonly declared: number | undefined; readonly ms: number } | undefined;
9
+
10
+ /**
11
+ * `configureHttp({ requestTimeoutMs })`, else http's default; `0` is "no deadline". Read on every
12
+ * call because the app declares it at module scope AFTER the boot has built its stores — resolved
13
+ * once per declared value, since `defineHttpConfig` screens a whole config to answer one field.
14
+ */
15
+ export function requestDeadlineMs(): number {
16
+ const declared = configuredHttp()?.requestTimeoutMs;
17
+ if (resolved === undefined || resolved.declared !== declared) {
18
+ const config = defineHttpConfig({
19
+ ...(declared === undefined ? {} : { requestTimeoutMs: declared }),
20
+ rateLimit: { enabled: false, scope: 'process' },
21
+ });
22
+ resolved = { declared, ms: config.requestTimeoutMs };
23
+ }
24
+ return resolved.ms;
25
+ }
package/src/stable.ts CHANGED
@@ -9,13 +9,6 @@
9
9
  * published. Ordinary payloads are byte-identical between the two; `stable.test.ts` pins that.
10
10
  */
11
11
 
12
- /**
13
- * `@ultimat3/core`'s, re-exported so `./stable` stays this package's one import path for the JSON
14
- * helpers. It was declared here AND identically in `@ultimat3/query`'s own `stable.ts`, which is
15
- * the duplication `client-wire.ts` moving to tier 0 made unnecessary.
16
- */
17
- export { isJsonObject } from '@ultimat3/core';
18
-
19
12
  export type JsonObject = Record<string, unknown>;
20
13
 
21
14
  /** JSON with object keys sorted at every depth. No timestamps, no insertion-order leaks. */
package/src/transition.ts CHANGED
@@ -17,15 +17,14 @@ import type {
17
17
  StandardSchemaV1,
18
18
  StringSchema,
19
19
  } from '@ultimat3/schema';
20
- import { t } from '@ultimat3/schema';
20
+ import { nodeOf, t } from '@ultimat3/schema';
21
21
  import { type Mutator, mutator } from './mutator';
22
22
  import type { ActionPolicy } from './policy-gate';
23
23
 
24
24
  /**
25
25
  * The one method this factory calls, declared structurally: `@ultimat3/entity`'s `Table.transition`
26
- * satisfies it as written. Structural and not an import because `@ultimat3/action` holds no
27
- * dependency edge on `@ultimat3/entity` — the tier table permits one (2 is below 3), the manifest
28
- * and the lockfile do not — the same trade `@ultimat3/db`'s `entity-shape.ts` makes one tier down.
26
+ * satisfies it as written. Structural because it is all this file needs of a table — one method —
27
+ * and a fake that implements it is the whole test seam; the package does import entity elsewhere.
29
28
  *
30
29
  * `id` is a plain `string` rather than entity's `IdOf<Row>`: that alias "collapses to `string` for
31
30
  * every unbranded entity" by its own account, and a branded one still satisfies this because a
@@ -69,16 +68,22 @@ export interface TransitionDef<
69
68
  * tool's `inputSchema` carries it, the typed client refuses a typo at COMPILE time, and a
70
69
  * misspelled state is `X_INPUT_INVALID` before the request reaches a database.
71
70
  *
72
- * It is the one thing restated from the column's own declaration, and the reason is a boundary:
73
- * reading the machine off the entity needs `@ultimat3/entity` as a real dependency of this
74
- * package. Listing a SUBSET refuses a legal move at the input schema — loud, and the fix is the
75
- * enum in the refusal.
71
+ * It is the one thing restated from the column's own declaration: `table` is resolved per request
72
+ * (`(ctx) => …`), and the input schema is needed at declaration, before any table exists to read
73
+ * a machine off. Listing a SUBSET refuses a legal move at the input schema — loud, and the fix is
74
+ * the enum in the refusal.
76
75
  */
77
76
  readonly states: readonly [S, ...S[]];
78
77
  /** The local store's name for this entity — what the optimistic twin patches. */
79
78
  readonly localTable: string;
80
79
  /** The projection the caller gets back. Unknown keys are dropped by the parse, so a `$view` works. */
81
80
  readonly output: TOutput;
81
+ /**
82
+ * The key's schema, for an `output` that does not carry the key as `id`. Omitted — the usual
83
+ * case — it is read off `output.id` (`keySchemaOf`), which for an entity `$view` IS the key
84
+ * column's own shape.
85
+ */
86
+ readonly id?: StringSchema;
82
87
  readonly policy: ActionPolicy;
83
88
  /**
84
89
  * OFF unless the app says otherwise, and deliberately not `?? true`.
@@ -115,9 +120,12 @@ export function transition<
115
120
  // can reach these two callbacks.
116
121
  const valuesOf = (raw: unknown): TransitionValues<S> => raw as TransitionValues<S>;
117
122
  return mutator({
118
- input: t.object({ id: t.uuid, from: state, to: state }),
123
+ input: t.object({ id: def.id ?? keySchemaOf(def.output), from: state, to: state }),
119
124
  output: def.output,
120
125
  policy: def.policy,
126
+ // A compare-and-set move replayed under its key answers the first outcome, never a second
127
+ // `X_STATE_CONFLICT` for a move that already happened.
128
+ idempotent: true,
121
129
  ...(def.audit === undefined ? {} : { audit: def.audit }),
122
130
  // Never overridable: the server is the half that REFUSED the move, and a local twin that won
123
131
  // the rebase would leave the client showing a state the database rejected.
@@ -142,3 +150,21 @@ export function transition<
142
150
  },
143
151
  });
144
152
  }
153
+
154
+ /**
155
+ * The `id` a move takes, from the key the OUTPUT declares — never a fixed `t.uuid`, which made
156
+ * every call on an entity keyed by `text()` or `bigint()` `X_INPUT_INVALID` while the mechanism
157
+ * underneath addresses any single-column key. An entity `$view` builds its `id` node from the key
158
+ * column, so the bounds copied here are that column's: a uuid stays a uuid (and a malformed one is
159
+ * still refused before a database reads it), a `bigint()` keeps its digits pattern, a `text()` its
160
+ * length. Never empty: an empty string names no row. An output with no string `id` keeps the
161
+ * framework's default key type, `uuid().primaryKey()`.
162
+ */
163
+ function keySchemaOf(output: StandardSchemaV1): StringSchema {
164
+ const key = nodeOf(output)?.properties?.['id'];
165
+ if (key === undefined || key.kind !== 'string' || key.format === 'uuid') return t.uuid;
166
+ let schema = t.string.min(Math.max(1, key.minLength ?? 1));
167
+ if (key.maxLength !== undefined) schema = schema.max(key.maxLength);
168
+ if (key.pattern !== undefined) schema = schema.pattern(new RegExp(key.pattern, key.patternFlags));
169
+ return schema;
170
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The open database transaction, as this package needs it — **the only** file here that imports
3
+ * `@ultimat3/db` (`tx-scope.test.ts` holds that). When is a write durable (`openCommitScope`, the
4
+ * cache bust), and is a transaction really OPEN, on which client (`liveTransaction`, idempotency).
5
+ */
6
+
7
+ // Type-only: `idempotency-postgres.ts` imports this module, and a runtime edge would be a cycle.
8
+ import type { PgExecutor } from '@ultimat3/core';
9
+ import { currentTx, liveTxConnection } from '@ultimat3/db';
10
+
11
+ /** The half of a transaction a deferred effect needs. `@ultimat3/db`'s `DbTx` satisfies it. */
12
+ export interface CommitScope {
13
+ /** Fired once the ROOT transaction has committed; dropped on rollback or a lost COMMIT. */
14
+ onCommit(effect: () => void): void;
15
+ }
16
+
17
+ /**
18
+ * The transaction this call runs inside, or `undefined`. `currentTx()` on purpose, FINISHED scopes
19
+ * included: a promise chain the body forgot to await still finds the handle after the scope
20
+ * closed, and `onCommit` on it runs the effect at once after a COMMIT and drops it after a
21
+ * ROLLBACK — the answer `@ultimat3/entity`'s row observer gets from the same call, so a late bust
22
+ * and a late change report never disagree about one write.
23
+ */
24
+ export function openCommitScope(): CommitScope | undefined {
25
+ return currentTx();
26
+ }
27
+
28
+ /** A transaction that is still OPEN: statements sent now are inside it. */
29
+ export interface LiveTransaction extends CommitScope {
30
+ /** The client it was opened on — which DATABASE this is, compared by identity. */
31
+ readonly origin: object;
32
+ /** Fired when the scope rolls back; never after a commit. */
33
+ onRollback(undo: () => void): void;
34
+ /** `(text, values)` on the transaction's OWN connection. */
35
+ readonly executor: PgExecutor;
36
+ }
37
+
38
+ /**
39
+ * The open transaction, or `undefined` — outside one, and ALSO for a finished scope's handle. A
40
+ * settlement bound to a transaction that already ended is bound to nothing: it would run as its
41
+ * own commit while the record claimed otherwise, and that record is the one a retry may reclaim.
42
+ *
43
+ * The fragment is assembled by hand, exactly as `@ultimat3/cli`'s `pgExecutorFor` does: the caller
44
+ * wrote the `$1..$n` text itself and hands over already-bound values.
45
+ */
46
+ export function liveTransaction(): LiveTransaction | undefined {
47
+ const tx = currentTx();
48
+ if (tx === undefined || liveTxConnection() === undefined) return undefined;
49
+ return {
50
+ origin: tx.origin,
51
+ onCommit: (effect) => tx.onCommit(effect),
52
+ onRollback: (undo) => tx.onRollback(undo),
53
+ executor: {
54
+ query: <R>(text: string, values: readonly unknown[]) => tx.query<R>({ text, values }),
55
+ },
56
+ };
57
+ }
package/src/type-pins.ts CHANGED
@@ -3,18 +3,32 @@
3
3
  // type-level claim written in one can never fail. This module emits nothing and exports nothing
4
4
  // anybody imports — a regression here is a build error, the only enforcement that counts.
5
5
 
6
- import type { Row } from '@ultimat3/core';
6
+ import type { AuditRecord, McpExposureDeclaration, Row } from '@ultimat3/core';
7
7
  import type { StandardSchemaV1 } from '@ultimat3/schema';
8
- import type { Action, AnyAction } from './action';
8
+ import type { Action, ActionDef, AnyAction, AnyActionDef } from './action';
9
9
  import type { ClientMethod } from './client';
10
+ import type {
11
+ IdempotencyRecord,
12
+ IdempotencyReservation,
13
+ IdempotencyScope,
14
+ IdempotencyStore,
15
+ } from './idempotency';
10
16
  import type { ActionJobHandle } from './job-handle';
11
- import type { LocalTable } from './mutator';
17
+ import type { LocalTable, MutatorDef } from './mutator';
12
18
 
13
19
  /** Fails to compile when `T` is anything but `true`. The whole mechanism. */
14
20
  type Assert<T extends true> = T;
15
21
 
16
22
  type Equals<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
17
23
 
24
+ /**
25
+ * IDENTICAL, not merely mutually assignable: an object type without an optional key is assignable
26
+ * to one with it and back, so `Equals` cannot see an optional field added on one side only — and
27
+ * every field of the `mcp` block is optional but `expose`.
28
+ */
29
+ type Identical<A, B> =
30
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
31
+
18
32
  type PublishInput = StandardSchemaV1<{ readonly postId: string }>;
19
33
  type PublishOutput = StandardSchemaV1<{ readonly published: boolean }>;
20
34
  type PublishPost = Action<PublishInput, PublishOutput>;
@@ -59,3 +73,84 @@ export type _LocalTableIsTheStoreTxShape = Assert<
59
73
  export type _LocalInsertTakesTheKey = Assert<
60
74
  Equals<Parameters<LocalTable['insert']>, [key: string, row: Row]>
61
75
  >;
76
+
77
+ /**
78
+ * #591: a store written before answers were redacted at rest drops `settle`'s `redacted` flag and
79
+ * would replay `[redacted]` as the answer. A required 4th PARAMETER cannot refuse it — TypeScript
80
+ * accepts an implementation with fewer parameters — so the store DECLARES it keeps the flag
81
+ * (`keepsRedaction: true`), and a pre-25 store without the declaration is a build error here.
82
+ */
83
+ interface PreRedactionStore {
84
+ readonly scope?: IdempotencyScope | undefined;
85
+ reserve(key: string, requestHash: string): Promise<IdempotencyReservation>;
86
+ settle(key: string, value: unknown, reservationId: string): Promise<void>;
87
+ release(key: string): Promise<void>;
88
+ get(key: string): Promise<IdempotencyRecord | undefined>;
89
+ }
90
+
91
+ export type _APreRedactionStoreIsNotAStore = Assert<
92
+ Equals<PreRedactionStore extends IdempotencyStore ? true : false, false>
93
+ >;
94
+
95
+ /** …and `settle`'s flag is required of every CALLER, so a wrapping store cannot drop it either. */
96
+ export type _SettleRequiresTheRedactedFlag = Assert<
97
+ Equals<Parameters<IdempotencyStore['settle']>['length'], 4>
98
+ >;
99
+
100
+ /**
101
+ * 25.0.0 (plan 101, M9): `name` and `primitive` are REQUIRED on an audit record and the `action`
102
+ * alias is gone. Pinned as keys rather than with a literal record, because a literal would need a
103
+ * `Ctx` this module has no business building: a field that turned optional again, or an alias
104
+ * that came back, flips one of these to `false`.
105
+ */
106
+ type RequiredKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T];
107
+
108
+ export type _AuditRecordRequiresNameAndPrimitive = Assert<
109
+ Equals<Extract<RequiredKeys<AuditRecord>, 'name' | 'primitive'>, 'name' | 'primitive'>
110
+ >;
111
+
112
+ export type _AuditRecordHasNoActionAlias = Assert<
113
+ Equals<Extract<keyof AuditRecord, 'action'>, never>
114
+ >;
115
+
116
+ /**
117
+ * 25.0.0 (plan 101, M5): the deprecation TYPES are `@ultimat3/core`'s alone, as the helpers are.
118
+ * A runtime test cannot see a type re-export, so each is an expected error: a re-export coming
119
+ * back makes the directive unused, which `tsc` refuses.
120
+ */
121
+ // @ts-expect-error — `Deprecation` is imported from `@ultimat3/core`, never from this barrel.
122
+ export type _NoDeprecationReexport = import('./index').Deprecation;
123
+ // @ts-expect-error — `DeprecationField` is imported from `@ultimat3/core`.
124
+ export type _NoDeprecationFieldReexport = import('./index').DeprecationField;
125
+ // @ts-expect-error — `DeprecationRender` is imported from `@ultimat3/core`.
126
+ export type _NoDeprecationRenderReexport = import('./index').DeprecationRender;
127
+
128
+ /**
129
+ * O-tool, 25.0.0: an action projects no MCP tool of its own — `@ultimat3/mcp`'s `toolFrom`
130
+ * is the one projection, and a tier-3 `.tool()` could only ever be a second one. A `tool` member
131
+ * coming back on either view flips these to `false`.
132
+ */
133
+ export type _AnActionHasNoToolTwin = Assert<Equals<Extract<keyof AnyAction, 'tool'>, never>>;
134
+ export type _ATypedActionHasNoToolTwin = Assert<Equals<Extract<keyof PublishPost, 'tool'>, never>>;
135
+
136
+ /**
137
+ * 25.0.0: an action's `mcp` block is core's ONE `McpExposureDeclaration`, minus the list
138
+ * whitelist an action has nothing to compose over — on the declaration, the erased declaration,
139
+ * the erased action and a mutator alike. `ActionMcp` restated the block field by field (and
140
+ * `McpAnnotationHints` its hints); a field drifting on either side flips these to `false`.
141
+ */
142
+ type ActionBlock = Omit<McpExposureDeclaration, 'listParams'>;
143
+ export type _ActionDeclaresCoresBlock = Assert<
144
+ Identical<NonNullable<ActionDef<PublishInput, PublishOutput>['mcp']>, ActionBlock>
145
+ >;
146
+ export type _ErasedActionDefDeclaresCoresBlock = Assert<
147
+ Identical<NonNullable<AnyActionDef['mcp']>, ActionBlock>
148
+ >;
149
+ export type _AnyActionCarriesCoresBlock = Assert<
150
+ Identical<NonNullable<AnyAction['mcp']>, ActionBlock>
151
+ >;
152
+ export type _MutatorDeclaresCoresBlock = Assert<
153
+ Identical<NonNullable<MutatorDef<PublishInput, PublishOutput>['mcp']>, ActionBlock>
154
+ >;
155
+ // @ts-expect-error — `McpAnnotationHints` is `@ultimat3/core`'s, never this barrel's.
156
+ export type _NoAnnotationHintsTwin = import('./index').McpAnnotationHints;