@quolu/lattice 0.52.0 → 0.52.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-mcp.mjs +0 -0
  5. package/bin/lattice-scripted-adapter.mjs +0 -0
  6. package/bin/lattice-scripted-worker.mjs +0 -0
  7. package/bin/lattice-work-order-adapter.mjs +0 -0
  8. package/bin/lattice.mjs +0 -0
  9. package/docs/bridge-setup.md +132 -132
  10. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  11. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  12. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  13. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  14. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  15. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  16. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  17. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  18. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  19. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  20. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  21. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  22. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  23. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  24. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  25. package/package.json +103 -103
  26. package/sensor/LICENSE +21 -21
  27. package/sensor/NOTICE +19 -19
  28. package/sensor/dist/bin/lattice-sensor.js +9 -9
  29. package/sensor/dist/db/index.js +24 -24
  30. package/sensor/dist/db/migrations.js +41 -41
  31. package/sensor/dist/db/queries.js +164 -164
  32. package/sensor/dist/db/schema.sql +205 -205
  33. package/sensor/dist/directory.js +5 -5
  34. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  35. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  36. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  49. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  50. package/sensor/dist/mcp/server-instructions.js +95 -95
  51. package/sensor/package.json +56 -56
  52. package/src/artifact-contracts-v2.mjs +325 -325
  53. package/src/artifact-contracts.mjs +895 -895
  54. package/src/boundary-compiler.mjs +712 -712
  55. package/src/boundary-observation-compiler-v2.mjs +344 -344
  56. package/src/bounded-seam.mjs +230 -230
  57. package/src/bridge-address.mjs +107 -107
  58. package/src/bridge-cli.mjs +297 -297
  59. package/src/bridge-config.mjs +346 -346
  60. package/src/bridge-daemon.mjs +378 -378
  61. package/src/bridge-launch-agent.mjs +323 -323
  62. package/src/bridge-registrar.mjs +102 -102
  63. package/src/bridge-server.mjs +376 -376
  64. package/src/cli-help.mjs +308 -308
  65. package/src/cli-stdio.mjs +40 -40
  66. package/src/control-compiler.mjs +532 -532
  67. package/src/dag-chain.mjs +261 -261
  68. package/src/factory-diagnostics.mjs +188 -188
  69. package/src/hash-chain.mjs +76 -76
  70. package/src/hooks-cli.mjs +1057 -1053
  71. package/src/isolation-runner.mjs +409 -409
  72. package/src/node-version-guard.mjs +44 -44
  73. package/src/project-cli.mjs +697 -697
  74. package/src/project-identity.mjs +130 -130
  75. package/src/rc1-black-box-oracle.mjs +906 -906
  76. package/src/rc1-comparison.mjs +154 -154
  77. package/src/rc1-evidence-bundle.mjs +456 -456
  78. package/src/rc1-v4-campaign.mjs +708 -708
  79. package/src/rc1-v4-transform.mjs +467 -467
  80. package/src/rc1-v5-artifact-set.mjs +855 -855
  81. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  82. package/src/rc1-v5-campaign.mjs +797 -797
  83. package/src/rc1-v5-transform.mjs +421 -421
  84. package/src/rc1-v6-artifact-set.mjs +807 -807
  85. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  86. package/src/rc1-v6-campaign.mjs +623 -623
  87. package/src/rc1-v6-causal-binding.mjs +473 -473
  88. package/src/rc1-v6-measurement.mjs +313 -313
  89. package/src/rc2-artifact-set.mjs +1584 -1584
  90. package/src/rc2-campaign.mjs +1506 -1502
  91. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  92. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  93. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  94. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  95. package/src/rc3-actual-dogfood.mjs +652 -652
  96. package/src/rc3-dogfood-scaffold.mjs +315 -315
  97. package/src/rc3-scripted-campaign.mjs +1383 -1383
  98. package/src/rc4-stage1-dogfood.mjs +673 -673
  99. package/src/runtime-adapter-registry.mjs +524 -520
  100. package/src/runtime-cli.mjs +4588 -4584
  101. package/src/runtime-contracts.mjs +824 -824
  102. package/src/runtime-control-store.mjs +604 -600
  103. package/src/runtime-controller-protocol.mjs +587 -587
  104. package/src/runtime-decision-verifier.mjs +701 -701
  105. package/src/runtime-diff-observer.mjs +361 -361
  106. package/src/runtime-direct-os-observer.mjs +301 -301
  107. package/src/runtime-driver-state.mjs +166 -162
  108. package/src/runtime-engine.mjs +779 -779
  109. package/src/runtime-errors.mjs +356 -356
  110. package/src/runtime-event-store.mjs +189 -189
  111. package/src/runtime-front-end.mjs +925 -925
  112. package/src/runtime-gate-store.mjs +481 -477
  113. package/src/runtime-hold-recompile.mjs +916 -916
  114. package/src/runtime-io-sentinel.mjs +391 -391
  115. package/src/runtime-lifecycle-lock.mjs +294 -290
  116. package/src/runtime-managed-supervisor.mjs +1490 -1490
  117. package/src/runtime-multi-epoch-store.mjs +838 -834
  118. package/src/runtime-projection.mjs +269 -269
  119. package/src/runtime-pull-intake.mjs +1192 -1188
  120. package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
  121. package/src/runtime-scripted-executor.mjs +163 -163
  122. package/src/runtime-scripted-worktree.mjs +104 -104
  123. package/src/runtime-seam-resolve.mjs +428 -428
  124. package/src/runtime-seam-treatment.mjs +173 -173
  125. package/src/runtime-socket-owner.mjs +125 -125
  126. package/src/runtime-work-order-contracts.mjs +91 -91
  127. package/src/runtime-work-order-controller.mjs +1171 -1167
  128. package/src/runtime-worktree-executor.mjs +199 -199
  129. package/src/schedulability-compiler-v2.mjs +303 -303
  130. package/src/schedulability-verifier-v2.mjs +317 -317
  131. package/src/seam-apply.mjs +549 -549
  132. package/src/seam-commit-shared.mjs +22 -22
  133. package/src/seam-commit-transform.mjs +81 -81
  134. package/src/seam-commit.mjs +18 -18
  135. package/src/seam-cost.mjs +322 -322
  136. package/src/seam-derivation.mjs +188 -188
  137. package/src/seam-gate.mjs +146 -146
  138. package/src/seam-proposal-contracts.mjs +446 -446
  139. package/src/seam-proposal-queries.mjs +521 -521
  140. package/src/seam-proposal.mjs +2011 -2011
  141. package/src/seam-ref.mjs +33 -33
  142. package/src/seam-rewrite.mjs +286 -286
  143. package/src/seam-transform.mjs +554 -554
  144. package/src/seam-verification.mjs +260 -260
  145. package/src/sensor-adapter.mjs +432 -432
  146. package/src/sensor-cli.mjs +139 -139
  147. package/src/sensor-diff.mjs +661 -661
  148. package/src/sensor-node-runtime.mjs +53 -53
  149. package/src/sensor-runtime.mjs +52 -52
  150. package/src/timestamp-contract.mjs +8 -8
  151. package/src/todo-audit-pending.mjs +91 -91
  152. package/src/todo-chain.mjs +178 -178
  153. package/src/todo-cli.mjs +3141 -3126
  154. package/src/todo-contracts.mjs +728 -728
  155. package/src/todo-dashboard-registry.mjs +573 -573
  156. package/src/todo-dispatch-shape.mjs +190 -190
  157. package/src/todo-gantt-html-independence.mjs +239 -239
  158. package/src/todo-gantt-html-shared.mjs +226 -226
  159. package/src/todo-gantt-html-style.mjs +131 -131
  160. package/src/todo-gantt-html.mjs +248 -248
  161. package/src/todo-gantt-layout.mjs +974 -974
  162. package/src/todo-gantt-live.mjs +361 -361
  163. package/src/todo-gantt-nested.mjs +263 -263
  164. package/src/todo-gantt-presentation.mjs +217 -217
  165. package/src/todo-gantt-scope.mjs +123 -123
  166. package/src/todo-gantt-svg.mjs +353 -353
  167. package/src/todo-independence-contracts.mjs +595 -595
  168. package/src/todo-independence-guidance.mjs +322 -322
  169. package/src/todo-independence.mjs +640 -640
  170. package/src/todo-markdown-renderer.mjs +260 -260
  171. package/src/todo-migration.mjs +448 -448
  172. package/src/todo-narrative-anchor.mjs +130 -130
  173. package/src/todo-note-store.mjs +629 -625
  174. package/src/todo-parallel-candidates.mjs +114 -114
  175. package/src/todo-revision.mjs +995 -995
  176. package/src/todo-split.mjs +472 -472
  177. package/src/todo-status.mjs +690 -690
  178. package/src/todo-store-git-transaction.mjs +418 -418
  179. package/src/todo-store.mjs +4322 -4314
  180. package/src/treatment-compiler.mjs +728 -728
  181. package/src/treatment-runner.mjs +656 -656
  182. package/src/witness-scaffold.mjs +180 -180
