@quolu/lattice 0.12.23 → 0.12.25

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.
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ runScriptedAdapterController,
5
+ ScriptedAdapterControllerError,
6
+ } from '../src/runtime-scripted-adapter-controller.mjs';
7
+
8
+ try {
9
+ await runScriptedAdapterController();
10
+ } catch (error) {
11
+ const payload = {
12
+ schema: 'lattice.scripted_adapter_error.v1',
13
+ code: error instanceof ScriptedAdapterControllerError
14
+ ? error.code
15
+ : 'SCRIPTED_CONTROLLER_FAILED',
16
+ message: String(error?.message ?? error),
17
+ };
18
+ process.stderr.write(`${JSON.stringify(payload)}\n`);
19
+ process.exitCode = 1;
20
+ }
@@ -0,0 +1,78 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/kitepon-rgb/Lattice/blob/main/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json",
4
+ "title": "lattice.runtime_adapter_registration_input.v1",
5
+ "description": "lattice run adapter register の入力契約。digestと固定capabilitiesはCLIが導出する。",
6
+ "oneOf": [
7
+ {
8
+ "type": "object",
9
+ "additionalProperties": false,
10
+ "required": [
11
+ "schema",
12
+ "adapter_kind",
13
+ "launch_kind",
14
+ "binary_path",
15
+ "argv",
16
+ "config_ref"
17
+ ],
18
+ "properties": {
19
+ "schema": {
20
+ "const": "lattice.runtime_adapter_registration_input.v1"
21
+ },
22
+ "adapter_kind": {
23
+ "$ref": "#/$defs/identifier"
24
+ },
25
+ "launch_kind": {
26
+ "const": "host_binary"
27
+ },
28
+ "binary_path": {
29
+ "type": "string",
30
+ "pattern": "^/"
31
+ },
32
+ "argv": {
33
+ "type": "array",
34
+ "maxItems": 64,
35
+ "items": {
36
+ "type": "string",
37
+ "pattern": "^[^\\u0000]*$"
38
+ }
39
+ },
40
+ "config_ref": {
41
+ "type": "string",
42
+ "minLength": 1
43
+ }
44
+ }
45
+ },
46
+ {
47
+ "type": "object",
48
+ "additionalProperties": false,
49
+ "required": [
50
+ "schema",
51
+ "adapter_kind",
52
+ "launch_kind",
53
+ "endpoint"
54
+ ],
55
+ "properties": {
56
+ "schema": {
57
+ "const": "lattice.runtime_adapter_registration_input.v1"
58
+ },
59
+ "adapter_kind": {
60
+ "$ref": "#/$defs/identifier"
61
+ },
62
+ "launch_kind": {
63
+ "const": "existing_endpoint"
64
+ },
65
+ "endpoint": {
66
+ "type": "string",
67
+ "minLength": 1
68
+ }
69
+ }
70
+ }
71
+ ],
72
+ "$defs": {
73
+ "identifier": {
74
+ "type": "string",
75
+ "pattern": "^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$"
76
+ }
77
+ }
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.12.23",
3
+ "version": "0.12.25",
4
4
  "description": "Lattice — phase-aware TODO graph compiler and conflict-aware orchestration runtime",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -13,10 +13,12 @@
13
13
  },
14
14
  "bin": {
15
15
  "lattice": "bin/lattice.mjs",
16
- "lattice-mcp": "bin/lattice-mcp.mjs"
16
+ "lattice-mcp": "bin/lattice-mcp.mjs",
17
+ "lattice-scripted-adapter": "bin/lattice-scripted-adapter.mjs"
17
18
  },
