@mnmal-ai/substrate 1.0.0-alpha.10 → 1.0.0-alpha.11

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.
Files changed (37) hide show
  1. package/dist/{boot-store-BVqfFxh1.js → boot-store-C5vNZJ3i.js} +13 -8
  2. package/dist/{bridge-Cp4PaIYO.d.ts → bridge-COu0Tg_h.d.ts} +1 -1
  3. package/dist/{cli-hSCBywhE.js → cli-BrwW4tjO.js} +41 -23
  4. package/dist/client.d.ts +3 -4
  5. package/dist/client.js +3 -3
  6. package/dist/{errors-7mycvNGq.d.ts → errors-BOllGhVx.d.ts} +15 -2
  7. package/dist/{index-DgSfwx7M.d.ts → index-Cp74OcmS.d.ts} +1 -1
  8. package/dist/pack.d.ts +2 -2
  9. package/dist/pack.js +1 -1
  10. package/dist/{pg-edges-store-Lxsl5ZnK.js → pg-edges-store-BLsbcXkk.js} +1 -1
  11. package/dist/{plugin-CtwOINCM.js → plugin-DIYm2cZE.js} +2 -2
  12. package/dist/proposals-bootstrap.js +2 -2
  13. package/dist/proposals.d.ts +2 -3
  14. package/dist/proposals.js +1 -1
  15. package/dist/recall-bootstrap.js +2 -2
  16. package/dist/recall.d.ts +1 -2
  17. package/dist/recall.js +2 -2
  18. package/dist/{repl-DqfHelK7.js → repl-B8gy0YM7.js} +22 -22
  19. package/dist/{row-BKKCXIG6.d.ts → row-DwaDU4b-.d.ts} +57 -10
  20. package/dist/{run-B5dTbZ3g.js → run-B18qtGKc.js} +23 -8
  21. package/dist/{dataset-CejF-Fr_.d.ts → schema-CijHRfuk.d.ts} +2225 -1604
  22. package/dist/sdk.d.ts +21 -11
  23. package/dist/sdk.js +4 -4
  24. package/dist/{src-7CUSMK66.js → src-Br6aDUti.js} +7 -3
  25. package/dist/{src-CqT-QWZ_.js → src-D041j6GS.js} +3 -3
  26. package/dist/{src-5SJ5GEIM.js → src-DK7VEQT6.js} +2572 -742
  27. package/dist/{src-hZb8wfvg.js → src-Dbvuel6w.js} +383 -284
  28. package/dist/{src-Da0t6si5.js → src-DpPdw2oL.js} +1 -1
  29. package/dist/{src-Bi849yhn.js → src-DptNGNYQ.js} +3 -3
  30. package/dist/{src-CyvV7dCK.js → src-gz4I1F29.js} +1027 -263
  31. package/dist/substrate-admin.js +1 -1
  32. package/dist/substrate.js +1 -1
  33. package/dist/testing.d.ts +28 -4
  34. package/dist/testing.js +4 -4
  35. package/dist/{ws-ByZyHk7m.d.ts → ws-DC8OhMaV.d.ts} +2 -3
  36. package/package.json +20 -19
  37. package/dist/schema-DoSc-4ig.d.ts +0 -470
