@quolu/lattice 0.14.0 → 0.15.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,484 @@
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
+ /**
133
+ * Build the schema-less `lattice.run_request.v1.sensor_query_set` vocabulary used by
134
+ * todo-independence. The wrapper records non-code conflicts without putting their targets
135
+ * on the sensor command line.
136
+ */
137
+ export function buildSeamProposalQuerySet({ conflictResources } = {}) {
138
+ const resources = assertConflictResources(conflictResources);
139
+ const queryById = new Map([[
140
+ 'seam-00-status',
141
+ { id: 'seam-00-status', operation: 'status' },
142
+ ]]);
143
+ const queryableKeys = new Set();
144
+ const excludedResources = [];
145
+
146
+ for (const resource of resources) {
147
+ if (!QUERYABLE_KINDS.has(resource.kind)) {
148
+ excludedResources.push({
149
+ resource_id: resource.resource_id,
150
+ kind: resource.kind,
151
+ target: resource.target,
152
+ reason: 'non_code_conflict',
153
+ });
154
+ continue;
155
+ }
156
+ const resourceKey = `${resource.kind}\0${resource.target}`;
157
+ if (queryableKeys.has(resourceKey)) continue;
158
+ queryableKeys.add(resourceKey);
159
+ const operations = resource.kind === 'symbol' ? SYMBOL_OPERATIONS : ['affected'];
160
+ for (const operation of operations) {
161
+ const id = queryId(operation, resource.kind, resource.target);
162
+ if (queryById.has(id)) {
163
+ fail('SEAM_QUERY_ID_COLLISION', 'deterministic_query_id_collision', {
164
+ query_id: id,
165
+ });
166
+ }
167
+ queryById.set(id, { id, operation, target: resource.target });
168
+ }
169
+ }
170
+
171
+ const querySet = {
172
+ queries: [...queryById.values()]
173
+ .sort((left, right) => compareText(left.id, right.id)),
174
+ };
175
+ if (querySet.queries.length > QUERY_LIMIT) {
176
+ fail('SEAM_QUERY_LIMIT_EXCEEDED', 'runtime_sensor_query_limit_exceeded', {
177
+ query_count: querySet.queries.length,
178
+ query_limit: QUERY_LIMIT,
179
+ });
180
+ }
181
+ assertRuntimeQuerySet(querySet);
182
+ return {
183
+ query_set: querySet,
184
+ excluded_resources: excludedResources,
185
+ };
186
+ }
187
+
188
+ function outcomeFailure(outcome, query) {
189
+ if (!plainRecord(outcome)
190
+ || outcome.id !== query.id
191
+ || outcome.operation !== query.operation
192
+ || !boundedText(outcome.outcome)) {
193
+ fail('SEAM_SENSOR_EVIDENCE_INVALID', 'sensor_outcome_query_mismatch', {
194
+ query_id: query.id,
195
+ });
196
+ }
197
+ if (new Set([
198
+ 'command_failure', 'invalid_json', 'unsupported', 'unresolved', 'stale',
199
+ ]).has(outcome.outcome)) {
200
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_query_failed', {
201
+ query_id: query.id,
202
+ operation: query.operation,
203
+ outcome: outcome.outcome,
204
+ });
205
+ }
206
+ }
207
+
208
+ function exactSymbolResolution(outcome, target, operation) {
209
+ if (outcome.outcome === 'symbol_absent') return { outcome: 'absent' };
210
+ if (outcome.outcome !== 'ready') {
211
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_symbol_query_not_ready', {
212
+ query_id: outcome.id,
213
+ operation,
214
+ outcome: outcome.outcome,
215
+ });
216
+ }
217
+ const records = operation === 'query' ? outcome.data : outcome.resolution;
218
+ if (!Array.isArray(records)) return { outcome: 'unknown' };
219
+ const exact = records.filter((entry) => {
220
+ const node = entry?.node;
221
+ return plainRecord(node) && (node.name === target || node.qualifiedName === target);
222
+ });
223
+ if (exact.length === 0) return { outcome: 'absent' };
224
+ if (exact.some(({ node }) => !repoRelativePath(node.filePath))) {
225
+ return { outcome: 'unknown' };
226
+ }
227
+ const paths = [...new Set(exact.map(({ node }) => node.filePath))].sort(compareText);
228
+ if (paths.length !== 1) return { outcome: 'unknown' };
229
+ return { outcome: 'resolved', resolved_name: target, resolved_path: paths[0] };
230
+ }
231
+
232
+ function symbolResolutionForEvidence(local, canonical) {
233
+ if (canonical.outcome === 'unknown') return { outcome: 'unknown' };
234
+ if (canonical.outcome === 'absent') {
235
+ return local.outcome === 'absent' ? local : { outcome: 'unknown' };
236
+ }
237
+ return local.outcome === 'resolved'
238
+ && local.resolved_name === canonical.resolved_name
239
+ && local.resolved_path === canonical.resolved_path
240
+ ? local
241
+ : { outcome: 'unknown' };
242
+ }
243
+
244
+ function affectedResolution(outcome, target) {
245
+ if (!['ready', 'empty'].includes(outcome.outcome)) {
246
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_affected_query_not_ready', {
247
+ query_id: outcome.id,
248
+ outcome: outcome.outcome,
249
+ });
250
+ }
251
+ if (!Array.isArray(outcome.targets) || outcome.targets.length !== 1) {
252
+ return { outcome: 'unknown' };
253
+ }
254
+ const [entry] = outcome.targets;
255
+ if (!plainRecord(entry) || entry.target !== target) return { outcome: 'unknown' };
256
+ if (entry.path_state === 'absent') return { outcome: 'absent' };
257
+ if (!['ready', 'empty'].includes(entry.outcome)
258
+ || !plainRecord(entry.data)
259
+ || !Array.isArray(entry.data.affectedTests)) {
260
+ return { outcome: 'unknown' };
261
+ }
262
+ return { outcome: 'resolved', resolved_name: null, resolved_path: target };
263
+ }
264
+
265
+ function evidenceQuery({ query, outcome, resolution }) {
266
+ return {
267
+ query_id: query.id,
268
+ operation: query.operation,
269
+ target: query.target ?? '.',
270
+ outcome: resolution.outcome,
271
+ resolved_name: resolution.resolved_name ?? null,
272
+ resolved_path: resolution.resolved_path ?? null,
273
+ result_digest: digestArtifact(portableSensorOutcome(outcome)),
274
+ };
275
+ }
276
+
277
+ /**
278
+ * Normalize already-collected outcomes. Unit tests can inject the `collected` fixture here;
279
+ * production collection remains owned by `collectSensorEvidence`.
280
+ */
281
+ export function normalizeSeamProposalEvidence({ querySet, collected } = {}) {
282
+ assertRuntimeQuerySet(querySet);
283
+ if (!plainRecord(collected) || !Array.isArray(collected.outcomes)
284
+ || collected.outcomes.length !== querySet.queries.length) {
285
+ fail('SEAM_SENSOR_EVIDENCE_INVALID', 'sensor_outcome_count_mismatch', {
286
+ expected: querySet.queries.length,
287
+ actual: Array.isArray(collected?.outcomes) ? collected.outcomes.length : null,
288
+ });
289
+ }
290
+
291
+ const outcomeById = new Map();
292
+ querySet.queries.forEach((query, index) => {
293
+ const outcome = collected.outcomes[index];
294
+ outcomeFailure(outcome, query);
295
+ outcomeById.set(query.id, outcome);
296
+ });
297
+
298
+ const statusQuery = querySet.queries.find(({ operation }) => operation === 'status');
299
+ const statusOutcome = outcomeById.get(statusQuery.id);
300
+ if (statusOutcome.outcome !== 'ready') {
301
+ fail('SEAM_SENSOR_STATUS_NOT_READY', 'sensor_status_not_ready', {
302
+ outcome: statusOutcome.outcome,
303
+ });
304
+ }
305
+
306
+ const canonicalByTarget = new Map();
307
+ for (const query of querySet.queries.filter(({ operation }) => operation === 'query')) {
308
+ canonicalByTarget.set(
309
+ query.target,
310
+ exactSymbolResolution(outcomeById.get(query.id), query.target, query.operation),
311
+ );
312
+ }
313
+
314
+ const queries = querySet.queries.map((query) => {
315
+ const outcome = outcomeById.get(query.id);
316
+ if (query.operation === 'status') {
317
+ return evidenceQuery({ query, outcome, resolution: { outcome: 'resolved' } });
318
+ }
319
+ if (query.operation === 'affected') {
320
+ return evidenceQuery({
321
+ query,
322
+ outcome,
323
+ resolution: affectedResolution(outcome, query.target),
324
+ });
325
+ }
326
+ const local = exactSymbolResolution(outcome, query.target, query.operation);
327
+ const canonical = canonicalByTarget.get(query.target);
328
+ return evidenceQuery({
329
+ query,
330
+ outcome,
331
+ resolution: query.operation === 'query'
332
+ ? local
333
+ : symbolResolutionForEvidence(local, canonical),
334
+ });
335
+ }).sort((left, right) => compareText(left.query_id, right.query_id));
336
+
337
+ const evidence = {
338
+ query_set_digest: digestArtifact(querySet),
339
+ evidence_digest: '',
340
+ queries,
341
+ };
342
+ evidence.evidence_digest = todoSelfDigest(evidence, 'evidence_digest');
343
+ return evidence;
344
+ }
345
+
346
+ function observedGraphNode(entry) {
347
+ const node = entry?.node ?? entry;
348
+ if (!plainRecord(node)
349
+ || !boundedText(node.name)
350
+ || !repoRelativePath(node.filePath)) return null;
351
+ return { name: node.name, filePath: node.filePath };
352
+ }
353
+
354
+ function graphNodeKey(node) {
355
+ return `${node.name}\0${node.filePath}`;
356
+ }
357
+
358
+ async function collectCalleeClosure({
359
+ cwd,
360
+ initialCollected,
361
+ execute,
362
+ inspectAffectedPath,
363
+ }) {
364
+ const queueByKey = new Map();
365
+ let complete = true;
366
+ for (const outcome of initialCollected.outcomes) {
367
+ if (outcome.operation !== 'callees' || outcome.outcome !== 'ready'
368
+ || !plainRecord(outcome.data) || !Array.isArray(outcome.data.callees)) continue;
369
+ for (const entry of outcome.data.callees) {
370
+ const node = observedGraphNode(entry);
371
+ if (node === null) complete = false;
372
+ else queueByKey.set(graphNodeKey(node), node);
373
+ }
374
+ }
375
+ const seen = new Set();
376
+ const expansions = [];
377
+ while (queueByKey.size > 0) {
378
+ if (seen.size >= GRAPH_NODE_LIMIT) {
379
+ complete = false;
380
+ break;
381
+ }
382
+ const [key, node] = [...queueByKey.entries()]
383
+ .sort((left, right) => compareText(left[0], right[0]))[0];
384
+ queueByKey.delete(key);
385
+ if (seen.has(key)) continue;
386
+ seen.add(key);
387
+ const token = sha16(key);
388
+ const querySet = {
389
+ queries: [
390
+ { id: `seam-expand-callees-${token}`, operation: 'callees', target: node.name },
391
+ { id: `seam-expand-query-${token}`, operation: 'query', target: node.name },
392
+ { id: `seam-expand-status-${token}`, operation: 'status' },
393
+ ].sort((left, right) => compareText(left.id, right.id)),
394
+ };
395
+ const collected = await collectSensorEvidence({
396
+ cwd,
397
+ querySet,
398
+ ...(execute === undefined ? {} : { execute }),
399
+ ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
400
+ });
401
+ const queryOutcome = collected.outcomes.find(({ operation }) => operation === 'query');
402
+ const calleeOutcome = collected.outcomes.find(({ operation }) => operation === 'callees');
403
+ const exactPaths = Array.isArray(queryOutcome?.data)
404
+ ? sortedUnique(queryOutcome.data.map(observedGraphNode)
405
+ .filter((entry) => entry !== null && entry.name === node.name)
406
+ .map(({ filePath }) => filePath))
407
+ : [];
408
+ const resolutionPaths = Array.isArray(calleeOutcome?.resolution)
409
+ ? sortedUnique(calleeOutcome.resolution.map(observedGraphNode)
410
+ .filter((entry) => entry !== null && entry.name === node.name)
411
+ .map(({ filePath }) => filePath))
412
+ : [];
413
+ const exact = queryOutcome?.outcome === 'ready'
414
+ && calleeOutcome?.outcome === 'ready'
415
+ && exactPaths.length === 1
416
+ && resolutionPaths.length === 1
417
+ && exactPaths[0] === node.filePath
418
+ && resolutionPaths[0] === node.filePath
419
+ && plainRecord(calleeOutcome.data)
420
+ && Array.isArray(calleeOutcome.data.callees);
421
+ expansions.push({
422
+ parent: node,
423
+ query_outcome: queryOutcome ?? null,
424
+ callees_outcome: calleeOutcome ?? null,
425
+ exact,
426
+ });
427
+ if (!exact) {
428
+ complete = false;
429
+ continue;
430
+ }
431
+ for (const entry of calleeOutcome.data.callees) {
432
+ const child = observedGraphNode(entry);
433
+ if (child === null) {
434
+ complete = false;
435
+ continue;
436
+ }
437
+ const childKey = graphNodeKey(child);
438
+ if (!seen.has(childKey)) queueByKey.set(childKey, child);
439
+ }
440
+ }
441
+ return {
442
+ complete: complete && queueByKey.size === 0,
443
+ node_limit: GRAPH_NODE_LIMIT,
444
+ expansions,
445
+ };
446
+ }
447
+
448
+ /**
449
+ * Collect through the bundled sensor adapter. The normalized evidence remains the only
450
+ * contract-shaped artifact; raw outcomes are returned on a separate, in-memory channel for
451
+ * structural cut enumeration and must not be embedded in lattice.seam_proposal.v1.
452
+ */
453
+ export async function collectSeamProposalEvidenceBundle({
454
+ cwd,
455
+ querySet,
456
+ execute = undefined,
457
+ inspectAffectedPath = undefined,
458
+ } = {}) {
459
+ const collected = await collectSensorEvidence({
460
+ cwd,
461
+ querySet,
462
+ ...(execute === undefined ? {} : { execute }),
463
+ ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
464
+ });
465
+ const graphClosure = await collectCalleeClosure({
466
+ cwd,
467
+ initialCollected: collected,
468
+ execute,
469
+ inspectAffectedPath,
470
+ });
471
+ return {
472
+ evidence: normalizeSeamProposalEvidence({ querySet, collected }),
473
+ raw_collected: {
474
+ ...collected,
475
+ graph_closure: graphClosure,
476
+ },
477
+ };
478
+ }
479
+
480
+ /** Backward-compatible normalized-only collection entry point. */
481
+ export async function collectSeamProposalEvidence(options = {}) {
482
+ const bundle = await collectSeamProposalEvidenceBundle(options);
483
+ return bundle.evidence;
484
+ }