18
19
  "files": [
19
20
  "bin",
21
+ "bin/lattice-scripted-adapter.mjs",
20
22
  "src",
21
23
  "docs/schemas/lattice.plan_create_input.v1.schema.json",
22
24
  "docs/schemas/lattice.plan_create_input.v2.schema.json",
@@ -24,6 +26,7 @@
24
26
  "docs/schemas/lattice.run_request.v1.schema.json",
25
27
  "docs/schemas/lattice.executor_packet.v1.schema.json",
26
28
  "docs/schemas/lattice.executor_receipt.v1.schema.json",
29
+ "docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json",
27
30
  "docs/bridge-setup.md",
28
31
  "sensor/dist",
29
32
  "!sensor/dist/bin/lattice-sensor.*",
@@ -57,7 +60,7 @@
57
60
  "test": "node scripts/run-product-tests.mjs",
58
61
  "test:sensor": "npm --prefix sensor test",
59
62
  "precheck": "node --check src/bridge-launch-agent.mjs",
60
- "check": "node --check bin/lattice.mjs && node --check bin/lattice-mcp.mjs && node --check bin/lattice-dashboard.mjs && node --check bin/lattice-bridge.mjs && node --check src/cli-stdio.mjs && node --check src/bridge-address.mjs && node --check src/bridge-registrar.mjs && node --check src/todo-gantt-layout.mjs && node --check src/todo-gantt-scope.mjs && node --check src/bridge-config.mjs && node --check src/bridge-server.mjs && node --check src/bridge-daemon.mjs && node --check src/bridge-cli.mjs && node --check src/project-cli.mjs && node --check src/sensor-cli.mjs && node --check src/sensor-runtime.mjs && node --check src/sensor-adapter.mjs && node --check src/factory-diagnostics.mjs && node --check src/runtime-errors.mjs && node --check src/runtime-contracts.mjs && node --check src/runtime-event-store.mjs && node --check src/hash-chain.mjs && node --check src/dag-chain.mjs && node --check src/todo-contracts.mjs && node --check src/todo-chain.mjs && node --check src/todo-store.mjs && node --check src/todo-migration.mjs && node --check src/todo-revision.mjs && node --check src/todo-status.mjs && node --check src/todo-cli.mjs && node --check src/todo-dashboard-registry.mjs && node --check src/todo-gantt-presentation.mjs && node --check src/todo-gantt-live.mjs && node --check src/bounded-seam.mjs && node --check src/todo-narrative-anchor.mjs && node --check src/todo-markdown-renderer.mjs && node --check src/todo-gantt-svg.mjs && node --check src/todo-gantt-html.mjs && node --check src/runtime-projection.mjs && node --check src/runtime-decision-verifier.mjs && node --check src/runtime-front-end.mjs && node --check src/runtime-cli.mjs && node --check src/rc3-dogfood-scaffold.mjs && node --check src/runtime-engine.mjs && node --check src/runtime-scripted-executor.mjs && node --check src/runtime-diff-observer.mjs && node --check src/runtime-worktree-executor.mjs && node --check src/runtime-hold-recompile.mjs && node --check src/rc3-scripted-campaign.mjs && node --check src/rc3-actual-dogfood.mjs && node --check src/rc4-stage1-dogfood.mjs && node --check research/fixtures/dispatch-record/src/dispatch-record.mjs && node --check test/research-dispatch-record.test.mjs",
63
+ "check": "node --check bin/lattice.mjs && node --check bin/lattice-mcp.mjs && node --check bin/lattice-dashboard.mjs && node --check bin/lattice-bridge.mjs && node --check bin/lattice-scripted-adapter.mjs && node --check src/cli-stdio.mjs && node --check src/bridge-address.mjs && node --check src/bridge-registrar.mjs && node --check src/todo-gantt-layout.mjs && node --check src/todo-gantt-scope.mjs && node --check src/bridge-config.mjs && node --check src/bridge-server.mjs && node --check src/bridge-daemon.mjs && node --check src/bridge-cli.mjs && node --check src/project-cli.mjs && node --check src/sensor-cli.mjs && node --check src/sensor-runtime.mjs && node --check src/sensor-adapter.mjs && node --check src/factory-diagnostics.mjs && node --check src/runtime-errors.mjs && node --check src/runtime-contracts.mjs && node --check src/runtime-event-store.mjs && node --check src/runtime-adapter-registry.mjs && node --check src/runtime-scripted-adapter-controller.mjs && node --check src/hash-chain.mjs && node --check src/dag-chain.mjs && node --check src/todo-contracts.mjs && node --check src/todo-chain.mjs && node --check src/todo-store.mjs && node --check src/todo-migration.mjs && node --check src/todo-revision.mjs && node --check src/todo-status.mjs && node --check src/todo-cli.mjs && node --check src/todo-dashboard-registry.mjs && node --check src/todo-gantt-presentation.mjs && node --check src/todo-gantt-live.mjs && node --check src/bounded-seam.mjs && node --check src/todo-narrative-anchor.mjs && node --check src/todo-markdown-renderer.mjs && node --check src/todo-gantt-svg.mjs && node --check src/todo-gantt-html.mjs && node --check src/runtime-projection.mjs && node --check src/runtime-decision-verifier.mjs && node --check src/runtime-front-end.mjs && node --check src/runtime-cli.mjs && node --check src/rc3-dogfood-scaffold.mjs && node --check src/runtime-engine.mjs && node --check src/runtime-scripted-executor.mjs && node --check src/runtime-diff-observer.mjs && node --check src/runtime-worktree-executor.mjs && node --check src/runtime-hold-recompile.mjs && node --check src/rc3-scripted-campaign.mjs && node --check src/rc3-actual-dogfood.mjs && node --check src/rc4-stage1-dogfood.mjs && node --check research/fixtures/dispatch-record/src/dispatch-record.mjs && node --check test/research-dispatch-record.test.mjs",
61
64
  "check:project-identity": "node --check src/project-identity.mjs",
62
65
  "ci": "npm run test && npm run test:sensor && npm run check && npm run check:project-identity"
63
66
  }
