@brud/kernel 0.0.0-stage → 0.0.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.
Files changed (278) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +63 -2
  3. package/dist/index.d.ts +15 -0
  4. package/dist/index.js +13 -0
  5. package/dist/serviceModules/events.d.ts +1 -0
  6. package/dist/serviceModules/events.js +1 -0
  7. package/dist/serviceModules/exposedApiRegistry.d.ts +1 -0
  8. package/dist/serviceModules/exposedApiRegistry.js +1 -0
  9. package/dist/serviceModules/identityRegistry.d.ts +1 -0
  10. package/dist/serviceModules/identityRegistry.js +1 -0
  11. package/dist/serviceModules/interception.d.ts +1 -0
  12. package/dist/serviceModules/interception.js +1 -0
  13. package/dist/serviceModules/parser.d.ts +1 -0
  14. package/dist/serviceModules/parser.js +1 -0
  15. package/dist/serviceModules/router.d.ts +1 -0
  16. package/dist/serviceModules/router.js +1 -0
  17. package/dist/serviceModules/wasmCage.d.ts +1 -0
  18. package/dist/serviceModules/wasmCage.js +1 -0
  19. package/dist/services/Events/contracts/IEventsService.d.ts +64 -0
  20. package/dist/services/Events/contracts/IEventsService.js +1 -0
  21. package/dist/services/Events/contracts/errors.d.ts +31 -0
  22. package/dist/services/Events/contracts/errors.js +40 -0
  23. package/dist/services/Events/contracts/index.d.ts +3 -0
  24. package/dist/services/Events/contracts/index.js +3 -0
  25. package/dist/services/Events/contracts/tokens.d.ts +2 -0
  26. package/dist/services/Events/contracts/tokens.js +2 -0
  27. package/dist/services/Events/descriptor/EventsDescriptor.d.ts +9 -0
  28. package/dist/services/Events/descriptor/EventsDescriptor.js +56 -0
  29. package/dist/services/Events/descriptor/tokens.d.ts +1 -0
  30. package/dist/services/Events/descriptor/tokens.js +1 -0
  31. package/dist/services/Events/index.d.ts +4 -0
  32. package/dist/services/Events/index.js +4 -0
  33. package/dist/services/Events/orchestrator/EventsService.d.ts +51 -0
  34. package/dist/services/Events/orchestrator/EventsService.js +339 -0
  35. package/dist/services/Events/orchestrator/index.d.ts +2 -0
  36. package/dist/services/Events/orchestrator/index.js +2 -0
  37. package/dist/services/Events/orchestrator/limits.d.ts +22 -0
  38. package/dist/services/Events/orchestrator/limits.js +33 -0
  39. package/dist/services/Events/serviceModule.d.ts +2 -0
  40. package/dist/services/Events/serviceModule.js +5 -0
  41. package/dist/services/ExposedApiRegistry/contracts/IExposedApiRegistry.d.ts +44 -0
  42. package/dist/services/ExposedApiRegistry/contracts/IExposedApiRegistry.js +1 -0
  43. package/dist/services/ExposedApiRegistry/contracts/errors.d.ts +132 -0
  44. package/dist/services/ExposedApiRegistry/contracts/errors.js +195 -0
  45. package/dist/services/ExposedApiRegistry/contracts/index.d.ts +9 -0
  46. package/dist/services/ExposedApiRegistry/contracts/index.js +4 -0
  47. package/dist/services/ExposedApiRegistry/contracts/policy.d.ts +90 -0
  48. package/dist/services/ExposedApiRegistry/contracts/policy.js +169 -0
  49. package/dist/services/ExposedApiRegistry/contracts/registrant.d.ts +37 -0
  50. package/dist/services/ExposedApiRegistry/contracts/registrant.js +36 -0
  51. package/dist/services/ExposedApiRegistry/contracts/types.d.ts +112 -0
  52. package/dist/services/ExposedApiRegistry/contracts/types.js +73 -0
  53. package/dist/services/ExposedApiRegistry/descriptor/ExposedApiRegistryDescriptor.d.ts +44 -0
  54. package/dist/services/ExposedApiRegistry/descriptor/ExposedApiRegistryDescriptor.js +58 -0
  55. package/dist/services/ExposedApiRegistry/descriptor/tokens.d.ts +8 -0
  56. package/dist/services/ExposedApiRegistry/descriptor/tokens.js +8 -0
  57. package/dist/services/ExposedApiRegistry/index.d.ts +6 -0
  58. package/dist/services/ExposedApiRegistry/index.js +5 -0
  59. package/dist/services/ExposedApiRegistry/orchestrator/ExposedApiRegistryService.d.ts +61 -0
  60. package/dist/services/ExposedApiRegistry/orchestrator/ExposedApiRegistryService.js +407 -0
  61. package/dist/services/ExposedApiRegistry/orchestrator/index.d.ts +2 -0
  62. package/dist/services/ExposedApiRegistry/orchestrator/index.js +1 -0
  63. package/dist/services/ExposedApiRegistry/serviceModule.d.ts +10 -0
  64. package/dist/services/ExposedApiRegistry/serviceModule.js +20 -0
  65. package/dist/services/ExposedApiRegistry/storage/protection.d.ts +21 -0
  66. package/dist/services/ExposedApiRegistry/storage/protection.js +35 -0
  67. package/dist/services/ExposedApiRegistry/storage/scopeRecord.d.ts +45 -0
  68. package/dist/services/ExposedApiRegistry/storage/scopeRecord.js +178 -0
  69. package/dist/services/IdentityRegistry/contracts/errors.d.ts +88 -0
  70. package/dist/services/IdentityRegistry/contracts/errors.js +128 -0
  71. package/dist/services/IdentityRegistry/contracts/index.d.ts +5 -0
  72. package/dist/services/IdentityRegistry/contracts/index.js +3 -0
  73. package/dist/services/IdentityRegistry/contracts/types.d.ts +77 -0
  74. package/dist/services/IdentityRegistry/contracts/types.js +18 -0
  75. package/dist/services/IdentityRegistry/descriptor/descriptor.d.ts +36 -0
  76. package/dist/services/IdentityRegistry/descriptor/descriptor.js +44 -0
  77. package/dist/services/IdentityRegistry/descriptor/tokens.d.ts +8 -0
  78. package/dist/services/IdentityRegistry/descriptor/tokens.js +8 -0
  79. package/dist/services/IdentityRegistry/index.d.ts +11 -0
  80. package/dist/services/IdentityRegistry/index.js +6 -0
  81. package/dist/services/IdentityRegistry/orchestrator/IdentityRegistryService.d.ts +47 -0
  82. package/dist/services/IdentityRegistry/orchestrator/IdentityRegistryService.js +240 -0
  83. package/dist/services/IdentityRegistry/serviceModule.d.ts +10 -0
  84. package/dist/services/IdentityRegistry/serviceModule.js +24 -0
  85. package/dist/services/IdentityRegistry/storage/registryDocument.d.ts +55 -0
  86. package/dist/services/IdentityRegistry/storage/registryDocument.js +235 -0
  87. package/dist/services/Interception/contracts/IInterceptionService.d.ts +65 -0
  88. package/dist/services/Interception/contracts/IInterceptionService.js +1 -0
  89. package/dist/services/Interception/contracts/errors.d.ts +26 -0
  90. package/dist/services/Interception/contracts/errors.js +35 -0
  91. package/dist/services/Interception/contracts/index.d.ts +3 -0
  92. package/dist/services/Interception/contracts/index.js +3 -0
  93. package/dist/services/Interception/contracts/tokens.d.ts +2 -0
  94. package/dist/services/Interception/contracts/tokens.js +2 -0
  95. package/dist/services/Interception/descriptor/InterceptionDescriptor.d.ts +9 -0
  96. package/dist/services/Interception/descriptor/InterceptionDescriptor.js +49 -0
  97. package/dist/services/Interception/descriptor/tokens.d.ts +1 -0
  98. package/dist/services/Interception/descriptor/tokens.js +1 -0
  99. package/dist/services/Interception/index.d.ts +4 -0
  100. package/dist/services/Interception/index.js +4 -0
  101. package/dist/services/Interception/orchestrator/InterceptionService.d.ts +32 -0
  102. package/dist/services/Interception/orchestrator/InterceptionService.js +180 -0
  103. package/dist/services/Interception/orchestrator/index.d.ts +1 -0
  104. package/dist/services/Interception/orchestrator/index.js +1 -0
  105. package/dist/services/Interception/serviceModule.d.ts +2 -0
  106. package/dist/services/Interception/serviceModule.js +5 -0
  107. package/dist/services/Parser/contracts/IParserService.d.ts +21 -0
  108. package/dist/services/Parser/contracts/IParserService.js +1 -0
  109. package/dist/services/Parser/contracts/errors.d.ts +25 -0
  110. package/dist/services/Parser/contracts/errors.js +33 -0
  111. package/dist/services/Parser/contracts/index.d.ts +4 -0
  112. package/dist/services/Parser/contracts/index.js +1 -0
  113. package/dist/services/Parser/contracts/types.d.ts +42 -0
  114. package/dist/services/Parser/contracts/types.js +1 -0
  115. package/dist/services/Parser/descriptor/ParserDescriptor.d.ts +23 -0
  116. package/dist/services/Parser/descriptor/ParserDescriptor.js +50 -0
  117. package/dist/services/Parser/descriptor/tokens.d.ts +8 -0
  118. package/dist/services/Parser/descriptor/tokens.js +8 -0
  119. package/dist/services/Parser/index.d.ts +8 -0
  120. package/dist/services/Parser/index.js +8 -0
  121. package/dist/services/Parser/orchestrator/ParserService.d.ts +20 -0
  122. package/dist/services/Parser/orchestrator/ParserService.js +105 -0
  123. package/dist/services/Parser/orchestrator/index.d.ts +1 -0
  124. package/dist/services/Parser/orchestrator/index.js +1 -0
  125. package/dist/services/Parser/parser/indexSynthesis.d.ts +11 -0
  126. package/dist/services/Parser/parser/indexSynthesis.js +13 -0
  127. package/dist/services/Parser/parser/parameters.d.ts +14 -0
  128. package/dist/services/Parser/parser/parameters.js +89 -0
  129. package/dist/services/Parser/parser/scanner.d.ts +48 -0
  130. package/dist/services/Parser/parser/scanner.js +156 -0
  131. package/dist/services/Parser/parser/syntax.d.ts +30 -0
  132. package/dist/services/Parser/parser/syntax.js +34 -0
  133. package/dist/services/Parser/serviceModule.d.ts +2 -0
  134. package/dist/services/Parser/serviceModule.js +5 -0
  135. package/dist/services/Router/bootOptions.d.ts +2 -0
  136. package/dist/services/Router/bootOptions.js +2 -0
  137. package/dist/services/Router/contracts/IRouterService.d.ts +43 -0
  138. package/dist/services/Router/contracts/IRouterService.js +1 -0
  139. package/dist/services/Router/contracts/caller.d.ts +6 -0
  140. package/dist/services/Router/contracts/caller.js +6 -0
  141. package/dist/services/Router/contracts/errors.d.ts +56 -0
  142. package/dist/services/Router/contracts/errors.js +75 -0
  143. package/dist/services/Router/contracts/index.d.ts +8 -0
  144. package/dist/services/Router/contracts/index.js +4 -0
  145. package/dist/services/Router/contracts/kind.d.ts +7 -0
  146. package/dist/services/Router/contracts/kind.js +10 -0
  147. package/dist/services/Router/contracts/registrant.d.ts +23 -0
  148. package/dist/services/Router/contracts/registrant.js +13 -0
  149. package/dist/services/Router/contracts/types.d.ts +90 -0
  150. package/dist/services/Router/contracts/types.js +1 -0
  151. package/dist/services/Router/descriptor/RouterDescriptor.d.ts +32 -0
  152. package/dist/services/Router/descriptor/RouterDescriptor.js +92 -0
  153. package/dist/services/Router/descriptor/tokens.d.ts +9 -0
  154. package/dist/services/Router/descriptor/tokens.js +9 -0
  155. package/dist/services/Router/index.d.ts +4 -0
  156. package/dist/services/Router/index.js +4 -0
  157. package/dist/services/Router/orchestrator/RouterService.d.ts +74 -0
  158. package/dist/services/Router/orchestrator/RouterService.js +332 -0
  159. package/dist/services/Router/orchestrator/index.d.ts +2 -0
  160. package/dist/services/Router/orchestrator/index.js +1 -0
  161. package/dist/services/Router/serviceModule.d.ts +4 -0
  162. package/dist/services/Router/serviceModule.js +22 -0
  163. package/dist/services/WasmCage/index.d.ts +7 -0
  164. package/dist/services/WasmCage/index.js +4 -0
  165. package/dist/services/WasmCage/scripts/prepin.d.ts +1 -0
  166. package/dist/services/WasmCage/scripts/prepin.js +38 -0
  167. package/dist/services/WasmCage/serviceModule.d.ts +12 -0
  168. package/dist/services/WasmCage/serviceModule.js +18 -0
  169. package/dist/services/WasmCage/src/caged.d.ts +104 -0
  170. package/dist/services/WasmCage/src/caged.js +381 -0
  171. package/dist/services/WasmCage/src/descriptor.d.ts +47 -0
  172. package/dist/services/WasmCage/src/descriptor.js +56 -0
  173. package/dist/services/WasmCage/src/native.d.ts +29 -0
  174. package/dist/services/WasmCage/src/native.js +66 -0
  175. package/dist/services/WasmCage/src/nativeDigests.d.ts +9 -0
  176. package/dist/services/WasmCage/src/nativeDigests.js +15 -0
  177. package/dist/services/WasmCage/src/package.d.ts +36 -0
  178. package/dist/services/WasmCage/src/package.js +122 -0
  179. package/dist/services/shared/canonicalJson.d.ts +29 -0
  180. package/dist/services/shared/canonicalJson.js +93 -0
  181. package/dist/services/shared/documentStore.d.ts +16 -0
  182. package/dist/services/shared/documentStore.js +98 -0
  183. package/dist/src/bootstrap/bootKernelInternal.d.ts +18 -0
  184. package/dist/src/bootstrap/bootKernelInternal.js +420 -0
  185. package/dist/src/bootstrap/bootTypes.d.ts +89 -0
  186. package/dist/src/bootstrap/bootTypes.js +1 -0
  187. package/dist/src/bootstrap/config/index.d.ts +3 -0
  188. package/dist/src/bootstrap/config/index.js +2 -0
  189. package/dist/src/bootstrap/config/integrity.d.ts +34 -0
  190. package/dist/src/bootstrap/config/integrity.js +79 -0
  191. package/dist/src/bootstrap/config/parse.d.ts +15 -0
  192. package/dist/src/bootstrap/config/parse.js +81 -0
  193. package/dist/src/bootstrap/config/pathWriteGuard.d.ts +20 -0
  194. package/dist/src/bootstrap/config/pathWriteGuard.js +349 -0
  195. package/dist/src/bootstrap/config/types.d.ts +41 -0
  196. package/dist/src/bootstrap/config/types.js +15 -0
  197. package/dist/src/bootstrap/hardcore.d.ts +212 -0
  198. package/dist/src/bootstrap/hardcore.js +312 -0
  199. package/dist/src/bootstrap/hardcoreServices.d.ts +10 -0
  200. package/dist/src/bootstrap/hardcoreServices.js +258 -0
  201. package/dist/src/bootstrap/index.d.ts +8 -0
  202. package/dist/src/bootstrap/index.js +5 -0
  203. package/dist/src/bootstrap/packageRequirements.d.ts +26 -0
  204. package/dist/src/bootstrap/packageRequirements.js +52 -0
  205. package/dist/src/contracts/accessBroker.d.ts +53 -0
  206. package/dist/src/contracts/accessBroker.js +1 -0
  207. package/dist/src/contracts/brudOperation.d.ts +20 -0
  208. package/dist/src/contracts/brudOperation.js +20 -0
  209. package/dist/src/contracts/callChain.d.ts +161 -0
  210. package/dist/src/contracts/callChain.js +19 -0
  211. package/dist/src/contracts/capability.d.ts +26 -0
  212. package/dist/src/contracts/capability.js +26 -0
  213. package/dist/src/contracts/container.d.ts +17 -0
  214. package/dist/src/contracts/container.js +8 -0
  215. package/dist/src/contracts/context.d.ts +19 -0
  216. package/dist/src/contracts/context.js +1 -0
  217. package/dist/src/contracts/contextContract.d.ts +129 -0
  218. package/dist/src/contracts/contextContract.js +285 -0
  219. package/dist/src/contracts/dispatchView.d.ts +21 -0
  220. package/dist/src/contracts/dispatchView.js +1 -0
  221. package/dist/src/contracts/handler.d.ts +28 -0
  222. package/dist/src/contracts/handler.js +1 -0
  223. package/dist/src/contracts/index.d.ts +25 -0
  224. package/dist/src/contracts/index.js +8 -0
  225. package/dist/src/contracts/kernel.d.ts +60 -0
  226. package/dist/src/contracts/kernel.js +1 -0
  227. package/dist/src/contracts/lifecycle.d.ts +59 -0
  228. package/dist/src/contracts/lifecycle.js +1 -0
  229. package/dist/src/contracts/manifest.d.ts +145 -0
  230. package/dist/src/contracts/manifest.js +295 -0
  231. package/dist/src/contracts/pipeline.d.ts +8 -0
  232. package/dist/src/contracts/pipeline.js +1 -0
  233. package/dist/src/contracts/policy.d.ts +75 -0
  234. package/dist/src/contracts/policy.js +77 -0
  235. package/dist/src/contracts/registry.d.ts +7 -0
  236. package/dist/src/contracts/registry.js +1 -0
  237. package/dist/src/contracts/serviceDescriptor.d.ts +67 -0
  238. package/dist/src/contracts/serviceDescriptor.js +1 -0
  239. package/dist/src/contracts/serviceToken.d.ts +36 -0
  240. package/dist/src/contracts/serviceToken.js +16 -0
  241. package/dist/src/engine/BrudKernel.d.ts +118 -0
  242. package/dist/src/engine/BrudKernel.js +366 -0
  243. package/dist/src/engine/ExecutionPipeline.d.ts +13 -0
  244. package/dist/src/engine/ExecutionPipeline.js +62 -0
  245. package/dist/src/engine/KernelAccessBroker.d.ts +47 -0
  246. package/dist/src/engine/KernelAccessBroker.js +107 -0
  247. package/dist/src/engine/KernelRegistry.d.ts +14 -0
  248. package/dist/src/engine/KernelRegistry.js +33 -0
  249. package/dist/src/engine/OperationRegistry.d.ts +9 -0
  250. package/dist/src/engine/OperationRegistry.js +18 -0
  251. package/dist/src/engine/ServiceContainer.d.ts +13 -0
  252. package/dist/src/engine/ServiceContainer.js +53 -0
  253. package/dist/src/engine/callChain.d.ts +68 -0
  254. package/dist/src/engine/callChain.js +180 -0
  255. package/dist/src/engine/dag.d.ts +2 -0
  256. package/dist/src/engine/dag.js +34 -0
  257. package/dist/src/engine/errors.d.ts +26 -0
  258. package/dist/src/engine/errors.js +52 -0
  259. package/dist/src/engine/index.d.ts +11 -0
  260. package/dist/src/engine/index.js +8 -0
  261. package/dist/src/engine/state.d.ts +1 -0
  262. package/dist/src/engine/state.js +1 -0
  263. package/dist/src/validation/jsonSchema/compile.d.ts +8 -0
  264. package/dist/src/validation/jsonSchema/compile.js +386 -0
  265. package/dist/src/validation/jsonSchema/index.d.ts +3 -0
  266. package/dist/src/validation/jsonSchema/index.js +2 -0
  267. package/dist/src/validation/jsonSchema/jsonValue.d.ts +29 -0
  268. package/dist/src/validation/jsonSchema/jsonValue.js +190 -0
  269. package/dist/src/validation/jsonSchema/pattern.d.ts +28 -0
  270. package/dist/src/validation/jsonSchema/pattern.js +155 -0
  271. package/dist/src/validation/jsonSchema/types.d.ts +71 -0
  272. package/dist/src/validation/jsonSchema/types.js +15 -0
  273. package/package.json +59 -4
  274. package/services/WasmCage/native/brud-wasm-cage.darwin-arm64.node +0 -0
  275. package/services/WasmCage/native/brud-wasm-cage.darwin-x64.node +0 -0
  276. package/services/WasmCage/native/brud-wasm-cage.linux-arm64-gnu.node +0 -0
  277. package/services/WasmCage/native/brud-wasm-cage.linux-x64-gnu.node +0 -0
  278. package/services/WasmCage/native/brud-wasm-cage.win32-x64-msvc.node +0 -0
