@quolu/lattice 0.52.0 → 0.52.2

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 (182) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-mcp.mjs +0 -0
  5. package/bin/lattice-scripted-adapter.mjs +0 -0
  6. package/bin/lattice-scripted-worker.mjs +0 -0
  7. package/bin/lattice-work-order-adapter.mjs +0 -0
  8. package/bin/lattice.mjs +0 -0
  9. package/docs/bridge-setup.md +132 -132
  10. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  11. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  12. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  13. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  14. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  15. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  16. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  17. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  18. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  19. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  20. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  21. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  22. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  23. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  24. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  25. package/package.json +103 -103
  26. package/sensor/LICENSE +21 -21
  27. package/sensor/NOTICE +19 -19
  28. package/sensor/dist/bin/lattice-sensor.js +9 -9
  29. package/sensor/dist/db/index.js +24 -24
  30. package/sensor/dist/db/migrations.js +41 -41
  31. package/sensor/dist/db/queries.js +164 -164
  32. package/sensor/dist/db/schema.sql +205 -205
  33. package/sensor/dist/directory.js +5 -5
  34. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  35. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  36. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  49. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  50. package/sensor/dist/mcp/server-instructions.js +95 -95
  51. package/sensor/package.json +56 -56
  52. package/src/artifact-contracts-v2.mjs +325 -325
  53. package/src/artifact-contracts.mjs +895 -895
  54. package/src/boundary-compiler.mjs +712 -712
  55. package/src/boundary-observation-compiler-v2.mjs +344 -344
  56. package/src/bounded-seam.mjs +230 -230
  57. package/src/bridge-address.mjs +107 -107
  58. package/src/bridge-cli.mjs +297 -297
  59. package/src/bridge-config.mjs +346 -346
  60. package/src/bridge-daemon.mjs +378 -378
  61. package/src/bridge-launch-agent.mjs +323 -323
  62. package/src/bridge-registrar.mjs +102 -102
  63. package/src/bridge-server.mjs +376 -376
  64. package/src/cli-help.mjs +308 -308
  65. package/src/cli-stdio.mjs +40 -40
  66. package/src/control-compiler.mjs +532 -532
  67. package/src/dag-chain.mjs +261 -261
  68. package/src/factory-diagnostics.mjs +188 -188
  69. package/src/hash-chain.mjs +76 -76
  70. package/src/hooks-cli.mjs +1057 -1053
  71. package/src/isolation-runner.mjs +409 -409
  72. package/src/node-version-guard.mjs +44 -44
  73. package/src/project-cli.mjs +697 -697
  74. package/src/project-identity.mjs +130 -130
  75. package/src/rc1-black-box-oracle.mjs +906 -906
  76. package/src/rc1-comparison.mjs +154 -154
  77. package/src/rc1-evidence-bundle.mjs +456 -456
  78. package/src/rc1-v4-campaign.mjs +708 -708
  79. package/src/rc1-v4-transform.mjs +467 -467
  80. package/src/rc1-v5-artifact-set.mjs +855 -855
  81. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  82. package/src/rc1-v5-campaign.mjs +797 -797
  83. package/src/rc1-v5-transform.mjs +421 -421
  84. package/src/rc1-v6-artifact-set.mjs +807 -807
  85. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  86. package/src/rc1-v6-campaign.mjs +623 -623
  87. package/src/rc1-v6-causal-binding.mjs +473 -473
  88. package/src/rc1-v6-measurement.mjs +313 -313
  89. package/src/rc2-artifact-set.mjs +1584 -1584
  90. package/src/rc2-campaign.mjs +1506 -1502
  91. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  92. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  93. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  94. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  95. package/src/rc3-actual-dogfood.mjs +652 -652
  96. package/src/rc3-dogfood-scaffold.mjs +315 -315
  97. package/src/rc3-scripted-campaign.mjs +1383 -1383
  98. package/src/rc4-stage1-dogfood.mjs +673 -673
  99. package/src/runtime-adapter-registry.mjs +524 -520
  100. package/src/runtime-cli.mjs +4588 -4584
  101. package/src/runtime-contracts.mjs +824 -824
  102. package/src/runtime-control-store.mjs +604 -600
  103. package/src/runtime-controller-protocol.mjs +587 -587
  104. package/src/runtime-decision-verifier.mjs +701 -701
  105. package/src/runtime-diff-observer.mjs +361 -361
  106. package/src/runtime-direct-os-observer.mjs +301 -301
  107. package/src/runtime-driver-state.mjs +166 -162
  108. package/src/runtime-engine.mjs +779 -779
  109. package/src/runtime-errors.mjs +356 -356
  110. package/src/runtime-event-store.mjs +189 -189
  111. package/src/runtime-front-end.mjs +925 -925
  112. package/src/runtime-gate-store.mjs +481 -477
  113. package/src/runtime-hold-recompile.mjs +916 -916
  114. package/src/runtime-io-sentinel.mjs +391 -391
  115. package/src/runtime-lifecycle-lock.mjs +294 -290
  116. package/src/runtime-managed-supervisor.mjs +1490 -1490
  117. package/src/runtime-multi-epoch-store.mjs +838 -834
  118. package/src/runtime-projection.mjs +269 -269
  119. package/src/runtime-pull-intake.mjs +1192 -1188
  120. package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
  121. package/src/runtime-scripted-executor.mjs +163 -163
  122. package/src/runtime-scripted-worktree.mjs +104 -104
  123. package/src/runtime-seam-resolve.mjs +428 -428
  124. package/src/runtime-seam-treatment.mjs +173 -173
  125. package/src/runtime-socket-owner.mjs +125 -125
  126. package/src/runtime-work-order-contracts.mjs +91 -91
  127. package/src/runtime-work-order-controller.mjs +1171 -1167
  128. package/src/runtime-worktree-executor.mjs +199 -199
  129. package/src/schedulability-compiler-v2.mjs +303 -303
  130. package/src/schedulability-verifier-v2.mjs +317 -317
  131. package/src/seam-apply.mjs +549 -549
  132. package/src/seam-commit-shared.mjs +22 -22
  133. package/src/seam-commit-transform.mjs +81 -81
  134. package/src/seam-commit.mjs +18 -18
  135. package/src/seam-cost.mjs +322 -322
  136. package/src/seam-derivation.mjs +188 -188
  137. package/src/seam-gate.mjs +146 -146
  138. package/src/seam-proposal-contracts.mjs +446 -446
  139. package/src/seam-proposal-queries.mjs +521 -521
  140. package/src/seam-proposal.mjs +2011 -2011
  141. package/src/seam-ref.mjs +33 -33
  142. package/src/seam-rewrite.mjs +286 -286
  143. package/src/seam-transform.mjs +554 -554
  144. package/src/seam-verification.mjs +260 -260
  145. package/src/sensor-adapter.mjs +432 -432
  146. package/src/sensor-cli.mjs +139 -139
  147. package/src/sensor-diff.mjs +661 -661
  148. package/src/sensor-node-runtime.mjs +53 -53
  149. package/src/sensor-runtime.mjs +52 -52
  150. package/src/timestamp-contract.mjs +8 -8
  151. package/src/todo-audit-pending.mjs +91 -91
  152. package/src/todo-chain.mjs +178 -178
  153. package/src/todo-cli.mjs +3141 -3126
  154. package/src/todo-contracts.mjs +728 -728
  155. package/src/todo-dashboard-registry.mjs +573 -573
  156. package/src/todo-dispatch-shape.mjs +190 -190
  157. package/src/todo-gantt-html-independence.mjs +239 -239
  158. package/src/todo-gantt-html-shared.mjs +226 -226
  159. package/src/todo-gantt-html-style.mjs +131 -131
  160. package/src/todo-gantt-html.mjs +248 -248
  161. package/src/todo-gantt-layout.mjs +974 -974
  162. package/src/todo-gantt-live.mjs +361 -361
  163. package/src/todo-gantt-nested.mjs +263 -263
  164. package/src/todo-gantt-presentation.mjs +217 -217
  165. package/src/todo-gantt-scope.mjs +123 -123
  166. package/src/todo-gantt-svg.mjs +353 -353
  167. package/src/todo-independence-contracts.mjs +595 -595
  168. package/src/todo-independence-guidance.mjs +322 -322
  169. package/src/todo-independence.mjs +640 -640
  170. package/src/todo-markdown-renderer.mjs +260 -260
  171. package/src/todo-migration.mjs +448 -448
  172. package/src/todo-narrative-anchor.mjs +130 -130
  173. package/src/todo-note-store.mjs +629 -625
  174. package/src/todo-parallel-candidates.mjs +114 -114
  175. package/src/todo-revision.mjs +995 -995
  176. package/src/todo-split.mjs +472 -472
  177. package/src/todo-status.mjs +690 -690
  178. package/src/todo-store-git-transaction.mjs +418 -418
  179. package/src/todo-store.mjs +4322 -4314
  180. package/src/treatment-compiler.mjs +728 -728
  181. package/src/treatment-runner.mjs +656 -656
  182. package/src/witness-scaffold.mjs +180 -180