@@ -1,895 +1,895 @@
1
- import { createHash } from 'node:crypto';
2
-
3
- const MAX_DEPTH = 32;
4
- const MAX_NODES = 10_000;
5
- const MAX_COLLECTION_ITEMS = 256;
6
- const MAX_STRING_BYTES = 16_384;
7
- const MAX_TEXT_BYTES = 4_096;
8
- const MAX_PATH_BYTES = 1_024;
9
- const MAX_CANONICAL_BYTES = 1_048_576;
10
-
11
- const SHA256 = /^[0-9a-f]{64}$/;
12
- const SHA1 = /^[0-9a-f]{40}$/;
13
- const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
14
- const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
15
-
16
- const RESOURCE_KINDS = new Set([
17
- 'symbol',
18
- 'path',
19
- 'state',
20
- 'effect',
21
- 'semantic',
22
- 'dynamic',
23
- ]);
24
- const GRAPH_OPERATIONS = new Set([
25
- 'status',
26
- 'query',
27
- 'callers',
28
- 'callees',
29
- 'impact',
30
- 'affected',
31
- ]);
32
- const GRAPH_STATUSES = new Set([
33
- 'ready',
34
- 'absent',
35
- 'symbol_absent',
36
- 'empty',
37
- 'command_failure',
38
- 'invalid_json',
39
- 'stale',
40
- 'unresolved',
41
- 'unsupported',
42
- ]);
43
- const GRAPH_STATUS_BY_OPERATION = new Map([
44
- ['status', new Set([
45
- 'ready',
46
- 'absent',
47
- 'command_failure',
48
- 'invalid_json',
49
- 'stale',
50
- 'unresolved',
51
- 'unsupported',
52
- ])],
53
- ['query', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
54
- ['callers', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
55
- ['callees', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
56
- ['impact', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
57
- ['affected', new Set(['ready', 'empty', 'unresolved'])],
58
- ]);
59
- const VERDICTS = new Set([
60
- 'parallel_ready',
61
- 'seam_candidate',
62
- 'intentional_serial',
63
- 'unknown_requires_evidence',
64
- ]);
65
- const EDGE_KINDS = new Set([
66
- 'hard_need',
67
- 'write_conflict',
68
- 'state_conflict',
69
- 'effect_conflict',
70
- 'semantic_conflict',
71
- 'dynamic_unknown',
72
- ]);
73
- const INVALIDATION_KINDS = new Set([
74
- 'old_plan',
75
- 'agent_context',
76
- 'partial_patch',
77
- 'interface_assumption',
78
- ]);
79
- const TRANSFORM_STATUSES = new Set(['accepted', 'rejected']);
80
- const VERIFICATION_STATUSES = new Set(['passed', 'failed', 'not_run']);
81
- const RECEIPT_OUTCOMES = new Set(['passed', 'failed']);
82
- const CLEANUP_STATUSES = new Set(['passed', 'failed', 'unresolved']);
83
- const SOURCE_STATUSES = new Set(['unchanged', 'changed', 'unresolved']);
84
- // **これは製品のfinding種別ではない。** RC1/RC2の変換拒否理由であり、同名の
85
- // `undeclared_write`(実行時competitionの観測)とは別空間である。研究成果物へ
86
- // 焼き込まれているので、名前を動かすと当時の記録と食い違う。
87
- const TRANSFORM_REJECTION_KINDS = new Set([
88
- 'scope_violation',
89
- 'behavior_verification_failed',
90
- 'snapshot_mutation',
91
- 'source_invariant_violation',
92
- 'cleanup_failure',
93
- 'execution_failure',
94
- ]);
95
-
96
- function invalidArtifact(reason) {
97
- throw new TypeError(`artifact契約違反: ${reason}`);
98
- }
99
-
100
- function byteLength(value) {
101
- return Buffer.byteLength(value, 'utf8');
102
- }
103
-
104
- function requireBoundedString(value, label = 'string') {
105
- if (byteLength(value) > MAX_STRING_BYTES) {
106
- invalidArtifact(`${label}が上限を超えている`);
107
- }
108
- }
109
-
110
- function inspectArray(value, state, depth) {
111
- if (Object.getPrototypeOf(value) !== Array.prototype) {
112
- invalidArtifact('array prototypeが不正');
113
- }
114
-
115
- const ownKeys = Reflect.ownKeys(value);
116
- if (ownKeys.some((key) => typeof key !== 'string')) {
117
- invalidArtifact('arrayにsymbol keyがある');
118
- }
119
- const expectedKeys = new Set([
120
- ...Array.from({ length: value.length }, (_, index) => String(index)),
121
- 'length',
122
- ]);
123
- if (ownKeys.length !== expectedKeys.size || ownKeys.some((key) => !expectedKeys.has(key))) {
124
- invalidArtifact('arrayがsparseまたはextra propertyを持つ');
125
- }
126
-
127
- const parts = [];
128
- for (let index = 0; index < value.length; index += 1) {
129
- const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
130
- if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {
131
- invalidArtifact('array itemがdata propertyではない');
132
- }
133
- parts.push(canonicalPart(descriptor.value, state, depth + 1));
134
- }
135
- return `[${parts.join(',')}]`;
136
- }
137
-
138
- function inspectObject(value, state, depth) {
139
- if (Object.getPrototypeOf(value) !== Object.prototype) {
140
- invalidArtifact('plain objectではない');
141
- }
142
-
143
- const ownKeys = Reflect.ownKeys(value);
144
- if (ownKeys.length > MAX_COLLECTION_ITEMS) {
145
- invalidArtifact('object key数が上限を超えている');
146
- }
147
- if (ownKeys.some((key) => typeof key !== 'string')) {
148
- invalidArtifact('objectにsymbol keyがある');
149
- }
150
-
151
- const entries = [];
152
- for (const key of ownKeys.sort()) {
153
- requireBoundedString(key, 'object key');
154
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
155
- if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {
156
- invalidArtifact('object propertyがenumerable data propertyではない');
157
- }
158
- entries.push(`${JSON.stringify(key)}:${canonicalPart(descriptor.value, state, depth + 1)}`);
159
- }
160
- return `{${entries.join(',')}}`;
161
- }
162
-
163
- function canonicalPart(value, state, depth) {
164
- state.nodes += 1;
165
- if (state.nodes > MAX_NODES) {
166
- invalidArtifact('node数が上限を超えている');
167
- }
168
- if (depth > MAX_DEPTH) {
169
- invalidArtifact('nestingが上限を超えている');
170
- }
171
-
172
- if (value === null) return 'null';
173
- if (typeof value === 'boolean') return value ? 'true' : 'false';
174
- if (typeof value === 'string') {
175
- requireBoundedString(value);
176
- return JSON.stringify(value);
177
- }
178
- if (typeof value === 'number') {
179
- if (!Number.isFinite(value) || Object.is(value, -0)) {
180
- invalidArtifact('numberがfiniteでないかnegative zero');
181
- }
182
- return JSON.stringify(value);
183
- }
184
- if (typeof value !== 'object') {
185
- invalidArtifact('JSON valueではない');
186
- }
187
- if (state.seen.has(value)) {
188
- invalidArtifact('循環参照がある');
189
- }
190
-
191
- state.seen.add(value);
192
- try {
193
- return Array.isArray(value)
194
- ? inspectArray(value, state, depth)
195
- : inspectObject(value, state, depth);
196
- } finally {
197
- state.seen.delete(value);
198
- }
199
- }
200
-
201
- /**
202
- * JSON互換payloadをobject keyの辞書順でUTF-8 canonical JSONへ変換する。
203
- * @param {unknown} value
204
- * @returns {string}
205
- */
206
- export function canonicalizeArtifact(value) {
207
- const canonical = canonicalPart(value, { nodes: 0, seen: new Set() }, 0);
208
- if (byteLength(canonical) > MAX_CANONICAL_BYTES) {
209
- invalidArtifact('canonical byte列が上限を超えている');
210
- }
211
- return canonical;
212
- }
213
-
214
- /**
215
- * canonical payload byte列のSHA-256をlowercase hexで返す。
216
- * @param {unknown} value
217
- * @returns {string}
218
- */
219
- export function digestArtifact(value) {
220
- return createHash('sha256')
221
- .update(Buffer.from(canonicalizeArtifact(value), 'utf8'))
222
- .digest('hex');
223
- }
224
-
225
- function exactRecord(value, keys) {
226
- if (value === null || typeof value !== 'object' || Array.isArray(value)
227
- || Object.getPrototypeOf(value) !== Object.prototype) {
228
- return false;
229
- }
230
- const actual = Object.keys(value).sort();
231
- const expected = [...keys].sort();
232
- return actual.length === expected.length
233
- && actual.every((key, index) => key === expected[index]);
234
- }
235
-
236
- function boundedText(value, maxBytes = MAX_TEXT_BYTES) {
237
- return typeof value === 'string'
238
- && value.length > 0
239
- && value === value.trim()
240
- && !CONTROL_CHARACTER.test(value)
241
- && byteLength(value) <= maxBytes;
242
- }
243
-
244
- function identifier(value) {
245
- return typeof value === 'string' && IDENTIFIER.test(value);
246
- }
247
-
248
- function digest(value) {
249
- return typeof value === 'string' && SHA256.test(value);
250
- }
251
-
252
- function nonNegativeInteger(value) {
253
- return Number.isSafeInteger(value) && value >= 0;
254
- }
255
-
256
- function positiveInteger(value) {
257
- return Number.isSafeInteger(value) && value >= 1;
258
- }
259
-
260
- function repoPath(value, { allowDot = false } = {}) {
261
- if (allowDot && value === '.') return true;
262
- if (!boundedText(value, MAX_PATH_BYTES)
263
- || value.startsWith('/')
264
- || value.endsWith('/')
265
- || value.includes('\\')
266
- || /^[A-Za-z]:/.test(value)) {
267
- return false;
268
- }
269
- const segments = value.split('/');
270
- return segments.length > 0
271
- && segments.every((segment) => segment !== '' && segment !== '.' && segment !== '..');
272
- }
273
-
274
- function boundedArray(value, validator, { min = 0, max = MAX_COLLECTION_ITEMS } = {}) {
275
- return Array.isArray(value)
276
- && value.length >= min
277
- && value.length <= max
278
- && value.every((entry) => validator(entry));
279
- }
280
-
281
- function uniqueStrings(value, validator = boundedText, options = {}) {
282
- return boundedArray(value, validator, options) && new Set(value).size === value.length;
283
- }
284
-
285
- function disjoint(...arrays) {
286
- const seen = new Set();
287
- for (const array of arrays) {
288
- for (const value of array) {
289
- if (seen.has(value)) return false;
290
- seen.add(value);
291
- }
292
- }
293
- return true;
294
- }
295
-
296
- function resource(value, allowedKinds = RESOURCE_KINDS) {
297
- return exactRecord(value, ['kind', 'target'])
298
- && allowedKinds.has(value.kind)
299
- && (value.kind === 'path' ? repoPath(value.target) : boundedText(value.target, 512));
300
- }
301
-
302
- function resources(value, { min = 0, allowedKinds = RESOURCE_KINDS } = {}) {
303
- return boundedArray(value, (entry) => resource(entry, allowedKinds), { min })
304
- && new Set(value.map((entry) => `${entry.kind}\u0000${entry.target}`)).size === value.length;
305
- }
306
-
307
- function resourceKey(value) {
308
- return `${value.kind}\u0000${value.target}`;
309
- }
310
-
311
- function validateSafely(value, validator) {
312
- try {
313
- canonicalizeArtifact(value);
314
- return validator(value) === true;
315
- } catch {
316
- return false;
317
- }
318
- }
319
-
320
- function planTodo(value) {
321
- return exactRecord(value, ['id', 'outcome', 'concern', 'anchor'])
322
- && identifier(value.id)
323
- && boundedText(value.outcome)
324
- && identifier(value.concern)
325
- && exactRecord(value.anchor, ['symbol', 'path'])
326
- && boundedText(value.anchor.symbol, 512)
327
- && repoPath(value.anchor.path);
328
- }
329
-
330
- /** @param {unknown} value @returns {boolean} */
331
- export function validatePlanInput(value) {
332
- return validateSafely(value, (input) => {
333
- if (!exactRecord(input, [
334
- 'schema',
335
- 'project',
336
- 'plan_version',
337
- 'capacity',
338
- 'todos',
339
- 'manual_evidence_ref',
340
- 'query_set_ref',
341
- ]) || input.schema !== 'lattice.plan_input.v1') {
342
- return false;
343
- }
344
- if (!exactRecord(input.project, ['root', 'fixture_entry'])
345
- || !repoPath(input.project.root, { allowDot: true })
346
- || !repoPath(input.project.fixture_entry)) {
347
- return false;
348
- }
349
- if (!identifier(input.plan_version)
350
- || !exactRecord(input.capacity, ['writers'])
351
- || !positiveInteger(input.capacity.writers)
352
- || input.capacity.writers > 64
353
- || !boundedArray(input.todos, planTodo, { min: 1 })) {
354
- return false;
355
- }
356
- const todoIds = input.todos.map((todo) => todo.id);
357
- return new Set(todoIds).size === todoIds.length
358
- && repoPath(input.manual_evidence_ref)
359
- && repoPath(input.query_set_ref);
360
- });
361
- }
362
-
363
- function graphEvidence(value) {
364
- return exactRecord(value, ['id', 'operation', 'status', 'result_digest'])
365
- && identifier(value.id)
366
- && GRAPH_OPERATIONS.has(value.operation)
367
- && GRAPH_STATUSES.has(value.status)
368
- && GRAPH_STATUS_BY_OPERATION.get(value.operation).has(value.status)
369
- && digest(value.result_digest);
370
- }
371
-
372
- function manualEvidence(value) {
373
- return exactRecord(value, ['id', 'todo_id', 'result_digest'])
374
- && identifier(value.id)
375
- && identifier(value.todo_id)
376
- && digest(value.result_digest);
377
- }
378
-
379
- function manifestTodo(value) {
380
- const ownedKinds = new Set(['symbol', 'path']);
381
- return exactRecord(value, [
382
- 'id',
383
- 'owns',
384
- 'reads',
385
- 'writes',
386
- 'hard_needs',
387
- 'conflict_ids',
388
- 'unknowns',
389
- 'tests',
390
- 'evidence_refs',
391
- ])
392
- && identifier(value.id)
393
- && resources(value.owns, { min: 1, allowedKinds: ownedKinds })
394
- && resources(value.reads)
395
- && resources(value.writes, { min: 1 })
396
- && uniqueStrings(value.hard_needs, identifier)
397
- && uniqueStrings(value.conflict_ids, identifier)
398
- && uniqueStrings(value.unknowns)
399
- && uniqueStrings(value.tests, (entry) => repoPath(entry), { min: 1 })
400
- && uniqueStrings(value.evidence_refs, identifier, { min: 1 });
401
- }
402
-
403
- function manifestConflict(value) {
404
- return exactRecord(value, ['id', 'kind', 'todo_ids', 'resource', 'evidence_refs'])
405
- && identifier(value.id)
406
- && new Set([
407
- 'write_boundary',
408
- 'state',
409
- 'effect',
410
- 'semantic',
411
- 'dynamic_unknown',
412
- ]).has(value.kind)
413
- && uniqueStrings(value.todo_ids, identifier, { min: 2, max: 2 })
414
- && resource(value.resource)
415
- && uniqueStrings(value.evidence_refs, identifier, { min: 1 });
416
- }
417
-
418
- /** @param {unknown} value @returns {boolean} */
419
- export function validateBoundaryManifest(value) {
420
- return validateSafely(value, (manifest) => {
421
- if (!exactRecord(manifest, [
422
- 'schema',
423
- 'plan_input_digest',
424
- 'source',
425
- 'graph_evidence',
426
- 'manual_evidence',
427
- 'todos',
428
- 'conflicts',
429
- 'unknowns',
430
- ]) || manifest.schema !== 'lattice.boundary_manifest.v1'
431
- || !digest(manifest.plan_input_digest)) {
432
- return false;
433
- }
434
- if (!exactRecord(manifest.source, [
435
- 'code_snapshot_digest',
436
- 'query_set_digest',
437
- 'manual_evidence_digest',
438
- 'sensor_version',
439
- ])
440
- || !digest(manifest.source.code_snapshot_digest)
441
- || !digest(manifest.source.query_set_digest)
442
- || !digest(manifest.source.manual_evidence_digest)
443
- || !boundedText(manifest.source.sensor_version, 128)) {
444
- return false;
445
- }
446
- if (!boundedArray(manifest.graph_evidence, graphEvidence, { min: 1 })
447
- || !boundedArray(manifest.manual_evidence, manualEvidence, { min: 1 })
448
- || !boundedArray(manifest.todos, manifestTodo, { min: 1 })
449
- || !boundedArray(manifest.conflicts, manifestConflict)
450
- || !uniqueStrings(manifest.unknowns)) {
451
- return false;
452
- }
453
-
454
- const graphEvidenceIds = new Set(manifest.graph_evidence.map((entry) => entry.id));
455
- const manualEvidenceIds = new Set(manifest.manual_evidence.map((entry) => entry.id));
456
- const evidenceIds = new Set([...graphEvidenceIds, ...manualEvidenceIds]);
457
- const todoIds = new Set(manifest.todos.map((todo) => todo.id));
458
- const conflictIds = new Set(manifest.conflicts.map((conflict) => conflict.id));
459
- const manualTodoIds = new Set(manifest.manual_evidence.map((entry) => entry.todo_id));
460
- if (graphEvidenceIds.size !== manifest.graph_evidence.length
461
- || manualEvidenceIds.size !== manifest.manual_evidence.length
462
- || evidenceIds.size !== graphEvidenceIds.size + manualEvidenceIds.size
463
- || todoIds.size !== manifest.todos.length
464
- || conflictIds.size !== manifest.conflicts.length
465
- || manualTodoIds.size !== manifest.manual_evidence.length
466
- || manualTodoIds.size !== todoIds.size
467
- || manifest.manual_evidence.some((entry) => !todoIds.has(entry.todo_id))) {
468
- return false;
469
- }
470
- const manualByTodo = new Map(manifest.manual_evidence
471
- .map((entry) => [entry.todo_id, entry.id]));
472
- for (const todo of manifest.todos) {
473
- if (todo.hard_needs.some((id) => id === todo.id || !todoIds.has(id))
474
- || todo.conflict_ids.some((id) => !conflictIds.has(id))
475
- || todo.evidence_refs.some((id) => !evidenceIds.has(id))
476
- || !todo.evidence_refs.includes(manualByTodo.get(todo.id))) {
477
- return false;
478
- }
479
- }
480
- for (const conflict of manifest.conflicts) {
481
- const conflictResource = resourceKey(conflict.resource);
482
- const requiresManualEvidence = conflict.kind === 'state'
483
- || conflict.kind === 'effect'
484
- || conflict.kind === 'dynamic_unknown';
485
- if (conflict.todo_ids.some((id) => !todoIds.has(id))
486
- || conflict.evidence_refs.some((id) => !evidenceIds.has(id))
487
- || (conflict.kind === 'write_boundary'
488
- && !conflict.evidence_refs.some((id) => graphEvidenceIds.has(id)))
489
- || (requiresManualEvidence && conflict.todo_ids
490
- .some((id) => !conflict.evidence_refs.includes(manualByTodo.get(id))))
491
- || conflict.todo_ids.some((id) => {
492
- const todo = manifest.todos.find((entry) => entry.id === id);
493
- const relevantResources = conflict.kind === 'write_boundary'
494
- ? todo.writes
495
- : [...todo.owns, ...todo.reads, ...todo.writes];
496
- return !todo.conflict_ids.includes(conflict.id)
497
- || !relevantResources.some((entry) => resourceKey(entry) === conflictResource);
498
- })) {
499
- return false;
500
- }
501
- }
502
- return true;
503
- });
504
- }
505
-
506
- function seamCandidate(value, todoIds) {
507
- const ownedKinds = new Set(['symbol', 'path']);
508
- if (!exactRecord(value, ['id', 'proposed_owns', 'preconditions'])
509
- || !identifier(value.id)
510
- || !boundedArray(value.proposed_owns, (entry) => exactRecord(entry, ['todo_id', 'resources'])
511
- && identifier(entry.todo_id)
512
- && resources(entry.resources, { min: 1, allowedKinds: ownedKinds }), { min: 1 })
513
- || !uniqueStrings(value.preconditions, boundedText, { min: 1 })) {
514
- return false;
515
- }
516
- const proposedIds = value.proposed_owns.map((entry) => entry.todo_id);
517
- const proposedResources = value.proposed_owns
518
- .flatMap((entry) => entry.resources.map(resourceKey));
519
- return new Set(proposedIds).size === proposedIds.length
520
- && proposedIds.length === todoIds.length
521
- && proposedIds.every((id) => todoIds.includes(id))
522
- && new Set(proposedResources).size === proposedResources.length;
523
- }
524
-
525
- function verdict(value) {
526
- if (!exactRecord(value, [
527
- 'id',
528
- 'todo_ids',
529
- 'verdict',
530
- 'conflict_ids',
531
- 'seam_candidate',
532
- 'reasons',
533
- 'unknowns',
534
- ])
535
- || !identifier(value.id)
536
- || !uniqueStrings(value.todo_ids, identifier, { min: 2, max: 2 })
537
- || !VERDICTS.has(value.verdict)
538
- || !uniqueStrings(value.conflict_ids, identifier)
539
- || !uniqueStrings(value.reasons, boundedText, { min: 1 })
540
- || !uniqueStrings(value.unknowns)) {
541
- return false;
542
- }
543
- if (value.verdict === 'seam_candidate') {
544
- return value.conflict_ids.length > 0 && seamCandidate(value.seam_candidate, value.todo_ids);
545
- }
546
- if (value.seam_candidate !== null) return false;
547
- if (value.verdict === 'parallel_ready') {
548
- return value.conflict_ids.length === 0 && value.unknowns.length === 0;
549
- }
550
- return value.verdict !== 'unknown_requires_evidence' || value.unknowns.length > 0;
551
- }
552
-
553
- /** @param {unknown} value @returns {boolean} */
554
- export function validateBoundaryVerdict(value) {
555
- return validateSafely(value, (artifact) => exactRecord(artifact, [
556
- 'schema',
557
- 'boundary_manifest_digest',
558
- 'verdicts',
559
- ])
560
- && artifact.schema === 'lattice.boundary_verdict.v1'
561
- && digest(artifact.boundary_manifest_digest)
562
- && boundedArray(artifact.verdicts, verdict, { min: 1 })
563
- && new Set(artifact.verdicts.map((entry) => entry.id)).size === artifact.verdicts.length);
564
- }
565
-
566
- function planNode(value) {
567
- const ownedKinds = new Set(['symbol', 'path']);
568
- return exactRecord(value, ['id', 'outcome', 'owned_boundaries'])
569
- && identifier(value.id)
570
- && boundedText(value.outcome)
571
- && resources(value.owned_boundaries, { min: 1, allowedKinds: ownedKinds });
572
- }
573
-
574
- function planEdge(value) {
575
- return exactRecord(value, ['id', 'from', 'to', 'kind', 'evidence_refs'])
576
- && identifier(value.id)
577
- && identifier(value.from)
578
- && identifier(value.to)
579
- && value.from !== value.to
580
- && EDGE_KINDS.has(value.kind)
581
- && uniqueStrings(value.evidence_refs, identifier, { min: 1 });
582
- }
583
-
584
- function planJoin(value) {
585
- return exactRecord(value, ['id', 'after', 'before'])
586
- && identifier(value.id)
587
- && uniqueStrings(value.after, identifier, { min: 1 })
588
- && identifier(value.before)
589
- && !value.after.includes(value.before);
590
- }
591
-
592
- /** @param {unknown} value @returns {boolean} */
593
- export function validatePlanGraph(value) {
594
- return validateSafely(value, (graph) => {
595
- if (!exactRecord(graph, [
596
- 'schema',
597
- 'plan_version',
598
- 'source_manifest_digest',
599
- 'capacity',
600
- 'nodes',
601
- 'edges',
602
- 'joins',
603
- 'waves',
604
- 'minimum_feasible_waves',
605
- ])
606
- || graph.schema !== 'lattice.plan_graph.v1'
607
- || !identifier(graph.plan_version)
608
- || !digest(graph.source_manifest_digest)
609
- || !exactRecord(graph.capacity, ['writers'])
610
- || !positiveInteger(graph.capacity.writers)
611
- || graph.capacity.writers > 64
612
- || !boundedArray(graph.nodes, planNode, { min: 1 })
613
- || !boundedArray(graph.edges, planEdge)
614
- || !boundedArray(graph.joins, planJoin)
615
- || !boundedArray(graph.waves, (wave) => exactRecord(wave, ['index', 'todo_ids'])
616
- && nonNegativeInteger(wave.index)
617
- && uniqueStrings(wave.todo_ids, identifier, { min: 1 }))
618
- || !positiveInteger(graph.minimum_feasible_waves)) {
619
- return false;
620
- }
621
-
622
- const nodeIds = new Set(graph.nodes.map((node) => node.id));
623
- if (nodeIds.size !== graph.nodes.length
624
- || new Set(graph.edges.map((edge) => edge.id)).size !== graph.edges.length
625
- || new Set(graph.joins.map((join) => join.id)).size !== graph.joins.length
626
- || graph.edges.some((edge) => !nodeIds.has(edge.from) || !nodeIds.has(edge.to))
627
- || graph.joins.some((join) => !nodeIds.has(join.before)
628
- || join.after.some((id) => !nodeIds.has(id)))) {
629
- return false;
630
- }
631
-
632
- const scheduled = [];
633
- const waveByTodo = new Map();
634
- for (let index = 0; index < graph.waves.length; index += 1) {
635
- const wave = graph.waves[index];
636
- if (wave.index !== index
637
- || wave.todo_ids.length > graph.capacity.writers
638
- || wave.todo_ids.some((id) => !nodeIds.has(id))) {
639
- return false;
640
- }
641
- scheduled.push(...wave.todo_ids);
642
- for (const id of wave.todo_ids) waveByTodo.set(id, index);
643
- }
644
- if (graph.minimum_feasible_waves !== graph.waves.length
645
- || scheduled.length !== graph.nodes.length
646
- || new Set(scheduled).size !== scheduled.length
647
- || graph.edges.some((edge) => waveByTodo.get(edge.from) >= waveByTodo.get(edge.to))
648
- || graph.joins.some((join) => join.after
649
- .some((id) => waveByTodo.get(id) >= waveByTodo.get(join.before)))) {
650
- return false;
651
- }
652
-
653
- const ownedByTodo = new Map(graph.nodes.map((node) => [
654
- node.id,
655
- new Set(node.owned_boundaries.map(resourceKey)),
656
- ]));
657
- for (let leftIndex = 0; leftIndex < graph.nodes.length; leftIndex += 1) {
658
- for (let rightIndex = leftIndex + 1; rightIndex < graph.nodes.length; rightIndex += 1) {
659
- const left = graph.nodes[leftIndex].id;
660
- const right = graph.nodes[rightIndex].id;
661
- const overlaps = [...ownedByTodo.get(left)].some((key) => ownedByTodo.get(right).has(key));
662
- const hasConflictEdge = graph.edges.some((edge) => edge.kind === 'write_conflict'
663
- && ((edge.from === left && edge.to === right)
664
- || (edge.from === right && edge.to === left)));
665
- if (overlaps !== hasConflictEdge) return false;
666
- }
667
- }
668
- return true;
669
- });
670
- }
671
-
672
- function planDescriptor(value) {
673
- return exactRecord(value, ['version', 'digest'])
674
- && identifier(value.version)
675
- && digest(value.digest);
676
- }
677
-
678
- function sortedPaths(value, { min = 0 } = {}) {
679
- return uniqueStrings(value, (entry) => repoPath(entry), { min })
680
- && value.every((entry, index) => index === 0 || value[index - 1] < entry);
681
- }
682
-
683
- function transformSource(value) {
684
- return exactRecord(value, [
685
- 'base_sha',
686
- 'boundary_manifest_digest',
687
- 'boundary_verdict_digest',
688
- 'control_plan_digest',
689
- 'query_set_digest',
690
- 'code_snapshot_digest',
691
- ])
692
- && typeof value.base_sha === 'string'
693
- && SHA1.test(value.base_sha)
694
- && digest(value.boundary_manifest_digest)
695
- && digest(value.boundary_verdict_digest)
696
- && digest(value.control_plan_digest)
697
- && digest(value.query_set_digest)
698
- && digest(value.code_snapshot_digest);
699
- }
700
-
701
- function verificationReceipt(value) {
702
- return exactRecord(value, [
703
- 'id',
704
- 'command',
705
- 'args',
706
- 'outcome',
707
- 'exit_code',
708
- 'stdout_digest',
709
- 'stderr_digest',
710
- ])
711
- && identifier(value.id)
712
- && boundedText(value.command, 512)
713
- && boundedArray(value.args, (entry) => boundedText(entry, 1_024))
714
- && RECEIPT_OUTCOMES.has(value.outcome)
715
- && nonNegativeInteger(value.exit_code)
716
- && digest(value.stdout_digest)
717
- && digest(value.stderr_digest);
718
- }
719
-
720
- function transformVerification(value) {
721
- if (!exactRecord(value, ['status', 'digest', 'receipts'])
722
- || !VERIFICATION_STATUSES.has(value.status)
723
- || !digest(value.digest)
724
- || !boundedArray(value.receipts, verificationReceipt)
725
- || new Set(value.receipts.map(({ id }) => id)).size !== value.receipts.length
726
- || value.digest !== digestArtifact({ status: value.status, receipts: value.receipts })) {
727
- return false;
728
- }
729
- if (value.status === 'passed') {
730
- return value.receipts.length > 0
731
- && value.receipts.every((receipt) => receipt.outcome === 'passed' && receipt.exit_code === 0);
732
- }
733
- if (value.status === 'not_run') return value.receipts.length === 0;
734
- return value.receipts.length > 0;
735
- }
736
-
737
- function outputFile(value) {
738
- return exactRecord(value, ['path', 'content_digest'])
739
- && repoPath(value.path)
740
- && digest(value.content_digest);
741
- }
742
-
743
- function transformOutput(value, changedPaths) {
744
- if (!exactRecord(value, ['snapshot_digest', 'files'])
745
- || !boundedArray(value.files, outputFile)
746
- || new Set(value.files.map(({ path }) => path)).size !== value.files.length
747
- || value.files.some((entry, index) => index > 0 && value.files[index - 1].path >= entry.path)) {
748
- return false;
749
- }
750
- if (value.files.length === 0) return value.snapshot_digest === null;
751
- return digest(value.snapshot_digest)
752
- && value.snapshot_digest === digestArtifact({ files: value.files })
753
- && value.files.length === changedPaths.length
754
- && value.files.every((entry, index) => entry.path === changedPaths[index]);
755
- }
756
-
757
- function transformRejection(value) {
758
- return exactRecord(value, ['kind', 'reasons', 'evidence_digest'])
759
- && TRANSFORM_REJECTION_KINDS.has(value.kind)
760
- && uniqueStrings(value.reasons, boundedText, { min: 1 })
761
- && digest(value.evidence_digest)
762
- && value.evidence_digest === digestArtifact({ kind: value.kind, reasons: value.reasons });
763
- }
764
-
765
- /** @param {unknown} value @returns {boolean} */
766
- export function validateTransformArtifact(value) {
767
- return validateSafely(value, (artifact) => {
768
- if (!exactRecord(artifact, [
769
- 'schema',
770
- 'candidate_id',
771
- 'status',
772
- 'source',
773
- 'scope',
774
- 'patch',
775
- 'verification',
776
- 'output',
777
- 'cleanup',
778
- 'rejection',
779
- 'unknowns',
780
- ])
781
- || artifact.schema !== 'lattice.transform_artifact.v1'
782
- || !identifier(artifact.candidate_id)
783
- || !TRANSFORM_STATUSES.has(artifact.status)
784
- || !transformSource(artifact.source)
785
- || !exactRecord(artifact.scope, ['allowed_paths', 'changed_paths'])
786
- || !sortedPaths(artifact.scope.allowed_paths, { min: 1 })
787
- || !sortedPaths(artifact.scope.changed_paths)
788
- || artifact.scope.changed_paths.some((entry) => !artifact.scope.allowed_paths.includes(entry))
789
- || !exactRecord(artifact.patch, ['digest', 'bytes'])
790
- || !((artifact.patch.digest === null && artifact.patch.bytes === 0)
791
- || (digest(artifact.patch.digest) && positiveInteger(artifact.patch.bytes)))
792
- || !transformVerification(artifact.verification)
793
- || !transformOutput(artifact.output, artifact.scope.changed_paths)
794
- || !exactRecord(artifact.cleanup, ['status', 'source_status'])
795
- || !CLEANUP_STATUSES.has(artifact.cleanup.status)
796
- || !SOURCE_STATUSES.has(artifact.cleanup.source_status)
797
- || !uniqueStrings(artifact.unknowns)) {
798
- return false;
799
- }
800
-
801
- if (artifact.status === 'accepted') {
802
- return artifact.rejection === null
803
- && artifact.scope.changed_paths.length > 0
804
- && digest(artifact.patch.digest)
805
- && positiveInteger(artifact.patch.bytes)
806
- && artifact.verification.status === 'passed'
807
- && artifact.output.files.length === artifact.scope.changed_paths.length
808
- && artifact.cleanup.status === 'passed'
809
- && artifact.cleanup.source_status === 'unchanged';
810
- }
811
- return transformRejection(artifact.rejection)
812
- && artifact.verification.status !== 'passed';
813
- });
814
- }
815
-
816
- function changeSet(value, keys) {
817
- return exactRecord(value, keys)
818
- && keys.every((key) => uniqueStrings(value[key], identifier));
819
- }
820
-
821
- function invalidatedContext(value) {
822
- return exactRecord(value, ['kind', 'ref', 'reason'])
823
- && INVALIDATION_KINDS.has(value.kind)
824
- && boundedText(value.ref, 512)
825
- && boundedText(value.reason);
826
- }
827
-
828
- function metricSet(value) {
829
- const keys = [
830
- 'write_conflicts_before',
831
- 'write_conflicts_after',
832
- 'hard_precedence_before',
833
- 'hard_precedence_after',
834
- 'minimum_feasible_waves_before',
835
- 'minimum_feasible_waves_after',
836
- ];
837
- return exactRecord(value, keys)
838
- && keys.every((key) => nonNegativeInteger(value[key]))
839
- && value.minimum_feasible_waves_before >= 1
840
- && value.minimum_feasible_waves_after >= 1;
841
- }
842
-
843
- /** @param {unknown} value @returns {boolean} */
844
- export function validatePlanDiff(value) {
845
- return validateSafely(value, (diff) => {
846
- if (!exactRecord(diff, [
847
- 'schema',
848
- 'old_plan',
849
- 'new_plan',
850
- 'transform',
851
- 'query_set_digest',
852
- 'snapshots',
853
- 'nodes',
854
- 'edges',
855
- 'invalidated_contexts',
856
- 'metrics',
857
- ])
858
- || diff.schema !== 'lattice.plan_diff.v1'
859
- || !planDescriptor(diff.old_plan)
860
- || !planDescriptor(diff.new_plan)
861
- || diff.old_plan.version === diff.new_plan.version
862
- || diff.old_plan.digest === diff.new_plan.digest
863
- || !exactRecord(diff.transform, [
864
- 'status',
865
- 'artifact_digest',
866
- 'patch_digest',
867
- 'verification_digest',
868
- 'changed_paths',
869
- ])
870
- || diff.transform.status !== 'accepted'
871
- || !digest(diff.transform.artifact_digest)
872
- || !digest(diff.transform.patch_digest)
873
- || !digest(diff.transform.verification_digest)
874
- || !uniqueStrings(diff.transform.changed_paths, (entry) => repoPath(entry), { min: 1 })
875
- || !digest(diff.query_set_digest)
876
- || !exactRecord(diff.snapshots, ['before_digest', 'after_digest'])
877
- || !digest(diff.snapshots.before_digest)
878
- || !digest(diff.snapshots.after_digest)
879
- || diff.snapshots.before_digest === diff.snapshots.after_digest
880
- || !changeSet(diff.nodes, ['added', 'removed', 'changed'])
881
- || !changeSet(diff.edges, ['added', 'removed'])
882
- || !disjoint(diff.nodes.added, diff.nodes.removed, diff.nodes.changed)
883
- || !disjoint(diff.edges.added, diff.edges.removed)
884
- || !boundedArray(diff.invalidated_contexts, invalidatedContext, { min: 1 })
885
- || new Set(diff.invalidated_contexts
886
- .map((entry) => `${entry.kind}\u0000${entry.ref}`)).size !== diff.invalidated_contexts.length
887
- || !diff.invalidated_contexts.some((entry) => entry.kind === 'old_plan'
888
- && entry.ref === diff.old_plan.version)
889
- || !metricSet(diff.metrics)) {
890
- return false;
891
- }
892
- return diff.nodes.added.length + diff.nodes.removed.length + diff.nodes.changed.length
893
- + diff.edges.added.length + diff.edges.removed.length > 0;
894
- });
895
- }
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const MAX_DEPTH = 32;
4
+ const MAX_NODES = 10_000;
5
+ const MAX_COLLECTION_ITEMS = 256;
6
+ const MAX_STRING_BYTES = 16_384;
7
+ const MAX_TEXT_BYTES = 4_096;
8
+ const MAX_PATH_BYTES = 1_024;
9
+ const MAX_CANONICAL_BYTES = 1_048_576;
10
+
11
+ const SHA256 = /^[0-9a-f]{64}$/;
12
+ const SHA1 = /^[0-9a-f]{40}$/;
13
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
14
+ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
15
+
16
+ const RESOURCE_KINDS = new Set([
17
+ 'symbol',
18
+ 'path',
19
+ 'state',
20
+ 'effect',
21
+ 'semantic',
22
+ 'dynamic',
23
+ ]);
24
+ const GRAPH_OPERATIONS = new Set([
25
+ 'status',
26
+ 'query',
27
+ 'callers',
28
+ 'callees',
29
+ 'impact',
30
+ 'affected',
31
+ ]);
32
+ const GRAPH_STATUSES = new Set([
33
+ 'ready',
34
+ 'absent',
35
+ 'symbol_absent',
36
+ 'empty',
37
+ 'command_failure',
38
+ 'invalid_json',
39
+ 'stale',
40
+ 'unresolved',
41
+ 'unsupported',
42
+ ]);
43
+ const GRAPH_STATUS_BY_OPERATION = new Map([
44
+ ['status', new Set([
45
+ 'ready',
46
+ 'absent',
47
+ 'command_failure',
48
+ 'invalid_json',
49
+ 'stale',
50
+ 'unresolved',
51
+ 'unsupported',
52
+ ])],
53
+ ['query', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
54
+ ['callers', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
55
+ ['callees', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
56
+ ['impact', new Set(['ready', 'symbol_absent', 'command_failure', 'invalid_json', 'unresolved'])],
57
+ ['affected', new Set(['ready', 'empty', 'unresolved'])],
58
+ ]);
59
+ const VERDICTS = new Set([
60
+ 'parallel_ready',
61
+ 'seam_candidate',
62
+ 'intentional_serial',
63
+ 'unknown_requires_evidence',
64
+ ]);
65
+ const EDGE_KINDS = new Set([
66
+ 'hard_need',
67
+ 'write_conflict',
68
+ 'state_conflict',
69
+ 'effect_conflict',
70
+ 'semantic_conflict',
71
+ 'dynamic_unknown',
72
+ ]);
73
+ const INVALIDATION_KINDS = new Set([
74
+ 'old_plan',
75
+ 'agent_context',
76
+ 'partial_patch',
77
+ 'interface_assumption',
78
+ ]);
79
+ const TRANSFORM_STATUSES = new Set(['accepted', 'rejected']);
80
+ const VERIFICATION_STATUSES = new Set(['passed', 'failed', 'not_run']);
81
+ const RECEIPT_OUTCOMES = new Set(['passed', 'failed']);
82
+ const CLEANUP_STATUSES = new Set(['passed', 'failed', 'unresolved']);
83
+ const SOURCE_STATUSES = new Set(['unchanged', 'changed', 'unresolved']);
84
+ // **これは製品のfinding種別ではない。** RC1/RC2の変換拒否理由であり、同名の
85
+ // `undeclared_write`(実行時competitionの観測)とは別空間である。研究成果物へ
86
+ // 焼き込まれているので、名前を動かすと当時の記録と食い違う。
87
+ const TRANSFORM_REJECTION_KINDS = new Set([
88
+ 'scope_violation',
89
+ 'behavior_verification_failed',
90
+ 'snapshot_mutation',
91
+ 'source_invariant_violation',
92
+ 'cleanup_failure',
93
+ 'execution_failure',
94
+ ]);
95
+
96
+ function invalidArtifact(reason) {
97
+ throw new TypeError(`artifact契約違反: ${reason}`);
98
+ }
99
+
100
+ function byteLength(value) {
101
+ return Buffer.byteLength(value, 'utf8');
102
+ }
103
+
104
+ function requireBoundedString(value, label = 'string') {
105
+ if (byteLength(value) > MAX_STRING_BYTES) {
106
+ invalidArtifact(`${label}が上限を超えている`);
107
+ }
108
+ }
109
+
110
+ function inspectArray(value, state, depth) {
111
+ if (Object.getPrototypeOf(value) !== Array.prototype) {
112
+ invalidArtifact('array prototypeが不正');
113
+ }
114
+
115
+ const ownKeys = Reflect.ownKeys(value);
116
+ if (ownKeys.some((key) => typeof key !== 'string')) {
117
+ invalidArtifact('arrayにsymbol keyがある');
118
+ }
119
+ const expectedKeys = new Set([
120
+ ...Array.from({ length: value.length }, (_, index) => String(index)),
121
+ 'length',
122
+ ]);
123
+ if (ownKeys.length !== expectedKeys.size || ownKeys.some((key) => !expectedKeys.has(key))) {
124
+ invalidArtifact('arrayがsparseまたはextra propertyを持つ');
125
+ }
126
+
127
+ const parts = [];
128
+ for (let index = 0; index < value.length; index += 1) {
129
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
130
+ if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {
131
+ invalidArtifact('array itemがdata propertyではない');
132
+ }
133
+ parts.push(canonicalPart(descriptor.value, state, depth + 1));
134
+ }
135
+ return `[${parts.join(',')}]`;
136
+ }
137
+
138
+ function inspectObject(value, state, depth) {
139
+ if (Object.getPrototypeOf(value) !== Object.prototype) {
140
+ invalidArtifact('plain objectではない');
141
+ }
142
+
143
+ const ownKeys = Reflect.ownKeys(value);
144
+ if (ownKeys.length > MAX_COLLECTION_ITEMS) {
145
+ invalidArtifact('object key数が上限を超えている');
146
+ }
147
+ if (ownKeys.some((key) => typeof key !== 'string')) {
148
+ invalidArtifact('objectにsymbol keyがある');
149
+ }
150
+
151
+ const entries = [];
152
+ for (const key of ownKeys.sort()) {
153
+ requireBoundedString(key, 'object key');
154
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
155
+ if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {
156
+ invalidArtifact('object propertyがenumerable data propertyではない');
157
+ }
158
+ entries.push(`${JSON.stringify(key)}:${canonicalPart(descriptor.value, state, depth + 1)}`);
159
+ }
160
+ return `{${entries.join(',')}}`;
161
+ }
162
+
163
+ function canonicalPart(value, state, depth) {
164
+ state.nodes += 1;
165
+ if (state.nodes > MAX_NODES) {
166
+ invalidArtifact('node数が上限を超えている');
167
+ }
168
+ if (depth > MAX_DEPTH) {
169
+ invalidArtifact('nestingが上限を超えている');
170
+ }
171
+
172
+ if (value === null) return 'null';
173
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
174
+ if (typeof value === 'string') {
175
+ requireBoundedString(value);
176
+ return JSON.stringify(value);
177
+ }
178
+ if (typeof value === 'number') {
179
+ if (!Number.isFinite(value) || Object.is(value, -0)) {
180
+ invalidArtifact('numberがfiniteでないかnegative zero');
181
+ }
182
+ return JSON.stringify(value);
183
+ }
184
+ if (typeof value !== 'object') {
185
+ invalidArtifact('JSON valueではない');
186
+ }
187
+ if (state.seen.has(value)) {
188
+ invalidArtifact('循環参照がある');
189
+ }
190
+
191
+ state.seen.add(value);
192
+ try {
193
+ return Array.isArray(value)
194
+ ? inspectArray(value, state, depth)
195
+ : inspectObject(value, state, depth);
196
+ } finally {
197
+ state.seen.delete(value);
198
+ }
199
+ }
200
+
201
+ /**
202
+ * JSON互換payloadをobject keyの辞書順でUTF-8 canonical JSONへ変換する。
203
+ * @param {unknown} value
204
+ * @returns {string}
205
+ */
206
+ export function canonicalizeArtifact(value) {
207
+ const canonical = canonicalPart(value, { nodes: 0, seen: new Set() }, 0);
208
+ if (byteLength(canonical) > MAX_CANONICAL_BYTES) {
209
+ invalidArtifact('canonical byte列が上限を超えている');
210
+ }
211
+ return canonical;
212
+ }
213
+
214
+ /**
215
+ * canonical payload byte列のSHA-256をlowercase hexで返す。
216
+ * @param {unknown} value
217
+ * @returns {string}
218
+ */
219
+ export function digestArtifact(value) {
220
+ return createHash('sha256')
221
+ .update(Buffer.from(canonicalizeArtifact(value), 'utf8'))
222
+ .digest('hex');
223
+ }
224
+
225
+ function exactRecord(value, keys) {
226
+ if (value === null || typeof value !== 'object' || Array.isArray(value)
227
+ || Object.getPrototypeOf(value) !== Object.prototype) {
228
+ return false;
229
+ }
230
+ const actual = Object.keys(value).sort();
231
+ const expected = [...keys].sort();
232
+ return actual.length === expected.length
233
+ && actual.every((key, index) => key === expected[index]);
234
+ }
235
+
236
+ function boundedText(value, maxBytes = MAX_TEXT_BYTES) {
237
+ return typeof value === 'string'
238
+ && value.length > 0
239
+ && value === value.trim()
240
+ && !CONTROL_CHARACTER.test(value)
241
+ && byteLength(value) <= maxBytes;
242
+ }
243
+
244
+ function identifier(value) {
245
+ return typeof value === 'string' && IDENTIFIER.test(value);
246
+ }
247
+
248
+ function digest(value) {
249
+ return typeof value === 'string' && SHA256.test(value);
250
+ }
251
+
252
+ function nonNegativeInteger(value) {
253
+ return Number.isSafeInteger(value) && value >= 0;
254
+ }
255
+
256
+ function positiveInteger(value) {
257
+ return Number.isSafeInteger(value) && value >= 1;
258
+ }
259
+
260
+ function repoPath(value, { allowDot = false } = {}) {
261
+ if (allowDot && value === '.') return true;
262
+ if (!boundedText(value, MAX_PATH_BYTES)
263
+ || value.startsWith('/')
264
+ || value.endsWith('/')
265
+ || value.includes('\\')
266
+ || /^[A-Za-z]:/.test(value)) {
267
+ return false;
268
+ }
269
+ const segments = value.split('/');
270
+ return segments.length > 0
271
+ && segments.every((segment) => segment !== '' && segment !== '.' && segment !== '..');
272
+ }
273
+
274
+ function boundedArray(value, validator, { min = 0, max = MAX_COLLECTION_ITEMS } = {}) {
275
+ return Array.isArray(value)
276
+ && value.length >= min
277
+ && value.length <= max
278
+ && value.every((entry) => validator(entry));
279
+ }
280
+
281
+ function uniqueStrings(value, validator = boundedText, options = {}) {
282
+ return boundedArray(value, validator, options) && new Set(value).size === value.length;
283
+ }
284
+
285
+ function disjoint(...arrays) {
286
+ const seen = new Set();
287
+ for (const array of arrays) {
288
+ for (const value of array) {
289
+ if (seen.has(value)) return false;
290
+ seen.add(value);
291
+ }
292
+ }
293
+ return true;
294
+ }
295
+
296
+ function resource(value, allowedKinds = RESOURCE_KINDS) {
297
+ return exactRecord(value, ['kind', 'target'])
298
+ && allowedKinds.has(value.kind)
299
+ && (value.kind === 'path' ? repoPath(value.target) : boundedText(value.target, 512));
300
+ }
301
+
302
+ function resources(value, { min = 0, allowedKinds = RESOURCE_KINDS } = {}) {
303
+ return boundedArray(value, (entry) => resource(entry, allowedKinds), { min })
304
+ && new Set(value.map((entry) => `${entry.kind}\u0000${entry.target}`)).size === value.length;
305
+ }
306
+
307
+ function resourceKey(value) {
308
+ return `${value.kind}\u0000${value.target}`;
309
+ }
310
+
311
+ function validateSafely(value, validator) {
312
+ try {
313
+ canonicalizeArtifact(value);
314
+ return validator(value) === true;
315
+ } catch {
316
+ return false;
317
+ }
318
+ }
319
+
320
+ function planTodo(value) {
321
+ return exactRecord(value, ['id', 'outcome', 'concern', 'anchor'])
322
+ && identifier(value.id)
323
+ && boundedText(value.outcome)
324
+ && identifier(value.concern)
325
+ && exactRecord(value.anchor, ['symbol', 'path'])
326
+ && boundedText(value.anchor.symbol, 512)
327
+ && repoPath(value.anchor.path);
328
+ }
329
+
330
+ /** @param {unknown} value @returns {boolean} */
331
+ export function validatePlanInput(value) {
332
+ return validateSafely(value, (input) => {
333
+ if (!exactRecord(input, [
334
+ 'schema',
335
+ 'project',
336
+ 'plan_version',
337
+ 'capacity',
338
+ 'todos',
339
+ 'manual_evidence_ref',
340
+ 'query_set_ref',
341
+ ]) || input.schema !== 'lattice.plan_input.v1') {
342
+ return false;
343
+ }
344
+ if (!exactRecord(input.project, ['root', 'fixture_entry'])
345
+ || !repoPath(input.project.root, { allowDot: true })
346
+ || !repoPath(input.project.fixture_entry)) {
347
+ return false;
348
+ }
349
+ if (!identifier(input.plan_version)
350
+ || !exactRecord(input.capacity, ['writers'])
351
+ || !positiveInteger(input.capacity.writers)
352
+ || input.capacity.writers > 64
353
+ || !boundedArray(input.todos, planTodo, { min: 1 })) {
354
+ return false;
355
+ }
356
+ const todoIds = input.todos.map((todo) => todo.id);
357
+ return new Set(todoIds).size === todoIds.length
358
+ && repoPath(input.manual_evidence_ref)
359
+ && repoPath(input.query_set_ref);
360
+ });
361
+ }
362
+
363
+ function graphEvidence(value) {
364
+ return exactRecord(value, ['id', 'operation', 'status', 'result_digest'])
365
+ && identifier(value.id)
366
+ && GRAPH_OPERATIONS.has(value.operation)
367
+ && GRAPH_STATUSES.has(value.status)
368
+ && GRAPH_STATUS_BY_OPERATION.get(value.operation).has(value.status)
369
+ && digest(value.result_digest);
370
+ }
371
+
372
+ function manualEvidence(value) {
373
+ return exactRecord(value, ['id', 'todo_id', 'result_digest'])
374
+ && identifier(value.id)
375
+ && identifier(value.todo_id)
376
+ && digest(value.result_digest);
377
+ }
378
+
379
+ function manifestTodo(value) {
380
+ const ownedKinds = new Set(['symbol', 'path']);
381
+ return exactRecord(value, [
382
+ 'id',
383
+ 'owns',
384
+ 'reads',
385
+ 'writes',
386
+ 'hard_needs',
387
+ 'conflict_ids',
388
+ 'unknowns',
389
+ 'tests',
390
+ 'evidence_refs',
391
+ ])
392
+ && identifier(value.id)
393
+ && resources(value.owns, { min: 1, allowedKinds: ownedKinds })
394
+ && resources(value.reads)
395
+ && resources(value.writes, { min: 1 })
396
+ && uniqueStrings(value.hard_needs, identifier)
397
+ && uniqueStrings(value.conflict_ids, identifier)
398
+ && uniqueStrings(value.unknowns)
399
+ && uniqueStrings(value.tests, (entry) => repoPath(entry), { min: 1 })
400
+ && uniqueStrings(value.evidence_refs, identifier, { min: 1 });
401
+ }
402
+
403
+ function manifestConflict(value) {
404
+ return exactRecord(value, ['id', 'kind', 'todo_ids', 'resource', 'evidence_refs'])
405
+ && identifier(value.id)
406
+ && new Set([
407
+ 'write_boundary',
408
+ 'state',
409
+ 'effect',
410
+ 'semantic',
411
+ 'dynamic_unknown',
412
+ ]).has(value.kind)
413
+ && uniqueStrings(value.todo_ids, identifier, { min: 2, max: 2 })
414
+ && resource(value.resource)
415
+ && uniqueStrings(value.evidence_refs, identifier, { min: 1 });
416
+ }
417
+
418
+ /** @param {unknown} value @returns {boolean} */
419
+ export function validateBoundaryManifest(value) {
420
+ return validateSafely(value, (manifest) => {
421
+ if (!exactRecord(manifest, [
422
+ 'schema',
423
+ 'plan_input_digest',
424
+ 'source',
425
+ 'graph_evidence',
426
+ 'manual_evidence',
427
+ 'todos',
428
+ 'conflicts',
429
+ 'unknowns',
430
+ ]) || manifest.schema !== 'lattice.boundary_manifest.v1'
431
+ || !digest(manifest.plan_input_digest)) {
432
+ return false;
433
+ }
434
+ if (!exactRecord(manifest.source, [
435
+ 'code_snapshot_digest',
436
+ 'query_set_digest',
437
+ 'manual_evidence_digest',
438
+ 'sensor_version',
439
+ ])
440
+ || !digest(manifest.source.code_snapshot_digest)
441
+ || !digest(manifest.source.query_set_digest)
442
+ || !digest(manifest.source.manual_evidence_digest)
443
+ || !boundedText(manifest.source.sensor_version, 128)) {
444
+ return false;
445
+ }
446
+ if (!boundedArray(manifest.graph_evidence, graphEvidence, { min: 1 })
447
+ || !boundedArray(manifest.manual_evidence, manualEvidence, { min: 1 })
448
+ || !boundedArray(manifest.todos, manifestTodo, { min: 1 })
449
+ || !boundedArray(manifest.conflicts, manifestConflict)
450
+ || !uniqueStrings(manifest.unknowns)) {
451
+ return false;
452
+ }
453
+
454
+ const graphEvidenceIds = new Set(manifest.graph_evidence.map((entry) => entry.id));
455
+ const manualEvidenceIds = new Set(manifest.manual_evidence.map((entry) => entry.id));
456
+ const evidenceIds = new Set([...graphEvidenceIds, ...manualEvidenceIds]);
457
+ const todoIds = new Set(manifest.todos.map((todo) => todo.id));
458
+ const conflictIds = new Set(manifest.conflicts.map((conflict) => conflict.id));
459
+ const manualTodoIds = new Set(manifest.manual_evidence.map((entry) => entry.todo_id));
460
+ if (graphEvidenceIds.size !== manifest.graph_evidence.length
461
+ || manualEvidenceIds.size !== manifest.manual_evidence.length
462
+ || evidenceIds.size !== graphEvidenceIds.size + manualEvidenceIds.size
463
+ || todoIds.size !== manifest.todos.length
464
+ || conflictIds.size !== manifest.conflicts.length
465
+ || manualTodoIds.size !== manifest.manual_evidence.length
466
+ || manualTodoIds.size !== todoIds.size
467
+ || manifest.manual_evidence.some((entry) => !todoIds.has(entry.todo_id))) {
468
+ return false;
469
+ }
470
+ const manualByTodo = new Map(manifest.manual_evidence
471
+ .map((entry) => [entry.todo_id, entry.id]));
472
+ for (const todo of manifest.todos) {
473
+ if (todo.hard_needs.some((id) => id === todo.id || !todoIds.has(id))
474
+ || todo.conflict_ids.some((id) => !conflictIds.has(id))
475
+ || todo.evidence_refs.some((id) => !evidenceIds.has(id))
476
+ || !todo.evidence_refs.includes(manualByTodo.get(todo.id))) {
477
+ return false;
478
+ }
479
+ }
480
+ for (const conflict of manifest.conflicts) {
481
+ const conflictResource = resourceKey(conflict.resource);
482
+ const requiresManualEvidence = conflict.kind === 'state'
483
+ || conflict.kind === 'effect'
484
+ || conflict.kind === 'dynamic_unknown';
485
+ if (conflict.todo_ids.some((id) => !todoIds.has(id))
486
+ || conflict.evidence_refs.some((id) => !evidenceIds.has(id))
487
+ || (conflict.kind === 'write_boundary'
488
+ && !conflict.evidence_refs.some((id) => graphEvidenceIds.has(id)))
489
+ || (requiresManualEvidence && conflict.todo_ids
490
+ .some((id) => !conflict.evidence_refs.includes(manualByTodo.get(id))))
491
+ || conflict.todo_ids.some((id) => {
492
+ const todo = manifest.todos.find((entry) => entry.id === id);
493
+ const relevantResources = conflict.kind === 'write_boundary'
494
+ ? todo.writes
495
+ : [...todo.owns, ...todo.reads, ...todo.writes];
496
+ return !todo.conflict_ids.includes(conflict.id)
497
+ || !relevantResources.some((entry) => resourceKey(entry) === conflictResource);
498
+ })) {
499
+ return false;
500
+ }
501
+ }
502
+ return true;
503
+ });
504
+ }
505
+
506
+ function seamCandidate(value, todoIds) {
507
+ const ownedKinds = new Set(['symbol', 'path']);
508
+ if (!exactRecord(value, ['id', 'proposed_owns', 'preconditions'])
509
+ || !identifier(value.id)
510
+ || !boundedArray(value.proposed_owns, (entry) => exactRecord(entry, ['todo_id', 'resources'])
511
+ && identifier(entry.todo_id)
512
+ && resources(entry.resources, { min: 1, allowedKinds: ownedKinds }), { min: 1 })
513
+ || !uniqueStrings(value.preconditions, boundedText, { min: 1 })) {
514
+ return false;
515
+ }
516
+ const proposedIds = value.proposed_owns.map((entry) => entry.todo_id);
517
+ const proposedResources = value.proposed_owns
518
+ .flatMap((entry) => entry.resources.map(resourceKey));
519
+ return new Set(proposedIds).size === proposedIds.length
520
+ && proposedIds.length === todoIds.length
521
+ && proposedIds.every((id) => todoIds.includes(id))
522
+ && new Set(proposedResources).size === proposedResources.length;
523
+ }
524
+
525
+ function verdict(value) {
526
+ if (!exactRecord(value, [
527
+ 'id',
528
+ 'todo_ids',
529
+ 'verdict',
530
+ 'conflict_ids',
531
+ 'seam_candidate',
532
+ 'reasons',
533
+ 'unknowns',
534
+ ])
535
+ || !identifier(value.id)
536
+ || !uniqueStrings(value.todo_ids, identifier, { min: 2, max: 2 })
537
+ || !VERDICTS.has(value.verdict)
538
+ || !uniqueStrings(value.conflict_ids, identifier)
539
+ || !uniqueStrings(value.reasons, boundedText, { min: 1 })
540
+ || !uniqueStrings(value.unknowns)) {
541
+ return false;
542
+ }
543
+ if (value.verdict === 'seam_candidate') {
544
+ return value.conflict_ids.length > 0 && seamCandidate(value.seam_candidate, value.todo_ids);
545
+ }
546
+ if (value.seam_candidate !== null) return false;
547
+ if (value.verdict === 'parallel_ready') {
548
+ return value.conflict_ids.length === 0 && value.unknowns.length === 0;
549
+ }
550
+ return value.verdict !== 'unknown_requires_evidence' || value.unknowns.length > 0;
551
+ }
552
+
553
+ /** @param {unknown} value @returns {boolean} */
554
+ export function validateBoundaryVerdict(value) {
555
+ return validateSafely(value, (artifact) => exactRecord(artifact, [
556
+ 'schema',
557
+ 'boundary_manifest_digest',
558
+ 'verdicts',
559
+ ])
560
+ && artifact.schema === 'lattice.boundary_verdict.v1'
561
+ && digest(artifact.boundary_manifest_digest)
562
+ && boundedArray(artifact.verdicts, verdict, { min: 1 })
563
+ && new Set(artifact.verdicts.map((entry) => entry.id)).size === artifact.verdicts.length);
564
+ }
565
+
566
+ function planNode(value) {
567
+ const ownedKinds = new Set(['symbol', 'path']);
568
+ return exactRecord(value, ['id', 'outcome', 'owned_boundaries'])
569
+ && identifier(value.id)
570
+ && boundedText(value.outcome)
571
+ && resources(value.owned_boundaries, { min: 1, allowedKinds: ownedKinds });
572
+ }
573
+
574
+ function planEdge(value) {
575
+ return exactRecord(value, ['id', 'from', 'to', 'kind', 'evidence_refs'])
576
+ && identifier(value.id)
577
+ && identifier(value.from)
578
+ && identifier(value.to)
579
+ && value.from !== value.to
580
+ && EDGE_KINDS.has(value.kind)
581
+ && uniqueStrings(value.evidence_refs, identifier, { min: 1 });
582
+ }
583
+
584
+ function planJoin(value) {
585
+ return exactRecord(value, ['id', 'after', 'before'])
586
+ && identifier(value.id)
587
+ && uniqueStrings(value.after, identifier, { min: 1 })
588
+ && identifier(value.before)
589
+ && !value.after.includes(value.before);
590
+ }
591
+
592
+ /** @param {unknown} value @returns {boolean} */
593
+ export function validatePlanGraph(value) {
594
+ return validateSafely(value, (graph) => {
595
+ if (!exactRecord(graph, [
596
+ 'schema',
597
+ 'plan_version',
598
+ 'source_manifest_digest',
599
+ 'capacity',
600
+ 'nodes',
601
+ 'edges',
602
+ 'joins',
603
+ 'waves',
604
+ 'minimum_feasible_waves',
605
+ ])
606
+ || graph.schema !== 'lattice.plan_graph.v1'
607
+ || !identifier(graph.plan_version)
608
+ || !digest(graph.source_manifest_digest)
609
+ || !exactRecord(graph.capacity, ['writers'])
610
+ || !positiveInteger(graph.capacity.writers)
611
+ || graph.capacity.writers > 64
612
+ || !boundedArray(graph.nodes, planNode, { min: 1 })
613
+ || !boundedArray(graph.edges, planEdge)
614
+ || !boundedArray(graph.joins, planJoin)
615
+ || !boundedArray(graph.waves, (wave) => exactRecord(wave, ['index', 'todo_ids'])
616
+ && nonNegativeInteger(wave.index)
617
+ && uniqueStrings(wave.todo_ids, identifier, { min: 1 }))
618
+ || !positiveInteger(graph.minimum_feasible_waves)) {
619
+ return false;
620
+ }
621
+
622
+ const nodeIds = new Set(graph.nodes.map((node) => node.id));
623
+ if (nodeIds.size !== graph.nodes.length
624
+ || new Set(graph.edges.map((edge) => edge.id)).size !== graph.edges.length
625
+ || new Set(graph.joins.map((join) => join.id)).size !== graph.joins.length
626
+ || graph.edges.some((edge) => !nodeIds.has(edge.from) || !nodeIds.has(edge.to))
627
+ || graph.joins.some((join) => !nodeIds.has(join.before)
628
+ || join.after.some((id) => !nodeIds.has(id)))) {
629
+ return false;
630
+ }
631
+
632
+ const scheduled = [];
633
+ const waveByTodo = new Map();
634
+ for (let index = 0; index < graph.waves.length; index += 1) {
635
+ const wave = graph.waves[index];
636
+ if (wave.index !== index
637
+ || wave.todo_ids.length > graph.capacity.writers
638
+ || wave.todo_ids.some((id) => !nodeIds.has(id))) {
639
+ return false;
640
+ }
641
+ scheduled.push(...wave.todo_ids);
642
+ for (const id of wave.todo_ids) waveByTodo.set(id, index);
643
+ }
644
+ if (graph.minimum_feasible_waves !== graph.waves.length
645
+ || scheduled.length !== graph.nodes.length
646
+ || new Set(scheduled).size !== scheduled.length
647
+ || graph.edges.some((edge) => waveByTodo.get(edge.from) >= waveByTodo.get(edge.to))
648
+ || graph.joins.some((join) => join.after
649
+ .some((id) => waveByTodo.get(id) >= waveByTodo.get(join.before)))) {
650
+ return false;
651
+ }
652
+
653
+ const ownedByTodo = new Map(graph.nodes.map((node) => [
654
+ node.id,
655
+ new Set(node.owned_boundaries.map(resourceKey)),
656
+ ]));
657
+ for (let leftIndex = 0; leftIndex < graph.nodes.length; leftIndex += 1) {
658
+ for (let rightIndex = leftIndex + 1; rightIndex < graph.nodes.length; rightIndex += 1) {
659
+ const left = graph.nodes[leftIndex].id;
660
+ const right = graph.nodes[rightIndex].id;
661
+ const overlaps = [...ownedByTodo.get(left)].some((key) => ownedByTodo.get(right).has(key));
662
+ const hasConflictEdge = graph.edges.some((edge) => edge.kind === 'write_conflict'
663
+ && ((edge.from === left && edge.to === right)
664
+ || (edge.from === right && edge.to === left)));
665
+ if (overlaps !== hasConflictEdge) return false;
666
+ }
667
+ }
668
+ return true;
669
+ });
670
+ }
671
+
672
+ function planDescriptor(value) {
673
+ return exactRecord(value, ['version', 'digest'])
674
+ && identifier(value.version)
675
+ && digest(value.digest);
676
+ }
677
+
678
+ function sortedPaths(value, { min = 0 } = {}) {
679
+ return uniqueStrings(value, (entry) => repoPath(entry), { min })
680
+ && value.every((entry, index) => index === 0 || value[index - 1] < entry);
681
+ }
682
+
683
+ function transformSource(value) {
684
+ return exactRecord(value, [
685
+ 'base_sha',
686
+ 'boundary_manifest_digest',
687
+ 'boundary_verdict_digest',
688
+ 'control_plan_digest',
689
+ 'query_set_digest',
690
+ 'code_snapshot_digest',
691
+ ])
692
+ && typeof value.base_sha === 'string'
693
+ && SHA1.test(value.base_sha)
694
+ && digest(value.boundary_manifest_digest)
695
+ && digest(value.boundary_verdict_digest)
696
+ && digest(value.control_plan_digest)
697
+ && digest(value.query_set_digest)
698
+ && digest(value.code_snapshot_digest);
699
+ }
700
+
701
+ function verificationReceipt(value) {
702
+ return exactRecord(value, [
703
+ 'id',
704
+ 'command',
705
+ 'args',
706
+ 'outcome',
707
+ 'exit_code',
708
+ 'stdout_digest',
709
+ 'stderr_digest',
710
+ ])
711
+ && identifier(value.id)
712
+ && boundedText(value.command, 512)
713
+ && boundedArray(value.args, (entry) => boundedText(entry, 1_024))
714
+ && RECEIPT_OUTCOMES.has(value.outcome)
715
+ && nonNegativeInteger(value.exit_code)
716
+ && digest(value.stdout_digest)
717
+ && digest(value.stderr_digest);
718
+ }
719
+
720
+ function transformVerification(value) {
721
+ if (!exactRecord(value, ['status', 'digest', 'receipts'])
722
+ || !VERIFICATION_STATUSES.has(value.status)
723
+ || !digest(value.digest)
724
+ || !boundedArray(value.receipts, verificationReceipt)
725
+ || new Set(value.receipts.map(({ id }) => id)).size !== value.receipts.length
726
+ || value.digest !== digestArtifact({ status: value.status, receipts: value.receipts })) {
727
+ return false;
728
+ }
729
+ if (value.status === 'passed') {
730
+ return value.receipts.length > 0
731
+ && value.receipts.every((receipt) => receipt.outcome === 'passed' && receipt.exit_code === 0);
732
+ }
733
+ if (value.status === 'not_run') return value.receipts.length === 0;
734
+ return value.receipts.length > 0;
735
+ }
736
+
737
+ function outputFile(value) {
738
+ return exactRecord(value, ['path', 'content_digest'])
739
+ && repoPath(value.path)
740
+ && digest(value.content_digest);
741
+ }
742
+
743
+ function transformOutput(value, changedPaths) {
744
+ if (!exactRecord(value, ['snapshot_digest', 'files'])
745
+ || !boundedArray(value.files, outputFile)
746
+ || new Set(value.files.map(({ path }) => path)).size !== value.files.length
747
+ || value.files.some((entry, index) => index > 0 && value.files[index - 1].path >= entry.path)) {
748
+ return false;
749
+ }
750
+ if (value.files.length === 0) return value.snapshot_digest === null;
751
+ return digest(value.snapshot_digest)
752
+ && value.snapshot_digest === digestArtifact({ files: value.files })
753
+ && value.files.length === changedPaths.length
754
+ && value.files.every((entry, index) => entry.path === changedPaths[index]);
755
+ }
756
+
757
+ function transformRejection(value) {
758
+ return exactRecord(value, ['kind', 'reasons', 'evidence_digest'])
759
+ && TRANSFORM_REJECTION_KINDS.has(value.kind)
760
+ && uniqueStrings(value.reasons, boundedText, { min: 1 })
761
+ && digest(value.evidence_digest)
762
+ && value.evidence_digest === digestArtifact({ kind: value.kind, reasons: value.reasons });
763
+ }
764
+
765
+ /** @param {unknown} value @returns {boolean} */
766
+ export function validateTransformArtifact(value) {
767
+ return validateSafely(value, (artifact) => {
768
+ if (!exactRecord(artifact, [
769
+ 'schema',
770
+ 'candidate_id',
771
+ 'status',
772
+ 'source',
773
+ 'scope',
774
+ 'patch',
775
+ 'verification',
776
+ 'output',
777
+ 'cleanup',
778
+ 'rejection',
779
+ 'unknowns',
780
+ ])
781
+ || artifact.schema !== 'lattice.transform_artifact.v1'
782
+ || !identifier(artifact.candidate_id)
783
+ || !TRANSFORM_STATUSES.has(artifact.status)
784
+ || !transformSource(artifact.source)
785
+ || !exactRecord(artifact.scope, ['allowed_paths', 'changed_paths'])
786
+ || !sortedPaths(artifact.scope.allowed_paths, { min: 1 })
787
+ || !sortedPaths(artifact.scope.changed_paths)
788
+ || artifact.scope.changed_paths.some((entry) => !artifact.scope.allowed_paths.includes(entry))
789
+ || !exactRecord(artifact.patch, ['digest', 'bytes'])
790
+ || !((artifact.patch.digest === null && artifact.patch.bytes === 0)
791
+ || (digest(artifact.patch.digest) && positiveInteger(artifact.patch.bytes)))
792
+ || !transformVerification(artifact.verification)
793
+ || !transformOutput(artifact.output, artifact.scope.changed_paths)
794
+ || !exactRecord(artifact.cleanup, ['status', 'source_status'])
795
+ || !CLEANUP_STATUSES.has(artifact.cleanup.status)
796
+ || !SOURCE_STATUSES.has(artifact.cleanup.source_status)
797
+ || !uniqueStrings(artifact.unknowns)) {
798
+ return false;
799
+ }
800
+
801
+ if (artifact.status === 'accepted') {
802
+ return artifact.rejection === null
803
+ && artifact.scope.changed_paths.length > 0
804
+ && digest(artifact.patch.digest)
805
+ && positiveInteger(artifact.patch.bytes)
806
+ && artifact.verification.status === 'passed'
807
+ && artifact.output.files.length === artifact.scope.changed_paths.length
808
+ && artifact.cleanup.status === 'passed'
809
+ && artifact.cleanup.source_status === 'unchanged';
810
+ }
811
+ return transformRejection(artifact.rejection)
812
+ && artifact.verification.status !== 'passed';
813
+ });
814
+ }
815
+
816
+ function changeSet(value, keys) {
817
+ return exactRecord(value, keys)
818
+ && keys.every((key) => uniqueStrings(value[key], identifier));
819
+ }
820
+
821
+ function invalidatedContext(value) {
822
+ return exactRecord(value, ['kind', 'ref', 'reason'])
823
+ && INVALIDATION_KINDS.has(value.kind)
824
+ && boundedText(value.ref, 512)
825
+ && boundedText(value.reason);
826
+ }
827
+
828
+ function metricSet(value) {
829
+ const keys = [
830
+ 'write_conflicts_before',
831
+ 'write_conflicts_after',
832
+ 'hard_precedence_before',
833
+ 'hard_precedence_after',
834
+ 'minimum_feasible_waves_before',
835
+ 'minimum_feasible_waves_after',
836
+ ];
837
+ return exactRecord(value, keys)
838
+ && keys.every((key) => nonNegativeInteger(value[key]))
839
+ && value.minimum_feasible_waves_before >= 1
840
+ && value.minimum_feasible_waves_after >= 1;
841
+ }
842
+
843
+ /** @param {unknown} value @returns {boolean} */
844
+ export function validatePlanDiff(value) {
845
+ return validateSafely(value, (diff) => {
846
+ if (!exactRecord(diff, [
847
+ 'schema',
848
+ 'old_plan',
849
+ 'new_plan',
850
+ 'transform',
851
+ 'query_set_digest',
852
+ 'snapshots',
853
+ 'nodes',
854
+ 'edges',
855
+ 'invalidated_contexts',
856
+ 'metrics',
857
+ ])
858
+ || diff.schema !== 'lattice.plan_diff.v1'
859
+ || !planDescriptor(diff.old_plan)
860
+ || !planDescriptor(diff.new_plan)
861
+ || diff.old_plan.version === diff.new_plan.version
862
+ || diff.old_plan.digest === diff.new_plan.digest
863
+ || !exactRecord(diff.transform, [
864
+ 'status',
865
+ 'artifact_digest',
866
+ 'patch_digest',
867
+ 'verification_digest',
868
+ 'changed_paths',
869
+ ])
870
+ || diff.transform.status !== 'accepted'
871
+ || !digest(diff.transform.artifact_digest)
872
+ || !digest(diff.transform.patch_digest)
873
+ || !digest(diff.transform.verification_digest)
874
+ || !uniqueStrings(diff.transform.changed_paths, (entry) => repoPath(entry), { min: 1 })
875
+ || !digest(diff.query_set_digest)
876
+ || !exactRecord(diff.snapshots, ['before_digest', 'after_digest'])
877
+ || !digest(diff.snapshots.before_digest)
878
+ || !digest(diff.snapshots.after_digest)
879
+ || diff.snapshots.before_digest === diff.snapshots.after_digest
880
+ || !changeSet(diff.nodes, ['added', 'removed', 'changed'])
881
+ || !changeSet(diff.edges, ['added', 'removed'])
882
+ || !disjoint(diff.nodes.added, diff.nodes.removed, diff.nodes.changed)
883
+ || !disjoint(diff.edges.added, diff.edges.removed)
884
+ || !boundedArray(diff.invalidated_contexts, invalidatedContext, { min: 1 })
885
+ || new Set(diff.invalidated_contexts
886
+ .map((entry) => `${entry.kind}\u0000${entry.ref}`)).size !== diff.invalidated_contexts.length
887
+ || !diff.invalidated_contexts.some((entry) => entry.kind === 'old_plan'
888
+ && entry.ref === diff.old_plan.version)
889
+ || !metricSet(diff.metrics)) {
890
+ return false;
891
+ }
892
+ return diff.nodes.added.length + diff.nodes.removed.length + diff.nodes.changed.length
893
+ + diff.edges.added.length + diff.edges.removed.length > 0;
894
+ });
895
+ }