@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,173 +1,173 @@
1
- /**
2
- * 実行時競合を、実際の変換で解消する処置へ変える(請求項8・ADR 0137〜0139)。
3
- *
4
- * 実行時の入力は観測である。どのpathでどの2 taskがぶつかったかは`detectCheckpointFindings`が
5
- * 実際に変更された資源から返すので、ここで影響範囲を探し直さない。
6
- *
7
- * 変換の導出はbase状態に対して行う。holdされたTODOは再計画で旧contextを失効させられ、
8
- * 新plan_ref由来のpacketで再開するため、進行中の編集は設計上そこで捨てられる。
9
- * `head_sha`が効くのは止めずに継続するcarry-over側であり、held側ではない。
10
- */
11
-
12
- import { createHash } from 'node:crypto';
13
-
14
- import { canonicalizeArtifact } from './artifact-contracts.mjs';
15
- import { selfDigest } from './runtime-contracts.mjs';
16
- import { seamConflictFromFinding } from './seam-apply.mjs';
17
-
18
- const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
19
- const sha16 = (value) => createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
20
-
21
- /** 資源idはidentifier規律なのでpathをそのまま使えない。boundary compilerと同じ合成形にする。 */
22
- export function pathResourceId(target) {
23
- return `own-path-${sha16(target)}`;
24
- }
25
-
26
- function sealed(value, field) {
27
- const record = { ...value, [field]: '' };
28
- record[field] = selfDigest(record, field);
29
- return record;
30
- }
31
-
32
- function canonicalSort(entries) {
33
- return [...entries].sort((left, right) => compareText(
34
- canonicalizeArtifact(left), canonicalizeArtifact(right),
35
- ));
36
- }
37
-
38
- /**
39
- * 採用された変換から、再計画が読む`lattice.runtime_seam_split.v1`を組む。
40
- *
41
- * 所有の差分は「係争資源の所有を降りて、自分の新資源を所有する」である。競合辺は消える——
42
- * それが変換の目的であり、消えていなければ五条件のoverlap_reducedが通っていない。
43
- */
44
- export function buildRuntimeSeamSplit({
45
- conflict, candidate, taskMigrationDigest, verifierRefs = [],
46
- } = {}) {
47
- const owned = (candidate?.surfaces ?? []).filter(({ role }) => role === 'task_owned');
48
- if (owned.length < 2) return { split: null, reasons: ['owned_surfaces_below_two'] };
49
- const sourceResource = pathResourceId(conflict.sourcePath);
50
-
51
- const removed = canonicalSort(conflict.taskIds.map((taskId) => ({
52
- resource_id: sourceResource, owner_todo_id: taskId, access_kind: 'own',
53
- })));
54
- const added = canonicalSort(owned.map((surface) => ({
55
- resource_id: pathResourceId(surface.path),
56
- owner_todo_id: surface.owner_task_ids[0],
57
- access_kind: 'own',
58
- })));
59
-
60
- // 競合辺は消える側だけを載せる。変換で新しい競合を作っていないことは
61
- // 五条件のoverlap_reduced(plan全体の競合対が増えない)が既に見ている。
62
- const removedEdges = [];
63
- for (let left = 0; left < conflict.taskIds.length; left += 1) {
64
- for (let right = left + 1; right < conflict.taskIds.length; right += 1) {
65
- const pair = [conflict.taskIds[left], conflict.taskIds[right]].sort(compareText);
66
- removedEdges.push({ from_todo_id: pair[0], to_todo_id: pair[1], kind: 'conflict' });
67
- }
68
- }
69
-
70
- const split = sealed({
71
- schema: 'lattice.runtime_seam_split.v1',
72
- finding_digest: conflict.findingDigest,
73
- predecessor_task_ids: [...conflict.taskIds].sort(compareText),
74
- task_migration_digest: taskMigrationDigest,
75
- ownership_diff: sealed({
76
- schema: 'lattice.runtime_ownership_diff.v1', added, removed, diff_digest: '',
77
- }, 'diff_digest'),
78
- edge_diff: sealed({
79
- schema: 'lattice.runtime_edge_diff.v1',
80
- added: [], removed: canonicalSort(removedEdges), diff_digest: '',
81
- }, 'diff_digest'),
82
- verifier_refs: [...new Set(verifierRefs)].sort(compareText),
83
- split_digest: '',
84
- }, 'split_digest');
85
- return { split, reasons: [] };
86
- }
87
-
88
- /**
89
- * 実行時競合の処置を決める。
90
- *
91
- * 事前宣言された処置があればそれを使う。無ければ**その場で変換候補を導出して適用を試みる**——
92
- * ここが請求項8の一手で、従来は事前宣言が無い競合をすべて意図的直列へ倒していた。
93
- *
94
- * 変換は五条件を通ったときだけ処置になる。1つでも欠けたら意図的直列へ送り、欠けた条件を残す。
95
- * 「実行時だから緩める」ことをしない——緩めると、外部挙動を変えうる変更が便益の証明なしに
96
- * 実行中のrunへ入る。
97
- */
98
- export async function resolveRuntimeSeamTreatment(options = {}) {
99
- const {
100
- finding, witnessSet, pathNames = {}, predeclaredTreatments = [],
101
- applyConflict, commitTransform, baseSha, manifestDigest, affectedTests = [],
102
- taskMigrationDigest, recordedFindingDigest = null,
103
- } = options;
104
-
105
- if (finding?.kind === 'observed_write_conflict' && typeof finding.path === 'string') {
106
- for (const treatment of predeclaredTreatments) {
107
- if (Array.isArray(treatment.covered_paths) && treatment.covered_paths.includes(finding.path)) {
108
- return { lane: 'seam_transform', treatment: structuredClone(treatment), split: null, reasons: [] };
109
- }
110
- }
111
- }
112
-
113
- const { conflict, reasons } = seamConflictFromFinding({
114
- finding, witnessSet, pathNames, affectedTests, baseSha, manifestDigest,
115
- recordedFindingDigest,
116
- });
117
- if (conflict === null) {
118
- return { lane: 'intentional_serial', treatment: null, split: null, reasons };
119
- }
120
- if (typeof applyConflict !== 'function') {
121
- return {
122
- lane: 'intentional_serial', treatment: null, split: null, reasons: ['applier_absent'],
123
- };
124
- }
125
-
126
- const applied = await applyConflict({ conflict });
127
- if (applied?.outcome?.decision === 'accepted' && typeof commitTransform !== 'function') {
128
- // 確定する手段が無いまま採用すると、splitは所有を宣言するのに再開先へその成果が無い。
129
- // 「変換した」と言いながら再開できない状態を作らない(ADR 0141)。
130
- return {
131
- lane: 'intentional_serial', treatment: null, split: null, reasons: ['committer_absent'],
132
- };
133
- }
134
- if (applied?.outcome?.decision !== 'accepted') {
135
- return {
136
- lane: 'intentional_serial',
137
- treatment: null,
138
- split: null,
139
- reasons: [...(applied?.outcome?.reasons ?? ['transform_rejected'])],
140
- };
141
- }
142
-
143
- const built = buildRuntimeSeamSplit({
144
- conflict,
145
- candidate: applied.candidate ?? { surfaces: applied.outcome.surfaces ?? [] },
146
- taskMigrationDigest,
147
- verifierRefs: affectedTests,
148
- });
149
- if (built.split === null) {
150
- return { lane: 'intentional_serial', treatment: null, split: null, reasons: built.reasons };
151
- }
152
- // 再開先が実在するbaseを要る。branchを動かさずcommitとして確定し、そのshaを後継planへ渡す。
153
- const committed = await commitTransform({
154
- conflict, files: applied.files ?? {}, candidateId: conflict.candidateId,
155
- });
156
- if (!/^[0-9a-f]{40}$/u.test(committed?.commitSha ?? '')) {
157
- return {
158
- lane: 'intentional_serial', treatment: null, split: null, reasons: ['transform_not_committed'],
159
- };
160
- }
161
- return {
162
- lane: 'seam_transform',
163
- treatment: {
164
- covered_paths: [conflict.sourcePath],
165
- candidate_digest: applied.outcome.candidate_digest,
166
- },
167
- split: built.split,
168
- files: applied.files ?? null,
169
- successor_base_sha: committed.commitSha,
170
- successor_base_ref: committed.ref ?? null,
171
- reasons: [],
172
- };
173
- }
1
+ /**
2
+ * 実行時競合を、実際の変換で解消する処置へ変える(請求項8・ADR 0137〜0139)。
3
+ *
4
+ * 実行時の入力は観測である。どのpathでどの2 taskがぶつかったかは`detectCheckpointFindings`が
5
+ * 実際に変更された資源から返すので、ここで影響範囲を探し直さない。
6
+ *
7
+ * 変換の導出はbase状態に対して行う。holdされたTODOは再計画で旧contextを失効させられ、
8
+ * 新plan_ref由来のpacketで再開するため、進行中の編集は設計上そこで捨てられる。
9
+ * `head_sha`が効くのは止めずに継続するcarry-over側であり、held側ではない。
10
+ */
11
+
12
+ import { createHash } from 'node:crypto';
13
+
14
+ import { canonicalizeArtifact } from './artifact-contracts.mjs';
15
+ import { selfDigest } from './runtime-contracts.mjs';
16
+ import { seamConflictFromFinding } from './seam-apply.mjs';
17
+
18
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
19
+ const sha16 = (value) => createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
20
+
21
+ /** 資源idはidentifier規律なのでpathをそのまま使えない。boundary compilerと同じ合成形にする。 */
22
+ export function pathResourceId(target) {
23
+ return `own-path-${sha16(target)}`;
24
+ }
25
+
26
+ function sealed(value, field) {
27
+ const record = { ...value, [field]: '' };
28
+ record[field] = selfDigest(record, field);
29
+ return record;
30
+ }
31
+
32
+ function canonicalSort(entries) {
33
+ return [...entries].sort((left, right) => compareText(
34
+ canonicalizeArtifact(left), canonicalizeArtifact(right),
35
+ ));
36
+ }
37
+
38
+ /**
39
+ * 採用された変換から、再計画が読む`lattice.runtime_seam_split.v1`を組む。
40
+ *
41
+ * 所有の差分は「係争資源の所有を降りて、自分の新資源を所有する」である。競合辺は消える——
42
+ * それが変換の目的であり、消えていなければ五条件のoverlap_reducedが通っていない。
43
+ */
44
+ export function buildRuntimeSeamSplit({
45
+ conflict, candidate, taskMigrationDigest, verifierRefs = [],
46
+ } = {}) {
47
+ const owned = (candidate?.surfaces ?? []).filter(({ role }) => role === 'task_owned');
48
+ if (owned.length < 2) return { split: null, reasons: ['owned_surfaces_below_two'] };
49
+ const sourceResource = pathResourceId(conflict.sourcePath);
50
+
51
+ const removed = canonicalSort(conflict.taskIds.map((taskId) => ({
52
+ resource_id: sourceResource, owner_todo_id: taskId, access_kind: 'own',
53
+ })));
54
+ const added = canonicalSort(owned.map((surface) => ({
55
+ resource_id: pathResourceId(surface.path),
56
+ owner_todo_id: surface.owner_task_ids[0],
57
+ access_kind: 'own',
58
+ })));
59
+
60
+ // 競合辺は消える側だけを載せる。変換で新しい競合を作っていないことは
61
+ // 五条件のoverlap_reduced(plan全体の競合対が増えない)が既に見ている。
62
+ const removedEdges = [];
63
+ for (let left = 0; left < conflict.taskIds.length; left += 1) {
64
+ for (let right = left + 1; right < conflict.taskIds.length; right += 1) {
65
+ const pair = [conflict.taskIds[left], conflict.taskIds[right]].sort(compareText);
66
+ removedEdges.push({ from_todo_id: pair[0], to_todo_id: pair[1], kind: 'conflict' });
67
+ }
68
+ }
69
+
70
+ const split = sealed({
71
+ schema: 'lattice.runtime_seam_split.v1',
72
+ finding_digest: conflict.findingDigest,
73
+ predecessor_task_ids: [...conflict.taskIds].sort(compareText),
74
+ task_migration_digest: taskMigrationDigest,
75
+ ownership_diff: sealed({
76
+ schema: 'lattice.runtime_ownership_diff.v1', added, removed, diff_digest: '',
77
+ }, 'diff_digest'),
78
+ edge_diff: sealed({
79
+ schema: 'lattice.runtime_edge_diff.v1',
80
+ added: [], removed: canonicalSort(removedEdges), diff_digest: '',
81
+ }, 'diff_digest'),
82
+ verifier_refs: [...new Set(verifierRefs)].sort(compareText),
83
+ split_digest: '',
84
+ }, 'split_digest');
85
+ return { split, reasons: [] };
86
+ }
87
+
88
+ /**
89
+ * 実行時競合の処置を決める。
90
+ *
91
+ * 事前宣言された処置があればそれを使う。無ければ**その場で変換候補を導出して適用を試みる**——
92
+ * ここが請求項8の一手で、従来は事前宣言が無い競合をすべて意図的直列へ倒していた。
93
+ *
94
+ * 変換は五条件を通ったときだけ処置になる。1つでも欠けたら意図的直列へ送り、欠けた条件を残す。
95
+ * 「実行時だから緩める」ことをしない——緩めると、外部挙動を変えうる変更が便益の証明なしに
96
+ * 実行中のrunへ入る。
97
+ */
98
+ export async function resolveRuntimeSeamTreatment(options = {}) {
99
+ const {
100
+ finding, witnessSet, pathNames = {}, predeclaredTreatments = [],
101
+ applyConflict, commitTransform, baseSha, manifestDigest, affectedTests = [],
102
+ taskMigrationDigest, recordedFindingDigest = null,
103
+ } = options;
104
+
105
+ if (finding?.kind === 'observed_write_conflict' && typeof finding.path === 'string') {
106
+ for (const treatment of predeclaredTreatments) {
107
+ if (Array.isArray(treatment.covered_paths) && treatment.covered_paths.includes(finding.path)) {
108
+ return { lane: 'seam_transform', treatment: structuredClone(treatment), split: null, reasons: [] };
109
+ }
110
+ }
111
+ }
112
+
113
+ const { conflict, reasons } = seamConflictFromFinding({
114
+ finding, witnessSet, pathNames, affectedTests, baseSha, manifestDigest,
115
+ recordedFindingDigest,
116
+ });
117
+ if (conflict === null) {
118
+ return { lane: 'intentional_serial', treatment: null, split: null, reasons };
119
+ }
120
+ if (typeof applyConflict !== 'function') {
121
+ return {
122
+ lane: 'intentional_serial', treatment: null, split: null, reasons: ['applier_absent'],
123
+ };
124
+ }
125
+
126
+ const applied = await applyConflict({ conflict });
127
+ if (applied?.outcome?.decision === 'accepted' && typeof commitTransform !== 'function') {
128
+ // 確定する手段が無いまま採用すると、splitは所有を宣言するのに再開先へその成果が無い。
129
+ // 「変換した」と言いながら再開できない状態を作らない(ADR 0141)。
130
+ return {
131
+ lane: 'intentional_serial', treatment: null, split: null, reasons: ['committer_absent'],
132
+ };
133
+ }
134
+ if (applied?.outcome?.decision !== 'accepted') {
135
+ return {
136
+ lane: 'intentional_serial',
137
+ treatment: null,
138
+ split: null,
139
+ reasons: [...(applied?.outcome?.reasons ?? ['transform_rejected'])],
140
+ };
141
+ }
142
+
143
+ const built = buildRuntimeSeamSplit({
144
+ conflict,
145
+ candidate: applied.candidate ?? { surfaces: applied.outcome.surfaces ?? [] },
146
+ taskMigrationDigest,
147
+ verifierRefs: affectedTests,
148
+ });
149
+ if (built.split === null) {
150
+ return { lane: 'intentional_serial', treatment: null, split: null, reasons: built.reasons };
151
+ }
152
+ // 再開先が実在するbaseを要る。branchを動かさずcommitとして確定し、そのshaを後継planへ渡す。
153
+ const committed = await commitTransform({
154
+ conflict, files: applied.files ?? {}, candidateId: conflict.candidateId,
155
+ });
156
+ if (!/^[0-9a-f]{40}$/u.test(committed?.commitSha ?? '')) {
157
+ return {
158
+ lane: 'intentional_serial', treatment: null, split: null, reasons: ['transform_not_committed'],
159
+ };
160
+ }
161
+ return {
162
+ lane: 'seam_transform',
163
+ treatment: {
164
+ covered_paths: [conflict.sourcePath],
165
+ candidate_digest: applied.outcome.candidate_digest,
166
+ },
167
+ split: built.split,
168
+ files: applied.files ?? null,
169
+ successor_base_sha: committed.commitSha,
170
+ successor_base_ref: committed.ref ?? null,
171
+ reasons: [],
172
+ };
173
+ }
@@ -1,125 +1,125 @@
1
- /**
2
- * unix domain socketの所有関係をOS非依存に観測する。
3
- *
4
- * 管理runtimeは「そのPIDが本当にそのcontrol socketを持っているか」を確かめてから接続する。
5
- * この検査は成りすましたsocketへ繋がないための要であり、緩めない。
6
- *
7
- * 実装は`/usr/sbin/lsof`をhard-codeしていた。**これはmacOS専用のpathで、Linuxでは管理runtime
8
- * が丸ごと動かなかった**(CIで実測:実daemonを起動するtestが軒並み`socket owner観測失敗`で
9
- * 落ちていた)。移植性の欠陥であってtestの都合ではない。
10
- *
11
- * Linuxには`/proc`という一次情報があるので、外部commandを介さずに同じことが分かる。
12
- * `/proc/<pid>/fd/*`のsymlinkが`socket:[inode]`を指し、`/proc/net/unix`がinodeとpathを結ぶ。
13
- * lsofを持たない最小構成のcontainerでも動くので、Linuxでは`/proc`を優先する。
14
- *
15
- * どちらの手段でも観測できない環境では、**観測できたことにしない**。呼び出し側がfail closed
16
- * するために、例外を投げるか空を返す(「所有していない」ではなく「分からない」を返さない設計に
17
- * するため、判定は必ず呼び出し側の`some(...)`で行う)。
18
- */
19
-
20
- import { execFile } from 'node:child_process';
21
- import { readdir, readFile, readlink } from 'node:fs/promises';
22
- import { promisify } from 'node:util';
23
-
24
- const execFileAsync = promisify(execFile);
25
-
26
- /** lsofの絶対path候補。PATHは引かない——探索経路を広げるとsocket検査の前提が緩む。 */
27
- const LSOF_PATHS = Object.freeze(['/usr/sbin/lsof', '/usr/bin/lsof', '/bin/lsof']);
28
-
29
- const SOCKET_INODE = /^socket:\[(\d+)\]$/u;
30
-
31
- async function runLsof(args) {
32
- let lastError = new Error('lsof not found');
33
- for (const binary of LSOF_PATHS) {
34
- try {
35
- const { stdout } = await execFileAsync(binary, args, { encoding: 'utf8' });
36
- return stdout;
37
- } catch (error) {
38
- // ENOENTは「その場所に無い」だけなので次の候補へ。
39
- if (error?.code === 'ENOENT') { lastError = error; continue; }
40
- // lsofは該当が無いとexit 1を返す。これは観測の失敗ではなく「所有者なし」である。
41
- // ここを潰すと、誰も掴んでいないstale socketが観測失敗として扱われ、正常な後片付けが
42
- // 止まる(元の呼び出し側も同じ区別をしていた)。
43
- if (error?.code === 1 && String(error?.stdout ?? '').trim() === '') return '';
44
- throw error;
45
- }
46
- }
47
- throw lastError;
48
- }
49
-
50
- /** `/proc/<pid>/fd`からunix socketのinodeを集める。Linux専用。 */
51
- async function procSocketInodes(pid) {
52
- const entries = await readdir(`/proc/${pid}/fd`);
53
- const inodes = new Set();
54
- for (const entry of entries) {
55
- let target;
56
- try { target = await readlink(`/proc/${pid}/fd/${entry}`); } catch { continue; }
57
- const matched = SOCKET_INODE.exec(target);
58
- if (matched !== null) inodes.add(matched[1]);
59
- }
60
- return inodes;
61
- }
62
-
63
- /** `/proc/net/unix`を読み、inode -> pathの対応を返す。 */
64
- async function procUnixSocketPaths() {
65
- const text = await readFile('/proc/net/unix', 'utf8');
66
- const byInode = new Map();
67
- for (const line of text.split('\n').slice(1)) {
68
- // Num RefCount Protocol Flags Type St Inode Path
69
- const fields = line.trim().split(/\s+/u);
70
- if (fields.length < 8) continue;
71
- const inode = fields[6];
72
- const socketPath = fields.slice(7).join(' ');
73
- if (socketPath.length === 0) continue;
74
- if (!byInode.has(inode)) byInode.set(inode, []);
75
- byInode.get(inode).push(socketPath);
76
- }
77
- return byInode;
78
- }
79
-
80
- /**
81
- * 指定PIDが開いているunix socketのpath一覧を返す。
82
- *
83
- * @returns {Promise<string[]>} 観測できたpath。観測手段が無ければthrowする。
84
- */
85
- export async function socketPathsOwnedByPid(pid) {
86
- if (process.platform === 'linux') {
87
- const inodes = await procSocketInodes(pid);
88
- if (inodes.size === 0) return [];
89
- const byInode = await procUnixSocketPaths();
90
- return [...inodes].flatMap((inode) => byInode.get(inode) ?? []);
91
- }
92
- const stdout = await runLsof(['-a', '-p', String(pid), '-U', '-F', 'fn']);
93
- return stdout.split('\n')
94
- .filter((line) => line.startsWith('n'))
95
- .map((line) => line.slice(1));
96
- }
97
-
98
- /**
99
- * 指定socket pathを開いているPID一覧を返す。
100
- *
101
- * @returns {Promise<number[]>} 観測できたPID。観測手段が無ければthrowする。
102
- */
103
- export async function pidsOwningSocketPath(socketPath) {
104
- if (process.platform === 'linux') {
105
- const byInode = await procUnixSocketPaths();
106
- const wanted = new Set();
107
- for (const [inode, paths] of byInode) {
108
- if (paths.includes(socketPath)) wanted.add(inode);
109
- }
110
- if (wanted.size === 0) return [];
111
- const pids = new Set();
112
- for (const entry of await readdir('/proc')) {
113
- if (!/^\d+$/u.test(entry)) continue;
114
- let inodes;
115
- // 他ユーザーのprocessは読めない。読めないものを「所有していない」へ丸めるが、
116
- // これはlsofが権限不足で黙るのと同じ性質であり、判定は所有を**肯定**する側でのみ使う。
117
- try { inodes = await procSocketInodes(entry); } catch { continue; }
118
- if ([...wanted].some((inode) => inodes.has(inode))) pids.add(Number(entry));
119
- }
120
- return [...pids];
121
- }
122
- const stdout = await runLsof(['-t', socketPath]);
123
- return stdout.split('\n').map((line) => line.trim())
124
- .filter((line) => /^\d+$/u.test(line)).map(Number);
125
- }
1
+ /**
2
+ * unix domain socketの所有関係をOS非依存に観測する。
3
+ *
4
+ * 管理runtimeは「そのPIDが本当にそのcontrol socketを持っているか」を確かめてから接続する。
5
+ * この検査は成りすましたsocketへ繋がないための要であり、緩めない。
6
+ *
7
+ * 実装は`/usr/sbin/lsof`をhard-codeしていた。**これはmacOS専用のpathで、Linuxでは管理runtime
8
+ * が丸ごと動かなかった**(CIで実測:実daemonを起動するtestが軒並み`socket owner観測失敗`で
9
+ * 落ちていた)。移植性の欠陥であってtestの都合ではない。
10
+ *
11
+ * Linuxには`/proc`という一次情報があるので、外部commandを介さずに同じことが分かる。
12
+ * `/proc/<pid>/fd/*`のsymlinkが`socket:[inode]`を指し、`/proc/net/unix`がinodeとpathを結ぶ。
13
+ * lsofを持たない最小構成のcontainerでも動くので、Linuxでは`/proc`を優先する。
14
+ *
15
+ * どちらの手段でも観測できない環境では、**観測できたことにしない**。呼び出し側がfail closed
16
+ * するために、例外を投げるか空を返す(「所有していない」ではなく「分からない」を返さない設計に
17
+ * するため、判定は必ず呼び出し側の`some(...)`で行う)。
18
+ */
19
+
20
+ import { execFile } from 'node:child_process';
21
+ import { readdir, readFile, readlink } from 'node:fs/promises';
22
+ import { promisify } from 'node:util';
23
+
24
+ const execFileAsync = promisify(execFile);
25
+
26
+ /** lsofの絶対path候補。PATHは引かない——探索経路を広げるとsocket検査の前提が緩む。 */
27
+ const LSOF_PATHS = Object.freeze(['/usr/sbin/lsof', '/usr/bin/lsof', '/bin/lsof']);
28
+
29
+ const SOCKET_INODE = /^socket:\[(\d+)\]$/u;
30
+
31
+ async function runLsof(args) {
32
+ let lastError = new Error('lsof not found');
33
+ for (const binary of LSOF_PATHS) {
34
+ try {
35
+ const { stdout } = await execFileAsync(binary, args, { encoding: 'utf8' });
36
+ return stdout;
37
+ } catch (error) {
38
+ // ENOENTは「その場所に無い」だけなので次の候補へ。
39
+ if (error?.code === 'ENOENT') { lastError = error; continue; }
40
+ // lsofは該当が無いとexit 1を返す。これは観測の失敗ではなく「所有者なし」である。
41
+ // ここを潰すと、誰も掴んでいないstale socketが観測失敗として扱われ、正常な後片付けが
42
+ // 止まる(元の呼び出し側も同じ区別をしていた)。
43
+ if (error?.code === 1 && String(error?.stdout ?? '').trim() === '') return '';
44
+ throw error;
45
+ }
46
+ }
47
+ throw lastError;
48
+ }
49
+
50
+ /** `/proc/<pid>/fd`からunix socketのinodeを集める。Linux専用。 */
51
+ async function procSocketInodes(pid) {
52
+ const entries = await readdir(`/proc/${pid}/fd`);
53
+ const inodes = new Set();
54
+ for (const entry of entries) {
55
+ let target;
56
+ try { target = await readlink(`/proc/${pid}/fd/${entry}`); } catch { continue; }
57
+ const matched = SOCKET_INODE.exec(target);
58
+ if (matched !== null) inodes.add(matched[1]);
59
+ }
60
+ return inodes;
61
+ }
62
+
63
+ /** `/proc/net/unix`を読み、inode -> pathの対応を返す。 */
64
+ async function procUnixSocketPaths() {
65
+ const text = await readFile('/proc/net/unix', 'utf8');
66
+ const byInode = new Map();
67
+ for (const line of text.split('\n').slice(1)) {
68
+ // Num RefCount Protocol Flags Type St Inode Path
69
+ const fields = line.trim().split(/\s+/u);
70
+ if (fields.length < 8) continue;
71
+ const inode = fields[6];
72
+ const socketPath = fields.slice(7).join(' ');
73
+ if (socketPath.length === 0) continue;
74
+ if (!byInode.has(inode)) byInode.set(inode, []);
75
+ byInode.get(inode).push(socketPath);
76
+ }
77
+ return byInode;
78
+ }
79
+
80
+ /**
81
+ * 指定PIDが開いているunix socketのpath一覧を返す。
82
+ *
83
+ * @returns {Promise<string[]>} 観測できたpath。観測手段が無ければthrowする。
84
+ */
85
+ export async function socketPathsOwnedByPid(pid) {
86
+ if (process.platform === 'linux') {
87
+ const inodes = await procSocketInodes(pid);
88
+ if (inodes.size === 0) return [];
89
+ const byInode = await procUnixSocketPaths();
90
+ return [...inodes].flatMap((inode) => byInode.get(inode) ?? []);
91
+ }
92
+ const stdout = await runLsof(['-a', '-p', String(pid), '-U', '-F', 'fn']);
93
+ return stdout.split('\n')
94
+ .filter((line) => line.startsWith('n'))
95
+ .map((line) => line.slice(1));
96
+ }
97
+
98
+ /**
99
+ * 指定socket pathを開いているPID一覧を返す。
100
+ *
101
+ * @returns {Promise<number[]>} 観測できたPID。観測手段が無ければthrowする。
102
+ */
103
+ export async function pidsOwningSocketPath(socketPath) {
104
+ if (process.platform === 'linux') {
105
+ const byInode = await procUnixSocketPaths();
106
+ const wanted = new Set();
107
+ for (const [inode, paths] of byInode) {
108
+ if (paths.includes(socketPath)) wanted.add(inode);
109
+ }
110
+ if (wanted.size === 0) return [];
111
+ const pids = new Set();
112
+ for (const entry of await readdir('/proc')) {
113
+ if (!/^\d+$/u.test(entry)) continue;
114
+ let inodes;
115
+ // 他ユーザーのprocessは読めない。読めないものを「所有していない」へ丸めるが、
116
+ // これはlsofが権限不足で黙るのと同じ性質であり、判定は所有を**肯定**する側でのみ使う。
117
+ try { inodes = await procSocketInodes(entry); } catch { continue; }
118
+ if ([...wanted].some((inode) => inodes.has(inode))) pids.add(Number(entry));
119
+ }
120
+ return [...pids];
121
+ }
122
+ const stdout = await runLsof(['-t', socketPath]);
123
+ return stdout.split('\n').map((line) => line.trim())
124
+ .filter((line) => /^\d+$/u.test(line)).map(Number);
125
+ }