@@ -1,520 +1,524 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { constants as fsConstants } from 'node:fs';
3
- import {
4
- lstat,
5
- mkdir,
6
- open,
7
- readFile,
8
- realpath,
9
- rename,
10
- rm,
11
- } from 'node:fs/promises';
12
- import path from 'node:path';
13
-
14
- import { canonicalizeArtifact } from './artifact-contracts.mjs';
15
- import {
16
- CONTROLLER_OPERATIONS,
17
- validateAdapterLaunchDescriptor,
18
- validateAdapterRegistry,
19
- validateRuntimeAdapterCapabilities,
20
- } from './runtime-controller-protocol.mjs';
21
- import { selfDigest } from './runtime-contracts.mjs';
22
- import { observeMacosBinaryIdentity } from './runtime-managed-supervisor.mjs';
23
-
24
- const INPUT_SCHEMA = 'lattice.runtime_adapter_registration_input.v2';
25
- const LEGACY_INPUT_SCHEMA = 'lattice.runtime_adapter_registration_input.v1';
26
- const REGISTRY_SCHEMA = 'lattice.runtime_adapter_registry.v1';
27
- const DESCRIPTOR_SCHEMA = 'lattice.runtime_adapter_launch_descriptor.v1';
28
- const REGISTRY_REF = '.lattice/runtime/adapter-registry/registry.json';
29
- const DESCRIPTOR_ROOT_REF = '.lattice/runtime/adapter-registry/descriptors';
30
- const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
31
-
32
- export class AdapterRegistryError extends Error {
33
- constructor(code, message, detail) {
34
- super(message);
35
- this.name = 'AdapterRegistryError';
36
- this.code = code;
37
- this.detail = detail;
38
- }
39
- }
40
-
41
- function fail(code, message, detail) {
42
- throw new AdapterRegistryError(code, message, detail);
43
- }
44
-
45
- function sha256Bytes(bytes) {
46
- return createHash('sha256').update(bytes).digest('hex');
47
- }
48
-
49
- function plain(value) {
50
- return value !== null && typeof value === 'object' && !Array.isArray(value)
51
- && Object.getPrototypeOf(value) === Object.prototype;
52
- }
53
-
54
- function exact(value, fields) {
55
- if (!plain(value)) return false;
56
- const actual = Object.keys(value).sort();
57
- const expected = [...fields].sort();
58
- return actual.length === expected.length
59
- && actual.every((field, index) => field === expected[index]);
60
- }
61
-
62
- function inputFailure(reason, inputPath = '') {
63
- fail(
64
- 'INVALID_ADAPTER_REGISTRATION_INPUT',
65
- 'adapter registration inputが公開契約を満たさない',
66
- { reason, path: inputPath },
67
- );
68
- }
69
-
70
- function validateRegistrationInput(value) {
71
- if (!plain(value)) inputFailure('input_must_be_object');
72
- if (![LEGACY_INPUT_SCHEMA, INPUT_SCHEMA].includes(value.schema)) {
73
- inputFailure('unsupported_schema', '/schema');
74
- }
75
- if (!ID.test(value.adapter_kind ?? '')) inputFailure('invalid_adapter_kind', '/adapter_kind');
76
- const hostDrivenFields = value.schema === INPUT_SCHEMA ? ['host_driven_epoch'] : [];
77
- if (value.schema === INPUT_SCHEMA && typeof value.host_driven_epoch !== 'boolean') {
78
- inputFailure('host_driven_epoch_must_be_boolean', '/host_driven_epoch');
79
- }
80
- if (value.launch_kind === 'host_binary') {
81
- if (!exact(value, ['schema', 'adapter_kind', 'launch_kind', 'binary_path', 'argv',
82
- 'config_ref', ...hostDrivenFields])) {
83
- inputFailure('unexpected_or_missing_keys');
84
- }
85
- if (typeof value.binary_path !== 'string' || !path.isAbsolute(value.binary_path)) {
86
- inputFailure('binary_path_must_be_absolute', '/binary_path');
87
- }
88
- if (!Array.isArray(value.argv) || value.argv.length > 64
89
- || !value.argv.every((arg) => typeof arg === 'string' && !arg.includes('\0'))) {
90
- inputFailure('invalid_argv', '/argv');
91
- }
92
- if (typeof value.config_ref !== 'string' || value.config_ref.length === 0) {
93
- inputFailure('invalid_config_ref', '/config_ref');
94
- }
95
- return;
96
- }
97
- if (value.launch_kind === 'existing_endpoint') {
98
- if (!exact(value, ['schema', 'adapter_kind', 'launch_kind', 'endpoint',
99
- ...hostDrivenFields])) {
100
- inputFailure('unexpected_or_missing_keys');
101
- }
102
- if (typeof value.endpoint !== 'string' || value.endpoint.length === 0) {
103
- inputFailure('invalid_endpoint', '/endpoint');
104
- }
105
- // activateはendpointへ絶対pathを要求する(ADAPTER_LAUNCH_INVALID)。登録時点で
106
- // 確定する条件をここで揃え、「登録できたのにactivateできない」descriptorを作らせない。
107
- // 親directoryがcanonicalかはactivate時にしか判定できないため、そこは動的検査へ残す。
108
- if (!path.isAbsolute(value.endpoint)) {
109
- inputFailure('endpoint_must_be_absolute', '/endpoint');
110
- }
111
- return;
112
- }
113
- inputFailure('unsupported_launch_kind', '/launch_kind');
114
- }
115
-
116
- function createCapabilities(input = { schema: LEGACY_INPUT_SCHEMA }) {
117
- const capabilities = {
118
- schema: input.schema === INPUT_SCHEMA
119
- ? 'lattice.runtime_adapter_capabilities.v2'
120
- : 'lattice.runtime_adapter_capabilities.v1',
121
- operations: [...CONTROLLER_OPERATIONS],
122
- process_observation: true,
123
- worktree_fingerprint: true,
124
- staged_write_lease: true,
125
- durable_dispatch: true,
126
- capabilities_digest: '',
127
- };
128
- if (input.schema === INPUT_SCHEMA) {
129
- capabilities.host_driven_epoch = input.host_driven_epoch;
130
- }
131
- capabilities.capabilities_digest = selfDigest(capabilities, 'capabilities_digest');
132
- if (!validateRuntimeAdapterCapabilities(capabilities)) {
133
- throw new TypeError('runtime adapter capabilities生成不正');
134
- }
135
- return capabilities;
136
- }
137
-
138
- async function readCanonicalRegular(filePath, label) {
139
- let info;
140
- try {
141
- info = await lstat(filePath);
142
- } catch (error) {
143
- if (error?.code === 'ENOENT') throw error;
144
- fail('ADAPTER_REGISTRY_INVALID', `${label}を読めない`, { path: filePath, reason: 'unreadable' });
145
- }
146
- if (!info.isFile() || info.isSymbolicLink()) {
147
- fail('ADAPTER_REGISTRY_INVALID', `${label}がregular fileではない`, {
148
- path: filePath,
149
- reason: 'not_regular_file',
150
- });
151
- }
152
- let bytes;
153
- try {
154
- bytes = await readFile(filePath);
155
- } catch {
156
- fail('ADAPTER_REGISTRY_INVALID', `${label}を読めない`, { path: filePath, reason: 'unreadable' });
157
- }
158
- let value;
159
- try {
160
- value = JSON.parse(bytes.toString('utf8'));
161
- } catch {
162
- fail('ADAPTER_REGISTRY_INVALID', `${label}がJSONとして不正`, {
163
- path: filePath,
164
- reason: 'invalid_json',
165
- });
166
- }
167
- if (bytes.toString('utf8') !== `${canonicalizeArtifact(value)}\n`) {
168
- fail('ADAPTER_REGISTRY_INVALID', `${label}がcanonical bytesではない`, {
169
- path: filePath,
170
- reason: 'noncanonical_bytes',
171
- });
172
- }
173
- return { value, bytes };
174
- }
175
-
176
- async function durableReplaceBytes(directory, name, bytes) {
177
- const temporaryPath = path.join(directory, `.${name}-${process.pid}-${randomUUID()}.tmp`);
178
- let handle;
179
- try {
180
- handle = await open(
181
- temporaryPath,
182
- fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
183
- 0o600,
184
- );
185
- await handle.writeFile(bytes);
186
- await handle.sync();
187
- await handle.close();
188
- handle = null;
189
- await rename(temporaryPath, path.join(directory, name));
190
- const directoryHandle = await open(directory, fsConstants.O_RDONLY);
191
- try {
192
- await directoryHandle.sync();
193
- } finally {
194
- await directoryHandle.close();
195
- }
196
- } finally {
197
- if (handle) await handle.close().catch(() => {});
198
- await rm(temporaryPath, { force: true }).catch(() => {});
199
- }
200
- }
201
-
202
- async function ensureRegistryDirectories(repoRoot) {
203
- const registryDir = path.join(repoRoot, '.lattice/runtime/adapter-registry');
204
- const descriptorDir = path.join(registryDir, 'descriptors');
205
- await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
206
- for (const directory of [registryDir, descriptorDir]) {
207
- let observed;
208
- try {
209
- observed = await realpath(directory);
210
- } catch {
211
- fail('ADAPTER_REGISTRY_INVALID', 'adapter registry directoryを解決できない', {
212
- path: directory,
213
- reason: 'directory_unresolved',
214
- });
215
- }
216
- if (observed !== directory) {
217
- fail('ADAPTER_REGISTRY_INVALID', 'adapter registry directoryにsymlinkを使えない', {
218
- path: directory,
219
- reason: 'directory_not_canonical',
220
- });
221
- }
222
- }
223
- return { registryDir, descriptorDir };
224
- }
225
-
226
- async function acquireRegistryLock(registryDir) {
227
- const lockPath = path.join(registryDir, '.registry.lock');
228
- let handle;
229
- try {
230
- handle = await open(
231
- lockPath,
232
- fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
233
- 0o600,
234
- );
235
- await handle.writeFile(`${process.pid}\n`);
236
- await handle.sync();
237
- } catch (error) {
238
- await handle?.close().catch(() => {});
239
- if (error?.code === 'EEXIST') {
240
- fail('ADAPTER_REGISTRY_BUSY', 'adapter registryを別processが更新中', {
241
- path: lockPath,
242
- reason: 'lock_exists',
243
- });
244
- }
245
- throw error;
246
- }
247
- return async () => {
248
- await handle.close().catch(() => {});
249
- await rm(lockPath, { force: true });
250
- };
251
- }
252
-
253
- async function readRegistry(repoRoot, { missingIsEmpty }) {
254
- const registryPath = path.join(repoRoot, REGISTRY_REF);
255
- let artifact;
256
- try {
257
- artifact = await readCanonicalRegular(registryPath, 'adapter registry');
258
- } catch (error) {
259
- if (error?.code === 'ENOENT' && missingIsEmpty) return null;
260
- if (error?.code === 'ENOENT') {
261
- fail('ADAPTER_REGISTRY_INVALID', 'adapter registryが存在しない', {
262
- path: registryPath,
263
- reason: 'missing',
264
- });
265
- }
266
- throw error;
267
- }
268
- if (!validateAdapterRegistry(artifact.value)) {
269
- fail('ADAPTER_REGISTRY_INVALID', 'adapter registry contract不正', {
270
- path: registryPath,
271
- reason: 'contract_violation',
272
- });
273
- }
274
- return artifact;
275
- }
276
-
277
- async function resolveHostBinary(repoRoot, input, binaryIdentityObserver) {
278
- let binaryInfo;
279
- try {
280
- binaryInfo = await lstat(input.binary_path);
281
- } catch {
282
- inputFailure('binary_unreadable', '/binary_path');
283
- }
284
- if (!binaryInfo.isFile() || binaryInfo.isSymbolicLink() || (binaryInfo.mode & 0o111) === 0) {
285
- inputFailure('binary_must_be_executable_regular_file', '/binary_path');
286
- }
287
- let binaryReal;
288
- try {
289
- binaryReal = await realpath(input.binary_path);
290
- } catch {
291
- inputFailure('binary_unreadable', '/binary_path');
292
- }
293
- if (binaryReal !== input.binary_path) {
294
- inputFailure('binary_path_must_be_canonical', '/binary_path');
295
- }
296
-
297
- const configPath = path.resolve(repoRoot, input.config_ref);
298
- if (!configPath.startsWith(`${repoRoot}${path.sep}`)) {
299
- inputFailure('config_ref_outside_repo', '/config_ref');
300
- }
301
- let configInfo;
302
- let configReal;
303
- try {
304
- [configInfo, configReal] = await Promise.all([lstat(configPath), realpath(configPath)]);
305
- } catch {
306
- inputFailure('config_unreadable', '/config_ref');
307
- }
308
- if (!configInfo.isFile() || configInfo.isSymbolicLink() || configReal !== configPath) {
309
- inputFailure('config_must_be_canonical_regular_file', '/config_ref');
310
- }
311
-
312
- let binaryIdentity = null;
313
- let observation;
314
- if (process.platform !== 'darwin') {
315
- observation = {
316
- status: 'not_observed',
317
- reason: 'platform_not_darwin',
318
- message: 'macOS binary identity観測はdarwin以外では利用できない',
319
- };
320
- } else {
321
- try {
322
- binaryIdentity = await binaryIdentityObserver(binaryReal);
323
- observation = { status: 'observed', reason: null, message: null };
324
- } catch (error) {
325
- observation = {
326
- status: 'not_observed',
327
- reason: 'identity_observation_failed',
328
- message: error?.message ?? 'macOS binary identity観測に失敗した',
329
- };
330
- }
331
- }
332
-
333
- return {
334
- binaryPath: binaryReal,
335
- binaryDigest: sha256Bytes(await readFile(binaryReal)),
336
- binaryIdentity,
337
- configDigest: sha256Bytes(await readFile(configReal)),
338
- observation,
339
- };
340
- }
341
-
342
- async function buildLaunchDescriptor(repoRoot, input, binaryIdentityObserver) {
343
- const capabilities = createCapabilities(input);
344
- let observation = { status: 'not_applicable', reason: null, message: null };
345
- let descriptor;
346
- if (input.launch_kind === 'host_binary') {
347
- const host = await resolveHostBinary(repoRoot, input, binaryIdentityObserver);
348
- observation = host.observation;
349
- descriptor = {
350
- schema: DESCRIPTOR_SCHEMA,
351
- adapter_kind: input.adapter_kind,
352
- launch_kind: input.launch_kind,
353
- binary_path: host.binaryPath,
354
- binary_digest: host.binaryDigest,
355
- binary_identity: host.binaryIdentity,
356
- argv: [...input.argv],
357
- config_ref: input.config_ref,
358
- config_digest: host.configDigest,
359
- endpoint: null,
360
- capabilities_digest: capabilities.capabilities_digest,
361
- descriptor_digest: '',
362
- };
363
- } else {
364
- descriptor = {
365
- schema: DESCRIPTOR_SCHEMA,
366
- adapter_kind: input.adapter_kind,
367
- launch_kind: input.launch_kind,
368
- binary_path: null,
369
- binary_digest: null,
370
- binary_identity: null,
371
- argv: [],
372
- config_ref: null,
373
- config_digest: null,
374
- endpoint: input.endpoint,
375
- capabilities_digest: capabilities.capabilities_digest,
376
- descriptor_digest: '',
377
- };
378
- }
379
- descriptor.descriptor_digest = selfDigest(descriptor, 'descriptor_digest');
380
- // 公開入力から導出した成果物も、activationと同じ正本validatorを通過した時だけ永続化する。
381
- if (!validateAdapterLaunchDescriptor(descriptor)) {
382
- throw new TypeError('adapter launch descriptor生成不正');
383
- }
384
- return { descriptor, observation };
385
- }
386
-
387
- export async function registerRuntimeAdapter({
388
- repoRoot,
389
- input,
390
- binaryIdentityObserver = observeMacosBinaryIdentity,
391
- }) {
392
- const canonicalRepo = await realpath(repoRoot);
393
- validateRegistrationInput(input);
394
- const { descriptor, observation } = await buildLaunchDescriptor(
395
- canonicalRepo,
396
- input,
397
- binaryIdentityObserver,
398
- );
399
- const { registryDir, descriptorDir } = await ensureRegistryDirectories(canonicalRepo);
400
- const releaseLock = await acquireRegistryLock(registryDir);
401
- try {
402
- const current = await readRegistry(canonicalRepo, { missingIsEmpty: true });
403
- const existing = current?.value.entries.find(
404
- (entry) => entry.adapter_kind === input.adapter_kind,
405
- );
406
- const descriptorRef = `${DESCRIPTOR_ROOT_REF}/${input.adapter_kind}.json`;
407
- const entry = {
408
- adapter_kind: input.adapter_kind,
409
- launch_descriptor_ref: descriptorRef,
410
- launch_descriptor_digest: descriptor.descriptor_digest,
411
- };
412
- const entries = [
413
- ...(current?.value.entries ?? []).filter(
414
- (candidate) => candidate.adapter_kind !== input.adapter_kind,
415
- ),
416
- entry,
417
- ].sort((left, right) => (
418
- left.adapter_kind < right.adapter_kind ? -1 : left.adapter_kind > right.adapter_kind ? 1 : 0
419
- ));
420
- if (entries.length > 256) {
421
- fail('ADAPTER_REGISTRY_LIMIT_EXCEEDED', 'adapter registryは256件を超えられない', {
422
- limit: 256,
423
- });
424
- }
425
- const registry = { schema: REGISTRY_SCHEMA, entries, registry_digest: '' };
426
- registry.registry_digest = selfDigest(registry, 'registry_digest');
427
- if (!validateAdapterRegistry(registry)) throw new TypeError('adapter registry生成不正');
428
-
429
- await durableReplaceBytes(
430
- descriptorDir,
431
- `${input.adapter_kind}.json`,
432
- Buffer.from(`${canonicalizeArtifact(descriptor)}\n`),
433
- );
434
- await durableReplaceBytes(
435
- registryDir,
436
- 'registry.json',
437
- Buffer.from(`${canonicalizeArtifact(registry)}\n`),
438
- );
439
-
440
- const result = {
441
- schema: 'lattice.runtime_adapter_register_result.v1',
442
- outcome: existing === undefined ? 'created' : 'replaced',
443
- adapter_kind: input.adapter_kind,
444
- launch_descriptor_ref: descriptorRef,
445
- launch_descriptor_digest: descriptor.descriptor_digest,
446
- registry_ref: REGISTRY_REF,
447
- registry_digest: registry.registry_digest,
448
- binary_identity_observation: observation,
449
- result_digest: '',
450
- };
451
- result.result_digest = selfDigest(result, 'result_digest');
452
- return result;
453
- } finally {
454
- await releaseLock();
455
- }
456
- }
457
-
458
- export async function listRuntimeAdapters({ repoRoot }) {
459
- const canonicalRepo = await realpath(repoRoot);
460
- const registryArtifact = await readRegistry(canonicalRepo, { missingIsEmpty: true });
461
- const adapters = [];
462
- for (const entry of registryArtifact?.value.entries ?? []) {
463
- const descriptorPath = path.join(canonicalRepo, entry.launch_descriptor_ref);
464
- if (!descriptorPath.startsWith(`${canonicalRepo}${path.sep}`)) {
465
- fail('ADAPTER_REGISTRY_INVALID', 'launch descriptorがrepo外を指す', {
466
- path: descriptorPath,
467
- reason: 'descriptor_outside_repo',
468
- });
469
- }
470
- let artifact;
471
- try {
472
- artifact = await readCanonicalRegular(descriptorPath, 'adapter launch descriptor');
473
- } catch (error) {
474
- if (error?.code === 'ENOENT') {
475
- fail('ADAPTER_REGISTRY_INVALID', 'adapter launch descriptorが存在しない', {
476
- path: descriptorPath,
477
- reason: 'descriptor_missing',
478
- });
479
- }
480
- throw error;
481
- }
482
- const descriptor = artifact.value;
483
- if (!validateAdapterLaunchDescriptor(descriptor)
484
- || descriptor.adapter_kind !== entry.adapter_kind
485
- || descriptor.descriptor_digest !== entry.launch_descriptor_digest) {
486
- fail('ADAPTER_REGISTRY_INVALID', 'adapter launch descriptor binding不正', {
487
- path: descriptorPath,
488
- reason: 'descriptor_binding_invalid',
489
- });
490
- }
491
- adapters.push({
492
- adapter_kind: descriptor.adapter_kind,
493
- launch_kind: descriptor.launch_kind,
494
- launch_descriptor_ref: entry.launch_descriptor_ref,
495
- launch_descriptor_digest: descriptor.descriptor_digest,
496
- binary_path: descriptor.binary_path,
497
- binary_identity_observed: descriptor.binary_identity !== null,
498
- argv: [...descriptor.argv],
499
- config_ref: descriptor.config_ref,
500
- endpoint: descriptor.endpoint,
501
- capabilities_digest: descriptor.capabilities_digest,
502
- });
503
- }
504
- const result = {
505
- schema: 'lattice.runtime_adapter_list_result.v1',
506
- registry_ref: REGISTRY_REF,
507
- registry_digest: registryArtifact?.value.registry_digest ?? null,
508
- adapters,
509
- result_digest: '',
510
- };
511
- result.result_digest = selfDigest(result, 'result_digest');
512
- return result;
513
- }
514
-
515
- export const runtimeAdapterRegistryInternal = Object.freeze({
516
- INPUT_SCHEMA,
517
- REGISTRY_REF,
518
- validateRegistrationInput,
519
- createCapabilities,
520
- });
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ open,
7
+ readFile,
8
+ realpath,
9
+ rename,
10
+ rm,
11
+ } from 'node:fs/promises';
12
+ import path from 'node:path';
13
+
14
+ import { canonicalizeArtifact } from './artifact-contracts.mjs';
15
+ import {
16
+ CONTROLLER_OPERATIONS,
17
+ validateAdapterLaunchDescriptor,
18
+ validateAdapterRegistry,
19
+ validateRuntimeAdapterCapabilities,
20
+ } from './runtime-controller-protocol.mjs';
21
+ import { selfDigest } from './runtime-contracts.mjs';
22
+ import { observeMacosBinaryIdentity } from './runtime-managed-supervisor.mjs';
23
+
24
+ const INPUT_SCHEMA = 'lattice.runtime_adapter_registration_input.v2';
25
+ const LEGACY_INPUT_SCHEMA = 'lattice.runtime_adapter_registration_input.v1';
26
+ const REGISTRY_SCHEMA = 'lattice.runtime_adapter_registry.v1';
27
+ const DESCRIPTOR_SCHEMA = 'lattice.runtime_adapter_launch_descriptor.v1';
28
+ const REGISTRY_REF = '.lattice/runtime/adapter-registry/registry.json';
29
+ const DESCRIPTOR_ROOT_REF = '.lattice/runtime/adapter-registry/descriptors';
30
+ const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
31
+
32
+ export class AdapterRegistryError extends Error {
33
+ constructor(code, message, detail) {
34
+ super(message);
35
+ this.name = 'AdapterRegistryError';
36
+ this.code = code;
37
+ this.detail = detail;
38
+ }
39
+ }
40
+
41
+ function fail(code, message, detail) {
42
+ throw new AdapterRegistryError(code, message, detail);
43
+ }
44
+
45
+ function sha256Bytes(bytes) {
46
+ return createHash('sha256').update(bytes).digest('hex');
47
+ }
48
+
49
+ function plain(value) {
50
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
51
+ && Object.getPrototypeOf(value) === Object.prototype;
52
+ }
53
+
54
+ function exact(value, fields) {
55
+ if (!plain(value)) return false;
56
+ const actual = Object.keys(value).sort();
57
+ const expected = [...fields].sort();
58
+ return actual.length === expected.length
59
+ && actual.every((field, index) => field === expected[index]);
60
+ }
61
+
62
+ function inputFailure(reason, inputPath = '') {
63
+ fail(
64
+ 'INVALID_ADAPTER_REGISTRATION_INPUT',
65
+ 'adapter registration inputが公開契約を満たさない',
66
+ { reason, path: inputPath },
67
+ );
68
+ }
69
+
70
+ function validateRegistrationInput(value) {
71
+ if (!plain(value)) inputFailure('input_must_be_object');
72
+ if (![LEGACY_INPUT_SCHEMA, INPUT_SCHEMA].includes(value.schema)) {
73
+ inputFailure('unsupported_schema', '/schema');
74
+ }
75
+ if (!ID.test(value.adapter_kind ?? '')) inputFailure('invalid_adapter_kind', '/adapter_kind');
76
+ const hostDrivenFields = value.schema === INPUT_SCHEMA ? ['host_driven_epoch'] : [];
77
+ if (value.schema === INPUT_SCHEMA && typeof value.host_driven_epoch !== 'boolean') {
78
+ inputFailure('host_driven_epoch_must_be_boolean', '/host_driven_epoch');
79
+ }
80
+ if (value.launch_kind === 'host_binary') {
81
+ if (!exact(value, ['schema', 'adapter_kind', 'launch_kind', 'binary_path', 'argv',
82
+ 'config_ref', ...hostDrivenFields])) {
83
+ inputFailure('unexpected_or_missing_keys');
84
+ }
85
+ if (typeof value.binary_path !== 'string' || !path.isAbsolute(value.binary_path)) {
86
+ inputFailure('binary_path_must_be_absolute', '/binary_path');
87
+ }
88
+ if (!Array.isArray(value.argv) || value.argv.length > 64
89
+ || !value.argv.every((arg) => typeof arg === 'string' && !arg.includes('\0'))) {
90
+ inputFailure('invalid_argv', '/argv');
91
+ }
92
+ if (typeof value.config_ref !== 'string' || value.config_ref.length === 0) {
93
+ inputFailure('invalid_config_ref', '/config_ref');
94
+ }
95
+ return;
96
+ }
97
+ if (value.launch_kind === 'existing_endpoint') {
98
+ if (!exact(value, ['schema', 'adapter_kind', 'launch_kind', 'endpoint',
99
+ ...hostDrivenFields])) {
100
+ inputFailure('unexpected_or_missing_keys');
101
+ }
102
+ if (typeof value.endpoint !== 'string' || value.endpoint.length === 0) {
103
+ inputFailure('invalid_endpoint', '/endpoint');
104
+ }
105
+ // activateはendpointへ絶対pathを要求する(ADAPTER_LAUNCH_INVALID)。登録時点で
106
+ // 確定する条件をここで揃え、「登録できたのにactivateできない」descriptorを作らせない。
107
+ // 親directoryがcanonicalかはactivate時にしか判定できないため、そこは動的検査へ残す。
108
+ if (!path.isAbsolute(value.endpoint)) {
109
+ inputFailure('endpoint_must_be_absolute', '/endpoint');
110
+ }
111
+ return;
112
+ }
113
+ inputFailure('unsupported_launch_kind', '/launch_kind');
114
+ }
115
+
116
+ function createCapabilities(input = { schema: LEGACY_INPUT_SCHEMA }) {
117
+ const capabilities = {
118
+ schema: input.schema === INPUT_SCHEMA
119
+ ? 'lattice.runtime_adapter_capabilities.v2'
120
+ : 'lattice.runtime_adapter_capabilities.v1',
121
+ operations: [...CONTROLLER_OPERATIONS],
122
+ process_observation: true,
123
+ worktree_fingerprint: true,
124
+ staged_write_lease: true,
125
+ durable_dispatch: true,
126
+ capabilities_digest: '',
127
+ };
128
+ if (input.schema === INPUT_SCHEMA) {
129
+ capabilities.host_driven_epoch = input.host_driven_epoch;
130
+ }
131
+ capabilities.capabilities_digest = selfDigest(capabilities, 'capabilities_digest');
132
+ if (!validateRuntimeAdapterCapabilities(capabilities)) {
133
+ throw new TypeError('runtime adapter capabilities生成不正');
134
+ }
135
+ return capabilities;
136
+ }
137
+
138
+ async function readCanonicalRegular(filePath, label) {
139
+ let info;
140
+ try {
141
+ info = await lstat(filePath);
142
+ } catch (error) {
143
+ if (error?.code === 'ENOENT') throw error;
144
+ fail('ADAPTER_REGISTRY_INVALID', `${label}を読めない`, { path: filePath, reason: 'unreadable' });
145
+ }
146
+ if (!info.isFile() || info.isSymbolicLink()) {
147
+ fail('ADAPTER_REGISTRY_INVALID', `${label}がregular fileではない`, {
148
+ path: filePath,
149
+ reason: 'not_regular_file',
150
+ });
151
+ }
152
+ let bytes;
153
+ try {
154
+ bytes = await readFile(filePath);
155
+ } catch {
156
+ fail('ADAPTER_REGISTRY_INVALID', `${label}を読めない`, { path: filePath, reason: 'unreadable' });
157
+ }
158
+ let value;
159
+ try {
160
+ value = JSON.parse(bytes.toString('utf8'));
161
+ } catch {
162
+ fail('ADAPTER_REGISTRY_INVALID', `${label}がJSONとして不正`, {
163
+ path: filePath,
164
+ reason: 'invalid_json',
165
+ });
166
+ }
167
+ if (bytes.toString('utf8') !== `${canonicalizeArtifact(value)}\n`) {
168
+ fail('ADAPTER_REGISTRY_INVALID', `${label}がcanonical bytesではない`, {
169
+ path: filePath,
170
+ reason: 'noncanonical_bytes',
171
+ });
172
+ }
173
+ return { value, bytes };
174
+ }
175
+
176
+ async function durableReplaceBytes(directory, name, bytes) {
177
+ const temporaryPath = path.join(directory, `.${name}-${process.pid}-${randomUUID()}.tmp`);
178
+ let handle;
179
+ try {
180
+ handle = await open(
181
+ temporaryPath,
182
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
183
+ 0o600,
184
+ );
185
+ await handle.writeFile(bytes);
186
+ await handle.sync();
187
+ await handle.close();
188
+ handle = null;
189
+ await rename(temporaryPath, path.join(directory, name));
190
+ const directoryHandle = await open(directory, fsConstants.O_RDONLY);
191
+ // Windowsはdirectory handleのfsyncを許さず常にEPERM/EINVALを返す(Node仕様)。
192
+ // win32のこの2値だけ許容し、他OS・他エラーは従来どおり失敗させる。
193
+ try {
194
+ await directoryHandle.sync();
195
+ } catch (error) {
196
+ if (process.platform !== 'win32' || !['EPERM', 'EINVAL'].includes(error?.code)) throw error;
197
+ } finally {
198
+ await directoryHandle.close();
199
+ }
200
+ } finally {
201
+ if (handle) await handle.close().catch(() => {});
202
+ await rm(temporaryPath, { force: true }).catch(() => {});
203
+ }
204
+ }
205
+
206
+ async function ensureRegistryDirectories(repoRoot) {
207
+ const registryDir = path.join(repoRoot, '.lattice/runtime/adapter-registry');
208
+ const descriptorDir = path.join(registryDir, 'descriptors');
209
+ await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
210
+ for (const directory of [registryDir, descriptorDir]) {
211
+ let observed;
212
+ try {
213
+ observed = await realpath(directory);
214
+ } catch {
215
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registry directoryを解決できない', {
216
+ path: directory,
217
+ reason: 'directory_unresolved',
218
+ });
219
+ }
220
+ if (observed !== directory) {
221
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registry directoryにsymlinkを使えない', {
222
+ path: directory,
223
+ reason: 'directory_not_canonical',
224
+ });
225
+ }
226
+ }
227
+ return { registryDir, descriptorDir };
228
+ }
229
+
230
+ async function acquireRegistryLock(registryDir) {
231
+ const lockPath = path.join(registryDir, '.registry.lock');
232
+ let handle;
233
+ try {
234
+ handle = await open(
235
+ lockPath,
236
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
237
+ 0o600,
238
+ );
239
+ await handle.writeFile(`${process.pid}\n`);
240
+ await handle.sync();
241
+ } catch (error) {
242
+ await handle?.close().catch(() => {});
243
+ if (error?.code === 'EEXIST') {
244
+ fail('ADAPTER_REGISTRY_BUSY', 'adapter registryを別processが更新中', {
245
+ path: lockPath,
246
+ reason: 'lock_exists',
247
+ });
248
+ }
249
+ throw error;
250
+ }
251
+ return async () => {
252
+ await handle.close().catch(() => {});
253
+ await rm(lockPath, { force: true });
254
+ };
255
+ }
256
+
257
+ async function readRegistry(repoRoot, { missingIsEmpty }) {
258
+ const registryPath = path.join(repoRoot, REGISTRY_REF);
259
+ let artifact;
260
+ try {
261
+ artifact = await readCanonicalRegular(registryPath, 'adapter registry');
262
+ } catch (error) {
263
+ if (error?.code === 'ENOENT' && missingIsEmpty) return null;
264
+ if (error?.code === 'ENOENT') {
265
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registryが存在しない', {
266
+ path: registryPath,
267
+ reason: 'missing',
268
+ });
269
+ }
270
+ throw error;
271
+ }
272
+ if (!validateAdapterRegistry(artifact.value)) {
273
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registry contract不正', {
274
+ path: registryPath,
275
+ reason: 'contract_violation',
276
+ });
277
+ }
278
+ return artifact;
279
+ }
280
+
281
+ async function resolveHostBinary(repoRoot, input, binaryIdentityObserver) {
282
+ let binaryInfo;
283
+ try {
284
+ binaryInfo = await lstat(input.binary_path);
285
+ } catch {
286
+ inputFailure('binary_unreadable', '/binary_path');
287
+ }
288
+ if (!binaryInfo.isFile() || binaryInfo.isSymbolicLink() || (binaryInfo.mode & 0o111) === 0) {
289
+ inputFailure('binary_must_be_executable_regular_file', '/binary_path');
290
+ }
291
+ let binaryReal;
292
+ try {
293
+ binaryReal = await realpath(input.binary_path);
294
+ } catch {
295
+ inputFailure('binary_unreadable', '/binary_path');
296
+ }
297
+ if (binaryReal !== input.binary_path) {
298
+ inputFailure('binary_path_must_be_canonical', '/binary_path');
299
+ }
300
+
301
+ const configPath = path.resolve(repoRoot, input.config_ref);
302
+ if (!configPath.startsWith(`${repoRoot}${path.sep}`)) {
303
+ inputFailure('config_ref_outside_repo', '/config_ref');
304
+ }
305
+ let configInfo;
306
+ let configReal;
307
+ try {
308
+ [configInfo, configReal] = await Promise.all([lstat(configPath), realpath(configPath)]);
309
+ } catch {
310
+ inputFailure('config_unreadable', '/config_ref');
311
+ }
312
+ if (!configInfo.isFile() || configInfo.isSymbolicLink() || configReal !== configPath) {
313
+ inputFailure('config_must_be_canonical_regular_file', '/config_ref');
314
+ }
315
+
316
+ let binaryIdentity = null;
317
+ let observation;
318
+ if (process.platform !== 'darwin') {
319
+ observation = {
320
+ status: 'not_observed',
321
+ reason: 'platform_not_darwin',
322
+ message: 'macOS binary identity観測はdarwin以外では利用できない',
323
+ };
324
+ } else {
325
+ try {
326
+ binaryIdentity = await binaryIdentityObserver(binaryReal);
327
+ observation = { status: 'observed', reason: null, message: null };
328
+ } catch (error) {
329
+ observation = {
330
+ status: 'not_observed',
331
+ reason: 'identity_observation_failed',
332
+ message: error?.message ?? 'macOS binary identity観測に失敗した',
333
+ };
334
+ }
335
+ }
336
+
337
+ return {
338
+ binaryPath: binaryReal,
339
+ binaryDigest: sha256Bytes(await readFile(binaryReal)),
340
+ binaryIdentity,
341
+ configDigest: sha256Bytes(await readFile(configReal)),
342
+ observation,
343
+ };
344
+ }
345
+
346
+ async function buildLaunchDescriptor(repoRoot, input, binaryIdentityObserver) {
347
+ const capabilities = createCapabilities(input);
348
+ let observation = { status: 'not_applicable', reason: null, message: null };
349
+ let descriptor;
350
+ if (input.launch_kind === 'host_binary') {
351
+ const host = await resolveHostBinary(repoRoot, input, binaryIdentityObserver);
352
+ observation = host.observation;
353
+ descriptor = {
354
+ schema: DESCRIPTOR_SCHEMA,
355
+ adapter_kind: input.adapter_kind,
356
+ launch_kind: input.launch_kind,
357
+ binary_path: host.binaryPath,
358
+ binary_digest: host.binaryDigest,
359
+ binary_identity: host.binaryIdentity,
360
+ argv: [...input.argv],
361
+ config_ref: input.config_ref,
362
+ config_digest: host.configDigest,
363
+ endpoint: null,
364
+ capabilities_digest: capabilities.capabilities_digest,
365
+ descriptor_digest: '',
366
+ };
367
+ } else {
368
+ descriptor = {
369
+ schema: DESCRIPTOR_SCHEMA,
370
+ adapter_kind: input.adapter_kind,
371
+ launch_kind: input.launch_kind,
372
+ binary_path: null,
373
+ binary_digest: null,
374
+ binary_identity: null,
375
+ argv: [],
376
+ config_ref: null,
377
+ config_digest: null,
378
+ endpoint: input.endpoint,
379
+ capabilities_digest: capabilities.capabilities_digest,
380
+ descriptor_digest: '',
381
+ };
382
+ }
383
+ descriptor.descriptor_digest = selfDigest(descriptor, 'descriptor_digest');
384
+ // 公開入力から導出した成果物も、activationと同じ正本validatorを通過した時だけ永続化する。
385
+ if (!validateAdapterLaunchDescriptor(descriptor)) {
386
+ throw new TypeError('adapter launch descriptor生成不正');
387
+ }
388
+ return { descriptor, observation };
389
+ }
390
+
391
+ export async function registerRuntimeAdapter({
392
+ repoRoot,
393
+ input,
394
+ binaryIdentityObserver = observeMacosBinaryIdentity,
395
+ }) {
396
+ const canonicalRepo = await realpath(repoRoot);
397
+ validateRegistrationInput(input);
398
+ const { descriptor, observation } = await buildLaunchDescriptor(
399
+ canonicalRepo,
400
+ input,
401
+ binaryIdentityObserver,
402
+ );
403
+ const { registryDir, descriptorDir } = await ensureRegistryDirectories(canonicalRepo);
404
+ const releaseLock = await acquireRegistryLock(registryDir);
405
+ try {
406
+ const current = await readRegistry(canonicalRepo, { missingIsEmpty: true });
407
+ const existing = current?.value.entries.find(
408
+ (entry) => entry.adapter_kind === input.adapter_kind,
409
+ );
410
+ const descriptorRef = `${DESCRIPTOR_ROOT_REF}/${input.adapter_kind}.json`;
411
+ const entry = {
412
+ adapter_kind: input.adapter_kind,
413
+ launch_descriptor_ref: descriptorRef,
414
+ launch_descriptor_digest: descriptor.descriptor_digest,
415
+ };
416
+ const entries = [
417
+ ...(current?.value.entries ?? []).filter(
418
+ (candidate) => candidate.adapter_kind !== input.adapter_kind,
419
+ ),
420
+ entry,
421
+ ].sort((left, right) => (
422
+ left.adapter_kind < right.adapter_kind ? -1 : left.adapter_kind > right.adapter_kind ? 1 : 0
423
+ ));
424
+ if (entries.length > 256) {
425
+ fail('ADAPTER_REGISTRY_LIMIT_EXCEEDED', 'adapter registryは256件を超えられない', {
426
+ limit: 256,
427
+ });
428
+ }
429
+ const registry = { schema: REGISTRY_SCHEMA, entries, registry_digest: '' };
430
+ registry.registry_digest = selfDigest(registry, 'registry_digest');
431
+ if (!validateAdapterRegistry(registry)) throw new TypeError('adapter registry生成不正');
432
+
433
+ await durableReplaceBytes(
434
+ descriptorDir,
435
+ `${input.adapter_kind}.json`,
436
+ Buffer.from(`${canonicalizeArtifact(descriptor)}\n`),
437
+ );
438
+ await durableReplaceBytes(
439
+ registryDir,
440
+ 'registry.json',
441
+ Buffer.from(`${canonicalizeArtifact(registry)}\n`),
442
+ );
443
+
444
+ const result = {
445
+ schema: 'lattice.runtime_adapter_register_result.v1',
446
+ outcome: existing === undefined ? 'created' : 'replaced',
447
+ adapter_kind: input.adapter_kind,
448
+ launch_descriptor_ref: descriptorRef,
449
+ launch_descriptor_digest: descriptor.descriptor_digest,
450
+ registry_ref: REGISTRY_REF,
451
+ registry_digest: registry.registry_digest,
452
+ binary_identity_observation: observation,
453
+ result_digest: '',
454
+ };
455
+ result.result_digest = selfDigest(result, 'result_digest');
456
+ return result;
457
+ } finally {
458
+ await releaseLock();
459
+ }
460
+ }
461
+
462
+ export async function listRuntimeAdapters({ repoRoot }) {
463
+ const canonicalRepo = await realpath(repoRoot);
464
+ const registryArtifact = await readRegistry(canonicalRepo, { missingIsEmpty: true });
465
+ const adapters = [];
466
+ for (const entry of registryArtifact?.value.entries ?? []) {
467
+ const descriptorPath = path.join(canonicalRepo, entry.launch_descriptor_ref);
468
+ if (!descriptorPath.startsWith(`${canonicalRepo}${path.sep}`)) {
469
+ fail('ADAPTER_REGISTRY_INVALID', 'launch descriptorがrepo外を指す', {
470
+ path: descriptorPath,
471
+ reason: 'descriptor_outside_repo',
472
+ });
473
+ }
474
+ let artifact;
475
+ try {
476
+ artifact = await readCanonicalRegular(descriptorPath, 'adapter launch descriptor');
477
+ } catch (error) {
478
+ if (error?.code === 'ENOENT') {
479
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter launch descriptorが存在しない', {
480
+ path: descriptorPath,
481
+ reason: 'descriptor_missing',
482
+ });
483
+ }
484
+ throw error;
485
+ }
486
+ const descriptor = artifact.value;
487
+ if (!validateAdapterLaunchDescriptor(descriptor)
488
+ || descriptor.adapter_kind !== entry.adapter_kind
489
+ || descriptor.descriptor_digest !== entry.launch_descriptor_digest) {
490
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter launch descriptor binding不正', {
491
+ path: descriptorPath,
492
+ reason: 'descriptor_binding_invalid',
493
+ });
494
+ }
495
+ adapters.push({
496
+ adapter_kind: descriptor.adapter_kind,
497
+ launch_kind: descriptor.launch_kind,
498
+ launch_descriptor_ref: entry.launch_descriptor_ref,
499
+ launch_descriptor_digest: descriptor.descriptor_digest,
500
+ binary_path: descriptor.binary_path,
501
+ binary_identity_observed: descriptor.binary_identity !== null,
502
+ argv: [...descriptor.argv],
503
+ config_ref: descriptor.config_ref,
504
+ endpoint: descriptor.endpoint,
505
+ capabilities_digest: descriptor.capabilities_digest,
506
+ });
507
+ }
508
+ const result = {
509
+ schema: 'lattice.runtime_adapter_list_result.v1',
510
+ registry_ref: REGISTRY_REF,
511
+ registry_digest: registryArtifact?.value.registry_digest ?? null,
512
+ adapters,
513
+ result_digest: '',
514
+ };
515
+ result.result_digest = selfDigest(result, 'result_digest');
516
+ return result;
517
+ }
518
+
519
+ export const runtimeAdapterRegistryInternal = Object.freeze({
520
+ INPUT_SCHEMA,
521
+ REGISTRY_REF,
522
+ validateRegistrationInput,
523
+ createCapabilities,
524
+ });