@@ -0,0 +1,420 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, relative as relativePath, resolve as resolvePath } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { ContextContract, ContextContractError, } from '../contracts/contextContract.js';
6
+ import { admitParticipantManifest } from '../contracts/manifest.js';
7
+ import { BrudKernel } from '../engine/BrudKernel.js';
8
+ import { protectConfigFile, recordConfigRead, releaseConfigProtection, verifyConfigIntegrity, } from './config/integrity.js';
9
+ import { lineOf, parseBrudConfig } from './config/parse.js';
10
+ import { PackageRequirementsError, readPackageRequirements } from './packageRequirements.js';
11
+ import { buildHardcoreBootEntries, invokeHardcoreBootHooks, verifyHardcoreServices, } from './hardcore.js';
12
+ import { HARDCORE_SERVICES } from './hardcoreServices.js';
13
+ import { BrudConfigError, } from './config/types.js';
14
+ /** Root the `kernel:` module prefix resolves from (`packages/kernel/`). */
15
+ const KERNEL_PACKAGE_ROOT = new URL('../../', import.meta.url);
16
+ /** Fallback diagnostic sink used when the host does not supply one. */
17
+ const DEFAULT_KERNEL_LOGGER = {
18
+ warn: (message, meta) => {
19
+ console.warn(message, meta ?? {});
20
+ },
21
+ };
22
+ /** Returns the boot-policy hook exported by a module, if any. */
23
+ function pinBootPoliciesHook(moduleValue) {
24
+ if (!isRecord(moduleValue) || typeof moduleValue.pinBootPolicies !== 'function') {
25
+ return undefined;
26
+ }
27
+ return moduleValue.pinBootPolicies;
28
+ }
29
+ /** Returns the boot-registrant hook exported by a module, if any. */
30
+ function registerBootRegistrantsHook(moduleValue) {
31
+ if (!isRecord(moduleValue) || typeof moduleValue.registerBootRegistrants !== 'function') {
32
+ return undefined;
33
+ }
34
+ return moduleValue.registerBootRegistrants;
35
+ }
36
+ /**
37
+ * Reads, validates, composes, and boots a kernel from `brud.config.json`.
38
+ *
39
+ * @param configPath - Path to the config file.
40
+ * @param options - Generic options bag and logger.
41
+ */
42
+ export async function bootKernel(configPath, options) {
43
+ const kernel = createDeferredKernel(configPath, options);
44
+ await kernel.boot({
45
+ ...(options.options === undefined ? {} : { options: options.options }),
46
+ ...(options.logger === undefined ? {} : { logger: options.logger }),
47
+ });
48
+ return kernel;
49
+ }
50
+ /**
51
+ * Builds a kernel whose config is composed lazily on the first `boot()`.
52
+ *
53
+ * The host supplies the config path explicitly; the kernel never chooses or
54
+ * discovers a config. Deferring module imports until boot keeps module
55
+ * instances in the ESM cache instead of loading a second copy through
56
+ * `require`.
57
+ */
58
+ export function createDeferredKernel(configPath, options) {
59
+ let loadedServices = [];
60
+ let serviceContext;
61
+ let hardcoreBootEntries = [];
62
+ let hardcorePackageHashes = new Map();
63
+ let composedConfig = { services: [] };
64
+ let activeServiceOwner = 'brud.kernel.composition';
65
+ const contextContract = new ContextContract();
66
+ function declareContextFields(scopeOrDeclaration, fields) {
67
+ contextContract.declare(activeServiceOwner, scopeOrDeclaration, fields);
68
+ }
69
+ const kernel = new BrudKernel({
70
+ contextContract,
71
+ hardcoreTokens: HARDCORE_SERVICES.map((service) => service.token),
72
+ bootHardcore: (instances, authority) => {
73
+ const identities = invokeHardcoreBootHooks(HARDCORE_SERVICES, instances, hardcorePackageHashes, hardcoreBootEntries, composedConfig, authority);
74
+ // Each participant's caller is assigned here, by the kernel: its issued
75
+ // identity, its official status from the identity-to-official mapping,
76
+ // and the capabilities its manifest requests.
77
+ return hardcoreBootEntries.map((entry) => {
78
+ const caller = Object.freeze({
79
+ callerClass: 'participant',
80
+ identity: identities.get(entry.token) ?? null,
81
+ official: entry.official,
82
+ capabilities: Object.freeze(new Set(entry.manifest.capabilities)),
83
+ ...(entry.parentIdentity === undefined
84
+ ? {}
85
+ : { parentIdentity: entry.parentIdentity }),
86
+ });
87
+ return { tokenId: entry.token, caller };
88
+ });
89
+ },
90
+ bootPinner: async (instances) => {
91
+ const context = serviceContext;
92
+ if (context === undefined) {
93
+ return;
94
+ }
95
+ for (const loaded of loadedServices) {
96
+ const pin = pinBootPoliciesHook(loaded.module);
97
+ if (pin !== undefined) {
98
+ activeServiceOwner = `${String(loaded.index)}:${loaded.entry.path}`;
99
+ await pin(context, instances);
100
+ }
101
+ }
102
+ for (const loaded of loadedServices) {
103
+ const registrant = registerBootRegistrantsHook(loaded.module);
104
+ if (registrant !== undefined) {
105
+ activeServiceOwner = `${String(loaded.index)}:${loaded.entry.path}`;
106
+ registrant(context, instances);
107
+ }
108
+ }
109
+ },
110
+ });
111
+ let composition;
112
+ let protectedThisKernel = false;
113
+ const compose = (bootOptions) => {
114
+ composition ??= (async () => {
115
+ const raw = await readConfig(configPath);
116
+ recordConfigRead(configPath, raw);
117
+ protectConfigFile(configPath);
118
+ protectedThisKernel = true;
119
+ const config = parseBrudConfig(raw, configPath);
120
+ composedConfig = config;
121
+ const services = await loadServiceModules(config.services, configPath, raw);
122
+ const contextOptions = {
123
+ ...(options.options ?? {}),
124
+ ...(bootOptions.options ?? {}),
125
+ };
126
+ const contextLogger = bootOptions.logger ?? options.logger;
127
+ const context = {
128
+ options: contextOptions,
129
+ ...(contextLogger === undefined ? {} : { logger: contextLogger }),
130
+ shared: {},
131
+ declareContextFields,
132
+ getContextSchema: () => contextContract.schema(),
133
+ };
134
+ loadedServices = services;
135
+ serviceContext = context;
136
+ const owned = [];
137
+ for (const loaded of services) {
138
+ activeServiceOwner = `${String(loaded.index)}:${loaded.entry.path}`;
139
+ for (const descriptor of await descriptorsFromModule(loaded.module, loaded.entry, loaded.index, context, configPath, raw)) {
140
+ owned.push({
141
+ ownerId: activeServiceOwner,
142
+ service: {
143
+ descriptor,
144
+ path: loaded.entry.path,
145
+ ...(loaded.entry.official === undefined ? {} : { official: loaded.entry.official }),
146
+ resolvedPath: loaded.resolvedId,
147
+ // The manifest is admitted from declared data only; the
148
+ // participant's factory is not invoked.
149
+ manifest: admitParticipantManifest(descriptor.token.id, descriptor.manifest),
150
+ },
151
+ });
152
+ }
153
+ }
154
+ const composed = pruneForMissingContext(owned, contextContract, contextOptions, (participants, path, fields) => {
155
+ const detail = { participants, path, missingFields: fields };
156
+ (contextLogger ?? DEFAULT_KERNEL_LOGGER).warn(`Participant pruned before boot: required context field(s) ${fields.join(', ')} missing and nothing depends on it`, detail);
157
+ kernel.recordObservation('kernel.admission', 'participant-pruned', detail);
158
+ });
159
+ // The hardcore gate runs after descriptors exist and before any service
160
+ // is registered or initialized. A failure here never reaches the
161
+ // service initialization phase.
162
+ const packageHashes = verifyHardcoreServices(HARDCORE_SERVICES, composed, configPath);
163
+ hardcorePackageHashes = packageHashes;
164
+ hardcoreBootEntries = buildHardcoreBootEntries(composed, packageHashes, HARDCORE_SERVICES);
165
+ for (const service of composed) {
166
+ kernel.register(service.descriptor);
167
+ }
168
+ })();
169
+ return composition;
170
+ };
171
+ const boot = kernel.boot.bind(kernel);
172
+ kernel.boot = async (bootOptions) => {
173
+ try {
174
+ await compose(bootOptions);
175
+ // Store the bag the composition built: the host's options. Service
176
+ // modules publish no objects into it; a service-to-service handoff goes
177
+ // through an exposed API.
178
+ const bootBag = serviceContext?.options ?? {
179
+ ...(options.options ?? {}),
180
+ ...(bootOptions.options ?? {}),
181
+ };
182
+ await boot({
183
+ options: bootBag,
184
+ logger: bootOptions.logger ?? options.logger ?? DEFAULT_KERNEL_LOGGER,
185
+ });
186
+ // The config document is reread after boot. Refuse to hand back a kernel
187
+ // if it changed underneath us.
188
+ await verifyConfigIntegrity(configPath);
189
+ }
190
+ catch (error) {
191
+ if (kernel.lifecycleState === 'RUNNING') {
192
+ await kernel.shutdown().catch(() => undefined);
193
+ }
194
+ if (protectedThisKernel) {
195
+ protectedThisKernel = false;
196
+ releaseConfigProtection(configPath);
197
+ }
198
+ throw error;
199
+ }
200
+ };
201
+ const shutdown = kernel.shutdown.bind(kernel);
202
+ kernel.shutdown = async () => {
203
+ await shutdown();
204
+ if (protectedThisKernel) {
205
+ protectedThisKernel = false;
206
+ releaseConfigProtection(configPath);
207
+ }
208
+ };
209
+ return kernel;
210
+ }
211
+ /**
212
+ * Applies the missing-required-field rules before boot.
213
+ *
214
+ * A participant whose required context fields are missing is pruned with a
215
+ * clear reason when it is optional: it is not hardcore and nothing else in the
216
+ * composition depends on it. A hardcore participant, or one another
217
+ * participant depends on, refuses boot instead.
218
+ *
219
+ * @returns The composed descriptors that remain.
220
+ */
221
+ function pruneForMissingContext(owned, contextContract, options, onPruned) {
222
+ const missing = contextContract.missingRequiredByOwner(options);
223
+ if (missing.size === 0) {
224
+ return owned.map((entry) => entry.service);
225
+ }
226
+ const hardcoreTokens = new Set(HARDCORE_SERVICES.map((service) => service.token));
227
+ const pruned = new Set();
228
+ for (const [ownerId, fields] of missing) {
229
+ const services = owned.filter((entry) => entry.ownerId === ownerId);
230
+ const tokens = new Set(services.map((entry) => entry.service.descriptor.token.id));
231
+ const isHardcore = [...tokens].some((token) => hardcoreTokens.has(token));
232
+ const dependedOn = owned.some((entry) => entry.ownerId !== ownerId
233
+ && entry.service.descriptor.dependencies.some((dependency) => tokens.has(dependency.id)));
234
+ if (services.length === 0 || isHardcore || dependedOn) {
235
+ const reason = isHardcore
236
+ ? 'it is hardcore'
237
+ : dependedOn
238
+ ? 'another participant depends on it'
239
+ : 'it declared no participant';
240
+ throw new ContextContractError(`Required context field(s) ${fields.join(', ')} declared by "${ownerId}" are missing and ${reason}; boot refused.`, { field: fields[0], service: ownerId, actualType: 'missing' });
241
+ }
242
+ pruned.add(ownerId);
243
+ }
244
+ for (const ownerId of pruned) {
245
+ const services = owned.filter((entry) => entry.ownerId === ownerId);
246
+ contextContract.withdraw(ownerId);
247
+ onPruned(services.map((entry) => entry.service.descriptor.token.id), services[0]?.service.path ?? ownerId, missing.get(ownerId) ?? []);
248
+ }
249
+ return owned
250
+ .filter((entry) => !pruned.has(entry.ownerId))
251
+ .map((entry) => entry.service);
252
+ }
253
+ function descriptorsFromModule(moduleValue, entry, index, context, configPath, raw) {
254
+ return descriptorsFromModuleAsync(moduleValue, entry, index, context, configPath, raw);
255
+ }
256
+ async function descriptorsFromModuleAsync(moduleValue, entry, index, context, configPath, raw) {
257
+ if (!isRecord(moduleValue) || typeof moduleValue.createService !== 'function') {
258
+ throw new BrudConfigError('MODULE_CONTRACT', `Service module "${entry.path}" (services[${String(index)}]) must export createService(context)`, configPath, lineOf(raw, entry.path));
259
+ }
260
+ const createService = moduleValue.createService;
261
+ const declared = await createService(context);
262
+ const candidates = Array.isArray(declared) ? declared : [declared];
263
+ if (candidates.length === 0) {
264
+ throw new BrudConfigError('MODULE_CONTRACT', `Service module "${entry.path}" (services[${String(index)}]) exposed no service descriptor`, configPath, lineOf(raw, entry.path));
265
+ }
266
+ for (const candidate of candidates) {
267
+ if (!isServiceDescriptor(candidate)) {
268
+ throw new BrudConfigError('MODULE_CONTRACT', `Service module "${entry.path}" (services[${String(index)}]) did not return a service descriptor`, configPath, lineOf(raw, entry.path));
269
+ }
270
+ }
271
+ return candidates;
272
+ }
273
+ async function readConfig(configPath) {
274
+ try {
275
+ return await readFile(configPath, 'utf8');
276
+ }
277
+ catch (error) {
278
+ throw new BrudConfigError('CONFIG_READ', `Cannot read config: ${error instanceof Error ? error.message : String(error)}`, configPath);
279
+ }
280
+ }
281
+ const isParticipantPackage = (id) => id.endsWith('.json');
282
+ /** Reads the optional `native` entry of a participant package declared official. */
283
+ function packageRequirementsOf(manifestPath, declaredPath, configPath, label, line) {
284
+ try {
285
+ return readPackageRequirements(manifestPath);
286
+ }
287
+ catch (error) {
288
+ const reason = error instanceof PackageRequirementsError ? error.message : String(error);
289
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot read participant package "${declaredPath}" (${label}): ${reason}`, configPath, line);
290
+ }
291
+ }
292
+ function nativeEntryOf(manifestPath, configPath, label, line) {
293
+ let pkg;
294
+ try {
295
+ pkg = JSON.parse(readFileSync(manifestPath, 'utf8'));
296
+ }
297
+ catch (error) {
298
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot read participant package "${manifestPath}" (${label}): ${error instanceof Error ? error.message : String(error)}`, configPath, line);
299
+ }
300
+ const native = pkg?.native;
301
+ if (native === undefined) {
302
+ return undefined;
303
+ }
304
+ const resolvedNative = resolvePath(dirname(manifestPath), String(native));
305
+ const inside = relativePath(dirname(manifestPath), resolvedNative);
306
+ if (typeof native !== 'string' || inside.startsWith('..') || isAbsolute(inside)) {
307
+ throw new BrudConfigError('MODULE_RESOLVE', `Participant package "${manifestPath}" (${label}): native must be a path inside the package`, configPath, line);
308
+ }
309
+ return resolvedNative;
310
+ }
311
+ /**
312
+ * Loads every composition entry, enforcing the tier rule (W-01): an entry
313
+ * declared `official: true` runs as Node; every other entry must be a
314
+ * participant package, loaded by the package loader a hardcore provides, so
315
+ * none of its author code runs as Node. A non-official native module is
316
+ * refused at boot.
317
+ */
318
+ async function loadServiceModules(entries, configPath, raw) {
319
+ const resolved = entries.map((entry, index) => ({
320
+ index,
321
+ entry,
322
+ resolvedId: resolveModuleId(entry.path, configPath),
323
+ label: `services[${String(index)}]`,
324
+ line: lineOf(raw, entry.path),
325
+ }));
326
+ const official = new Map();
327
+ await Promise.all(resolved.map(async (item) => {
328
+ if (item.entry.official === true && !isParticipantPackage(item.resolvedId)) {
329
+ official.set(item.index, await importModule(item.resolvedId, configPath, item.entry.path, item.label, item.line));
330
+ }
331
+ }));
332
+ const loaders = [...official.values()].flatMap((module) => {
333
+ const loader = module?.loadParticipantPackage;
334
+ return typeof loader === 'function' ? [loader] : [];
335
+ });
336
+ return Promise.all(resolved.map(async (item) => {
337
+ const { index, entry, resolvedId, label, line } = item;
338
+ if (official.has(index)) {
339
+ return { index, entry, resolvedId, module: official.get(index) };
340
+ }
341
+ if (!isParticipantPackage(resolvedId)) {
342
+ throw new BrudConfigError('PARTICIPANT_TIER', `"${entry.path}" (${label}) is not declared official, so it cannot run as native code (W-01): ship it as a participant package (brud.participant.json) or declare it "official": true`, configPath, line);
343
+ }
344
+ const requirements = packageRequirementsOf(resolvedId, entry.path, configPath, label, line);
345
+ if (requirements.official && entry.official !== true) {
346
+ const needs = requirements.powers.length === 0 ? '' : ` It uses: ${requirements.powers.join(', ')}.`;
347
+ throw new BrudConfigError('PARTICIPANT_REQUIRES_OFFICIAL', `"${entry.path}" (${label}) requires the composition to declare it "official": true, because it cannot run caged.${needs} Declare it official to run it as trusted native code, or remove the entry`, configPath, line);
348
+ }
349
+ if (entry.official === true) {
350
+ const native = nativeEntryOf(resolvedId, configPath, label, line);
351
+ if (native !== undefined) {
352
+ return { index, entry, resolvedId, module: await importModule(native, configPath, entry.path, label, line) };
353
+ }
354
+ }
355
+ const loader = loaders.length === 1 ? loaders[0] : undefined;
356
+ if (loader === undefined) {
357
+ throw new BrudConfigError('PARTICIPANT_TIER', `"${entry.path}" (${label}) is a participant package, but the composition provides ${loaders.length === 0 ? 'no' : 'more than one'} participant package loader`, configPath, line);
358
+ }
359
+ try {
360
+ return { index, entry, resolvedId, module: await loader(resolvedId) };
361
+ }
362
+ catch (error) {
363
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot load participant package "${entry.path}" (${label}): ${error instanceof Error ? error.message : String(error)}`, configPath, line);
364
+ }
365
+ }));
366
+ }
367
+ async function importModule(id, configPath, declaredPath, label, line) {
368
+ try {
369
+ return await import(id.startsWith('file:') || isAbsolute(id) ? pathToFileURL(id).href : id);
370
+ }
371
+ catch (error) {
372
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot resolve module "${declaredPath}" (${label}): ${error instanceof Error ? error.message : String(error)}`, configPath, line);
373
+ }
374
+ }
375
+ function resolveModuleId(declaredPath, configPath) {
376
+ if (declaredPath.startsWith('kernel:')) {
377
+ return resolveExisting(fileURLToPath(new URL(declaredPath.slice('kernel:'.length), KERNEL_PACKAGE_ROOT)));
378
+ }
379
+ if (declaredPath.startsWith('file:')) {
380
+ return resolveExisting(fileURLToPath(declaredPath));
381
+ }
382
+ if (isAbsolute(declaredPath)) {
383
+ return resolveExisting(declaredPath);
384
+ }
385
+ if (declaredPath.startsWith('./') || declaredPath.startsWith('../')) {
386
+ return resolveExisting(resolvePath(dirname(configPath), declaredPath));
387
+ }
388
+ return declaredPath;
389
+ }
390
+ function resolveExisting(candidate) {
391
+ if (existsSync(candidate)) {
392
+ return candidate;
393
+ }
394
+ if (candidate.endsWith('.js')) {
395
+ const source = `${candidate.slice(0, -3)}.ts`;
396
+ if (existsSync(source)) {
397
+ return source;
398
+ }
399
+ }
400
+ if (!candidate.endsWith('.js') && !candidate.endsWith('.ts')) {
401
+ for (const suffix of ['.js', '.ts', '/index.js', '/index.ts']) {
402
+ const next = `${candidate}${suffix}`;
403
+ if (existsSync(next)) {
404
+ return next;
405
+ }
406
+ }
407
+ }
408
+ return candidate;
409
+ }
410
+ function isServiceDescriptor(value) {
411
+ if (!isRecord(value) || !isRecord(value.token)) {
412
+ return false;
413
+ }
414
+ return typeof value.token.id === 'string'
415
+ && typeof value.factory === 'function'
416
+ && Array.isArray(value.dependencies);
417
+ }
418
+ function isRecord(value) {
419
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
420
+ }
@@ -0,0 +1,89 @@
1
+ import type { ContextFieldDeclaration, ContextSchema, ContextScopeDeclaration } from '../contracts/contextContract.js';
2
+ import type { IServiceLifecycle, KernelLogger } from '../contracts/lifecycle.js';
3
+ /**
4
+ * Generic options accepted by {@link bootKernel}.
5
+ *
6
+ * The core names exactly two fields: an open options bag and a logger. Every
7
+ * service-specific option lives inside {@link BootKernelOptions.options} and
8
+ * is interpreted by the service module that owns it. The core never sees those
9
+ * names or types.
10
+ */
11
+ export interface BootKernelOptions {
12
+ /** Open options bag built by the host before boot. */
13
+ readonly options?: Readonly<Record<string, unknown>>;
14
+ /** Kernel diagnostic sink. Defaults to a console-backed sink. */
15
+ readonly logger?: KernelLogger;
16
+ }
17
+ /** Options accepted by {@link createDeferredKernel}. */
18
+ export interface ComposeKernelOptions {
19
+ /** Open options bag built by the host before boot. */
20
+ readonly options?: Readonly<Record<string, unknown>>;
21
+ /** Kernel diagnostic sink. Defaults to a console-backed sink. */
22
+ readonly logger?: KernelLogger;
23
+ }
24
+ /**
25
+ * Context handed to a config-selected service module.
26
+ *
27
+ * The module owns its descriptor; the loader owns ordering and official flags.
28
+ * The context deliberately contains no concrete service instances and no
29
+ * service option types: services read their own keys from the generic options
30
+ * bag and coordinate through owner-namespaced entries in the shared bag.
31
+ */
32
+ export interface KernelServiceModuleContext {
33
+ /** Generic options bag from the host. */
34
+ readonly options: Record<string, unknown>;
35
+ /** Kernel diagnostic sink. */
36
+ readonly logger?: KernelLogger;
37
+ /**
38
+ * Per-kernel owner-namespaced coordination bag.
39
+ *
40
+ * A module may publish an instance under a key inside its own namespace; the
41
+ * core treats the bag as opaque and never reads named slots. A service that
42
+ * needs another participant's API resolves it through the broker or the
43
+ * exposed-API registry, never through another owner's slot.
44
+ */
45
+ readonly shared: Record<string, unknown>;
46
+ /**
47
+ * Declares the context fields this service requires from the options bag.
48
+ *
49
+ * A service may only declare fields inside its own dot-separated namespace.
50
+ * Declarations are accepted during `createService` and `pinBootPolicies`, and
51
+ * are rejected once the kernel reaches `RUNNING`.
52
+ *
53
+ * @param scope - Namespace owned by the declaring service.
54
+ * @param fields - Fields to require or accept inside that namespace.
55
+ */
56
+ declareContextFields(scope: string, fields: readonly ContextFieldDeclaration[]): void;
57
+ /** Declares fields through a single scope-declaration record. */
58
+ declareContextFields(declaration: ContextScopeDeclaration): void;
59
+ /** Returns the schema collected so far, including fields from other services. */
60
+ getContextSchema(): ContextSchema;
61
+ }
62
+ /**
63
+ * Shape a config-selected service module exports.
64
+ *
65
+ * `createService` returns one descriptor, or an ordered list of descriptors
66
+ * when the module exposes more than one API. Each descriptor is registered as
67
+ * its own service; the descriptor shape itself does not change. The return is
68
+ * typed as `unknown` at this boundary because descriptors are invariant in
69
+ * their service type; the loader validates the runtime shape and narrows it.
70
+ *
71
+ * A module that must resolve host values before it can declare its descriptor
72
+ * may return a promise; the loader awaits every module before registration.
73
+ *
74
+ * The optional hooks are generic coordination points available to every
75
+ * participant. The loader invokes them without knowing which service
76
+ * implements them:
77
+ * - `pinBootPolicies` ingests a boot snapshot while the broker gate is open.
78
+ * - `registerBootRegistrants` makes boot-time claims before `RUNNING`.
79
+ * Exposures are not among them: they are declared in each participant's
80
+ * manifest and admitted by the kernel.
81
+ */
82
+ export interface ServiceModule {
83
+ /** Builds and returns this service's descriptor or descriptors. */
84
+ createService(context: KernelServiceModuleContext): unknown | Promise<unknown>;
85
+ /** Ingests frozen boot policy after construction. */
86
+ pinBootPolicies?(context: KernelServiceModuleContext, instances: readonly IServiceLifecycle[]): void | Promise<void>;
87
+ /** Registers boot-time claims against this service's instance. */
88
+ registerBootRegistrants?(context: KernelServiceModuleContext, instances: readonly IServiceLifecycle[]): void;
89
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export type { BrudConfig, BrudConfigEntry, BrudConfigErrorCode, } from './types.js';
2
+ export { BrudConfigError } from './types.js';
3
+ export { parseBrudConfig } from './parse.js';
@@ -0,0 +1,2 @@
1
+ export { BrudConfigError } from './types.js';
2
+ export { parseBrudConfig } from './parse.js';
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Records the digest of the raw config document and returns it.
3
+ *
4
+ * A second read at the same path must hash identically. This is what makes a
5
+ * modified config refuse a reboot even if it changed outside the guarded APIs.
6
+ *
7
+ * @param configPath - Path the document was read from.
8
+ * @param raw - Exact file contents.
9
+ */
10
+ export declare function recordConfigRead(configPath: string, raw: string): void;
11
+ /**
12
+ * Marks the root config read-only for the lifetime of one kernel.
13
+ *
14
+ * Both the declared path and its real path are protected so an alias cannot
15
+ * bypass the guard.
16
+ *
17
+ * @param configPath - Path the kernel read.
18
+ */
19
+ export declare function protectConfigFile(configPath: string): void;
20
+ /**
21
+ * Releases one kernel's claim on the config path.
22
+ *
23
+ * The digest record is intentionally retained for the process lifetime, so a
24
+ * later boot of the same path is still compared against the first read.
25
+ *
26
+ * @param configPath - Path the kernel read.
27
+ */
28
+ export declare function releaseConfigProtection(configPath: string): void;
29
+ /**
30
+ * Re-reads the config and compares it with the digest recorded at boot.
31
+ *
32
+ * @param configPath - Path the kernel read.
33
+ */
34
+ export declare function verifyConfigIntegrity(configPath: string): Promise<void>;
@@ -0,0 +1,79 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { resolve as resolvePath } from 'node:path';
4
+ import { BrudConfigError } from './types.js';
5
+ import { protectPath, releasePath } from './pathWriteGuard.js';
6
+ /**
7
+ * Runtime integrity for the root config document.
8
+ *
9
+ * The root config is read exactly once per boot. Its digest is recorded then,
10
+ * and every later read of that path is checked against the record. While a
11
+ * kernel is alive the path is also made read-only and mutating `node:fs`
12
+ * operations against it are refused before they reach the host.
13
+ */
14
+ const CONFIG_DIGESTS = new Map();
15
+ function digestOf(raw) {
16
+ return createHash('sha256').update(raw, 'utf8').digest('hex');
17
+ }
18
+ function configPathError(configPath, operation) {
19
+ return new BrudConfigError('CONFIG_INTEGRITY', `The root config file is protected and cannot be ${operation}: ${configPath}`, configPath);
20
+ }
21
+ /**
22
+ * Records the digest of the raw config document and returns it.
23
+ *
24
+ * A second read at the same path must hash identically. This is what makes a
25
+ * modified config refuse a reboot even if it changed outside the guarded APIs.
26
+ *
27
+ * @param configPath - Path the document was read from.
28
+ * @param raw - Exact file contents.
29
+ */
30
+ export function recordConfigRead(configPath, raw) {
31
+ const key = resolvePath(configPath);
32
+ const digest = digestOf(raw);
33
+ const recorded = CONFIG_DIGESTS.get(key);
34
+ if (recorded !== undefined && recorded !== digest) {
35
+ throw new BrudConfigError('CONFIG_INTEGRITY', `Config integrity check failed: "${key}" changed since it was first read`, configPath);
36
+ }
37
+ CONFIG_DIGESTS.set(key, digest);
38
+ }
39
+ /**
40
+ * Marks the root config read-only for the lifetime of one kernel.
41
+ *
42
+ * Both the declared path and its real path are protected so an alias cannot
43
+ * bypass the guard.
44
+ *
45
+ * @param configPath - Path the kernel read.
46
+ */
47
+ export function protectConfigFile(configPath) {
48
+ protectPath(configPath, (key, operation) => configPathError(key, operation));
49
+ }
50
+ /**
51
+ * Releases one kernel's claim on the config path.
52
+ *
53
+ * The digest record is intentionally retained for the process lifetime, so a
54
+ * later boot of the same path is still compared against the first read.
55
+ *
56
+ * @param configPath - Path the kernel read.
57
+ */
58
+ export function releaseConfigProtection(configPath) {
59
+ releasePath(configPath);
60
+ }
61
+ /**
62
+ * Re-reads the config and compares it with the digest recorded at boot.
63
+ *
64
+ * @param configPath - Path the kernel read.
65
+ */
66
+ export async function verifyConfigIntegrity(configPath) {
67
+ const key = resolvePath(configPath);
68
+ const recorded = CONFIG_DIGESTS.get(key);
69
+ let raw;
70
+ try {
71
+ raw = await readFile(configPath, 'utf8');
72
+ }
73
+ catch (error) {
74
+ throw new BrudConfigError('CONFIG_INTEGRITY', `Config integrity check failed: cannot re-read "${key}": ${error instanceof Error ? error.message : String(error)}`, configPath);
75
+ }
76
+ if (recorded === undefined || recorded !== digestOf(raw)) {
77
+ throw new BrudConfigError('CONFIG_INTEGRITY', `Config integrity check failed: "${key}" no longer matches its boot-time digest`, configPath);
78
+ }
79
+ }
@@ -0,0 +1,15 @@
1
+ import { type BrudConfig } from './types.js';
2
+ /**
3
+ * Parses and validates the kernel-owned sections of a `brud.config.json`
4
+ * document.
5
+ *
6
+ * The kernel owns `services` and `exposureOwners`. Other top-level sections
7
+ * belong to the participants that own them; the kernel carries them untouched
8
+ * and never interprets them.
9
+ *
10
+ * @param raw - File contents.
11
+ * @param configPath - Config path used in diagnostics.
12
+ */
13
+ export declare function parseBrudConfig(raw: string, configPath: string): BrudConfig;
14
+ /** Finds the first source line containing a token. */
15
+ export declare function lineOf(raw: string, token: string): number | undefined;