@quolu/lattice 0.14.0 → 0.16.0

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,508 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ import { digestArtifact } from './artifact-contracts.mjs';
4
+ import { SENSOR_QUERY_OPERATIONS } from './runtime-contracts.mjs';
5
+ import { collectSensorEvidence, portableSensorOutcome } from './sensor-adapter.mjs';
6
+ import { todoSelfDigest } from './todo-contracts.mjs';
7
+
8
+ const CONFLICT_KINDS = new Set(['symbol', 'path', 'state', 'effect']);
9
+ const QUERYABLE_KINDS = new Set(['symbol', 'path']);
10
+ const SYMBOL_OPERATIONS = Object.freeze(['query', 'callers', 'callees', 'impact']);
11
+ const SENSOR_OPERATIONS = new Set(SENSOR_QUERY_OPERATIONS);
12
+ const QUERY_LIMIT = 256;
13
+ const GRAPH_NODE_LIMIT = 64;
14
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
15
+ const CONTROL = /[\u0000-\u001f\u007f]/u;
16
+
17
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
18
+ const sortedUnique = (values) => [...new Set(values)].sort(compareText);
19
+
20
+ export class SeamProposalQueryError extends Error {
21
+ constructor(code, reason, detail = {}) {
22
+ super(reason);
23
+ this.name = 'SeamProposalQueryError';
24
+ this.code = code;
25
+ this.detail = { reason, ...detail };
26
+ }
27
+ }
28
+
29
+ function fail(code, reason, detail) {
30
+ throw new SeamProposalQueryError(code, reason, detail);
31
+ }
32
+
33
+ function plainRecord(value) {
34
+ return value !== null
35
+ && typeof value === 'object'
36
+ && !Array.isArray(value)
37
+ && Object.getPrototypeOf(value) === Object.prototype;
38
+ }
39
+
40
+ function exactRecord(value, keys) {
41
+ if (!plainRecord(value)) return false;
42
+ const actual = Object.keys(value).sort(compareText);
43
+ const expected = [...keys].sort(compareText);
44
+ return actual.length === expected.length
45
+ && actual.every((key, index) => key === expected[index]);
46
+ }
47
+
48
+ function boundedText(value, maxBytes = 4_096) {
49
+ return typeof value === 'string'
50
+ && value.length > 0
51
+ && value === value.trim()
52
+ && !CONTROL.test(value)
53
+ && Buffer.byteLength(value) <= maxBytes;
54
+ }
55
+
56
+ function repoRelativePathOrPrefix(value) {
57
+ if (!boundedText(value, 1_024) || value.startsWith('/') || value.includes('\\')
58
+ || /^[A-Za-z]:/u.test(value)) return false;
59
+ const body = value.endsWith('/') ? value.slice(0, -1) : value;
60
+ return body.length > 0 && body.split('/')
61
+ .every((segment) => segment !== '' && segment !== '.' && segment !== '..');
62
+ }
63
+
64
+ function repoRelativePath(value) {
65
+ return repoRelativePathOrPrefix(value) && !value.endsWith('/');
66
+ }
67
+
68
+ function sha16(value) {
69
+ return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
70
+ }
71
+
72
+ function queryId(operation, kind, target) {
73
+ return `seam-${operation}-${sha16(`${kind}\0${target}`)}`;
74
+ }
75
+
76
+ function assertConflictResources(conflictResources) {
77
+ if (!Array.isArray(conflictResources)) {
78
+ fail('SEAM_QUERY_RESOURCES_INVALID', 'conflict_resources_not_array');
79
+ }
80
+ const byId = new Map();
81
+ for (const resource of conflictResources) {
82
+ if (!exactRecord(resource, ['resource_id', 'kind', 'target'])
83
+ || !boundedText(resource.resource_id)
84
+ || !CONFLICT_KINDS.has(resource.kind)
85
+ || !boundedText(resource.target)
86
+ || (resource.kind === 'path' && !repoRelativePathOrPrefix(resource.target))) {
87
+ fail('SEAM_QUERY_RESOURCE_INVALID', 'conflict_resource_invalid', {
88
+ resource_id: resource?.resource_id ?? null,
89
+ });
90
+ }
91
+ if (byId.has(resource.resource_id)) {
92
+ fail('SEAM_QUERY_RESOURCE_DUPLICATE', 'conflict_resource_id_duplicate', {
93
+ resource_id: resource.resource_id,
94
+ });
95
+ }
96
+ byId.set(resource.resource_id, resource);
97
+ }
98
+ return [...byId.values()].sort((left, right) => compareText(
99
+ left.resource_id, right.resource_id,
100
+ ));
101
+ }
102
+
103
+ function assertRuntimeQuerySet(querySet) {
104
+ if (!exactRecord(querySet, ['queries']) || !Array.isArray(querySet.queries)
105
+ || querySet.queries.length > QUERY_LIMIT) {
106
+ fail('SEAM_QUERY_SET_INVALID', 'runtime_sensor_query_set_invalid');
107
+ }
108
+ let previousId = null;
109
+ for (const query of querySet.queries) {
110
+ const keys = query?.operation === 'status'
111
+ ? ['id', 'operation'] : ['id', 'operation', 'target'];
112
+ if (!exactRecord(query, keys)
113
+ || !IDENTIFIER.test(query.id)
114
+ || !SENSOR_OPERATIONS.has(query.operation)
115
+ || (keys.includes('target') && !boundedText(query.target))) {
116
+ fail('SEAM_QUERY_SET_INVALID', 'runtime_sensor_query_invalid', {
117
+ query_id: query?.id ?? null,
118
+ });
119
+ }
120
+ if (previousId !== null && compareText(previousId, query.id) >= 0) {
121
+ fail('SEAM_QUERY_SET_INVALID', 'query_ids_not_strictly_sorted_unique', {
122
+ query_id: query.id,
123
+ });
124
+ }
125
+ previousId = query.id;
126
+ }
127
+ if (querySet.queries.filter(({ operation }) => operation === 'status').length !== 1) {
128
+ fail('SEAM_QUERY_SET_INVALID', 'status_query_not_exactly_one');
129
+ }
130
+ }
131
+
132
+ function assertConcernSymbols(concernSymbols) {
133
+ if (!Array.isArray(concernSymbols) || concernSymbols.length > QUERY_LIMIT) {
134
+ fail('SEAM_QUERY_CONCERN_SYMBOLS_INVALID', 'concern_symbols_not_bounded_array');
135
+ }
136
+ for (const symbol of concernSymbols) {
137
+ if (!boundedText(symbol, 1_024)) {
138
+ fail('SEAM_QUERY_CONCERN_SYMBOL_INVALID', 'concern_symbol_invalid');
139
+ }
140
+ }
141
+ return sortedUnique(concernSymbols);
142
+ }
143
+
144
+ /**
145
+ * Build the schema-less `lattice.run_request.v1.sensor_query_set` vocabulary used by
146
+ * todo-independence. The wrapper records non-code conflicts without putting their targets
147
+ * on the sensor command line.
148
+ *
149
+ * `concernSymbols` are the symbol names declared through witness `concern_anchors`. They only
150
+ * need the `query` operation: the binder asks whether the declared name resolves to exactly one
151
+ * symbol, and where it lives. Graph expansion stays owned by the conflict resources.
152
+ */
153
+ export function buildSeamProposalQuerySet({ conflictResources, concernSymbols = [] } = {}) {
154
+ const resources = assertConflictResources(conflictResources);
155
+ const concerns = assertConcernSymbols(concernSymbols);
156
+ const queryById = new Map([[
157
+ 'seam-00-status',
158
+ { id: 'seam-00-status', operation: 'status' },
159
+ ]]);
160
+ const queryableKeys = new Set();
161
+ const excludedResources = [];
162
+
163
+ for (const resource of resources) {
164
+ if (!QUERYABLE_KINDS.has(resource.kind)) {
165
+ excludedResources.push({
166
+ resource_id: resource.resource_id,
167
+ kind: resource.kind,
168
+ target: resource.target,
169
+ reason: 'non_code_conflict',
170
+ });
171
+ continue;
172
+ }
173
+ const resourceKey = `${resource.kind}\0${resource.target}`;
174
+ if (queryableKeys.has(resourceKey)) continue;
175
+ queryableKeys.add(resourceKey);
176
+ const operations = resource.kind === 'symbol' ? SYMBOL_OPERATIONS : ['affected'];
177
+ for (const operation of operations) {
178
+ const id = queryId(operation, resource.kind, resource.target);
179
+ if (queryById.has(id)) {
180
+ fail('SEAM_QUERY_ID_COLLISION', 'deterministic_query_id_collision', {
181
+ query_id: id,
182
+ });
183
+ }
184
+ queryById.set(id, { id, operation, target: resource.target });
185
+ }
186
+ }
187
+
188
+ // 宣言concern symbolの解決query。conflict symbolと同名なら既存queryがそのまま答えになる。
189
+ for (const symbol of concerns) {
190
+ const id = queryId('query', 'symbol', symbol);
191
+ if (queryById.has(id)) continue;
192
+ queryById.set(id, { id, operation: 'query', target: symbol });
193
+ }
194
+
195
+ const querySet = {
196
+ queries: [...queryById.values()]
197
+ .sort((left, right) => compareText(left.id, right.id)),
198
+ };
199
+ if (querySet.queries.length > QUERY_LIMIT) {
200
+ fail('SEAM_QUERY_LIMIT_EXCEEDED', 'runtime_sensor_query_limit_exceeded', {
201
+ query_count: querySet.queries.length,
202
+ query_limit: QUERY_LIMIT,
203
+ });
204
+ }
205
+ assertRuntimeQuerySet(querySet);
206
+ return {
207
+ query_set: querySet,
208
+ excluded_resources: excludedResources,
209
+ };
210
+ }
211
+
212
+ function outcomeFailure(outcome, query) {
213
+ if (!plainRecord(outcome)
214
+ || outcome.id !== query.id
215
+ || outcome.operation !== query.operation
216
+ || !boundedText(outcome.outcome)) {
217
+ fail('SEAM_SENSOR_EVIDENCE_INVALID', 'sensor_outcome_query_mismatch', {
218
+ query_id: query.id,
219
+ });
220
+ }
221
+ if (new Set([
222
+ 'command_failure', 'invalid_json', 'unsupported', 'unresolved', 'stale',
223
+ ]).has(outcome.outcome)) {
224
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_query_failed', {
225
+ query_id: query.id,
226
+ operation: query.operation,
227
+ outcome: outcome.outcome,
228
+ });
229
+ }
230
+ }
231
+
232
+ function exactSymbolResolution(outcome, target, operation) {
233
+ if (outcome.outcome === 'symbol_absent') return { outcome: 'absent' };
234
+ if (outcome.outcome !== 'ready') {
235
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_symbol_query_not_ready', {
236
+ query_id: outcome.id,
237
+ operation,
238
+ outcome: outcome.outcome,
239
+ });
240
+ }
241
+ const records = operation === 'query' ? outcome.data : outcome.resolution;
242
+ if (!Array.isArray(records)) return { outcome: 'unknown' };
243
+ const exact = records.filter((entry) => {
244
+ const node = entry?.node;
245
+ return plainRecord(node) && (node.name === target || node.qualifiedName === target);
246
+ });
247
+ if (exact.length === 0) return { outcome: 'absent' };
248
+ if (exact.some(({ node }) => !repoRelativePath(node.filePath))) {
249
+ return { outcome: 'unknown' };
250
+ }
251
+ const paths = [...new Set(exact.map(({ node }) => node.filePath))].sort(compareText);
252
+ if (paths.length !== 1) return { outcome: 'unknown' };
253
+ return { outcome: 'resolved', resolved_name: target, resolved_path: paths[0] };
254
+ }
255
+
256
+ function symbolResolutionForEvidence(local, canonical) {
257
+ if (canonical.outcome === 'unknown') return { outcome: 'unknown' };
258
+ if (canonical.outcome === 'absent') {
259
+ return local.outcome === 'absent' ? local : { outcome: 'unknown' };
260
+ }
261
+ return local.outcome === 'resolved'
262
+ && local.resolved_name === canonical.resolved_name
263
+ && local.resolved_path === canonical.resolved_path
264
+ ? local
265
+ : { outcome: 'unknown' };
266
+ }
267
+
268
+ function affectedResolution(outcome, target) {
269
+ if (!['ready', 'empty'].includes(outcome.outcome)) {
270
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_affected_query_not_ready', {
271
+ query_id: outcome.id,
272
+ outcome: outcome.outcome,
273
+ });
274
+ }
275
+ if (!Array.isArray(outcome.targets) || outcome.targets.length !== 1) {
276
+ return { outcome: 'unknown' };
277
+ }
278
+ const [entry] = outcome.targets;
279
+ if (!plainRecord(entry) || entry.target !== target) return { outcome: 'unknown' };
280
+ if (entry.path_state === 'absent') return { outcome: 'absent' };
281
+ if (!['ready', 'empty'].includes(entry.outcome)
282
+ || !plainRecord(entry.data)
283
+ || !Array.isArray(entry.data.affectedTests)) {
284
+ return { outcome: 'unknown' };
285
+ }
286
+ return { outcome: 'resolved', resolved_name: null, resolved_path: target };
287
+ }
288
+
289
+ function evidenceQuery({ query, outcome, resolution }) {
290
+ return {
291
+ query_id: query.id,
292
+ operation: query.operation,
293
+ target: query.target ?? '.',
294
+ outcome: resolution.outcome,
295
+ resolved_name: resolution.resolved_name ?? null,
296
+ resolved_path: resolution.resolved_path ?? null,
297
+ result_digest: digestArtifact(portableSensorOutcome(outcome)),
298
+ };
299
+ }
300
+
301
+ /**
302
+ * Normalize already-collected outcomes. Unit tests can inject the `collected` fixture here;
303
+ * production collection remains owned by `collectSensorEvidence`.
304
+ */
305
+ export function normalizeSeamProposalEvidence({ querySet, collected } = {}) {
306
+ assertRuntimeQuerySet(querySet);
307
+ if (!plainRecord(collected) || !Array.isArray(collected.outcomes)
308
+ || collected.outcomes.length !== querySet.queries.length) {
309
+ fail('SEAM_SENSOR_EVIDENCE_INVALID', 'sensor_outcome_count_mismatch', {
310
+ expected: querySet.queries.length,
311
+ actual: Array.isArray(collected?.outcomes) ? collected.outcomes.length : null,
312
+ });
313
+ }
314
+
315
+ const outcomeById = new Map();
316
+ querySet.queries.forEach((query, index) => {
317
+ const outcome = collected.outcomes[index];
318
+ outcomeFailure(outcome, query);
319
+ outcomeById.set(query.id, outcome);
320
+ });
321
+
322
+ const statusQuery = querySet.queries.find(({ operation }) => operation === 'status');
323
+ const statusOutcome = outcomeById.get(statusQuery.id);
324
+ if (statusOutcome.outcome !== 'ready') {
325
+ fail('SEAM_SENSOR_STATUS_NOT_READY', 'sensor_status_not_ready', {
326
+ outcome: statusOutcome.outcome,
327
+ });
328
+ }
329
+
330
+ const canonicalByTarget = new Map();
331
+ for (const query of querySet.queries.filter(({ operation }) => operation === 'query')) {
332
+ canonicalByTarget.set(
333
+ query.target,
334
+ exactSymbolResolution(outcomeById.get(query.id), query.target, query.operation),
335
+ );
336
+ }
337
+
338
+ const queries = querySet.queries.map((query) => {
339
+ const outcome = outcomeById.get(query.id);
340
+ if (query.operation === 'status') {
341
+ return evidenceQuery({ query, outcome, resolution: { outcome: 'resolved' } });
342
+ }
343
+ if (query.operation === 'affected') {
344
+ return evidenceQuery({
345
+ query,
346
+ outcome,
347
+ resolution: affectedResolution(outcome, query.target),
348
+ });
349
+ }
350
+ const local = exactSymbolResolution(outcome, query.target, query.operation);
351
+ const canonical = canonicalByTarget.get(query.target);
352
+ return evidenceQuery({
353
+ query,
354
+ outcome,
355
+ resolution: query.operation === 'query'
356
+ ? local
357
+ : symbolResolutionForEvidence(local, canonical),
358
+ });
359
+ }).sort((left, right) => compareText(left.query_id, right.query_id));
360
+
361
+ const evidence = {
362
+ query_set_digest: digestArtifact(querySet),
363
+ evidence_digest: '',
364
+ queries,
365
+ };
366
+ evidence.evidence_digest = todoSelfDigest(evidence, 'evidence_digest');
367
+ return evidence;
368
+ }
369
+
370
+ function observedGraphNode(entry) {
371
+ const node = entry?.node ?? entry;
372
+ if (!plainRecord(node)
373
+ || !boundedText(node.name)
374
+ || !repoRelativePath(node.filePath)) return null;
375
+ return { name: node.name, filePath: node.filePath };
376
+ }
377
+
378
+ function graphNodeKey(node) {
379
+ return `${node.name}\0${node.filePath}`;
380
+ }
381
+
382
+ async function collectCalleeClosure({
383
+ cwd,
384
+ initialCollected,
385
+ execute,
386
+ inspectAffectedPath,
387
+ }) {
388
+ const queueByKey = new Map();
389
+ let complete = true;
390
+ for (const outcome of initialCollected.outcomes) {
391
+ if (outcome.operation !== 'callees' || outcome.outcome !== 'ready'
392
+ || !plainRecord(outcome.data) || !Array.isArray(outcome.data.callees)) continue;
393
+ for (const entry of outcome.data.callees) {
394
+ const node = observedGraphNode(entry);
395
+ if (node === null) complete = false;
396
+ else queueByKey.set(graphNodeKey(node), node);
397
+ }
398
+ }
399
+ const seen = new Set();
400
+ const expansions = [];
401
+ while (queueByKey.size > 0) {
402
+ if (seen.size >= GRAPH_NODE_LIMIT) {
403
+ complete = false;
404
+ break;
405
+ }
406
+ const [key, node] = [...queueByKey.entries()]
407
+ .sort((left, right) => compareText(left[0], right[0]))[0];
408
+ queueByKey.delete(key);
409
+ if (seen.has(key)) continue;
410
+ seen.add(key);
411
+ const token = sha16(key);
412
+ const querySet = {
413
+ queries: [
414
+ { id: `seam-expand-callees-${token}`, operation: 'callees', target: node.name },
415
+ { id: `seam-expand-query-${token}`, operation: 'query', target: node.name },
416
+ { id: `seam-expand-status-${token}`, operation: 'status' },
417
+ ].sort((left, right) => compareText(left.id, right.id)),
418
+ };
419
+ const collected = await collectSensorEvidence({
420
+ cwd,
421
+ querySet,
422
+ ...(execute === undefined ? {} : { execute }),
423
+ ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
424
+ });
425
+ const queryOutcome = collected.outcomes.find(({ operation }) => operation === 'query');
426
+ const calleeOutcome = collected.outcomes.find(({ operation }) => operation === 'callees');
427
+ const exactPaths = Array.isArray(queryOutcome?.data)
428
+ ? sortedUnique(queryOutcome.data.map(observedGraphNode)
429
+ .filter((entry) => entry !== null && entry.name === node.name)
430
+ .map(({ filePath }) => filePath))
431
+ : [];
432
+ const resolutionPaths = Array.isArray(calleeOutcome?.resolution)
433
+ ? sortedUnique(calleeOutcome.resolution.map(observedGraphNode)
434
+ .filter((entry) => entry !== null && entry.name === node.name)
435
+ .map(({ filePath }) => filePath))
436
+ : [];
437
+ const exact = queryOutcome?.outcome === 'ready'
438
+ && calleeOutcome?.outcome === 'ready'
439
+ && exactPaths.length === 1
440
+ && resolutionPaths.length === 1
441
+ && exactPaths[0] === node.filePath
442
+ && resolutionPaths[0] === node.filePath
443
+ && plainRecord(calleeOutcome.data)
444
+ && Array.isArray(calleeOutcome.data.callees);
445
+ expansions.push({
446
+ parent: node,
447
+ query_outcome: queryOutcome ?? null,
448
+ callees_outcome: calleeOutcome ?? null,
449
+ exact,
450
+ });
451
+ if (!exact) {
452
+ complete = false;
453
+ continue;
454
+ }
455
+ for (const entry of calleeOutcome.data.callees) {
456
+ const child = observedGraphNode(entry);
457
+ if (child === null) {
458
+ complete = false;
459
+ continue;
460
+ }
461
+ const childKey = graphNodeKey(child);
462
+ if (!seen.has(childKey)) queueByKey.set(childKey, child);
463
+ }
464
+ }
465
+ return {
466
+ complete: complete && queueByKey.size === 0,
467
+ node_limit: GRAPH_NODE_LIMIT,
468
+ expansions,
469
+ };
470
+ }
471
+
472
+ /**
473
+ * Collect through the bundled sensor adapter. The normalized evidence remains the only
474
+ * contract-shaped artifact; raw outcomes are returned on a separate, in-memory channel for
475
+ * structural cut enumeration and must not be embedded in lattice.seam_proposal.v1.
476
+ */
477
+ export async function collectSeamProposalEvidenceBundle({
478
+ cwd,
479
+ querySet,
480
+ execute = undefined,
481
+ inspectAffectedPath = undefined,
482
+ } = {}) {
483
+ const collected = await collectSensorEvidence({
484
+ cwd,
485
+ querySet,
486
+ ...(execute === undefined ? {} : { execute }),
487
+ ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
488
+ });
489
+ const graphClosure = await collectCalleeClosure({
490
+ cwd,
491
+ initialCollected: collected,
492
+ execute,
493
+ inspectAffectedPath,
494
+ });
495
+ return {
496
+ evidence: normalizeSeamProposalEvidence({ querySet, collected }),
497
+ raw_collected: {
498
+ ...collected,
499
+ graph_closure: graphClosure,
500
+ },
501
+ };
502
+ }
503
+
504
+ /** Backward-compatible normalized-only collection entry point. */
505
+ export async function collectSeamProposalEvidence(options = {}) {
506
+ const bundle = await collectSeamProposalEvidenceBundle(options);
507
+ return bundle.evidence;
508
+ }