package/src/cli-help.mjs CHANGED
@@ -32,6 +32,9 @@ Commands:
32
32
  Commands:
33
33
  start --request <request.json> --executor <adapter>
34
34
  start --schema --json # lattice.run_request.v1 の JSON Schema を出す
35
+ adapter register --input <descriptor.json>
36
+ adapter register --schema --json # 登録入力の JSON Schema を出す
37
+ adapter list --json
35
38
  observe --run .lattice/runs/<id>
36
39
  status --run .lattice/runs/<id>
37
40
  resume --run .lattice/runs/<id>
@@ -103,6 +106,8 @@ const SUBCOMMAND_USAGE = Object.freeze({
103
106
  'plan compile': 'plan compile --request <request.json> | --schema --json',
104
107
  'plan verify': 'plan verify --request <request.json> --plan <plan.json>',
105
108
  'run start': 'run start --request <request.json> --executor <adapter> | --schema --json',
109
+ 'run adapter register': 'run adapter register --input <descriptor.json> | --schema --json',
110
+ 'run adapter list': 'run adapter list --json',
106
111
  'run observe': 'run observe --run .lattice/runs/<id>',
107
112
  'run status': 'run status --run .lattice/runs/<id>',
108
113
  'run resume': 'run resume --run .lattice/runs/<id>',
@@ -0,0 +1,506 @@
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.v1';
25
+ const REGISTRY_SCHEMA = 'lattice.runtime_adapter_registry.v1';
26
+ const DESCRIPTOR_SCHEMA = 'lattice.runtime_adapter_launch_descriptor.v1';
27
+ const REGISTRY_REF = '.lattice/runtime/adapter-registry/registry.json';
28
+ const DESCRIPTOR_ROOT_REF = '.lattice/runtime/adapter-registry/descriptors';
29
+ const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
30
+
31
+ export class AdapterRegistryError extends Error {
32
+ constructor(code, message, detail) {
33
+ super(message);
34
+ this.name = 'AdapterRegistryError';
35
+ this.code = code;
36
+ this.detail = detail;
37
+ }
38
+ }
39
+
40
+ function fail(code, message, detail) {
41
+ throw new AdapterRegistryError(code, message, detail);
42
+ }
43
+
44
+ function sha256Bytes(bytes) {
45
+ return createHash('sha256').update(bytes).digest('hex');
46
+ }
47
+
48
+ function plain(value) {
49
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
50
+ && Object.getPrototypeOf(value) === Object.prototype;
51
+ }
52
+
53
+ function exact(value, fields) {
54
+ if (!plain(value)) return false;
55
+ const actual = Object.keys(value).sort();
56
+ const expected = [...fields].sort();
57
+ return actual.length === expected.length
58
+ && actual.every((field, index) => field === expected[index]);
59
+ }
60
+
61
+ function inputFailure(reason, inputPath = '') {
62
+ fail(
63
+ 'INVALID_ADAPTER_REGISTRATION_INPUT',
64
+ 'adapter registration inputが公開契約を満たさない',
65
+ { reason, path: inputPath },
66
+ );
67
+ }
68
+
69
+ function validateRegistrationInput(value) {
70
+ if (!plain(value)) inputFailure('input_must_be_object');
71
+ if (value.schema !== INPUT_SCHEMA) inputFailure('unsupported_schema', '/schema');
72
+ if (!ID.test(value.adapter_kind ?? '')) inputFailure('invalid_adapter_kind', '/adapter_kind');
73
+ if (value.launch_kind === 'host_binary') {
74
+ if (!exact(value, ['schema', 'adapter_kind', 'launch_kind', 'binary_path', 'argv', 'config_ref'])) {
75
+ inputFailure('unexpected_or_missing_keys');
76
+ }
77
+ if (typeof value.binary_path !== 'string' || !path.isAbsolute(value.binary_path)) {
78
+ inputFailure('binary_path_must_be_absolute', '/binary_path');
79
+ }
80
+ if (!Array.isArray(value.argv) || value.argv.length > 64
81
+ || !value.argv.every((arg) => typeof arg === 'string' && !arg.includes('\0'))) {
82
+ inputFailure('invalid_argv', '/argv');
83
+ }
84
+ if (typeof value.config_ref !== 'string' || value.config_ref.length === 0) {
85
+ inputFailure('invalid_config_ref', '/config_ref');
86
+ }
87
+ return;
88
+ }
89
+ if (value.launch_kind === 'existing_endpoint') {
90
+ if (!exact(value, ['schema', 'adapter_kind', 'launch_kind', 'endpoint'])) {
91
+ inputFailure('unexpected_or_missing_keys');
92
+ }
93
+ if (typeof value.endpoint !== 'string' || value.endpoint.length === 0) {
94
+ inputFailure('invalid_endpoint', '/endpoint');
95
+ }
96
+ // activateはendpointへ絶対pathを要求する(ADAPTER_LAUNCH_INVALID)。登録時点で
97
+ // 確定する条件をここで揃え、「登録できたのにactivateできない」descriptorを作らせない。
98
+ // 親directoryがcanonicalかはactivate時にしか判定できないため、そこは動的検査へ残す。
99
+ if (!path.isAbsolute(value.endpoint)) {
100
+ inputFailure('endpoint_must_be_absolute', '/endpoint');
101
+ }
102
+ return;
103
+ }
104
+ inputFailure('unsupported_launch_kind', '/launch_kind');
105
+ }
106
+
107
+ function createCapabilities() {
108
+ const capabilities = {
109
+ schema: 'lattice.runtime_adapter_capabilities.v1',
110
+ operations: [...CONTROLLER_OPERATIONS],
111
+ process_observation: true,
112
+ worktree_fingerprint: true,
113
+ staged_write_lease: true,
114
+ durable_dispatch: true,
115
+ capabilities_digest: '',
116
+ };
117
+ capabilities.capabilities_digest = selfDigest(capabilities, 'capabilities_digest');
118
+ if (!validateRuntimeAdapterCapabilities(capabilities)) {
119
+ throw new TypeError('runtime adapter capabilities生成不正');
120
+ }
121
+ return capabilities;
122
+ }
123
+
124
+ async function readCanonicalRegular(filePath, label) {
125
+ let info;
126
+ try {
127
+ info = await lstat(filePath);
128
+ } catch (error) {
129
+ if (error?.code === 'ENOENT') throw error;
130
+ fail('ADAPTER_REGISTRY_INVALID', `${label}を読めない`, { path: filePath, reason: 'unreadable' });
131
+ }
132
+ if (!info.isFile() || info.isSymbolicLink()) {
133
+ fail('ADAPTER_REGISTRY_INVALID', `${label}がregular fileではない`, {
134
+ path: filePath,
135
+ reason: 'not_regular_file',
136
+ });
137
+ }
138
+ let bytes;
139
+ try {
140
+ bytes = await readFile(filePath);
141
+ } catch {
142
+ fail('ADAPTER_REGISTRY_INVALID', `${label}を読めない`, { path: filePath, reason: 'unreadable' });
143
+ }
144
+ let value;
145
+ try {
146
+ value = JSON.parse(bytes.toString('utf8'));
147
+ } catch {
148
+ fail('ADAPTER_REGISTRY_INVALID', `${label}がJSONとして不正`, {
149
+ path: filePath,
150
+ reason: 'invalid_json',
151
+ });
152
+ }
153
+ if (bytes.toString('utf8') !== `${canonicalizeArtifact(value)}\n`) {
154
+ fail('ADAPTER_REGISTRY_INVALID', `${label}がcanonical bytesではない`, {
155
+ path: filePath,
156
+ reason: 'noncanonical_bytes',
157
+ });
158
+ }
159
+ return { value, bytes };
160
+ }
161
+
162
+ async function durableReplaceBytes(directory, name, bytes) {
163
+ const temporaryPath = path.join(directory, `.${name}-${process.pid}-${randomUUID()}.tmp`);
164
+ let handle;
165
+ try {
166
+ handle = await open(
167
+ temporaryPath,
168
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
169
+ 0o600,
170
+ );
171
+ await handle.writeFile(bytes);
172
+ await handle.sync();
173
+ await handle.close();
174
+ handle = null;
175
+ await rename(temporaryPath, path.join(directory, name));
176
+ const directoryHandle = await open(directory, fsConstants.O_RDONLY);
177
+ try {
178
+ await directoryHandle.sync();
179
+ } finally {
180
+ await directoryHandle.close();
181
+ }
182
+ } finally {
183
+ if (handle) await handle.close().catch(() => {});
184
+ await rm(temporaryPath, { force: true }).catch(() => {});
185
+ }
186
+ }
187
+
188
+ async function ensureRegistryDirectories(repoRoot) {
189
+ const registryDir = path.join(repoRoot, '.lattice/runtime/adapter-registry');
190
+ const descriptorDir = path.join(registryDir, 'descriptors');
191
+ await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
192
+ for (const directory of [registryDir, descriptorDir]) {
193
+ let observed;
194
+ try {
195
+ observed = await realpath(directory);
196
+ } catch {
197
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registry directoryを解決できない', {
198
+ path: directory,
199
+ reason: 'directory_unresolved',
200
+ });
201
+ }
202
+ if (observed !== directory) {
203
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registry directoryにsymlinkを使えない', {
204
+ path: directory,
205
+ reason: 'directory_not_canonical',
206
+ });
207
+ }
208
+ }
209
+ return { registryDir, descriptorDir };
210
+ }
211
+
212
+ async function acquireRegistryLock(registryDir) {
213
+ const lockPath = path.join(registryDir, '.registry.lock');
214
+ let handle;
215
+ try {
216
+ handle = await open(
217
+ lockPath,
218
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
219
+ 0o600,
220
+ );
221
+ await handle.writeFile(`${process.pid}\n`);
222
+ await handle.sync();
223
+ } catch (error) {
224
+ await handle?.close().catch(() => {});
225
+ if (error?.code === 'EEXIST') {
226
+ fail('ADAPTER_REGISTRY_BUSY', 'adapter registryを別processが更新中', {
227
+ path: lockPath,
228
+ reason: 'lock_exists',
229
+ });
230
+ }
231
+ throw error;
232
+ }
233
+ return async () => {
234
+ await handle.close().catch(() => {});
235
+ await rm(lockPath, { force: true });
236
+ };
237
+ }
238
+
239
+ async function readRegistry(repoRoot, { missingIsEmpty }) {
240
+ const registryPath = path.join(repoRoot, REGISTRY_REF);
241
+ let artifact;
242
+ try {
243
+ artifact = await readCanonicalRegular(registryPath, 'adapter registry');
244
+ } catch (error) {
245
+ if (error?.code === 'ENOENT' && missingIsEmpty) return null;
246
+ if (error?.code === 'ENOENT') {
247
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registryが存在しない', {
248
+ path: registryPath,
249
+ reason: 'missing',
250
+ });
251
+ }
252
+ throw error;
253
+ }
254
+ if (!validateAdapterRegistry(artifact.value)) {
255
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter registry contract不正', {
256
+ path: registryPath,
257
+ reason: 'contract_violation',
258
+ });
259
+ }
260
+ return artifact;
261
+ }
262
+
263
+ async function resolveHostBinary(repoRoot, input, binaryIdentityObserver) {
264
+ let binaryInfo;
265
+ try {
266
+ binaryInfo = await lstat(input.binary_path);
267
+ } catch {
268
+ inputFailure('binary_unreadable', '/binary_path');
269
+ }
270
+ if (!binaryInfo.isFile() || binaryInfo.isSymbolicLink() || (binaryInfo.mode & 0o111) === 0) {
271
+ inputFailure('binary_must_be_executable_regular_file', '/binary_path');
272
+ }
273
+ let binaryReal;
274
+ try {
275
+ binaryReal = await realpath(input.binary_path);
276
+ } catch {
277
+ inputFailure('binary_unreadable', '/binary_path');
278
+ }
279
+ if (binaryReal !== input.binary_path) {
280
+ inputFailure('binary_path_must_be_canonical', '/binary_path');
281
+ }
282
+
283
+ const configPath = path.resolve(repoRoot, input.config_ref);
284
+ if (!configPath.startsWith(`${repoRoot}${path.sep}`)) {
285
+ inputFailure('config_ref_outside_repo', '/config_ref');
286
+ }
287
+ let configInfo;
288
+ let configReal;
289
+ try {
290
+ [configInfo, configReal] = await Promise.all([lstat(configPath), realpath(configPath)]);
291
+ } catch {
292
+ inputFailure('config_unreadable', '/config_ref');
293
+ }
294
+ if (!configInfo.isFile() || configInfo.isSymbolicLink() || configReal !== configPath) {
295
+ inputFailure('config_must_be_canonical_regular_file', '/config_ref');
296
+ }
297
+
298
+ let binaryIdentity = null;
299
+ let observation;
300
+ if (process.platform !== 'darwin') {
301
+ observation = {
302
+ status: 'not_observed',
303
+ reason: 'platform_not_darwin',
304
+ message: 'macOS binary identity観測はdarwin以外では利用できない',
305
+ };
306
+ } else {
307
+ try {
308
+ binaryIdentity = await binaryIdentityObserver(binaryReal);
309
+ observation = { status: 'observed', reason: null, message: null };
310
+ } catch (error) {
311
+ observation = {
312
+ status: 'not_observed',
313
+ reason: 'identity_observation_failed',
314
+ message: error?.message ?? 'macOS binary identity観測に失敗した',
315
+ };
316
+ }
317
+ }
318
+
319
+ return {
320
+ binaryPath: binaryReal,
321
+ binaryDigest: sha256Bytes(await readFile(binaryReal)),
322
+ binaryIdentity,
323
+ configDigest: sha256Bytes(await readFile(configReal)),
324
+ observation,
325
+ };
326
+ }
327
+
328
+ async function buildLaunchDescriptor(repoRoot, input, binaryIdentityObserver) {
329
+ const capabilities = createCapabilities();
330
+ let observation = { status: 'not_applicable', reason: null, message: null };
331
+ let descriptor;
332
+ if (input.launch_kind === 'host_binary') {
333
+ const host = await resolveHostBinary(repoRoot, input, binaryIdentityObserver);
334
+ observation = host.observation;
335
+ descriptor = {
336
+ schema: DESCRIPTOR_SCHEMA,
337
+ adapter_kind: input.adapter_kind,
338
+ launch_kind: input.launch_kind,
339
+ binary_path: host.binaryPath,
340
+ binary_digest: host.binaryDigest,
341
+ binary_identity: host.binaryIdentity,
342
+ argv: [...input.argv],
343
+ config_ref: input.config_ref,
344
+ config_digest: host.configDigest,
345
+ endpoint: null,
346
+ capabilities_digest: capabilities.capabilities_digest,
347
+ descriptor_digest: '',
348
+ };
349
+ } else {
350
+ descriptor = {
351
+ schema: DESCRIPTOR_SCHEMA,
352
+ adapter_kind: input.adapter_kind,
353
+ launch_kind: input.launch_kind,
354
+ binary_path: null,
355
+ binary_digest: null,
356
+ binary_identity: null,
357
+ argv: [],
358
+ config_ref: null,
359
+ config_digest: null,
360
+ endpoint: input.endpoint,
361
+ capabilities_digest: capabilities.capabilities_digest,
362
+ descriptor_digest: '',
363
+ };
364
+ }
365
+ descriptor.descriptor_digest = selfDigest(descriptor, 'descriptor_digest');
366
+ // 公開入力から導出した成果物も、activationと同じ正本validatorを通過した時だけ永続化する。
367
+ if (!validateAdapterLaunchDescriptor(descriptor)) {
368
+ throw new TypeError('adapter launch descriptor生成不正');
369
+ }
370
+ return { descriptor, observation };
371
+ }
372
+
373
+ export async function registerRuntimeAdapter({
374
+ repoRoot,
375
+ input,
376
+ binaryIdentityObserver = observeMacosBinaryIdentity,
377
+ }) {
378
+ const canonicalRepo = await realpath(repoRoot);
379
+ validateRegistrationInput(input);
380
+ const { descriptor, observation } = await buildLaunchDescriptor(
381
+ canonicalRepo,
382
+ input,
383
+ binaryIdentityObserver,
384
+ );
385
+ const { registryDir, descriptorDir } = await ensureRegistryDirectories(canonicalRepo);
386
+ const releaseLock = await acquireRegistryLock(registryDir);
387
+ try {
388
+ const current = await readRegistry(canonicalRepo, { missingIsEmpty: true });
389
+ const existing = current?.value.entries.find(
390
+ (entry) => entry.adapter_kind === input.adapter_kind,
391
+ );
392
+ const descriptorRef = `${DESCRIPTOR_ROOT_REF}/${input.adapter_kind}.json`;
393
+ const entry = {
394
+ adapter_kind: input.adapter_kind,
395
+ launch_descriptor_ref: descriptorRef,
396
+ launch_descriptor_digest: descriptor.descriptor_digest,
397
+ };
398
+ const entries = [
399
+ ...(current?.value.entries ?? []).filter(
400
+ (candidate) => candidate.adapter_kind !== input.adapter_kind,
401
+ ),
402
+ entry,
403
+ ].sort((left, right) => (
404
+ left.adapter_kind < right.adapter_kind ? -1 : left.adapter_kind > right.adapter_kind ? 1 : 0
405
+ ));
406
+ if (entries.length > 256) {
407
+ fail('ADAPTER_REGISTRY_LIMIT_EXCEEDED', 'adapter registryは256件を超えられない', {
408
+ limit: 256,
409
+ });
410
+ }
411
+ const registry = { schema: REGISTRY_SCHEMA, entries, registry_digest: '' };
412
+ registry.registry_digest = selfDigest(registry, 'registry_digest');
413
+ if (!validateAdapterRegistry(registry)) throw new TypeError('adapter registry生成不正');
414
+
415
+ await durableReplaceBytes(
416
+ descriptorDir,
417
+ `${input.adapter_kind}.json`,
418
+ Buffer.from(`${canonicalizeArtifact(descriptor)}\n`),
419
+ );
420
+ await durableReplaceBytes(
421
+ registryDir,
422
+ 'registry.json',
423
+ Buffer.from(`${canonicalizeArtifact(registry)}\n`),
424
+ );
425
+
426
+ const result = {
427
+ schema: 'lattice.runtime_adapter_register_result.v1',
428
+ outcome: existing === undefined ? 'created' : 'replaced',
429
+ adapter_kind: input.adapter_kind,
430
+ launch_descriptor_ref: descriptorRef,
431
+ launch_descriptor_digest: descriptor.descriptor_digest,
432
+ registry_ref: REGISTRY_REF,
433
+ registry_digest: registry.registry_digest,
434
+ binary_identity_observation: observation,
435
+ result_digest: '',
436
+ };
437
+ result.result_digest = selfDigest(result, 'result_digest');
438
+ return result;
439
+ } finally {
440
+ await releaseLock();
441
+ }
442
+ }
443
+
444
+ export async function listRuntimeAdapters({ repoRoot }) {
445
+ const canonicalRepo = await realpath(repoRoot);
446
+ const registryArtifact = await readRegistry(canonicalRepo, { missingIsEmpty: true });
447
+ const adapters = [];
448
+ for (const entry of registryArtifact?.value.entries ?? []) {
449
+ const descriptorPath = path.join(canonicalRepo, entry.launch_descriptor_ref);
450
+ if (!descriptorPath.startsWith(`${canonicalRepo}${path.sep}`)) {
451
+ fail('ADAPTER_REGISTRY_INVALID', 'launch descriptorがrepo外を指す', {
452
+ path: descriptorPath,
453
+ reason: 'descriptor_outside_repo',
454
+ });
455
+ }
456
+ let artifact;
457
+ try {
458
+ artifact = await readCanonicalRegular(descriptorPath, 'adapter launch descriptor');
459
+ } catch (error) {
460
+ if (error?.code === 'ENOENT') {
461
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter launch descriptorが存在しない', {
462
+ path: descriptorPath,
463
+ reason: 'descriptor_missing',
464
+ });
465
+ }
466
+ throw error;
467
+ }
468
+ const descriptor = artifact.value;
469
+ if (!validateAdapterLaunchDescriptor(descriptor)
470
+ || descriptor.adapter_kind !== entry.adapter_kind
471
+ || descriptor.descriptor_digest !== entry.launch_descriptor_digest) {
472
+ fail('ADAPTER_REGISTRY_INVALID', 'adapter launch descriptor binding不正', {
473
+ path: descriptorPath,
474
+ reason: 'descriptor_binding_invalid',
475
+ });
476
+ }
477
+ adapters.push({
478
+ adapter_kind: descriptor.adapter_kind,
479
+ launch_kind: descriptor.launch_kind,
480
+ launch_descriptor_ref: entry.launch_descriptor_ref,
481
+ launch_descriptor_digest: descriptor.descriptor_digest,
482
+ binary_path: descriptor.binary_path,
483
+ binary_identity_observed: descriptor.binary_identity !== null,
484
+ argv: [...descriptor.argv],
485
+ config_ref: descriptor.config_ref,
486
+ endpoint: descriptor.endpoint,
487
+ capabilities_digest: descriptor.capabilities_digest,
488
+ });
489
+ }
490
+ const result = {
491
+ schema: 'lattice.runtime_adapter_list_result.v1',
492
+ registry_ref: REGISTRY_REF,
493
+ registry_digest: registryArtifact?.value.registry_digest ?? null,
494
+ adapters,
495
+ result_digest: '',
496
+ };
497
+ result.result_digest = selfDigest(result, 'result_digest');
498
+ return result;
499
+ }
500
+
501
+ export const runtimeAdapterRegistryInternal = Object.freeze({
502
+ INPUT_SCHEMA,
503
+ REGISTRY_REF,
504
+ validateRegistrationInput,
505
+ createCapabilities,
506
+ });