@@ -37,7 +37,7 @@ function isEntrypointPath(moduleUrl, argv1) {
37
37
  */
38
38
  if (isEntrypointPath(import.meta.url, process.argv[1])) {
39
39
  assertNodeVersion();
40
- import("./run-B5dTbZ3g.js").then(({ runAdminCli }) => runAdminCli());
40
+ import("./run-B18qtGKc.js").then(({ runAdminCli }) => runAdminCli());
41
41
  }
42
42
 
43
43
  //#endregion
package/dist/substrate.js CHANGED
@@ -4,7 +4,7 @@ import { t as assertNodeVersion } from "./node-version-C5FSmwJX.js";
4
4
 
5
5
  //#region src/bin/substrate.ts
6
6
  assertNodeVersion();
7
- import("./cli-hSCBywhE.js").then(({ runCli }) => runCli(process.argv.slice(2))).then((code) => process.exit(code));
7
+ import("./cli-BrwW4tjO.js").then(({ runCli }) => runCli(process.argv.slice(2))).then((code) => process.exit(code));
8
8
 
9
9
  //#endregion
10
10
  export { };
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { C as ActorIdentity, E as Id, M as WriteRow, _ as EdgePatch, b as EdgesStore, d as PackEnvelope, f as Schema, g as Edge, h as CanDeleteResult, k as Row, r as FieldDef, u as OrderedBy, v as EdgeRef, y as EdgeWriteInput } from "./schema-DoSc-4ig.js";
2
- import { $ as Registry$1, A as DropParticipant, C as ResolverStat, D as SlowRequest, Dt as PolicyDecision, G as NamespaceConfig, H as KernelPlugin, L as IndexDecl, N as EngineHandle, O as TypeStats, Ot as PolicyProbeContext, P as EngineInput, Q as QualifiedFrame, S as ResolveObservation, T as RuntimeErrors, _ as UpdateFieldRef, _t as SubstrateResponse, a as DropResult, at as ScheduledTask, b as WriteResult, bt as WsConnection, c as FilterCapabilities, d as ReadParams, dt as PluginRouter, et as RegistryBase, f as ReadResult, g as TypeStorageReport, gt as SubstrateRequest, ht as StartOpts, i as DeleteResult, k as CoordinatorPlugin, kt as RequestContext, l as IndexPlan, lt as HttpHandler, m as TxScopeHandles, mt as RuntimeOp, n as Dataset, nt as RegistryEntryInput, p as StorageReport, pt as RequestObserver, r as DatasetRegistry, t as ConditionalUpdateResult, tt as RegistryEntry, ut as HttpMethod, vt as SubstrateServer, wt as Identity, x as ProcessStat, xt as WsHandler, y as WriteOptions } from "./dataset-CejF-Fr_.js";
3
- import { a as WsResponseFrame, f as IdempotencyStore, l as SweepDeps, s as BridgeRegistry, u as SweepState } from "./ws-ByZyHk7m.js";
1
+ import { $ as PluginRouter, $t as WriteOptions, A as KernelPlugin, B as QualifiedFrame, Bt as ReadResult, Cn as Row, Dt as Dataset, En as WriteRow, Et as ConditionalUpdateResult, Gt as TypeStorageReport, H as RegistryBase, Ht as StorageReport, It as IndexPlan, Kt as UpdateFieldRef, N as NamespaceConfig, Ot as DatasetRegistry, Pt as FilterCapabilities, Q as HttpMethod, S as EngineInput, T as IndexDecl, U as RegistryEntry, Ut as TxScopeHandles, V as Registry$1, W as RegistryEntryInput, Z as HttpHandler, _ as CoordinatorPlugin, _n as ActorIdentity, _t as RequestContext, an as RuntimeErrors, at as SubstrateResponse, bn as Id, cn as TypeStats, ct as WsConnection, d as OrderedBy, dn as EdgePatch, en as WriteResult, f as PackEnvelope, fn as EdgeRef, ft as Identity, gt as PolicyProbeContext, ht as PolicyDecision, i as FieldDef, it as SubstrateRequest, jt as DropResult, kt as DeleteResult, ln as CanDeleteResult, lt as WsHandler, m as Schema, mn as EdgesStore, nn as ResolveObservation, nt as RuntimeOp, ot as SubstrateServer, pn as EdgeWriteInput, q as ScheduledTask, rn as ResolverStat, rt as StartOpts, sn as SlowRequest, tn as ProcessStat, tt as RequestObserver, un as Edge, v as DropParticipant, x as EngineHandle, yt as ResolverArgs, zt as ReadParams } from "./schema-CijHRfuk.js";
2
+ import { a as WsResponseFrame, f as IdempotencyStore, l as SweepDeps, s as BridgeRegistry, u as SweepState } from "./ws-DC8OhMaV.js";
4
3
  import { t as Embedder } from "./types-8c0gtnd2.js";
5
4
  import { Sql, TransactionSql } from "postgres";
6
5
  //#region ../../packages/substrate-compose/src/auth.d.ts
@@ -517,7 +516,7 @@ declare class Engine {
517
516
  * caller's `probe` context so policies reading headers, `clientIp`, `meta`
518
517
  * or `authEnabled` decide as they would in dispatch.
519
518
  */
520
- evaluateReadPolicy(ns: string, type: string, identity: Identity | null, probe?: PolicyProbeContext): PolicyDecision;
519
+ evaluateReadPolicy(ns: string, type: string, identity: Identity | null, probe?: PolicyProbeContext, args?: ResolverArgs): PolicyDecision;
521
520
  /**
522
521
  * Refresh the cached schemas for every registered bridge. Callers invoke
523
522
  * this at composition-root wire-up time to populate `federatedSchema()`'s
@@ -785,12 +784,25 @@ interface MemoryDatasetOptions {
785
784
  typeDefLookup?: (type: string, namespace: string) => {
786
785
  ordering?: 'visible';
787
786
  } | undefined;
787
+ /**
788
+ * Internal: binding assignments one read's walks may try before refusing
789
+ * `walk_budget_exceeded`. Defaults to `WALK_EVALUATION_BUDGET`; tests lower it.
790
+ */
791
+ walkBudget?: number;
792
+ /**
793
+ * Test-only: declare and answer the typed-edge-walk grammar. The memory
794
+ * dataset is the parity reference for the pg walk compiler, not a walk
795
+ * store; without this the engine refuses walks on it (`walks_unsupported_store`).
796
+ */
797
+ walkReference?: boolean;
788
798
  }
789
799
  export declare class MemoryDataset implements Dataset {
790
800
  #private;
791
801
  readonly namespace: string;
792
802
  readonly txScopeId: string;
793
803
  private readonly typeDefLookup;
804
+ private readonly walkBudget;
805
+ private readonly walkReference;
794
806
  /** Last seq assigned per visible-order type; never decreases, as pg's `visible_seqs`. */
795
807
  private seqs;
796
808
  readonly capabilities: FilterCapabilities;
@@ -801,6 +813,12 @@ export declare class MemoryDataset implements Dataset {
801
813
  constructor(options: MemoryDatasetOptions);
802
814
  private bucket;
803
815
  read(type: string, params: ReadParams): Promise<ReadResult>;
816
+ /**
817
+ * Walks over this namespace's live rows, for one read. Neighbours follow the
818
+ * row body's crossRef value (spec 2026-10-24-typed-edge-walks §1), indexed
819
+ * per (type, field) on first use.
820
+ */
821
+ private walkContext;
804
822
  write(type: string, rows: WriteRow[], options?: WriteOptions): Promise<WriteResult>;
805
823
  tombstone(type: string, ids: Id[]): Promise<DeleteResult>;
806
824
  purge(type: string, ids: Id[]): Promise<DeleteResult>;
@@ -1384,6 +1402,12 @@ export declare class PgDataset implements Dataset {
1384
1402
  readonly capabilities: FilterCapabilities;
1385
1403
  readonly txScopeId: string;
1386
1404
  constructor(options: PgDatasetOptions | InternalPgSubstrateDatasetOptions);
1405
+ /**
1406
+ * The walk grammar (spec 2026-10-24-typed-edge-walks §3) runs on the
1407
+ * partitioned layout only, and in a transaction under a `SET LOCAL`
1408
+ * statement timeout, since pg has no walk evaluation budget. Other reads
1409
+ * are unchanged.
1410
+ */
1387
1411
  read(type: string, params: ReadParams): Promise<ReadResult>;
1388
1412
  /**
1389
1413
  * Upsert `rows`. A row without an `id` gets one from the database's
package/dist/testing.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
- import { G as loadPlugins, W as MemoryEdgesStore, _t as signHs256, c as MemoryDataset, s as compose, yt as WS_REASON_SERVER_RESTART } from "./src-5SJ5GEIM.js";
3
- import "./src-hZb8wfvg.js";
4
- import { l as deriveListIndexMigration, m as runMigrations, p as runDerivedMigrations, t as PgDataset } from "./src-CyvV7dCK.js";
5
- import { t as PgEdgesStore } from "./pg-edges-store-Lxsl5ZnK.js";
2
+ import { Ct as signHs256, G as loadPlugins, Tt as WS_REASON_SERVER_RESTART, W as MemoryEdgesStore, c as MemoryDataset, s as compose } from "./src-DK7VEQT6.js";
3
+ import "./src-Dbvuel6w.js";
4
+ import { l as deriveListIndexMigration, m as runMigrations, p as runDerivedMigrations, t as PgDataset } from "./src-gz4I1F29.js";
5
+ import { t as PgEdgesStore } from "./pg-edges-store-BLsbcXkk.js";
6
6
  import { t as FakeEmbedder } from "./fake-DUVtKVSE.js";
7
7
  import { randomUUID } from "node:crypto";
8
8
  import postgres from "postgres";
@@ -1,6 +1,5 @@
1
- import { E as Id, b as EdgesStore, c as FieldInput, d as PackEnvelope, v as EdgeRef } from "./schema-DoSc-4ig.js";
2
- import { t as BridgeClient } from "./bridge-Cp4PaIYO.js";
3
- import { r as DatasetRegistry } from "./dataset-CejF-Fr_.js";
1
+ import { Ot as DatasetRegistry, bn as Id, f as PackEnvelope, fn as EdgeRef, l as FieldInput, mn as EdgesStore } from "./schema-CijHRfuk.js";
2
+ import { t as BridgeClient } from "./bridge-COu0Tg_h.js";
4
3
  //#region ../../packages/substrate-types/src/idempotency.d.ts
5
4
  interface IdempotencyStore {
6
5
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate",
3
- "version": "1.0.0-alpha.10",
3
+ "version": "1.0.0-alpha.11",
4
4
  "description": "Substrate — an agent-first typed-data server: the substrate and substrate-admin binaries, the built-in plugins and the SDK subpaths.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,24 +36,25 @@
36
36
  },
37
37
  "devDependencies": {
38
38
  "@inquirer/prompts": "^8.7.2",
39
- "@mnmal-ai/substrate-bootstrap": "1.0.0-alpha.10",
40
- "@mnmal-ai/substrate-client": "1.0.0-alpha.10",
41
- "@mnmal-ai/substrate-compose": "1.0.0-alpha.10",
42
- "@mnmal-ai/substrate-config": "1.0.0-alpha.10",
43
- "@mnmal-ai/substrate-core": "1.0.0-alpha.10",
44
- "@mnmal-ai/substrate-dataset-memory": "1.0.0-alpha.10",
45
- "@mnmal-ai/substrate-dataset-pg": "1.0.0-alpha.10",
46
- "@mnmal-ai/substrate-embedder": "1.0.0-alpha.10",
47
- "@mnmal-ai/substrate-filter": "1.0.0-alpha.10",
48
- "@mnmal-ai/substrate-pack": "1.0.0-alpha.10",
49
- "@mnmal-ai/substrate-policy": "1.0.0-alpha.10",
50
- "@mnmal-ai/substrate-proposals": "1.0.0-alpha.10",
51
- "@mnmal-ai/substrate-recall": "1.0.0-alpha.10",
52
- "@mnmal-ai/substrate-sdk": "1.0.0-alpha.10",
53
- "@mnmal-ai/substrate-sentinel-client": "1.0.0-alpha.10",
54
- "@mnmal-ai/substrate-server-fastify": "1.0.0-alpha.10",
55
- "@mnmal-ai/substrate-server-memory": "1.0.0-alpha.10",
56
- "@mnmal-ai/substrate-types": "1.0.0-alpha.10",
39
+ "@mnmal-ai/substrate-bootstrap": "1.0.0-alpha.11",
40
+ "@mnmal-ai/substrate-client": "1.0.0-alpha.11",
41
+ "@mnmal-ai/substrate-compose": "1.0.0-alpha.11",
42
+ "@mnmal-ai/substrate-config": "1.0.0-alpha.11",
43
+ "@mnmal-ai/substrate-core": "1.0.0-alpha.11",
44
+ "@mnmal-ai/substrate-dataset-memory": "1.0.0-alpha.11",
45
+ "@mnmal-ai/substrate-dataset-pg": "1.0.0-alpha.11",
46
+ "@mnmal-ai/substrate-embedder": "1.0.0-alpha.11",
47
+ "@mnmal-ai/substrate-filter": "1.0.0-alpha.11",
48
+ "@mnmal-ai/substrate-pack": "1.0.0-alpha.11",
49
+ "@mnmal-ai/substrate-policy": "1.0.0-alpha.11",
50
+ "@mnmal-ai/substrate-proposals": "1.0.0-alpha.11",
51
+ "@mnmal-ai/substrate-recall": "1.0.0-alpha.11",
52
+ "@mnmal-ai/substrate-sdk": "1.0.0-alpha.11",
53
+ "@mnmal-ai/substrate-sentinel-client": "1.0.0-alpha.11",
54
+ "@mnmal-ai/substrate-server-fastify": "1.0.0-alpha.11",
55
+ "@mnmal-ai/substrate-server-memory": "1.0.0-alpha.11",
56
+ "@mnmal-ai/substrate-types": "1.0.0-alpha.11",
57
+ "@mnmal-ai/surface-core": "0.15.0",
57
58
  "@types/node": "^26.6.4",
58
59
  "@types/semver": "^7.5.0",
59
60
  "@types/ws": "^8.18.1",
@@ -1,470 +0,0 @@
1
- //#region ../../packages/substrate-types/src/core.d.ts
2
- /**
3
- * Core substrate-neutral types. Spec: §4.5 Dataset, §4.6 Edge.
4
- */
5
- type Id = string | number;
6
- interface Row {
7
- id: Id;
8
- _deletedAt?: Date | null;
9
- /**
10
- * Server-managed row-lifecycle metadata, set by autoCRUD on create/update
11
- * and projected on every read alongside `id`. Each dataset stores it in
12
- * its own way.
13
- */
14
- _metadata?: RowMetadata;
15
- [field: string]: unknown;
16
- }
17
- /**
18
- * A row as passed to `Dataset.write`. `id` may be omitted: the dataset then
19
- * assigns a version-7 UUID and returns it in `WriteResult.ids`.
20
- */
21
- interface WriteRow {
22
- id?: Id;
23
- _deletedAt?: Date | null;
24
- _metadata?: RowMetadata;
25
- [field: string]: unknown;
26
- }
27
- /**
28
- * Refuse an upsert batch that names one id twice: the datasets would
29
- * otherwise disagree (pg cannot update a row twice in one statement).
30
- */
31
- declare function assertNoRepeatedIds(type: string, rows: readonly WriteRow[]): void;
32
- type IdentityKind = 'agent' | 'user' | 'system';
33
- /**
34
- * Row-attribution actor — records who created or last updated a row.
35
- * Distinct from the auth `Identity` in `policy.ts` (JWT principal).
36
- */
37
- interface ActorIdentity {
38
- readonly kind: IdentityKind;
39
- readonly id: string;
40
- }
41
- interface RowMetadata {
42
- readonly createdAt: string | null;
43
- readonly updatedAt: string | null;
44
- readonly createdBy: ActorIdentity | null;
45
- readonly updatedBy: ActorIdentity | null;
46
- /**
47
- * The row's place in its type's commit order, on a type declared
48
- * `ordering: 'visible'`; absent on every other type. Assigned on insert only.
49
- */
50
- readonly seq?: number;
51
- }
52
- declare const CLIENT_SUPPLIED_SERVER_FIELD: 'client_supplied_server_field';
53
- type ClientSuppliedServerFieldError = typeof CLIENT_SUPPLIED_SERVER_FIELD;
54
- declare const ROW_METADATA_FIELDS: readonly ['createdAt', 'updatedAt', 'createdBy', 'updatedBy'];
55
- type RowMetadataField = (typeof ROW_METADATA_FIELDS)[number];
56
- //#endregion
57
- //#region ../../packages/substrate-types/src/edge.d.ts
58
- type OnDelete = 'set_null' | 'cascade' | 'restrict' | 'orphan';
59
- type OnMissing = 'reject' | 'allow';
60
- interface EdgeRef {
61
- ns: string;
62
- type: string;
63
- id: Id;
64
- bridged?: boolean;
65
- }
66
- interface Edge {
67
- id: string;
68
- from: EdgeRef;
69
- to: EdgeRef;
70
- fieldName: string;
71
- policy: OnDelete;
72
- createdAt: Date;
73
- deletedAt?: Date;
74
- lastSweptAt?: Date;
75
- blocked?: boolean;
76
- }
77
- /**
78
- * Narrow patch type for `EdgesStore.update`. Immutable fields (from, to,
79
- * policy, fieldName, createdAt, id-as-identity) cannot be changed post-write.
80
- * `deletedAt` is managed exclusively by `tombstone(id)`.
81
- */
82
- type EdgePatch = Pick<Edge, 'id'> & Partial<Pick<Edge, 'lastSweptAt' | 'blocked'>>;
83
- type EdgeWriteInput = Omit<Edge, 'id' | 'createdAt' | 'lastSweptAt' | 'deletedAt' | 'blocked'>;
84
- type CanDeleteResult = {
85
- ok: true;
86
- } | {
87
- ok: false;
88
- blockedBy: Edge[];
89
- };
90
- interface EdgesStore {
91
- /**
92
- * Stable identifier for the storage substrate this edges store wraps.
93
- * Parallels `Dataset.txScopeId` (spec §5.3). When an `EdgesStore`
94
- * and a `Dataset` share a `txScopeId`, the engine enlists edge
95
- * mutations into the dataset's `withScopedTransaction`, making
96
- * row-tombstone + edge-tombstone within one frame atomic.
97
- *
98
- * Convention:
99
- * - pg: derived from the `postgres.Sql` pool reference identity. A
100
- * `PgEdgesStore` constructed against the same `Sql` as a
101
- * `PgDataset` advertises the same `txScopeId`.
102
- * - memory: unique per `MemoryEdgesStore` instance. A memory edges
103
- * store can never coalesce into a dataset's substrate tx; the engine
104
- * falls back to nested independent transactions for that case.
105
- */
106
- readonly txScopeId: string;
107
- write(input: EdgeWriteInput): Promise<Edge>;
108
- tombstone(id: string, at?: Date): Promise<void>;
109
- update(patch: EdgePatch): Promise<void>;
110
- readNextBatch(cursorId: string | null, size: number): Promise<{
111
- edges: Edge[];
112
- lastId: string | null;
113
- }>;
114
- findEdgesTo(ref: EdgeRef): Promise<Edge[]>;
115
- /**
116
- * Batched `findEdgesTo`: all live (non-tombstoned) inbound edges whose `to`
117
- * matches ANY of `refs`, in a single round-trip. Empty `refs` yields an
118
- * empty result. Callers group the flat result by `edge.to` themselves.
119
- */
120
- findEdgesToMany(refs: readonly EdgeRef[]): Promise<Edge[]>;
121
- findEdgesFrom(ref: EdgeRef): Promise<Edge[]>;
122
- canDelete(ref: EdgeRef): Promise<CanDeleteResult>;
123
- findBlocked(): Promise<Edge[]>;
124
- /**
125
- * List live (non-tombstoned) edges where `from_ns === namespace` OR
126
- * `to_ns === namespace`. Used by drop-namespace to detect dangling refs
127
- * when `cascade === 'refuse'`. Bounded by `limit` — callers only need
128
- * enough to decide + surface a sample.
129
- */
130
- findEdgesTouchingNamespace(namespace: string, limit: number): Promise<Edge[]>;
131
- /**
132
- * List live (non-tombstoned) edges where either endpoint matches
133
- * `(namespace, type)`. Used by drop-type for the same cascade-refuse check.
134
- */
135
- findEdgesTouchingType(namespace: string, type: string, limit: number): Promise<Edge[]>;
136
- /**
137
- * Distinct namespaces other than `namespace` at the far end of any edge
138
- * (tombstoned or live) touching `namespace`, or `(namespace, type)` when
139
- * `type` is given: the namespaces `dropEdgesByNamespace` / `dropEdgesByType`
140
- * would delete edges from.
141
- */
142
- namespacesLinkedTo(namespace: string, type?: string): Promise<string[]>;
143
- /**
144
- * Physically delete every edge (tombstoned or live) where `from_ns === namespace`
145
- * OR `to_ns === namespace`. Used by drop-namespace when `cascade === 'delete'`.
146
- * Returns the exact count physically removed.
147
- *
148
- * Same atomicity rules as `tombstone` — MUST run inside a caller-supplied
149
- * `withTransaction` for multi-store atomicity.
150
- */
151
- dropEdgesByNamespace(namespace: string, within?: readonly string[]): Promise<number>;
152
- /**
153
- * Physically delete every edge (tombstoned or live) where either endpoint
154
- * matches `(namespace, type)`. Used by drop-type when `cascade === 'delete'`.
155
- * `within` restricts both drops to edges whose far end is `namespace` or one
156
- * of the listed namespaces.
157
- */
158
- dropEdgesByType(namespace: string, type: string, within?: readonly string[]): Promise<number>;
159
- /**
160
- * Execute `fn` atomically. All ops performed on the `tx` argument run inside
161
- * one substrate transaction. On throw, every mutation inside the callback
162
- * rolls back; on resolve, the transaction commits and the value is returned.
163
- *
164
- * Nested calls flatten into the outer tx (savepoints out of scope).
165
- * Cross-store atomicity with a sibling `Dataset.withTransaction` is the
166
- * engine's concern; each store manages its own tx independently here.
167
- * For enlisted cross-store atomicity, see `Dataset.withScopedTransaction`
168
- * which yields a tx-bound `EdgesStore` alongside the tx-bound datasets.
169
- *
170
- * Mirrors `Dataset.withTransaction` (§4.5, G1 §5.3).
171
- */
172
- withTransaction<T>(fn: (tx: EdgesStore) => Promise<T>): Promise<T>;
173
- }
174
- //#endregion
175
- //#region ../../packages/substrate-types/src/schema.d.ts
176
- interface FieldDefScalar {
177
- kind: 'scalar';
178
- /**
179
- * `'json'` is an opaque body: msgpack-friendly nested object/array, value
180
- * round-trips unchanged, but no per-leaf filtering or ordering. Use it for
181
- * freeform payloads (audit details, debug bags). When you need filterable
182
- * inner keys, use `field.struct` instead.
183
- */
184
- type: 'string' | 'number' | 'boolean' | 'date' | 'json';
185
- /**
186
- * Tri-state. `true` builds an index (a btree; a GIN for json). Unset means
187
- * no index. `false` means no index AND not a search handle: long-form
188
- * prose that NL and similar consumers leave out. The field filters either
189
- * way. Physical consumers test `=== true`, so never normalise unset to
190
- * `false`.
191
- */
192
- indexed?: boolean;
193
- /** Metadata: when true, consumers SHOULD expect `null` as a legitimate value. */
194
- nullable?: boolean;
195
- /**
196
- * Metadata: when true, this field is populated by the engine (not the caller)
197
- * and write attempts that include it MUST be rejected. Used for the
198
- * auto-injected `shortId` field. Consumers (autoCRUD create, schema
199
- * publisher, client codegen) rely on this flag as a declarative contract —
200
- * do not imperatively guard readonly fields without also flipping this.
201
- */
202
- readonly?: boolean;
203
- /**
204
- * Server-managed date flag. Clients may not supply the field in the
205
- * indicated phase(s) — autoCRUD rejects it with `client_supplied_server_field`:
206
- * - 'create' — on create only
207
- * - 'update' — on update only
208
- * - 'both' — on create and update
209
- * Nothing stamps it automatically: server-side code (a custom resolver or a
210
- * system writer such as `applyUpdatePatch`) sets it. A non-nullable,
211
- * non-defaulted field gated on create is refused by autoCRUD at install,
212
- * since nothing could fill it. Only honoured on `type: 'date'`.
213
- */
214
- serverSet?: 'create' | 'update' | 'both';
215
- /**
216
- * Controlled vocabulary. When present, the value MUST be one of these
217
- * strings. Consumed by autoCRUD write-validation (covers memory + pg
218
- * uniformly) and surfaced verbatim in the published schema. `type` stays
219
- * 'string' — an enum is a constrained string, so pack / client decoder /
220
- * where-validation treat it identically with no new branch.
221
- */
222
- enum?: readonly string[];
223
- /**
224
- * Governed vocabulary: alias -> canonical value (each canonical value is in
225
- * `enum`). autoCRUD stores the canonical value when an alias is written, and
226
- * `where` filters on the field match it, so synonyms converge instead of
227
- * sprawling. Matching is case-insensitive. Published in the schema so every
228
- * client reads the same table.
229
- */
230
- aliases?: Readonly<Record<string, string>>;
231
- /**
232
- * `false` admits values outside `enum` (aliases are still normalised): a
233
- * transition mode for adopting a vocabulary over existing free-string data.
234
- * Absent means strict.
235
- */
236
- strict?: boolean;
237
- /**
238
- * Alias (or canonical value) -> sibling fields it implies, e.g.
239
- * `done -> { resolution: 'completed' }`. On write the siblings are filled
240
- * when the caller omits them and a contradicting value is refused; an
241
- * `eq` filter on the alias also matches the implied siblings. Keys match
242
- * case-insensitively.
243
- */
244
- implies?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
245
- /**
246
- * Default value applied by autoCRUD `create` when the caller omits this
247
- * field. Two effects: (1) the row is written with the default instead of
248
- * being absent; (2) it satisfies the non-nullable presence check, so a
249
- * non-nullable scalar WITHOUT a default that is omitted on create is
250
- * rejected (`missing_required_field`) — that is how "required" is expressed.
251
- * Only applied on create (update is a partial patch). The value should match
252
- * `type` (booleans for boolean, ISO string for date, etc.).
253
- */
254
- default?: string | number | boolean;
255
- }
256
- interface FieldDefCrossRef {
257
- kind: 'crossRef';
258
- ns: string;
259
- type: string;
260
- onDelete: OnDelete;
261
- /**
262
- * Write-time existence policy. 'reject' refuses a create/update
263
- * whose crossRef value points at a non-existent or tombstoned target;
264
- * 'allow' is the default when absent. Consulted only at write time, never
265
- * stored on the edge. Enforced only for locally-resolvable
266
- * target namespaces (compose rejects 'reject' on bridged/unknown targets).
267
- */
268
- onMissing?: OnMissing;
269
- /**
270
- * Substrate-level indexing hint for the edge-source column, mirroring
271
- * `FieldDefScalar.indexed`, so the dataset need not infer it from the
272
- * presence of the crossRef itself.
273
- */
274
- indexed?: boolean;
275
- /** Metadata: when true, consumers SHOULD expect `null` as a legitimate value. */
276
- nullable?: boolean;
277
- /**
278
- * Activation-spreading opt-in. When `spread: true`,
279
- * recall hits on a row touching this crossRef propagate a damped salience
280
- * boost to the linked row (forward direction, X → row X references) AND to
281
- * rows whose same field points at the boosted row (backward direction,
282
- * X ← rows that reference X). Default off — operators opt in per-edge to
283
- * avoid polluting attention with low-signal edges (e.g. Decision.sessionId).
284
- *
285
- * Damping (typically 0.3) + depth bound (1) are configured on the recall
286
- * substrate, not per-field.
287
- */
288
- spread?: boolean;
289
- /**
290
- * Cross-TYPE opt-in for the recall expansion path.
291
- * Only meaningful when `spread: true` (the SDK `field.crossRef` builder
292
- * rejects `expandCrossType` without `spread` at registration). When both
293
- * are set, BACKWARD walks via this edge are allowed to surface neighbours
294
- * whose type differs from the request's `scope.type` (e.g. a Concept-typed
295
- * query surfaces Decisions via inbound `Decision.establishesConcept`).
296
- *
297
- * Cross-NAMESPACE expansion is always rejected regardless of this flag.
298
- * Forward walks always honour scope strictly: allowing them lets
299
- * neighbour-type rows displace the rows that establish them in the ranking.
300
- * Default false.
301
- */
302
- expandCrossType?: boolean;
303
- }
304
- interface FieldDefStruct {
305
- kind: 'struct';
306
- fields: Record<string, FieldDef>;
307
- /** Metadata: when true, consumers SHOULD expect `null` as a legitimate value. */
308
- nullable?: boolean;
309
- }
310
- interface FieldDefList {
311
- kind: 'list';
312
- of: FieldDef;
313
- /**
314
- * When true, the `has` (element membership) operator is backed by a GIN
315
- * index on `(body -> '<field>')`. List fields are stored as native JSONB
316
- * arrays. Default false — `has` on an unindexed list still works, by
317
- * scanning the type's rows. The substrate binary derives the matching GIN
318
- * as an idempotent migration at boot from this flag; no hand-authored
319
- * migration is needed per field.
320
- */
321
- indexed?: boolean;
322
- /** Metadata: when true, consumers SHOULD expect `null` as a legitimate value. */
323
- nullable?: boolean;
324
- }
325
- type FieldDef = FieldDefScalar | FieldDefCrossRef | FieldDefStruct | FieldDefList;
326
- /**
327
- * Per-type schema entry. Fields may be declared at registration time; MVP emits
328
- * `fields: {}` for types registered without a field map (e.g. mutations whose
329
- * shape is inferred from the resolver's return).
330
- */
331
- interface TypeSchema {
332
- fields: Record<string, FieldDef>;
333
- /** The type's natural order; absent means {@link DEFAULT_ORDERED_BY}. */
334
- orderedBy?: OrderedBy;
335
- }
336
- /**
337
- * A type's natural order: exactly one `{ field: direction }` key, the order a
338
- * read with no `orderBy` returns. The datasets still append `id` as the tie-break.
339
- */
340
- type OrderedBy = Record<string, 'asc' | 'desc'>;
341
- /** Natural order of a type that declares none: newest first. */
342
- declare const DEFAULT_ORDERED_BY: OrderedBy;
343
- /** The declared natural order, or {@link DEFAULT_ORDERED_BY}. */
344
- declare function naturalOrderOf(schema: Pick<TypeSchema, 'orderedBy'>): OrderedBy;
345
- /**
346
- * Per-mutation schema entry. `params` describes the input shape a client
347
- * sends; `returns` describes the shape a client decodes on success. Both are
348
- * required — an empty param bag surfaces as `{}`, never as an absent key.
349
- *
350
- * `returns` is typically a `FieldDefStruct` describing the row shape the
351
- * mutation produces (e.g. `create<T>` returns the inserted row; `delete<T>`
352
- * returns `{ id, deleted }`). `get<T>` and `update<T>` mark the struct
353
- * `nullable: true` because an id-miss legitimately produces `null`.
354
- *
355
- * Mutations registered without explicit `returns` metadata receive a sentinel
356
- * fallback (`{ kind: 'scalar', type: 'string', nullable: true }`) so substrate-pack
357
- * can still round-trip the response — clients treating it as "unknown shape"
358
- * should fall back to JSON passthrough.
359
- */
360
- interface MutationSchema {
361
- params: Record<string, FieldDef>;
362
- returns: FieldDef;
363
- }
364
- /**
365
- * The published schema shape surfaced at `GET /substrate/v1/schema`. Spec: §4.2, §6.1,
366
- * §7.1. `schemaVersion` is the 12-char SHA-256 prefix over the canonicalized
367
- * schema JSON and travels on every response envelope (§7.0) so the client can
368
- * detect drift.
369
- */
370
- interface Schema {
371
- schemaVersion: string;
372
- types: Record<string, TypeSchema>;
373
- mutations: Record<string, MutationSchema>;
374
- /** Present (true) on substrate-contributed virtual namespaces: no autoCRUD, no storage, query/mutate one-shot only. */
375
- virtual?: true;
376
- /**
377
- * The namespace's opaque per-consumer metadata (`defineNamespace` option).
378
- * Not part of `schemaVersion`: an annotations-only change does not move it.
379
- */
380
- annotations?: Readonly<Record<string, unknown>>;
381
- }
382
- /**
383
- * Per-key shape. A single frame resolves to `'single' | 'list'`. A batched
384
- * mutate op-key (array of frames) resolves to `Array<'single' | 'list'>` —
385
- * one shape per frame, in frame-array order. The decoder keys off the
386
- * discriminator: string → single frame; array → batched.
387
- */
388
- type EnvelopeShape = 'single' | 'list' | Array<'single' | 'list'>;
389
- /**
390
- * The response envelope. Spec: §7.0.
391
- *
392
- * Query data values are positionally encoded using the client-sent `FieldInput`
393
- * selection; mutation data values are positionally encoded using the declared
394
- * `MutationSchema.returns` (§4.2) — mutations don't carry a FieldInput
395
- * since there's no field selection on a return row.
396
- */
397
- interface PackEnvelope {
398
- schemaVersion: string;
399
- data: Record<string, unknown>;
400
- shapes: Record<string, EnvelopeShape>;
401
- _meta?: Record<string, unknown>;
402
- _pagination?: Record<string, {
403
- nextCursor?: string;
404
- hasMore: boolean;
405
- }>;
406
- /**
407
- * Per-top-level-key completeness. ABSENT MEANS COMPLETE — callers that
408
- * predate this field stay correct without change.
409
- *
410
- * Set when a bridged key could not be fully resolved (§6.5 "reads never
411
- * fail" means such a read still returns 200 with orphan markers). The
412
- * per-row `__orphan` marker says a row is missing; this says the RESULT SET
413
- * is partial, which a consumer cannot otherwise distinguish from an
414
- * genuinely empty result.
415
- */
416
- _completeness?: Record<string, {
417
- complete: boolean;
418
- unreachable?: string[];
419
- }>;
420
- /**
421
- * Non-fatal read diagnostics, keyed by top-level frame key. ABSENT MEANS
422
- * NOTHING TO REPORT — callers that predate this field stay correct without
423
- * change, same contract as `_completeness`.
424
- *
425
- * Deliberately NOT `errors`: a consumer doing `if (env.errors) throw` would
426
- * start failing on reads that succeeded.
427
- *
428
- * A client that maps rows into declared interfaces MUST surface this (log,
429
- * attach to the result, or throw in development): an unknown projection key
430
- * arrives as `null`, satisfies the interface, and the read looks correct.
431
- */
432
- _diagnostics?: Record<string, {
433
- /**
434
- * Projection keys the type does not declare. The read still returned
435
- * every row; each unknown key materialises as `null` on all of them,
436
- * indistinguishable from a declared field that is null everywhere.
437
- */
438
- unknownProjectionFields?: string[];
439
- /**
440
- * The where-clause reached the substrate without being schema-validated,
441
- * because the type is registered but absent from its namespace's
442
- * published schema (e.g. runtime-created types). The result is still
443
- * correct — substrates refuse a predicate they cannot honour — but the
444
- * engine's operator and operand check did not run.
445
- */
446
- filterValidationSkipped?: string;
447
- }>;
448
- errors?: Array<{
449
- message: string;
450
- path?: string[];
451
- code?: string;
452
- /**
453
- * Optional structured payload — populated when the underlying error class
454
- * carries one (e.g. `ResolverFrameError({ field: '...' })`).
455
- */
456
- details?: Record<string, unknown>;
457
- }>;
458
- }
459
- /**
460
- * Client-sent field selection tree. Defined here rather than in
461
- * `@mnmal-ai/substrate-pack` so subscription and streaming machinery (§5.4, §5.5)
462
- * can reference the same shape without adding substrate-pack to their dependency
463
- * set — substrate-pack already imports from types, so moving the type upward
464
- * avoids the would-be cycle.
465
- */
466
- type FieldInput = {
467
- [field: string]: true | FieldInput;
468
- };
469
- //#endregion
470
- export { RowMetadata as A, ActorIdentity as C, IdentityKind as D, Id as E, WriteRow as M, assertNoRepeatedIds as N, ROW_METADATA_FIELDS as O, OnMissing as S, ClientSuppliedServerFieldError as T, EdgePatch as _, FieldDefList as a, EdgesStore as b, FieldInput as c, PackEnvelope as d, Schema as f, Edge as g, CanDeleteResult as h, FieldDefCrossRef as i, RowMetadataField as j, Row as k, MutationSchema as l, naturalOrderOf as m, EnvelopeShape as n, FieldDefScalar as o, TypeSchema as p, FieldDef as r, FieldDefStruct as s, DEFAULT_ORDERED_BY as t, OrderedBy as u, EdgeRef as v, CLIENT_SUPPLIED_SERVER_FIELD as w, OnDelete as x, EdgeWriteInput as y };