@quolu/lattice 0.52.3 → 0.53.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.
Files changed (188) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge.mjs +25 -0
  5. package/bin/lattice-hub.mjs +67 -0
  6. package/bin/lattice-mcp.mjs +0 -0
  7. package/bin/lattice-scripted-adapter.mjs +0 -0
  8. package/bin/lattice-scripted-worker.mjs +0 -0
  9. package/bin/lattice-work-order-adapter.mjs +0 -0
  10. package/bin/lattice.mjs +0 -0
  11. package/docs/bridge-setup.md +132 -132
  12. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  13. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  14. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  15. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  16. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  17. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  18. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  19. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  20. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  21. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  23. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  24. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  25. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  26. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  27. package/package.json +103 -103
  28. package/sensor/LICENSE +21 -21
  29. package/sensor/NOTICE +19 -19
  30. package/sensor/dist/bin/lattice-sensor.js +9 -9
  31. package/sensor/dist/db/index.js +24 -24
  32. package/sensor/dist/db/migrations.js +41 -41
  33. package/sensor/dist/db/queries.js +164 -164
  34. package/sensor/dist/db/schema.sql +205 -205
  35. package/sensor/dist/directory.js +5 -5
  36. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  51. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  52. package/sensor/dist/mcp/server-instructions.js +95 -95
  53. package/sensor/package.json +56 -56
  54. package/src/artifact-contracts-v2.mjs +325 -325
  55. package/src/artifact-contracts.mjs +895 -895
  56. package/src/boundary-compiler.mjs +712 -712
  57. package/src/boundary-observation-compiler-v2.mjs +344 -344
  58. package/src/bounded-seam.mjs +230 -230
  59. package/src/bridge-address.mjs +107 -107
  60. package/src/bridge-cli.mjs +303 -297
  61. package/src/bridge-config.mjs +382 -346
  62. package/src/bridge-daemon.mjs +378 -378
  63. package/src/bridge-hub-heartbeat.mjs +170 -0
  64. package/src/bridge-hub-protocol.mjs +198 -0
  65. package/src/bridge-hub-server.mjs +544 -0
  66. package/src/bridge-launch-agent.mjs +323 -323
  67. package/src/bridge-registrar.mjs +102 -102
  68. package/src/bridge-server.mjs +376 -376
  69. package/src/cli-help.mjs +308 -308
  70. package/src/cli-stdio.mjs +40 -40
  71. package/src/control-compiler.mjs +532 -532
  72. package/src/dag-chain.mjs +261 -261
  73. package/src/factory-diagnostics.mjs +188 -188
  74. package/src/git-process.mjs +72 -0
  75. package/src/hash-chain.mjs +76 -76
  76. package/src/hooks-cli.mjs +1057 -1057
  77. package/src/isolation-runner.mjs +409 -409
  78. package/src/node-version-guard.mjs +44 -44
  79. package/src/project-cli.mjs +3 -3
  80. package/src/project-identity.mjs +130 -130
  81. package/src/rc1-black-box-oracle.mjs +906 -906
  82. package/src/rc1-comparison.mjs +154 -154
  83. package/src/rc1-evidence-bundle.mjs +456 -456
  84. package/src/rc1-v4-campaign.mjs +708 -708
  85. package/src/rc1-v4-transform.mjs +467 -467
  86. package/src/rc1-v5-artifact-set.mjs +855 -855
  87. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  88. package/src/rc1-v5-campaign.mjs +797 -797
  89. package/src/rc1-v5-transform.mjs +421 -421
  90. package/src/rc1-v6-artifact-set.mjs +807 -807
  91. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  92. package/src/rc1-v6-campaign.mjs +623 -623
  93. package/src/rc1-v6-causal-binding.mjs +473 -473
  94. package/src/rc1-v6-measurement.mjs +313 -313
  95. package/src/rc2-artifact-set.mjs +1584 -1584
  96. package/src/rc2-campaign.mjs +1506 -1506
  97. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  98. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  99. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  100. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  101. package/src/rc3-actual-dogfood.mjs +652 -652
  102. package/src/rc3-dogfood-scaffold.mjs +315 -315
  103. package/src/rc3-scripted-campaign.mjs +1383 -1383
  104. package/src/rc4-stage1-dogfood.mjs +673 -673
  105. package/src/runtime-adapter-registry.mjs +524 -524
  106. package/src/runtime-cli.mjs +4588 -4588
  107. package/src/runtime-contracts.mjs +824 -824
  108. package/src/runtime-control-store.mjs +604 -604
  109. package/src/runtime-controller-protocol.mjs +587 -587
  110. package/src/runtime-decision-verifier.mjs +701 -701
  111. package/src/runtime-diff-observer.mjs +361 -361
  112. package/src/runtime-direct-os-observer.mjs +301 -301
  113. package/src/runtime-driver-state.mjs +166 -166
  114. package/src/runtime-engine.mjs +779 -779
  115. package/src/runtime-errors.mjs +356 -356
  116. package/src/runtime-event-store.mjs +189 -189
  117. package/src/runtime-front-end.mjs +925 -925
  118. package/src/runtime-gate-store.mjs +481 -481
  119. package/src/runtime-hold-recompile.mjs +916 -916
  120. package/src/runtime-io-sentinel.mjs +391 -391
  121. package/src/runtime-lifecycle-lock.mjs +294 -294
  122. package/src/runtime-managed-supervisor.mjs +1490 -1490
  123. package/src/runtime-multi-epoch-store.mjs +838 -838
  124. package/src/runtime-projection.mjs +269 -269
  125. package/src/runtime-pull-intake.mjs +1192 -1192
  126. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  127. package/src/runtime-scripted-executor.mjs +163 -163
  128. package/src/runtime-scripted-worktree.mjs +104 -104
  129. package/src/runtime-seam-resolve.mjs +428 -428
  130. package/src/runtime-seam-treatment.mjs +173 -173
  131. package/src/runtime-socket-owner.mjs +125 -125
  132. package/src/runtime-work-order-contracts.mjs +91 -91
  133. package/src/runtime-work-order-controller.mjs +1171 -1171
  134. package/src/runtime-worktree-executor.mjs +199 -199
  135. package/src/schedulability-compiler-v2.mjs +303 -303
  136. package/src/schedulability-verifier-v2.mjs +317 -317
  137. package/src/seam-apply.mjs +549 -549
  138. package/src/seam-commit-shared.mjs +22 -22
  139. package/src/seam-commit-transform.mjs +81 -81
  140. package/src/seam-commit.mjs +18 -18
  141. package/src/seam-cost.mjs +322 -322
  142. package/src/seam-derivation.mjs +188 -188
  143. package/src/seam-gate.mjs +146 -146
  144. package/src/seam-proposal-contracts.mjs +446 -446
  145. package/src/seam-proposal-queries.mjs +521 -521
  146. package/src/seam-proposal.mjs +2011 -2011
  147. package/src/seam-ref.mjs +33 -33
  148. package/src/seam-rewrite.mjs +286 -286
  149. package/src/seam-transform.mjs +554 -554
  150. package/src/seam-verification.mjs +260 -260
  151. package/src/sensor-adapter.mjs +432 -432
  152. package/src/sensor-cli.mjs +139 -139
  153. package/src/sensor-diff.mjs +661 -661
  154. package/src/sensor-node-runtime.mjs +53 -53
  155. package/src/sensor-runtime.mjs +52 -52
  156. package/src/timestamp-contract.mjs +8 -8
  157. package/src/todo-audit-pending.mjs +91 -91
  158. package/src/todo-chain.mjs +178 -178
  159. package/src/todo-cli.mjs +8 -8
  160. package/src/todo-contracts.mjs +728 -728
  161. package/src/todo-dashboard-registry.mjs +573 -573
  162. package/src/todo-dispatch-shape.mjs +190 -190
  163. package/src/todo-gantt-html-independence.mjs +239 -239
  164. package/src/todo-gantt-html-shared.mjs +226 -226
  165. package/src/todo-gantt-html-style.mjs +131 -131
  166. package/src/todo-gantt-html.mjs +248 -248
  167. package/src/todo-gantt-layout.mjs +974 -974
  168. package/src/todo-gantt-live.mjs +361 -361
  169. package/src/todo-gantt-nested.mjs +263 -263
  170. package/src/todo-gantt-presentation.mjs +217 -217
  171. package/src/todo-gantt-scope.mjs +123 -123
  172. package/src/todo-gantt-svg.mjs +353 -353
  173. package/src/todo-independence-contracts.mjs +595 -595
  174. package/src/todo-independence-guidance.mjs +322 -322
  175. package/src/todo-independence.mjs +640 -640
  176. package/src/todo-markdown-renderer.mjs +260 -260
  177. package/src/todo-migration.mjs +448 -448
  178. package/src/todo-narrative-anchor.mjs +130 -130
  179. package/src/todo-note-store.mjs +629 -629
  180. package/src/todo-parallel-candidates.mjs +114 -114
  181. package/src/todo-revision.mjs +995 -995
  182. package/src/todo-split.mjs +472 -472
  183. package/src/todo-status.mjs +690 -690
  184. package/src/todo-store-git-transaction.mjs +418 -418
  185. package/src/todo-store.mjs +42 -21
  186. package/src/treatment-compiler.mjs +728 -728
  187. package/src/treatment-runner.mjs +656 -656
  188. package/src/witness-scaffold.mjs +180 -180
