@mnmal-ai/substrate-sentinel 0.0.0 → 1.0.0-alpha.1

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
1
  # @mnmal-ai/substrate-sentinel
2
2
 
3
- Reserved by MNMAL. Nothing here yet.
3
+ Coordinator plugin: a registry for dynamic bridge discovery.
4
+
5
+ Owns the `sentinel` namespace (`Coordinator`, `CoordinatorNamespace`, `CoordinatorBridge`), describing the Substrate instances in a federation and the namespaces each serves. Peers register over the plugin's WebSocket route; a liveness loop pings them and marks a peer `offline` once it has been silent longer than `staleThresholdMs`. Other instances follow the registry over the plugin's WebSocket route with the sentinel client built into `@mnmal-ai/substrate` (enabled by `SUBSTRATE_SENTINEL_URL`), which registers and unregisters bridges as peers come and go.
6
+
7
+ ## Where it fits
8
+
9
+ Install it on the instance that acts as the federation's Sentinel. A single-instance deployment does not need it.
10
+
11
+ ## Usage
12
+
13
+ ```bash
14
+ cd <runtime-dir> # the directory SUBSTRATE_PLUGIN_DIR points at
15
+ pnpm add @mnmal-ai/substrate-sentinel@next
16
+ ```
17
+
18
+ Defaults in `default-config.json`: `namespace: "sentinel"`, `pingIntervalMs: 30000` (liveness tick), `staleThresholdMs: 90000` (age after which a peer is treated as stale). Override them in `<SUBSTRATE_PLUGIN_DIR>/substrate-sentinel.config.json`.
19
+
20
+ Routes: `GET /substrate/v1/plugins/substrate-sentinel/status` and the topology stream at `/substrate/v1/plugins/substrate-sentinel/ws`.
21
+
22
+ ## More
23
+
24
+ - Spec: §5.8 (bridges), [`docs/substrate-from-first-principles.md`](../../docs/substrate-from-first-principles.md)
25
+ - Source: `plugins/substrate-sentinel/src/`
26
+ - Client: `packages/substrate-sentinel-client/`
@@ -0,0 +1,24 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "namespace": {
6
+ "default": "sentinel",
7
+ "type": "string",
8
+ "minLength": 1
9
+ },
10
+ "pingIntervalMs": {
11
+ "default": 30000,
12
+ "type": "integer",
13
+ "exclusiveMinimum": 0,
14
+ "maximum": 9007199254740991
15
+ },
16
+ "staleThresholdMs": {
17
+ "default": 90000,
18
+ "type": "integer",
19
+ "exclusiveMinimum": 0,
20
+ "maximum": 9007199254740991
21
+ }
22
+ },
23
+ "additionalProperties": false
24
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "namespace": "sentinel",
3
+ "pingIntervalMs": 30000,
4
+ "staleThresholdMs": 90000
5
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Structured-config bootstrap for `@mnmal-ai/substrate-sentinel`.
3
+ *
4
+ * Consumed by the `SUBSTRATE_PLUGIN_DIR` manifest-driven loader; the package's
5
+ * `substrate.entry` manifest field points the loader here.
6
+ */
7
+ import { z } from 'zod';
8
+ export declare const SentinelBootstrapConfigSchema: z.ZodObject<{
9
+ namespace: z.ZodDefault<z.ZodString>;
10
+ pingIntervalMs: z.ZodDefault<z.ZodNumber>;
11
+ staleThresholdMs: z.ZodDefault<z.ZodNumber>;
12
+ }, z.core.$strict>;
13
+ export type SentinelBootstrapConfig = z.infer<typeof SentinelBootstrapConfigSchema>;
14
+ export declare const bootstrap: import("@mnmal-ai/substrate/sdk").CoordinatorBootstrap;
15
+ export default bootstrap;
16
+ //# sourceMappingURL=bootstrap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,eAAO,MAAM,6BAA6B;;;;kBAW/B,CAAC;AAEZ,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,6BAA6B,CAAC,CAAC;AAEpF,eAAO,MAAM,SAAS,wDAQpB,CAAC;eAEY,SAAS"}
@@ -0,0 +1,33 @@
1
+ import { t as createSentinelPlugin } from "./src-DSiwjCeD.js";
2
+ import { defineBootstrap } from "@mnmal-ai/substrate/sdk";
3
+ import { z } from "zod";
4
+
5
+ //#region src/bootstrap.ts
6
+ /**
7
+ * Structured-config bootstrap for `@mnmal-ai/substrate-sentinel`.
8
+ *
9
+ * Consumed by the `SUBSTRATE_PLUGIN_DIR` manifest-driven loader; the package's
10
+ * `substrate.entry` manifest field points the loader here.
11
+ */
12
+ const NamespaceSchema = z.string().min(1, "must not be empty").refine((s) => !s.includes("/"), { message: "must not contain '/'" });
13
+ const SentinelBootstrapConfigSchema = z.object({
14
+ namespace: NamespaceSchema.default("sentinel"),
15
+ /** Interval between liveness ticks in milliseconds. */
16
+ pingIntervalMs: z.number().int().positive().default(3e4),
17
+ /**
18
+ * Max heartbeat age before a coordinator is marked offline. Checked once
19
+ * per `pingIntervalMs` tick, so eviction lands up to one interval later.
20
+ */
21
+ staleThresholdMs: z.number().int().positive().default(9e4)
22
+ }).strict();
23
+ const bootstrap = defineBootstrap.coordinator({
24
+ schema: SentinelBootstrapConfigSchema,
25
+ build: (config) => createSentinelPlugin({
26
+ namespace: config.namespace,
27
+ pingIntervalMs: config.pingIntervalMs,
28
+ staleThresholdMs: config.staleThresholdMs
29
+ })
30
+ });
31
+
32
+ //#endregion
33
+ export { SentinelBootstrapConfigSchema, bootstrap, bootstrap as default };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * substrate-sentinel plugin config type. Populated by the structured-config
3
+ * bootstrap (`bootstrap.ts`) or by direct programmatic callers (tests).
4
+ */
5
+ export interface SentinelPluginConfig {
6
+ /** Namespace the plugin's types and routes register under. */
7
+ namespace: string;
8
+ /** Interval between liveness ticks in milliseconds. */
9
+ pingIntervalMs: number;
10
+ /**
11
+ * Max heartbeat age before a coordinator is marked offline. Checked once
12
+ * per `pingIntervalMs` tick, so eviction lands up to one interval later.
13
+ */
14
+ staleThresholdMs: number;
15
+ }
16
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,oBAAoB;IACnC,8DAA8D;IAC9D,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,cAAc,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,gBAAgB,EAAE,MAAM,CAAC;CAC1B"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @mnmal-ai/substrate-sentinel — coordinator plugin that manages dynamic
3
+ * discovery for Substrate coordinators (Coordinator, CoordinatorNamespace,
4
+ * CoordinatorBridge rows) plus a persistent WS surface for registration and
5
+ * topology watching.
6
+ *
7
+ * Coordinator plugin seam (§5.11):
8
+ * - `namespaces[0]` — the 3-type autoCRUD surface (see `./namespace.ts`).
9
+ * - `routes` — `/status` (health dashboard read) and `/ws` (registration +
10
+ * watcher heartbeat).
11
+ * - `schedule` — a single `<ns>-liveness` task runs every
12
+ * `pingIntervalMs` (default 30s), pings every socket, and evicts
13
+ * coordinators whose last heartbeat is older than `staleThresholdMs`.
14
+ *
15
+ * `createSentinelPlugin` is a pure factory taking a fully-resolved
16
+ * `SentinelPluginConfig`. The structured-config `bootstrap` is the canonical
17
+ * entry. Direct programmatic callers (tests, embedded
18
+ * harnesses) build a full config and call `createSentinelPlugin(config)`.
19
+ */
20
+ import type { CoordinatorPlugin } from '@mnmal-ai/substrate/sdk';
21
+ import type { SentinelPluginConfig } from './config.js';
22
+ export type { SentinelPluginConfig } from './config.js';
23
+ export { type CoordinatorConnection, createLivenessRegistry, type LivenessRegistry, type LivenessRegistryOptions, type LivenessTickResult, runLivenessTick } from './liveness.js';
24
+ export { buildSentinelNamespace, SENTINEL_TYPE_NAMES } from './namespace.js';
25
+ export { type CoordinatorRecord, registerSentinelStatusRoute } from './status-route.js';
26
+ export { registerSentinelWsRoute } from './ws-route.js';
27
+ export declare function createSentinelPlugin(cfg: SentinelPluginConfig): CoordinatorPlugin;
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAMxD,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EACL,KAAK,qBAAqB,EAC1B,sBAAsB,EACtB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,eAAe,EAChB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,KAAK,iBAAiB,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AACxF,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAExD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,oBAAoB,GAAG,iBAAiB,CAuBjF"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { a as buildSentinelNamespace, i as SENTINEL_TYPE_NAMES, n as registerSentinelWsRoute, o as createLivenessRegistry, r as registerSentinelStatusRoute, s as runLivenessTick, t as createSentinelPlugin } from "./src-DSiwjCeD.js";
2
+
3
+ export { SENTINEL_TYPE_NAMES, buildSentinelNamespace, createLivenessRegistry, createSentinelPlugin, registerSentinelStatusRoute, registerSentinelWsRoute, runLivenessTick };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Liveness bookkeeping for the sentinel WS surface.
3
+ *
4
+ * `WsConnection` has no native ping surface, so this module maintains an
5
+ * application-level liveness protocol over JSON frames:
6
+ *
7
+ * - The registry tracks every live socket in one of two sets: `coordinators`
8
+ * (registered HDS instances) or `watchers` (agents tailing topology).
9
+ * - Each tracked socket records when it was last heard from (`lastSeenMs`),
10
+ * set on add and refreshed by `markAlive()` on any inbound frame.
11
+ * - A tick (driven by the plugin's `ScheduledTask`) calls `drainStale`, which
12
+ * returns every socket whose last heartbeat is older than
13
+ * `staleThresholdMs`, then pings the survivors.
14
+ * - A stale coordinator is evicted: its connection is closed and the
15
+ * matching `Coordinator` row is updated to `status: 'offline'`. A stale
16
+ * watcher is dropped.
17
+ *
18
+ * Staleness is measured against a clock, not by counting ticks, so a late
19
+ * scheduler tick or a slow pong cannot evict a peer early. The registry holds
20
+ * no timers; the clock is injectable for tests.
21
+ */
22
+ import type { EngineHandle, WsConnection } from '@mnmal-ai/substrate/sdk';
23
+ /** Per-coordinator WS metadata captured on `register` frames. */
24
+ export interface CoordinatorConnection {
25
+ name: string;
26
+ coordinatorId: string;
27
+ url: string;
28
+ }
29
+ export interface LivenessRegistryOptions {
30
+ /** Max age of a socket's last heartbeat before it is drained as stale. */
31
+ staleThresholdMs: number;
32
+ /** Clock in epoch milliseconds. Defaults to `Date.now`. */
33
+ now?: () => number;
34
+ }
35
+ export interface LivenessRegistry {
36
+ /**
37
+ * Register a newly-online coordinator. Replaces any prior entry for the same
38
+ * conn, and drops and closes any other conn registered for the same row.
39
+ */
40
+ addCoordinator(conn: WsConnection, meta: CoordinatorConnection): void;
41
+ /** Remove a coordinator (on close or eviction). Returns its metadata if it was present. */
42
+ removeCoordinator(conn: WsConnection): CoordinatorConnection | undefined;
43
+ /** Register a conn as a topology watcher. Idempotent. */
44
+ addWatcher(conn: WsConnection): void;
45
+ /** Drop a watcher (on close). */
46
+ removeWatcher(conn: WsConnection): void;
47
+ /** Record a heartbeat now for any tracked conn (coordinator or watcher). */
48
+ markAlive(conn: WsConnection): void;
49
+ /** Fan out a JSON event to every watcher. Silently drops on send errors. */
50
+ broadcastEvent(event: Record<string, unknown>): void;
51
+ /**
52
+ * Sweep-tick primitive: returns every tracked conn whose last heartbeat is
53
+ * more than `staleThresholdMs` old. Does not remove them.
54
+ */
55
+ drainStale(): Array<WsConnection>;
56
+ /** Introspection for tests and the onClose handler. */
57
+ coordinators(): Array<{
58
+ conn: WsConnection;
59
+ meta: CoordinatorConnection;
60
+ }>;
61
+ /** Introspection for tests. */
62
+ watchers(): Array<WsConnection>;
63
+ }
64
+ export declare function createLivenessRegistry(opts: LivenessRegistryOptions): LivenessRegistry;
65
+ /** Result snapshot returned from a tick. Metric payload shape. */
66
+ export interface LivenessTickResult {
67
+ stalePinged: number;
68
+ markedOffline: number;
69
+ }
70
+ /**
71
+ * Drive one liveness cycle. Returns the number of sockets that were asked to
72
+ * ping this tick, and the number of coordinators evicted (closed + row
73
+ * flipped to offline).
74
+ */
75
+ export declare function runLivenessTick(registry: LivenessRegistry, engine: EngineHandle, namespace: string): Promise<LivenessTickResult>;
76
+ //# sourceMappingURL=liveness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"liveness.d.ts","sourceRoot":"","sources":["../src/liveness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAG1E,iEAAiE;AACjE,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,GAAG,EAAE,MAAM,CAAC;CACb;AAaD,MAAM,WAAW,uBAAuB;IACtC,0EAA0E;IAC1E,gBAAgB,EAAE,MAAM,CAAC;IACzB,2DAA2D;IAC3D,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,qBAAqB,GAAG,IAAI,CAAC;IACtE,2FAA2F;IAC3F,iBAAiB,CAAC,IAAI,EAAE,YAAY,GAAG,qBAAqB,GAAG,SAAS,CAAC;IACzE,yDAAyD;IACzD,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;IACrC,iCAAiC;IACjC,aAAa,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;IACxC,4EAA4E;IAC5E,SAAS,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;IACpC,4EAA4E;IAC5E,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACrD;;;OAGG;IACH,UAAU,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IAClC,uDAAuD;IACvD,YAAY,IAAI,KAAK,CAAC;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,IAAI,EAAE,qBAAqB,CAAA;KAAE,CAAC,CAAC;IAC3E,+BAA+B;IAC/B,QAAQ,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;CACjC;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,uBAAuB,GAAG,gBAAgB,CAkEtF;AAED,kEAAkE;AAClE,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;CACvB;AAyBD;;;;GAIG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,gBAAgB,EAC1B,MAAM,EAAE,YAAY,EACpB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,CAAC,CAuD7B"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * substrate-sentinel namespace definition.
3
+ *
4
+ * Three autoCRUD types: Coordinator, CoordinatorNamespace, CoordinatorBridge.
5
+ * The WS handler composes upsert on top of create/update.
6
+ *
7
+ * `coordinatorId` fields are plain string scalars rather than `field.crossRef`;
8
+ * the §6.1 edge wiring for this surface is deferred.
9
+ */
10
+ import type { NamespaceDefinition } from '@mnmal-ai/substrate/sdk';
11
+ export declare function buildSentinelNamespace(ns: string): NamespaceDefinition;
12
+ /** The canonical ordered list of type names registered by this namespace. */
13
+ export declare const SENTINEL_TYPE_NAMES: readonly ['Coordinator', 'CoordinatorNamespace', 'CoordinatorBridge'];
14
+ //# sourceMappingURL=namespace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespace.d.ts","sourceRoot":"","sources":["../src/namespace.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAGnE,wBAAgB,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,mBAAmB,CAmCtE;AAED,6EAA6E;AAC7E,eAAO,MAAM,mBAAmB,YAC9B,aAAa,EACb,sBAAsB,EACtB,mBAAmB,CACX,CAAC"}
@@ -0,0 +1,552 @@
1
+ import { defineNamespace, field, formatQualifiedKey, grantOf, grantedIn, jsonResponse, makeCtx, queryAll, resolveIdentity } from "@mnmal-ai/substrate/sdk";
2
+
3
+ //#region src/liveness.ts
4
+ function createLivenessRegistry(opts) {
5
+ const { staleThresholdMs } = opts;
6
+ const now = opts.now ?? Date.now;
7
+ const coords = /* @__PURE__ */ new Map();
8
+ const watchers = /* @__PURE__ */ new Map();
9
+ return {
10
+ addCoordinator(conn, meta) {
11
+ for (const [old, entry] of coords) {
12
+ if (old === conn || entry.meta.coordinatorId !== meta.coordinatorId) continue;
13
+ coords.delete(old);
14
+ try {
15
+ old.close(4409, "superseded by a newer registration");
16
+ } catch {}
17
+ }
18
+ coords.set(conn, {
19
+ conn,
20
+ meta,
21
+ lastSeenMs: now()
22
+ });
23
+ },
24
+ removeCoordinator(conn) {
25
+ const entry = coords.get(conn);
26
+ if (entry === void 0) return void 0;
27
+ coords.delete(conn);
28
+ return entry.meta;
29
+ },
30
+ addWatcher(conn) {
31
+ if (watchers.has(conn)) return;
32
+ watchers.set(conn, {
33
+ conn,
34
+ lastSeenMs: now()
35
+ });
36
+ },
37
+ removeWatcher(conn) {
38
+ watchers.delete(conn);
39
+ },
40
+ markAlive(conn) {
41
+ const at = now();
42
+ const coord = coords.get(conn);
43
+ if (coord !== void 0) coord.lastSeenMs = at;
44
+ const watcher = watchers.get(conn);
45
+ if (watcher !== void 0) watcher.lastSeenMs = at;
46
+ },
47
+ broadcastEvent(event) {
48
+ const msg = JSON.stringify(event);
49
+ for (const entry of watchers.values()) try {
50
+ entry.conn.send(msg);
51
+ } catch {}
52
+ },
53
+ drainStale() {
54
+ const cutoff = now() - staleThresholdMs;
55
+ const stale = [];
56
+ for (const entry of [...coords.values(), ...watchers.values()]) if (entry.lastSeenMs < cutoff) stale.push(entry.conn);
57
+ return stale;
58
+ },
59
+ coordinators() {
60
+ return [...coords.values()].map((e) => ({
61
+ conn: e.conn,
62
+ meta: e.meta
63
+ }));
64
+ },
65
+ watchers() {
66
+ return [...watchers.values()].map((e) => e.conn);
67
+ }
68
+ };
69
+ }
70
+ async function markCoordinatorOffline(engine, namespace, coordinatorId) {
71
+ const key = `${namespace}/updateCoordinator`;
72
+ await engine.mutate({
73
+ frame: { [key]: {
74
+ params: {
75
+ id: coordinatorId,
76
+ status: "offline"
77
+ },
78
+ fields: {
79
+ id: true,
80
+ status: true
81
+ }
82
+ } },
83
+ ctx: makeCtx(namespace, "mutate", {
84
+ kind: "system",
85
+ id: "sentinel-liveness",
86
+ grants: { "*": ["read", "mutate"] }
87
+ })
88
+ });
89
+ }
90
+ /**
91
+ * Drive one liveness cycle. Returns the number of sockets that were asked to
92
+ * ping this tick, and the number of coordinators evicted (closed + row
93
+ * flipped to offline).
94
+ */
95
+ async function runLivenessTick(registry, engine, namespace) {
96
+ const coordByConn = new Map(registry.coordinators().map((entry) => [entry.conn, entry.meta]));
97
+ const stale = registry.drainStale();
98
+ let markedOffline = 0;
99
+ for (const conn of stale) {
100
+ const meta = coordByConn.get(conn);
101
+ if (meta !== void 0) {
102
+ try {
103
+ conn.close(4408, "liveness timeout");
104
+ } catch {}
105
+ const coordId = registry.removeCoordinator(conn)?.coordinatorId ?? meta.coordinatorId;
106
+ try {
107
+ await markCoordinatorOffline(engine, namespace, coordId);
108
+ markedOffline++;
109
+ registry.broadcastEvent({
110
+ event: "offline",
111
+ name: meta.name,
112
+ url: meta.url
113
+ });
114
+ } catch {}
115
+ } else {
116
+ registry.removeWatcher(conn);
117
+ try {
118
+ conn.close(4408, "liveness timeout");
119
+ } catch {}
120
+ }
121
+ }
122
+ const pingMsg = JSON.stringify({ type: "ping" });
123
+ const survivors = [];
124
+ for (const entry of registry.coordinators()) survivors.push(entry.conn);
125
+ for (const w of registry.watchers()) survivors.push(w);
126
+ let stalePinged = 0;
127
+ for (const conn of survivors) try {
128
+ conn.send(pingMsg);
129
+ stalePinged++;
130
+ } catch {}
131
+ return {
132
+ stalePinged,
133
+ markedOffline
134
+ };
135
+ }
136
+
137
+ //#endregion
138
+ //#region src/namespace.ts
139
+ function buildSentinelNamespace(ns) {
140
+ return defineNamespace(ns, {
141
+ Coordinator: { fields: {
142
+ name: field.string(),
143
+ url: field.string(),
144
+ namespaces: field.string(),
145
+ status: field.string(),
146
+ lastHeartbeat: field.string(),
147
+ registeredAt: field.string(),
148
+ version: field.string()
149
+ } },
150
+ CoordinatorNamespace: { fields: {
151
+ coordinatorId: field.string(),
152
+ name: field.string(),
153
+ typeCount: field.number(),
154
+ schemaHash: field.string(),
155
+ url: field.string()
156
+ } },
157
+ CoordinatorBridge: { fields: {
158
+ coordinatorId: field.string(),
159
+ name: field.string(),
160
+ targetUrl: field.string(),
161
+ allowMutate: field.boolean(),
162
+ allowPropose: field.boolean()
163
+ } }
164
+ });
165
+ }
166
+ /** The canonical ordered list of type names registered by this namespace. */
167
+ const SENTINEL_TYPE_NAMES = [
168
+ "Coordinator",
169
+ "CoordinatorNamespace",
170
+ "CoordinatorBridge"
171
+ ];
172
+
173
+ //#endregion
174
+ //#region src/status-route.ts
175
+ const COORDINATOR_FIELDS$1 = {
176
+ id: true,
177
+ name: true,
178
+ url: true,
179
+ namespaces: true,
180
+ status: true,
181
+ lastHeartbeat: true,
182
+ registeredAt: true,
183
+ version: true
184
+ };
185
+ async function listCoordinators(engine, namespace, identity) {
186
+ return queryAll(engine, namespace, "Coordinator", {}, COORDINATOR_FIELDS$1, identity);
187
+ }
188
+ function registerSentinelStatusRoute(router, ctx, namespace) {
189
+ router.get("/status", async (req) => {
190
+ try {
191
+ const coordinators = await listCoordinators(ctx.engine, namespace, req.identity ?? null);
192
+ return jsonResponse(200, { coordinators });
193
+ } catch (err) {
194
+ const message = err instanceof Error ? err.message : String(err);
195
+ ctx.metric("sentinel_status_error", { error: message });
196
+ return jsonResponse(200, { coordinators: [] });
197
+ }
198
+ });
199
+ }
200
+
201
+ //#endregion
202
+ //#region src/ws-route.ts
203
+ const COORDINATOR_FIELDS = {
204
+ id: true,
205
+ name: true,
206
+ url: true,
207
+ namespaces: true,
208
+ status: true,
209
+ lastHeartbeat: true,
210
+ registeredAt: true,
211
+ version: true
212
+ };
213
+ const COORDINATOR_NS_FIELDS = {
214
+ id: true,
215
+ coordinatorId: true,
216
+ name: true,
217
+ typeCount: true,
218
+ schemaHash: true,
219
+ url: true
220
+ };
221
+ const BRIDGE_FIELDS = {
222
+ id: true,
223
+ coordinatorId: true,
224
+ name: true,
225
+ targetUrl: true,
226
+ allowMutate: true,
227
+ allowPropose: true
228
+ };
229
+ async function engineMutate(engine, namespace, mutationName, params, fields, identity) {
230
+ const key = formatQualifiedKey(namespace, mutationName);
231
+ const row = (await engine.mutate({
232
+ frame: { [key]: {
233
+ params,
234
+ fields
235
+ } },
236
+ ctx: makeCtx(namespace, "mutate", identity)
237
+ })).data[key];
238
+ if (row === void 0 || row === null) return void 0;
239
+ return row;
240
+ }
241
+ function queryOwned(engine, namespace, identity, where) {
242
+ return queryAll(engine, namespace, "Coordinator", { where }, {
243
+ ...COORDINATOR_FIELDS,
244
+ _metadata: { createdBy: true }
245
+ }, identity);
246
+ }
247
+ /** The actor a write by `identity` records as `createdBy`; null when it cannot be attributed. */
248
+ function actorOf(identity) {
249
+ try {
250
+ return resolveIdentity({ identity });
251
+ } catch {
252
+ return null;
253
+ }
254
+ }
255
+ async function upsertCoordinator(engine, namespace, identity, data) {
256
+ const now = (/* @__PURE__ */ new Date()).toISOString();
257
+ const byName = await queryOwned(engine, namespace, identity, { name: { eq: data.name } });
258
+ const byUrl = await queryOwned(engine, namespace, identity, { url: { eq: data.url } });
259
+ const actor = actorOf(identity);
260
+ const isAdmin = grantsCapability(identity ?? void 0, namespace, "admin");
261
+ const ownedByCaller = (row) => {
262
+ const by = row._metadata?.createdBy;
263
+ if (by === null || by === void 0) return isAdmin;
264
+ return actor !== null && by.kind === actor.kind && by.id === actor.id;
265
+ };
266
+ if (![...byName, ...byUrl].every(ownedByCaller)) return {
267
+ registered: false,
268
+ updated: false,
269
+ coordinator: void 0,
270
+ foreign: true
271
+ };
272
+ const prior = byName[0];
273
+ if (prior !== void 0) {
274
+ const updateParams = {
275
+ id: prior.id,
276
+ url: data.url,
277
+ namespaces: data.namespaces.join(","),
278
+ status: "online",
279
+ lastHeartbeat: now
280
+ };
281
+ if (data.version !== void 0) updateParams.version = data.version;
282
+ const updated = await engineMutate(engine, namespace, "updateCoordinator", updateParams, COORDINATOR_FIELDS, identity);
283
+ if (updated !== void 0) await syncNamespaces(engine, namespace, identity, updated.id, data.url, data.namespaces);
284
+ return {
285
+ registered: true,
286
+ updated: true,
287
+ coordinator: updated
288
+ };
289
+ }
290
+ const created = await engineMutate(engine, namespace, "createCoordinator", {
291
+ name: data.name,
292
+ url: data.url,
293
+ namespaces: data.namespaces.join(","),
294
+ status: "online",
295
+ lastHeartbeat: now,
296
+ registeredAt: now,
297
+ version: data.version ?? ""
298
+ }, COORDINATOR_FIELDS, identity);
299
+ if (created !== void 0) await syncNamespaces(engine, namespace, identity, created.id, data.url, data.namespaces);
300
+ return {
301
+ registered: true,
302
+ updated: false,
303
+ coordinator: created
304
+ };
305
+ }
306
+ async function syncNamespaces(engine, namespace, identity, coordinatorId, coordinatorUrl, desired) {
307
+ const existing = await queryAll(engine, namespace, "CoordinatorNamespace", { where: { coordinatorId: { eq: coordinatorId } } }, COORDINATOR_NS_FIELDS, identity);
308
+ const existingNames = new Set(existing.map((e) => e.name));
309
+ const desiredSet = new Set(desired);
310
+ for (const ns of desired) {
311
+ if (existingNames.has(ns)) continue;
312
+ await engineMutate(engine, namespace, "createCoordinatorNamespace", {
313
+ coordinatorId,
314
+ name: ns,
315
+ url: coordinatorUrl,
316
+ typeCount: 0,
317
+ schemaHash: ""
318
+ }, { id: true }, identity);
319
+ }
320
+ for (const entry of existing) {
321
+ if (desiredSet.has(entry.name)) continue;
322
+ await engineMutate(engine, namespace, "deleteCoordinatorNamespace", { id: entry.id }, { id: true }, identity);
323
+ }
324
+ }
325
+ async function syncBridges(engine, namespace, identity, coordinatorId, bridges) {
326
+ const existing = await queryAll(engine, namespace, "CoordinatorBridge", { where: { coordinatorId: { eq: coordinatorId } } }, BRIDGE_FIELDS, identity);
327
+ const desiredNames = new Set(bridges.map((b) => b.name));
328
+ const existingByName = new Map(existing.map((e) => [e.name, e]));
329
+ for (const bridge of bridges) {
330
+ const prev = existingByName.get(bridge.name);
331
+ if (prev === void 0) {
332
+ await engineMutate(engine, namespace, "createCoordinatorBridge", {
333
+ coordinatorId,
334
+ name: bridge.name,
335
+ targetUrl: bridge.url,
336
+ allowMutate: bridge.allowMutate,
337
+ allowPropose: bridge.allowPropose
338
+ }, { id: true }, identity);
339
+ continue;
340
+ }
341
+ if (prev.targetUrl !== bridge.url || prev.allowMutate !== bridge.allowMutate || prev.allowPropose !== bridge.allowPropose) await engineMutate(engine, namespace, "updateCoordinatorBridge", {
342
+ id: prev.id,
343
+ targetUrl: bridge.url,
344
+ allowMutate: bridge.allowMutate,
345
+ allowPropose: bridge.allowPropose
346
+ }, BRIDGE_FIELDS, identity);
347
+ }
348
+ for (const entry of existing) {
349
+ if (desiredNames.has(entry.name)) continue;
350
+ await engineMutate(engine, namespace, "deleteCoordinatorBridge", { id: entry.id }, { id: true }, identity);
351
+ }
352
+ }
353
+ /**
354
+ * Does this identity hold `capability` IN `namespace`?
355
+ *
356
+ * Resolved through `grantOf` — the SAME function the server's own gates use —
357
+ * so this verdict cannot drift from what the engine enforces.
358
+ */
359
+ function grantsCapability(identity, namespace, capability) {
360
+ if (identity === void 0) return false;
361
+ return grantedIn(grantOf(identity), namespace).includes(capability);
362
+ }
363
+ function sendJson(conn, payload) {
364
+ try {
365
+ conn.send(JSON.stringify(payload));
366
+ } catch {}
367
+ }
368
+ function parseFrame(buf) {
369
+ try {
370
+ const parsed = JSON.parse(buf.toString("utf8"));
371
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
372
+ return parsed;
373
+ } catch {
374
+ return;
375
+ }
376
+ }
377
+ function normaliseNamespaces(raw) {
378
+ if (!Array.isArray(raw)) return [];
379
+ const out = [];
380
+ for (const item of raw) if (typeof item === "string" && item.length > 0) out.push(item);
381
+ return out;
382
+ }
383
+ function normaliseBridges(raw) {
384
+ if (!Array.isArray(raw)) return [];
385
+ const out = [];
386
+ for (const item of raw) {
387
+ if (item === null || typeof item !== "object") continue;
388
+ const r = item;
389
+ if (typeof r.name !== "string" || typeof r.url !== "string" || typeof r.allowMutate !== "boolean" || typeof r.allowPropose !== "boolean") continue;
390
+ out.push({
391
+ name: r.name,
392
+ url: r.url,
393
+ allowMutate: r.allowMutate,
394
+ allowPropose: r.allowPropose
395
+ });
396
+ }
397
+ return out;
398
+ }
399
+ async function handleRegister(engine, namespace, identity, registry, conn, frame) {
400
+ const name = typeof frame.name === "string" ? frame.name : void 0;
401
+ const url = typeof frame.url === "string" ? frame.url : void 0;
402
+ if (name === void 0 || url === void 0) {
403
+ sendJson(conn, { error: "register requires name and url" });
404
+ return;
405
+ }
406
+ const namespaces = normaliseNamespaces(frame.namespaces);
407
+ const version = typeof frame.version === "string" ? frame.version : void 0;
408
+ const bridges = normaliseBridges(frame.bridges);
409
+ const upsertArgs = {
410
+ name,
411
+ url,
412
+ namespaces
413
+ };
414
+ if (version !== void 0) upsertArgs.version = version;
415
+ if (actorOf(identity) === null) {
416
+ sendJson(conn, { error: "register requires an attributable identity (an agent key, a token, or a system actor); this one cannot be recorded as the coordinator row's creator" });
417
+ return;
418
+ }
419
+ const result = await upsertCoordinator(engine, namespace, identity, upsertArgs);
420
+ if (result.foreign === true) {
421
+ sendJson(conn, { error: `coordinator '${name}' or url '${url}' is registered by another identity` });
422
+ return;
423
+ }
424
+ const coordinator = result.coordinator;
425
+ if (coordinator === void 0) {
426
+ sendJson(conn, { error: "failed to upsert coordinator record" });
427
+ return;
428
+ }
429
+ const meta = {
430
+ name,
431
+ coordinatorId: coordinator.id,
432
+ url
433
+ };
434
+ registry.addCoordinator(conn, meta);
435
+ if (bridges.length > 0) await syncBridges(engine, namespace, identity, coordinator.id, bridges);
436
+ sendJson(conn, {
437
+ ok: true,
438
+ registered: result.registered,
439
+ updated: result.updated,
440
+ coordinator
441
+ });
442
+ registry.broadcastEvent({
443
+ event: "online",
444
+ name,
445
+ url,
446
+ namespaces,
447
+ bridges: bridges.map((b) => ({
448
+ name: b.name,
449
+ url: b.url,
450
+ allowMutate: b.allowMutate,
451
+ allowPropose: b.allowPropose
452
+ }))
453
+ });
454
+ }
455
+ function handleWatch(registry, conn) {
456
+ registry.addWatcher(conn);
457
+ sendJson(conn, {
458
+ ok: true,
459
+ watching: true
460
+ });
461
+ }
462
+ async function handleClose(engine, namespace, identity, registry, conn) {
463
+ const meta = registry.removeCoordinator(conn);
464
+ registry.removeWatcher(conn);
465
+ if (meta === void 0) return;
466
+ try {
467
+ await engineMutate(engine, namespace, "updateCoordinator", {
468
+ id: meta.coordinatorId,
469
+ status: "offline"
470
+ }, {
471
+ id: true,
472
+ status: true
473
+ }, identity);
474
+ } catch {}
475
+ registry.broadcastEvent({
476
+ event: "offline",
477
+ name: meta.name,
478
+ url: meta.url
479
+ });
480
+ }
481
+ function registerSentinelWsRoute(router, ctx, namespace, registry) {
482
+ router.websocket("/ws", (req, conn) => {
483
+ const identity = req.identity;
484
+ conn.onMessage((buf) => {
485
+ const frame = parseFrame(buf);
486
+ if (frame === void 0) {
487
+ sendJson(conn, { error: "invalid JSON" });
488
+ return;
489
+ }
490
+ registry.markAlive(conn);
491
+ const type = typeof frame.type === "string" ? frame.type : void 0;
492
+ const required = type === "register" ? "mutate" : type === "watch" ? "read" : void 0;
493
+ if (required !== void 0) {
494
+ if (identity === void 0) {
495
+ ctx.metric("sentinel_frame_unauthorized", { type });
496
+ sendJson(conn, { error: "unauthorized" });
497
+ return;
498
+ }
499
+ if (!grantsCapability(identity, namespace, required)) {
500
+ ctx.metric("sentinel_frame_forbidden", {
501
+ type,
502
+ required
503
+ });
504
+ sendJson(conn, { error: "forbidden" });
505
+ return;
506
+ }
507
+ }
508
+ if (type === "register") {
509
+ handleRegister(ctx.engine, namespace, identity ?? null, registry, conn, frame).catch(() => {
510
+ sendJson(conn, { error: "register failed" });
511
+ });
512
+ return;
513
+ }
514
+ if (type === "watch") {
515
+ handleWatch(registry, conn);
516
+ return;
517
+ }
518
+ if (type === "pong") return;
519
+ sendJson(conn, { error: "unknown frame type" });
520
+ });
521
+ conn.onClose(() => {
522
+ handleClose(ctx.engine, namespace, identity ?? null, registry, conn).catch(() => {});
523
+ });
524
+ });
525
+ }
526
+
527
+ //#endregion
528
+ //#region src/index.ts
529
+ function createSentinelPlugin(cfg) {
530
+ const registry = createLivenessRegistry({ staleThresholdMs: cfg.staleThresholdMs });
531
+ return {
532
+ name: "substrate-sentinel",
533
+ contractVersion: ">=1.0.0-alpha.0 <2.0.0",
534
+ namespaces: [buildSentinelNamespace(cfg.namespace)],
535
+ schedule: [{
536
+ name: `${cfg.namespace}-liveness`,
537
+ intervalMs: cfg.pingIntervalMs,
538
+ runOnStart: false,
539
+ handler: async (taskCtx) => {
540
+ const result = await runLivenessTick(registry, taskCtx.engine, cfg.namespace);
541
+ taskCtx.metric("sentinel_liveness_tick", result);
542
+ }
543
+ }],
544
+ routes: (router, routeCtx) => {
545
+ registerSentinelStatusRoute(router, routeCtx, cfg.namespace);
546
+ registerSentinelWsRoute(router, routeCtx, cfg.namespace, registry);
547
+ }
548
+ };
549
+ }
550
+
551
+ //#endregion
552
+ export { buildSentinelNamespace as a, SENTINEL_TYPE_NAMES as i, registerSentinelWsRoute as n, createLivenessRegistry as o, registerSentinelStatusRoute as r, runLivenessTick as s, createSentinelPlugin as t };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Status route — `GET /plugins/substrate-sentinel/status`.
3
+ *
4
+ * Reads the current Coordinator set from the configured namespace and returns
5
+ * it as `{ coordinators: CoordinatorRecord[] }`, under the caller's grant and
6
+ * row policy. Engine faults and refusals yield an empty
7
+ * list (dashboards rely on a 200 JSON shape) plus a `sentinel_status_error`
8
+ * metric.
9
+ */
10
+ import type { PluginRouteContext, PluginRouter } from '@mnmal-ai/substrate/sdk';
11
+ export interface CoordinatorRecord {
12
+ id: number | string;
13
+ name: string;
14
+ url: string;
15
+ namespaces: string;
16
+ status: string;
17
+ lastHeartbeat: string;
18
+ registeredAt: string;
19
+ version: string;
20
+ }
21
+ export declare function registerSentinelStatusRoute(router: PluginRouter, ctx: PluginRouteContext, namespace: string): void;
22
+ //# sourceMappingURL=status-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status-route.d.ts","sourceRoot":"","sources":["../src/status-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAGV,kBAAkB,EAClB,YAAY,EAEb,MAAM,yBAAyB,CAAC;AAGjC,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;CACjB;AA4BD,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,YAAY,EACpB,GAAG,EAAE,kBAAkB,EACvB,SAAS,EAAE,MAAM,GAChB,IAAI,CAYN"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * WS route — `/substrate/v1/plugins/substrate-sentinel/ws`.
3
+ *
4
+ * Built on `PluginRouter.websocket`, a framework-agnostic primitive (§4.8) with
5
+ * no native ping/pong and no raw `terminate()`; `./liveness.ts` supplies an
6
+ * application-level heartbeat.
7
+ *
8
+ * Frame protocol (JSON, UTF-8):
9
+ * - client → server
10
+ * - `{ type: 'register', name, url, namespaces: string[], version?, bridges?: [...] }` (requires 'mutate')
11
+ * - `{ type: 'watch' }` (requires 'read')
12
+ * - `{ type: 'pong' }` (application heartbeat ack, unauthenticated)
13
+ * - server → client
14
+ * - `{ ok: true, registered, updated, coordinator }` (register reply)
15
+ * - `{ ok: true, watching: true }` (watch reply)
16
+ * - `{ event: 'online' | 'offline', name, url, ... }` (watcher broadcast)
17
+ * - `{ type: 'ping' }` (liveness tick)
18
+ * - `{ error: 'unknown frame type' }` (parser errors)
19
+ * - `{ error: 'unauthorized' }` (register/watch, no identity)
20
+ * - `{ error: 'forbidden' }` (register/watch, identity lacks the capability)
21
+ *
22
+ * Auth: `register` requires the 'mutate' capability (it mutates the
23
+ * coordinator table) and `watch` requires 'read' (it subscribes to the
24
+ * topology broadcast) — mirroring `withAuth`'s method-based capability map
25
+ * for the HTTP routes (`substrate-compose`'s `compose.ts`). Both require
26
+ * `req.identity` to be populated at all, resolved once at upgrade by
27
+ * `wrapWsHandler`: missing identity is 'unauthorized', an
28
+ * identity present but lacking the capability is 'forbidden'. `pong` carries
29
+ * no capability requirement of its own — it is liveness only — but that is
30
+ * not the same as being open to anonymous callers: under the default
31
+ * `required` auth mode an unauthenticated connection is closed at upgrade and
32
+ * never reaches this frame handler at all. Anonymous `pong` is reachable only
33
+ * where the transport admits anonymous connections (attribute mode).
34
+ */
35
+ import type { PluginRouteContext, PluginRouter } from '@mnmal-ai/substrate/sdk';
36
+ import type { LivenessRegistry } from './liveness.js';
37
+ export declare function registerSentinelWsRoute(router: PluginRouter, ctx: PluginRouteContext, namespace: string, registry: LivenessRegistry): void;
38
+ //# sourceMappingURL=ws-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws-route.d.ts","sourceRoot":"","sources":["../src/ws-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,KAAK,EAIV,kBAAkB,EAClB,YAAY,EAGb,MAAM,yBAAyB,CAAC;AASjC,OAAO,KAAK,EAAyB,gBAAgB,EAAE,MAAM,eAAe,CAAC;AA8e7E,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,YAAY,EACpB,GAAG,EAAE,kBAAkB,EACvB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,gBAAgB,GACzB,IAAI,CA4DN"}
package/package.json CHANGED
@@ -1,7 +1,60 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate-sentinel",
3
- "version": "0.0.0",
4
- "description": "Reserved by MNMAL. Not yet released.",
3
+ "version": "1.0.0-alpha.1",
4
+ "description": "Substrate coordinator plugin: registry for dynamic bridge discovery.",
5
5
  "license": "Apache-2.0",
6
- "files": ["README.md"]
7
- }
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mnmal-ai/substrate.git",
9
+ "directory": "plugins/substrate-sentinel"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts"
16
+ },
17
+ "./bootstrap": {
18
+ "import": "./dist/bootstrap.js",
19
+ "types": "./dist/bootstrap.d.ts"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "default-config.json",
25
+ "config.schema.json"
26
+ ],
27
+ "publishConfig": {
28
+ "registry": "https://registry.npmjs.org/",
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "zod": "^4.6.5"
33
+ },
34
+ "devDependencies": {
35
+ "@mnmal-ai/substrate": "1.0.0-alpha.1",
36
+ "@mnmal-ai/substrate-config": "1.0.0-alpha.1",
37
+ "@types/node": "^26.6.4",
38
+ "tsdown": "^0.23.0",
39
+ "typescript": "^7.0.2",
40
+ "vitest": "^5.0.3"
41
+ },
42
+ "peerDependencies": {
43
+ "@mnmal-ai/substrate": ">=1.0.0-alpha.0 <2.0.0"
44
+ },
45
+ "engines": {
46
+ "node": ">=26.2.0"
47
+ },
48
+ "substrate": {
49
+ "tier": "coordinator",
50
+ "entry": "./dist/bootstrap.js",
51
+ "configSchema": "./config.schema.json",
52
+ "defaultConfig": "./default-config.json"
53
+ },
54
+ "scripts": {
55
+ "build": "tsdown && tsc -p tsconfig.dts.json",
56
+ "test": "vitest run",
57
+ "check-types": "tsc -p tsconfig.json --noEmit",
58
+ "lint": "biome check ."
59
+ }
60
+ }