@@ -1,521 +1,521 @@
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', 'line']);
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) {
253
- return { outcome: 'resolved', resolved_name: target, resolved_path: paths[0] };
254
- }
255
- // 同名が複数fileにある。`query`は「その名前はどこに居るか」を問う操作なので、候補を
256
- // 持ったまま返す——宣言の`within`が指す資源で絞れば一意に決まる場合がある(ADR 0134)。
257
- // graph操作(callers/callees/impact)は逆に、展開の起点が一意でなければ意味を持たない。
258
- // 同じ曖昧さでも問いが違うので、そちらはunknownのまま潰す。
259
- if (operation === 'query') {
260
- return { outcome: 'ambiguous', resolved_name: target, candidate_paths: paths };
261
- }
262
- return { outcome: 'unknown' };
263
- }
264
-
265
- function symbolResolutionForEvidence(local, canonical) {
266
- // 起点が一意でない名前についてのgraph観測は、どのsymbolについての観測か確定しない。
267
- if (canonical.outcome === 'unknown' || canonical.outcome === 'ambiguous') {
268
- return { outcome: 'unknown' };
269
- }
270
- if (canonical.outcome === 'absent') {
271
- return local.outcome === 'absent' ? local : { outcome: 'unknown' };
272
- }
273
- return local.outcome === 'resolved'
274
- && local.resolved_name === canonical.resolved_name
275
- && local.resolved_path === canonical.resolved_path
276
- ? local
277
- : { outcome: 'unknown' };
278
- }
279
-
280
- function affectedResolution(outcome, target) {
281
- if (!['ready', 'empty'].includes(outcome.outcome)) {
282
- fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_affected_query_not_ready', {
283
- query_id: outcome.id,
284
- outcome: outcome.outcome,
285
- });
286
- }
287
- if (!Array.isArray(outcome.targets) || outcome.targets.length !== 1) {
288
- return { outcome: 'unknown' };
289
- }
290
- const [entry] = outcome.targets;
291
- if (!plainRecord(entry) || entry.target !== target) return { outcome: 'unknown' };
292
- if (entry.path_state === 'absent') return { outcome: 'absent' };
293
- if (!['ready', 'empty'].includes(entry.outcome)
294
- || !plainRecord(entry.data)
295
- || !Array.isArray(entry.data.affectedTests)) {
296
- return { outcome: 'unknown' };
297
- }
298
- return { outcome: 'resolved', resolved_name: null, resolved_path: target };
299
- }
300
-
301
- function evidenceQuery({ query, outcome, resolution }) {
302
- return {
303
- query_id: query.id,
304
- operation: query.operation,
305
- target: query.target ?? '.',
306
- outcome: resolution.outcome,
307
- resolved_name: resolution.resolved_name ?? null,
308
- resolved_path: resolution.resolved_path ?? null,
309
- candidate_paths: resolution.candidate_paths ?? [],
310
- result_digest: digestArtifact(portableSensorOutcome(outcome)),
311
- };
312
- }
313
-
314
- /**
315
- * Normalize already-collected outcomes. Unit tests can inject the `collected` fixture here;
316
- * production collection remains owned by `collectSensorEvidence`.
317
- */
318
- export function normalizeSeamProposalEvidence({ querySet, collected } = {}) {
319
- assertRuntimeQuerySet(querySet);
320
- if (!plainRecord(collected) || !Array.isArray(collected.outcomes)
321
- || collected.outcomes.length !== querySet.queries.length) {
322
- fail('SEAM_SENSOR_EVIDENCE_INVALID', 'sensor_outcome_count_mismatch', {
323
- expected: querySet.queries.length,
324
- actual: Array.isArray(collected?.outcomes) ? collected.outcomes.length : null,
325
- });
326
- }
327
-
328
- const outcomeById = new Map();
329
- querySet.queries.forEach((query, index) => {
330
- const outcome = collected.outcomes[index];
331
- outcomeFailure(outcome, query);
332
- outcomeById.set(query.id, outcome);
333
- });
334
-
335
- const statusQuery = querySet.queries.find(({ operation }) => operation === 'status');
336
- const statusOutcome = outcomeById.get(statusQuery.id);
337
- if (statusOutcome.outcome !== 'ready') {
338
- fail('SEAM_SENSOR_STATUS_NOT_READY', 'sensor_status_not_ready', {
339
- outcome: statusOutcome.outcome,
340
- });
341
- }
342
-
343
- const canonicalByTarget = new Map();
344
- for (const query of querySet.queries.filter(({ operation }) => operation === 'query')) {
345
- canonicalByTarget.set(
346
- query.target,
347
- exactSymbolResolution(outcomeById.get(query.id), query.target, query.operation),
348
- );
349
- }
350
-
351
- const queries = querySet.queries.map((query) => {
352
- const outcome = outcomeById.get(query.id);
353
- if (query.operation === 'status') {
354
- return evidenceQuery({ query, outcome, resolution: { outcome: 'resolved' } });
355
- }
356
- if (query.operation === 'affected') {
357
- return evidenceQuery({
358
- query,
359
- outcome,
360
- resolution: affectedResolution(outcome, query.target),
361
- });
362
- }
363
- const local = exactSymbolResolution(outcome, query.target, query.operation);
364
- const canonical = canonicalByTarget.get(query.target);
365
- return evidenceQuery({
366
- query,
367
- outcome,
368
- resolution: query.operation === 'query'
369
- ? local
370
- : symbolResolutionForEvidence(local, canonical),
371
- });
372
- }).sort((left, right) => compareText(left.query_id, right.query_id));
373
-
374
- const evidence = {
375
- query_set_digest: digestArtifact(querySet),
376
- evidence_digest: '',
377
- queries,
378
- };
379
- evidence.evidence_digest = todoSelfDigest(evidence, 'evidence_digest');
380
- return evidence;
381
- }
382
-
383
- function observedGraphNode(entry) {
384
- const node = entry?.node ?? entry;
385
- if (!plainRecord(node)
386
- || !boundedText(node.name)
387
- || !repoRelativePath(node.filePath)) return null;
388
- return { name: node.name, filePath: node.filePath };
389
- }
390
-
391
- function graphNodeKey(node) {
392
- return `${node.name}\0${node.filePath}`;
393
- }
394
-
395
- async function collectCalleeClosure({
396
- cwd,
397
- initialCollected,
398
- execute,
399
- inspectAffectedPath,
400
- }) {
401
- const queueByKey = new Map();
402
- let complete = true;
403
- for (const outcome of initialCollected.outcomes) {
404
- if (outcome.operation !== 'callees' || outcome.outcome !== 'ready'
405
- || !plainRecord(outcome.data) || !Array.isArray(outcome.data.callees)) continue;
406
- for (const entry of outcome.data.callees) {
407
- const node = observedGraphNode(entry);
408
- if (node === null) complete = false;
409
- else queueByKey.set(graphNodeKey(node), node);
410
- }
411
- }
412
- const seen = new Set();
413
- const expansions = [];
414
- while (queueByKey.size > 0) {
415
- if (seen.size >= GRAPH_NODE_LIMIT) {
416
- complete = false;
417
- break;
418
- }
419
- const [key, node] = [...queueByKey.entries()]
420
- .sort((left, right) => compareText(left[0], right[0]))[0];
421
- queueByKey.delete(key);
422
- if (seen.has(key)) continue;
423
- seen.add(key);
424
- const token = sha16(key);
425
- const querySet = {
426
- queries: [
427
- { id: `seam-expand-callees-${token}`, operation: 'callees', target: node.name },
428
- { id: `seam-expand-query-${token}`, operation: 'query', target: node.name },
429
- { id: `seam-expand-status-${token}`, operation: 'status' },
430
- ].sort((left, right) => compareText(left.id, right.id)),
431
- };
432
- const collected = await collectSensorEvidence({
433
- cwd,
434
- querySet,
435
- ...(execute === undefined ? {} : { execute }),
436
- ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
437
- });
438
- const queryOutcome = collected.outcomes.find(({ operation }) => operation === 'query');
439
- const calleeOutcome = collected.outcomes.find(({ operation }) => operation === 'callees');
440
- const exactPaths = Array.isArray(queryOutcome?.data)
441
- ? sortedUnique(queryOutcome.data.map(observedGraphNode)
442
- .filter((entry) => entry !== null && entry.name === node.name)
443
- .map(({ filePath }) => filePath))
444
- : [];
445
- const resolutionPaths = Array.isArray(calleeOutcome?.resolution)
446
- ? sortedUnique(calleeOutcome.resolution.map(observedGraphNode)
447
- .filter((entry) => entry !== null && entry.name === node.name)
448
- .map(({ filePath }) => filePath))
449
- : [];
450
- const exact = queryOutcome?.outcome === 'ready'
451
- && calleeOutcome?.outcome === 'ready'
452
- && exactPaths.length === 1
453
- && resolutionPaths.length === 1
454
- && exactPaths[0] === node.filePath
455
- && resolutionPaths[0] === node.filePath
456
- && plainRecord(calleeOutcome.data)
457
- && Array.isArray(calleeOutcome.data.callees);
458
- expansions.push({
459
- parent: node,
460
- query_outcome: queryOutcome ?? null,
461
- callees_outcome: calleeOutcome ?? null,
462
- exact,
463
- });
464
- if (!exact) {
465
- complete = false;
466
- continue;
467
- }
468
- for (const entry of calleeOutcome.data.callees) {
469
- const child = observedGraphNode(entry);
470
- if (child === null) {
471
- complete = false;
472
- continue;
473
- }
474
- const childKey = graphNodeKey(child);
475
- if (!seen.has(childKey)) queueByKey.set(childKey, child);
476
- }
477
- }
478
- return {
479
- complete: complete && queueByKey.size === 0,
480
- node_limit: GRAPH_NODE_LIMIT,
481
- expansions,
482
- };
483
- }
484
-
485
- /**
486
- * Collect through the bundled sensor adapter. The normalized evidence remains the only
487
- * contract-shaped artifact; raw outcomes are returned on a separate, in-memory channel for
488
- * structural cut enumeration and must not be embedded in lattice.seam_proposal.v2.
489
- */
490
- export async function collectSeamProposalEvidenceBundle({
491
- cwd,
492
- querySet,
493
- execute = undefined,
494
- inspectAffectedPath = undefined,
495
- } = {}) {
496
- const collected = await collectSensorEvidence({
497
- cwd,
498
- querySet,
499
- ...(execute === undefined ? {} : { execute }),
500
- ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
501
- });
502
- const graphClosure = await collectCalleeClosure({
503
- cwd,
504
- initialCollected: collected,
505
- execute,
506
- inspectAffectedPath,
507
- });
508
- return {
509
- evidence: normalizeSeamProposalEvidence({ querySet, collected }),
510
- raw_collected: {
511
- ...collected,
512
- graph_closure: graphClosure,
513
- },
514
- };
515
- }
516
-
517
- /** Backward-compatible normalized-only collection entry point. */
518
- export async function collectSeamProposalEvidence(options = {}) {
519
- const bundle = await collectSeamProposalEvidenceBundle(options);
520
- return bundle.evidence;
521
- }
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', 'line']);
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) {
253
+ return { outcome: 'resolved', resolved_name: target, resolved_path: paths[0] };
254
+ }
255
+ // 同名が複数fileにある。`query`は「その名前はどこに居るか」を問う操作なので、候補を
256
+ // 持ったまま返す——宣言の`within`が指す資源で絞れば一意に決まる場合がある(ADR 0134)。
257
+ // graph操作(callers/callees/impact)は逆に、展開の起点が一意でなければ意味を持たない。
258
+ // 同じ曖昧さでも問いが違うので、そちらはunknownのまま潰す。
259
+ if (operation === 'query') {
260
+ return { outcome: 'ambiguous', resolved_name: target, candidate_paths: paths };
261
+ }
262
+ return { outcome: 'unknown' };
263
+ }
264
+
265
+ function symbolResolutionForEvidence(local, canonical) {
266
+ // 起点が一意でない名前についてのgraph観測は、どのsymbolについての観測か確定しない。
267
+ if (canonical.outcome === 'unknown' || canonical.outcome === 'ambiguous') {
268
+ return { outcome: 'unknown' };
269
+ }
270
+ if (canonical.outcome === 'absent') {
271
+ return local.outcome === 'absent' ? local : { outcome: 'unknown' };
272
+ }
273
+ return local.outcome === 'resolved'
274
+ && local.resolved_name === canonical.resolved_name
275
+ && local.resolved_path === canonical.resolved_path
276
+ ? local
277
+ : { outcome: 'unknown' };
278
+ }
279
+
280
+ function affectedResolution(outcome, target) {
281
+ if (!['ready', 'empty'].includes(outcome.outcome)) {
282
+ fail('SEAM_SENSOR_QUERY_FAILED', 'sensor_affected_query_not_ready', {
283
+ query_id: outcome.id,
284
+ outcome: outcome.outcome,
285
+ });
286
+ }
287
+ if (!Array.isArray(outcome.targets) || outcome.targets.length !== 1) {
288
+ return { outcome: 'unknown' };
289
+ }
290
+ const [entry] = outcome.targets;
291
+ if (!plainRecord(entry) || entry.target !== target) return { outcome: 'unknown' };
292
+ if (entry.path_state === 'absent') return { outcome: 'absent' };
293
+ if (!['ready', 'empty'].includes(entry.outcome)
294
+ || !plainRecord(entry.data)
295
+ || !Array.isArray(entry.data.affectedTests)) {
296
+ return { outcome: 'unknown' };
297
+ }
298
+ return { outcome: 'resolved', resolved_name: null, resolved_path: target };
299
+ }
300
+
301
+ function evidenceQuery({ query, outcome, resolution }) {
302
+ return {
303
+ query_id: query.id,
304
+ operation: query.operation,
305
+ target: query.target ?? '.',
306
+ outcome: resolution.outcome,
307
+ resolved_name: resolution.resolved_name ?? null,
308
+ resolved_path: resolution.resolved_path ?? null,
309
+ candidate_paths: resolution.candidate_paths ?? [],
310
+ result_digest: digestArtifact(portableSensorOutcome(outcome)),
311
+ };
312
+ }
313
+
314
+ /**
315
+ * Normalize already-collected outcomes. Unit tests can inject the `collected` fixture here;
316
+ * production collection remains owned by `collectSensorEvidence`.
317
+ */
318
+ export function normalizeSeamProposalEvidence({ querySet, collected } = {}) {
319
+ assertRuntimeQuerySet(querySet);
320
+ if (!plainRecord(collected) || !Array.isArray(collected.outcomes)
321
+ || collected.outcomes.length !== querySet.queries.length) {
322
+ fail('SEAM_SENSOR_EVIDENCE_INVALID', 'sensor_outcome_count_mismatch', {
323
+ expected: querySet.queries.length,
324
+ actual: Array.isArray(collected?.outcomes) ? collected.outcomes.length : null,
325
+ });
326
+ }
327
+
328
+ const outcomeById = new Map();
329
+ querySet.queries.forEach((query, index) => {
330
+ const outcome = collected.outcomes[index];
331
+ outcomeFailure(outcome, query);
332
+ outcomeById.set(query.id, outcome);
333
+ });
334
+
335
+ const statusQuery = querySet.queries.find(({ operation }) => operation === 'status');
336
+ const statusOutcome = outcomeById.get(statusQuery.id);
337
+ if (statusOutcome.outcome !== 'ready') {
338
+ fail('SEAM_SENSOR_STATUS_NOT_READY', 'sensor_status_not_ready', {
339
+ outcome: statusOutcome.outcome,
340
+ });
341
+ }
342
+
343
+ const canonicalByTarget = new Map();
344
+ for (const query of querySet.queries.filter(({ operation }) => operation === 'query')) {
345
+ canonicalByTarget.set(
346
+ query.target,
347
+ exactSymbolResolution(outcomeById.get(query.id), query.target, query.operation),
348
+ );
349
+ }
350
+
351
+ const queries = querySet.queries.map((query) => {
352
+ const outcome = outcomeById.get(query.id);
353
+ if (query.operation === 'status') {
354
+ return evidenceQuery({ query, outcome, resolution: { outcome: 'resolved' } });
355
+ }
356
+ if (query.operation === 'affected') {
357
+ return evidenceQuery({
358
+ query,
359
+ outcome,
360
+ resolution: affectedResolution(outcome, query.target),
361
+ });
362
+ }
363
+ const local = exactSymbolResolution(outcome, query.target, query.operation);
364
+ const canonical = canonicalByTarget.get(query.target);
365
+ return evidenceQuery({
366
+ query,
367
+ outcome,
368
+ resolution: query.operation === 'query'
369
+ ? local
370
+ : symbolResolutionForEvidence(local, canonical),
371
+ });
372
+ }).sort((left, right) => compareText(left.query_id, right.query_id));
373
+
374
+ const evidence = {
375
+ query_set_digest: digestArtifact(querySet),
376
+ evidence_digest: '',
377
+ queries,
378
+ };
379
+ evidence.evidence_digest = todoSelfDigest(evidence, 'evidence_digest');
380
+ return evidence;
381
+ }
382
+
383
+ function observedGraphNode(entry) {
384
+ const node = entry?.node ?? entry;
385
+ if (!plainRecord(node)
386
+ || !boundedText(node.name)
387
+ || !repoRelativePath(node.filePath)) return null;
388
+ return { name: node.name, filePath: node.filePath };
389
+ }
390
+
391
+ function graphNodeKey(node) {
392
+ return `${node.name}\0${node.filePath}`;
393
+ }
394
+
395
+ async function collectCalleeClosure({
396
+ cwd,
397
+ initialCollected,
398
+ execute,
399
+ inspectAffectedPath,
400
+ }) {
401
+ const queueByKey = new Map();
402
+ let complete = true;
403
+ for (const outcome of initialCollected.outcomes) {
404
+ if (outcome.operation !== 'callees' || outcome.outcome !== 'ready'
405
+ || !plainRecord(outcome.data) || !Array.isArray(outcome.data.callees)) continue;
406
+ for (const entry of outcome.data.callees) {
407
+ const node = observedGraphNode(entry);
408
+ if (node === null) complete = false;
409
+ else queueByKey.set(graphNodeKey(node), node);
410
+ }
411
+ }
412
+ const seen = new Set();
413
+ const expansions = [];
414
+ while (queueByKey.size > 0) {
415
+ if (seen.size >= GRAPH_NODE_LIMIT) {
416
+ complete = false;
417
+ break;
418
+ }
419
+ const [key, node] = [...queueByKey.entries()]
420
+ .sort((left, right) => compareText(left[0], right[0]))[0];
421
+ queueByKey.delete(key);
422
+ if (seen.has(key)) continue;
423
+ seen.add(key);
424
+ const token = sha16(key);
425
+ const querySet = {
426
+ queries: [
427
+ { id: `seam-expand-callees-${token}`, operation: 'callees', target: node.name },
428
+ { id: `seam-expand-query-${token}`, operation: 'query', target: node.name },
429
+ { id: `seam-expand-status-${token}`, operation: 'status' },
430
+ ].sort((left, right) => compareText(left.id, right.id)),
431
+ };
432
+ const collected = await collectSensorEvidence({
433
+ cwd,
434
+ querySet,
435
+ ...(execute === undefined ? {} : { execute }),
436
+ ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
437
+ });
438
+ const queryOutcome = collected.outcomes.find(({ operation }) => operation === 'query');
439
+ const calleeOutcome = collected.outcomes.find(({ operation }) => operation === 'callees');
440
+ const exactPaths = Array.isArray(queryOutcome?.data)
441
+ ? sortedUnique(queryOutcome.data.map(observedGraphNode)
442
+ .filter((entry) => entry !== null && entry.name === node.name)
443
+ .map(({ filePath }) => filePath))
444
+ : [];
445
+ const resolutionPaths = Array.isArray(calleeOutcome?.resolution)
446
+ ? sortedUnique(calleeOutcome.resolution.map(observedGraphNode)
447
+ .filter((entry) => entry !== null && entry.name === node.name)
448
+ .map(({ filePath }) => filePath))
449
+ : [];
450
+ const exact = queryOutcome?.outcome === 'ready'
451
+ && calleeOutcome?.outcome === 'ready'
452
+ && exactPaths.length === 1
453
+ && resolutionPaths.length === 1
454
+ && exactPaths[0] === node.filePath
455
+ && resolutionPaths[0] === node.filePath
456
+ && plainRecord(calleeOutcome.data)
457
+ && Array.isArray(calleeOutcome.data.callees);
458
+ expansions.push({
459
+ parent: node,
460
+ query_outcome: queryOutcome ?? null,
461
+ callees_outcome: calleeOutcome ?? null,
462
+ exact,
463
+ });
464
+ if (!exact) {
465
+ complete = false;
466
+ continue;
467
+ }
468
+ for (const entry of calleeOutcome.data.callees) {
469
+ const child = observedGraphNode(entry);
470
+ if (child === null) {
471
+ complete = false;
472
+ continue;
473
+ }
474
+ const childKey = graphNodeKey(child);
475
+ if (!seen.has(childKey)) queueByKey.set(childKey, child);
476
+ }
477
+ }
478
+ return {
479
+ complete: complete && queueByKey.size === 0,
480
+ node_limit: GRAPH_NODE_LIMIT,
481
+ expansions,
482
+ };
483
+ }
484
+
485
+ /**
486
+ * Collect through the bundled sensor adapter. The normalized evidence remains the only
487
+ * contract-shaped artifact; raw outcomes are returned on a separate, in-memory channel for
488
+ * structural cut enumeration and must not be embedded in lattice.seam_proposal.v2.
489
+ */
490
+ export async function collectSeamProposalEvidenceBundle({
491
+ cwd,
492
+ querySet,
493
+ execute = undefined,
494
+ inspectAffectedPath = undefined,
495
+ } = {}) {
496
+ const collected = await collectSensorEvidence({
497
+ cwd,
498
+ querySet,
499
+ ...(execute === undefined ? {} : { execute }),
500
+ ...(inspectAffectedPath === undefined ? {} : { inspectAffectedPath }),
501
+ });
502
+ const graphClosure = await collectCalleeClosure({
503
+ cwd,
504
+ initialCollected: collected,
505
+ execute,
506
+ inspectAffectedPath,
507
+ });
508
+ return {
509
+ evidence: normalizeSeamProposalEvidence({ querySet, collected }),
510
+ raw_collected: {
511
+ ...collected,
512
+ graph_closure: graphClosure,
513
+ },
514
+ };
515
+ }
516
+
517
+ /** Backward-compatible normalized-only collection entry point. */
518
+ export async function collectSeamProposalEvidence(options = {}) {
519
+ const bundle = await collectSeamProposalEvidenceBundle(options);
520
+ return bundle.evidence;
521
+ }