semantic-atlas 0.1.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 (175) hide show
  1. package/.agents/skills/semantic-atlas/SKILL.md +172 -0
  2. package/.agents/skills/semantic-atlas/references/graph-patch.md +109 -0
  3. package/.agents/skills/semantic-atlas/references/result-routing.md +91 -0
  4. package/LICENSE +21 -0
  5. package/README.md +118 -0
  6. package/dist/business-flow/business-flow-derivation-service.d.ts +11 -0
  7. package/dist/business-flow/business-flow-derivation-service.d.ts.map +1 -0
  8. package/dist/business-flow/business-flow-derivation-service.js +151 -0
  9. package/dist/business-flow/business-flow-draft.d.ts +16 -0
  10. package/dist/business-flow/business-flow-draft.d.ts.map +1 -0
  11. package/dist/business-flow/business-flow-draft.js +150 -0
  12. package/dist/business-flow/framework-business-strategy.d.ts +7 -0
  13. package/dist/business-flow/framework-business-strategy.d.ts.map +1 -0
  14. package/dist/business-flow/framework-business-strategy.js +1 -0
  15. package/dist/business-flow/strategies/bullmq-business-strategy.d.ts +10 -0
  16. package/dist/business-flow/strategies/bullmq-business-strategy.d.ts.map +1 -0
  17. package/dist/business-flow/strategies/bullmq-business-strategy.js +79 -0
  18. package/dist/business-flow/strategies/called-operation-derivation.d.ts +13 -0
  19. package/dist/business-flow/strategies/called-operation-derivation.d.ts.map +1 -0
  20. package/dist/business-flow/strategies/called-operation-derivation.js +32 -0
  21. package/dist/business-flow/strategies/graphql-business-strategy.d.ts +8 -0
  22. package/dist/business-flow/strategies/graphql-business-strategy.d.ts.map +1 -0
  23. package/dist/business-flow/strategies/graphql-business-strategy.js +65 -0
  24. package/dist/business-flow/strategies/nestjs-business-strategy.d.ts +8 -0
  25. package/dist/business-flow/strategies/nestjs-business-strategy.d.ts.map +1 -0
  26. package/dist/business-flow/strategies/nestjs-business-strategy.js +72 -0
  27. package/dist/business-flow/strategies/strategy-helpers.d.ts +32 -0
  28. package/dist/business-flow/strategies/strategy-helpers.d.ts.map +1 -0
  29. package/dist/business-flow/strategies/strategy-helpers.js +49 -0
  30. package/dist/business-flow/strategies/typeorm-business-strategy.d.ts +10 -0
  31. package/dist/business-flow/strategies/typeorm-business-strategy.d.ts.map +1 -0
  32. package/dist/business-flow/strategies/typeorm-business-strategy.js +136 -0
  33. package/dist/business-flow/strategies/verified-invariant-strategy.d.ts +5 -0
  34. package/dist/business-flow/strategies/verified-invariant-strategy.d.ts.map +1 -0
  35. package/dist/business-flow/strategies/verified-invariant-strategy.js +38 -0
  36. package/dist/business-flow/strategies/verified-test-strategy.d.ts +5 -0
  37. package/dist/business-flow/strategies/verified-test-strategy.d.ts.map +1 -0
  38. package/dist/business-flow/strategies/verified-test-strategy.js +26 -0
  39. package/dist/business-flow/structural-flow-catalog.d.ts +21 -0
  40. package/dist/business-flow/structural-flow-catalog.d.ts.map +1 -0
  41. package/dist/business-flow/structural-flow-catalog.js +125 -0
  42. package/dist/business-flow/types.d.ts +51 -0
  43. package/dist/business-flow/types.d.ts.map +1 -0
  44. package/dist/business-flow/types.js +1 -0
  45. package/dist/cli/argument-parser.d.ts +3 -0
  46. package/dist/cli/argument-parser.d.ts.map +1 -0
  47. package/dist/cli/argument-parser.js +174 -0
  48. package/dist/cli/bin.d.ts +3 -0
  49. package/dist/cli/bin.d.ts.map +1 -0
  50. package/dist/cli/bin.js +23 -0
  51. package/dist/cli/cli-application.d.ts +38 -0
  52. package/dist/cli/cli-application.d.ts.map +1 -0
  53. package/dist/cli/cli-application.js +515 -0
  54. package/dist/cli/cli-error.d.ts +12 -0
  55. package/dist/cli/cli-error.d.ts.map +1 -0
  56. package/dist/cli/cli-error.js +44 -0
  57. package/dist/cli/cli-presenter.d.ts +14 -0
  58. package/dist/cli/cli-presenter.d.ts.map +1 -0
  59. package/dist/cli/cli-presenter.js +36 -0
  60. package/dist/cli/main.d.ts +3 -0
  61. package/dist/cli/main.d.ts.map +1 -0
  62. package/dist/cli/main.js +45 -0
  63. package/dist/cli/types.d.ts +46 -0
  64. package/dist/cli/types.d.ts.map +1 -0
  65. package/dist/cli/types.js +1 -0
  66. package/dist/contracts/cli.d.ts +2139 -0
  67. package/dist/contracts/cli.d.ts.map +1 -0
  68. package/dist/contracts/cli.js +232 -0
  69. package/dist/contracts/graph.d.ts +262 -0
  70. package/dist/contracts/graph.d.ts.map +1 -0
  71. package/dist/contracts/graph.js +182 -0
  72. package/dist/contracts/identifiers.d.ts +4 -0
  73. package/dist/contracts/identifiers.d.ts.map +1 -0
  74. package/dist/contracts/identifiers.js +7 -0
  75. package/dist/contracts/public-contracts.d.ts +4 -0
  76. package/dist/contracts/public-contracts.d.ts.map +1 -0
  77. package/dist/contracts/public-contracts.js +3 -0
  78. package/dist/evaluation/comparison.d.ts +30 -0
  79. package/dist/evaluation/comparison.d.ts.map +1 -0
  80. package/dist/evaluation/comparison.js +108 -0
  81. package/dist/evaluation/contracts.d.ts +204 -0
  82. package/dist/evaluation/contracts.d.ts.map +1 -0
  83. package/dist/evaluation/contracts.js +269 -0
  84. package/dist/graph/graph-store.d.ts +47 -0
  85. package/dist/graph/graph-store.d.ts.map +1 -0
  86. package/dist/graph/graph-store.js +719 -0
  87. package/dist/graph/types.d.ts +168 -0
  88. package/dist/graph/types.d.ts.map +1 -0
  89. package/dist/graph/types.js +1 -0
  90. package/dist/index.d.ts +19 -0
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +9 -0
  93. package/dist/knowledge/business-knowledge-service.d.ts +24 -0
  94. package/dist/knowledge/business-knowledge-service.d.ts.map +1 -0
  95. package/dist/knowledge/business-knowledge-service.js +200 -0
  96. package/dist/knowledge/graph-patch-conflict-error.d.ts +8 -0
  97. package/dist/knowledge/graph-patch-conflict-error.d.ts.map +1 -0
  98. package/dist/knowledge/graph-patch-conflict-error.js +12 -0
  99. package/dist/knowledge/structural-target-binding.d.ts +14 -0
  100. package/dist/knowledge/structural-target-binding.d.ts.map +1 -0
  101. package/dist/knowledge/structural-target-binding.js +11 -0
  102. package/dist/repository/git-command.d.ts +3 -0
  103. package/dist/repository/git-command.d.ts.map +1 -0
  104. package/dist/repository/git-command.js +25 -0
  105. package/dist/repository/repository-inspector.d.ts +7 -0
  106. package/dist/repository/repository-inspector.d.ts.map +1 -0
  107. package/dist/repository/repository-inspector.js +84 -0
  108. package/dist/repository/repository-language-support.d.ts +14 -0
  109. package/dist/repository/repository-language-support.d.ts.map +1 -0
  110. package/dist/repository/repository-language-support.js +64 -0
  111. package/dist/repository/types.d.ts +9 -0
  112. package/dist/repository/types.d.ts.map +1 -0
  113. package/dist/repository/types.js +1 -0
  114. package/dist/snapshots/repository-snapshot.d.ts +4 -0
  115. package/dist/snapshots/repository-snapshot.d.ts.map +1 -0
  116. package/dist/snapshots/repository-snapshot.js +119 -0
  117. package/dist/snapshots/types.d.ts +30 -0
  118. package/dist/snapshots/types.d.ts.map +1 -0
  119. package/dist/snapshots/types.js +1 -0
  120. package/dist/storage/atlas-database.d.ts +14 -0
  121. package/dist/storage/atlas-database.d.ts.map +1 -0
  122. package/dist/storage/atlas-database.js +552 -0
  123. package/dist/storage/snapshot-store.d.ts +19 -0
  124. package/dist/storage/snapshot-store.d.ts.map +1 -0
  125. package/dist/storage/snapshot-store.js +77 -0
  126. package/dist/structural-backend/codegraph-backend.d.ts +54 -0
  127. package/dist/structural-backend/codegraph-backend.d.ts.map +1 -0
  128. package/dist/structural-backend/codegraph-backend.js +1224 -0
  129. package/dist/structural-backend/codegraph-worker-client.d.ts +5 -0
  130. package/dist/structural-backend/codegraph-worker-client.d.ts.map +1 -0
  131. package/dist/structural-backend/codegraph-worker-client.js +118 -0
  132. package/dist/structural-backend/codegraph-worker-protocol.d.ts +35 -0
  133. package/dist/structural-backend/codegraph-worker-protocol.d.ts.map +1 -0
  134. package/dist/structural-backend/codegraph-worker-protocol.js +1 -0
  135. package/dist/structural-backend/codegraph-worker.d.ts +2 -0
  136. package/dist/structural-backend/codegraph-worker.d.ts.map +1 -0
  137. package/dist/structural-backend/codegraph-worker.js +131 -0
  138. package/dist/structural-backend/process-instance.d.ts +18 -0
  139. package/dist/structural-backend/process-instance.d.ts.map +1 -0
  140. package/dist/structural-backend/process-instance.js +207 -0
  141. package/dist/structural-backend/structural-fact-changes.d.ts +7 -0
  142. package/dist/structural-backend/structural-fact-changes.d.ts.map +1 -0
  143. package/dist/structural-backend/structural-fact-changes.js +78 -0
  144. package/dist/structural-backend/structural-publication.d.ts +12 -0
  145. package/dist/structural-backend/structural-publication.d.ts.map +1 -0
  146. package/dist/structural-backend/structural-publication.js +252 -0
  147. package/dist/structural-backend/structural-write-lock.d.ts +8 -0
  148. package/dist/structural-backend/structural-write-lock.d.ts.map +1 -0
  149. package/dist/structural-backend/structural-write-lock.js +415 -0
  150. package/dist/structural-backend/types.d.ts +144 -0
  151. package/dist/structural-backend/types.d.ts.map +1 -0
  152. package/dist/structural-backend/types.js +11 -0
  153. package/dist/world/types.d.ts +77 -0
  154. package/dist/world/types.d.ts.map +1 -0
  155. package/dist/world/types.js +1 -0
  156. package/dist/world/world-graph-query.d.ts +31 -0
  157. package/dist/world/world-graph-query.d.ts.map +1 -0
  158. package/dist/world/world-graph-query.js +453 -0
  159. package/dist/world/world-model-service.d.ts +21 -0
  160. package/dist/world/world-model-service.d.ts.map +1 -0
  161. package/dist/world/world-model-service.js +211 -0
  162. package/dist/world/world-snapshot-store.d.ts +40 -0
  163. package/dist/world/world-snapshot-store.d.ts.map +1 -0
  164. package/dist/world/world-snapshot-store.js +555 -0
  165. package/docs/architecture/codegraph-backend.md +193 -0
  166. package/docs/contracts/cli-v1.md +119 -0
  167. package/docs/contracts/graph-model.md +102 -0
  168. package/docs/contracts/graph-patch-v1.md +98 -0
  169. package/docs/evaluation.md +128 -0
  170. package/docs/product-contract.md +148 -0
  171. package/package.json +78 -0
  172. package/schemas/cli-envelope-v1.schema.json +1359 -0
  173. package/schemas/evaluation-plan-v1.schema.json +211 -0
  174. package/schemas/evaluation-run-v1.schema.json +365 -0
  175. package/schemas/graph-patch-v1.schema.json +392 -0
@@ -0,0 +1,252 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants as fileSystemConstants } from "node:fs";
3
+ import { lstat, mkdtemp, open, readdir, realpath, rename, rm, } from "node:fs/promises";
4
+ import { createRequire } from "node:module";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ const ACTIVE_PUBLICATION_DIRECTORY = ".structural-publication";
7
+ const STAGING_DIRECTORY_PREFIX = ".structural-publication-staging-";
8
+ const CLEANUP_DIRECTORY_PREFIX = ".structural-publication-cleanup-";
9
+ const PUBLICATION_MANIFEST = "publication.json";
10
+ const PUBLISHED_DATABASE = "published.db";
11
+ const DATABASE_SIDECARS = ["-wal", "-shm", "-journal"];
12
+ const require = createRequire(import.meta.url);
13
+ export class StructuralPublication {
14
+ #databasePath;
15
+ #atlasDirectory;
16
+ #activeDirectory;
17
+ #hasPublishedDatabase;
18
+ #active = true;
19
+ constructor(databasePath, hasPublishedDatabase) {
20
+ this.#databasePath = databasePath;
21
+ this.#atlasDirectory = dirname(databasePath);
22
+ this.#activeDirectory = join(this.#atlasDirectory, ACTIVE_PUBLICATION_DIRECTORY);
23
+ this.#hasPublishedDatabase = hasPublishedDatabase;
24
+ }
25
+ get backupPath() {
26
+ return join(this.#activeDirectory, PUBLISHED_DATABASE);
27
+ }
28
+ static async begin(databasePath, hasPublishedDatabase) {
29
+ const atlasDirectory = await verifyAtlasDatabaseLocation(databasePath);
30
+ const activeDirectory = join(atlasDirectory, ACTIVE_PUBLICATION_DIRECTORY);
31
+ await requireMissingPath(activeDirectory, "An unfinished structural publication already exists");
32
+ const stagingDirectory = await mkdtemp(join(atlasDirectory, STAGING_DIRECTORY_PREFIX));
33
+ try {
34
+ if (hasPublishedDatabase) {
35
+ const backupPath = join(stagingDirectory, PUBLISHED_DATABASE);
36
+ await captureDatabase(databasePath, backupPath);
37
+ await verifySqliteDatabase(backupPath);
38
+ }
39
+ await writeManifest(stagingDirectory, { version: 1, hasPublishedDatabase });
40
+ await rename(stagingDirectory, activeDirectory);
41
+ return new StructuralPublication(databasePath, hasPublishedDatabase);
42
+ }
43
+ catch (error) {
44
+ await rm(stagingDirectory, { recursive: true, force: true });
45
+ throw error;
46
+ }
47
+ }
48
+ static async recoverAbandoned(databasePath) {
49
+ const atlasDirectory = await verifyAtlasDatabaseLocation(databasePath);
50
+ const activeDirectory = join(atlasDirectory, ACTIVE_PUBLICATION_DIRECTORY);
51
+ await cleanupOrphanedPublicationDirectories(atlasDirectory);
52
+ let manifest;
53
+ try {
54
+ await verifyOwnedDirectory(activeDirectory, "The structural publication state");
55
+ manifest = await readManifest(activeDirectory);
56
+ }
57
+ catch (error) {
58
+ if (isFileSystemError(error, "ENOENT")) {
59
+ return false;
60
+ }
61
+ throw error;
62
+ }
63
+ const publication = new StructuralPublication(databasePath, manifest.hasPublishedDatabase);
64
+ await publication.rollback();
65
+ return true;
66
+ }
67
+ async commit() {
68
+ this.requireActive();
69
+ await verifyOwnedDirectory(this.#activeDirectory, "The structural publication state");
70
+ const cleanupDirectory = this.cleanupDirectoryPath();
71
+ await rename(this.#activeDirectory, cleanupDirectory);
72
+ this.#active = false;
73
+ await rm(cleanupDirectory, { recursive: true, force: true }).catch(() => undefined);
74
+ }
75
+ async rollback() {
76
+ this.requireActive();
77
+ await verifyOwnedDirectory(this.#activeDirectory, "The structural publication state");
78
+ const manifest = await readManifest(this.#activeDirectory);
79
+ if (manifest.hasPublishedDatabase !== this.#hasPublishedDatabase) {
80
+ throw new Error("The structural publication manifest changed during recovery");
81
+ }
82
+ if (this.#hasPublishedDatabase) {
83
+ await verifyOwnedRegularFile(this.backupPath, "The published structural database backup");
84
+ await restoreDatabase(this.backupPath, this.#databasePath);
85
+ await verifySqliteDatabase(this.#databasePath);
86
+ }
87
+ else {
88
+ await removeUnpublishedDatabase(this.#databasePath);
89
+ }
90
+ const cleanupDirectory = this.cleanupDirectoryPath();
91
+ await rename(this.#activeDirectory, cleanupDirectory);
92
+ this.#active = false;
93
+ await rm(cleanupDirectory, { recursive: true, force: true }).catch(() => undefined);
94
+ }
95
+ cleanupDirectoryPath() {
96
+ return join(this.#atlasDirectory, `${CLEANUP_DIRECTORY_PREFIX}${randomUUID()}`);
97
+ }
98
+ requireActive() {
99
+ if (!this.#active) {
100
+ throw new Error("The structural publication lifecycle has already finished");
101
+ }
102
+ }
103
+ }
104
+ async function captureDatabase(databasePath, backupPath) {
105
+ const sqlite = loadNodeSqliteBackup();
106
+ const database = new sqlite.DatabaseSync(databasePath, { readOnly: true });
107
+ try {
108
+ await sqlite.backup(database, backupPath);
109
+ }
110
+ finally {
111
+ database.close();
112
+ }
113
+ }
114
+ async function restoreDatabase(backupPath, databasePath) {
115
+ const sqlite = loadNodeSqliteBackup();
116
+ const publishedDatabase = new sqlite.DatabaseSync(backupPath, { readOnly: true });
117
+ try {
118
+ await removeUnpublishedDatabase(databasePath);
119
+ await sqlite.backup(publishedDatabase, databasePath);
120
+ }
121
+ finally {
122
+ publishedDatabase.close();
123
+ }
124
+ }
125
+ function loadNodeSqliteBackup() {
126
+ const sqlite = require("node:sqlite");
127
+ if (typeof sqlite.backup !== "function") {
128
+ throw new Error("The structural backend runtime does not support online SQLite backups");
129
+ }
130
+ return sqlite;
131
+ }
132
+ async function verifySqliteDatabase(databasePath) {
133
+ await verifyOwnedRegularFile(databasePath, "The structural database");
134
+ const { DatabaseSync } = loadNodeSqliteBackup();
135
+ const database = new DatabaseSync(databasePath, { readOnly: true });
136
+ try {
137
+ const result = database.prepare("PRAGMA integrity_check").get();
138
+ if (result?.integrity_check !== "ok") {
139
+ throw new Error("The restored structural database failed its integrity check");
140
+ }
141
+ }
142
+ finally {
143
+ database.close();
144
+ }
145
+ }
146
+ async function writeManifest(directoryPath, manifest) {
147
+ const manifestPath = join(directoryPath, PUBLICATION_MANIFEST);
148
+ const noFollow = fileSystemConstants.O_NOFOLLOW ?? 0;
149
+ const file = await open(manifestPath, fileSystemConstants.O_WRONLY |
150
+ fileSystemConstants.O_CREAT |
151
+ fileSystemConstants.O_EXCL |
152
+ noFollow, 0o600);
153
+ try {
154
+ await file.writeFile(`${JSON.stringify(manifest)}\n`, "utf8");
155
+ await file.sync();
156
+ }
157
+ finally {
158
+ await file.close();
159
+ }
160
+ }
161
+ async function readManifest(directoryPath) {
162
+ const manifestPath = join(directoryPath, PUBLICATION_MANIFEST);
163
+ await verifyOwnedRegularFile(manifestPath, "The structural publication manifest");
164
+ const noFollow = fileSystemConstants.O_NOFOLLOW ?? 0;
165
+ const file = await open(manifestPath, fileSystemConstants.O_RDONLY | noFollow);
166
+ try {
167
+ const parsed = JSON.parse(await file.readFile("utf8"));
168
+ if (typeof parsed !== "object" ||
169
+ parsed === null ||
170
+ !("version" in parsed) ||
171
+ parsed.version !== 1 ||
172
+ !("hasPublishedDatabase" in parsed) ||
173
+ typeof parsed.hasPublishedDatabase !== "boolean") {
174
+ throw new Error("The structural publication manifest is invalid");
175
+ }
176
+ return { version: 1, hasPublishedDatabase: parsed.hasPublishedDatabase };
177
+ }
178
+ finally {
179
+ await file.close();
180
+ }
181
+ }
182
+ async function removeUnpublishedDatabase(databasePath) {
183
+ for (const path of [databasePath, ...DATABASE_SIDECARS.map((suffix) => `${databasePath}${suffix}`)]) {
184
+ try {
185
+ const metadata = await lstat(path);
186
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
187
+ throw new Error("The unpublished structural database state is not a regular file");
188
+ }
189
+ await rm(path);
190
+ }
191
+ catch (error) {
192
+ if (!isFileSystemError(error, "ENOENT")) {
193
+ throw error;
194
+ }
195
+ }
196
+ }
197
+ }
198
+ async function cleanupOrphanedPublicationDirectories(atlasDirectory) {
199
+ const entries = await readdir(atlasDirectory, { withFileTypes: true });
200
+ for (const entry of entries) {
201
+ if (entry.name.startsWith(STAGING_DIRECTORY_PREFIX) ||
202
+ entry.name.startsWith(CLEANUP_DIRECTORY_PREFIX)) {
203
+ const path = join(atlasDirectory, entry.name);
204
+ await verifyOwnedDirectory(path, "The orphaned structural publication state");
205
+ await rm(path, { recursive: true, force: true });
206
+ }
207
+ }
208
+ }
209
+ async function verifyAtlasDatabaseLocation(databasePath) {
210
+ if (basename(databasePath) !== "codegraph.db") {
211
+ throw new Error("The structural publication database must use the Atlas database path");
212
+ }
213
+ const atlasDirectory = dirname(resolve(databasePath));
214
+ await verifyOwnedDirectory(atlasDirectory, "The Atlas store");
215
+ if (resolve(await realpath(atlasDirectory)) !== atlasDirectory) {
216
+ throw new Error("The Atlas store resolves outside the target worktree");
217
+ }
218
+ return atlasDirectory;
219
+ }
220
+ async function verifyOwnedDirectory(path, label) {
221
+ const metadata = await lstat(path);
222
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
223
+ throw new Error(`${label} must be a real directory`);
224
+ }
225
+ if (resolve(await realpath(path)) !== resolve(path)) {
226
+ throw new Error(`${label} resolves outside the Atlas store`);
227
+ }
228
+ }
229
+ async function verifyOwnedRegularFile(path, label) {
230
+ const metadata = await lstat(path);
231
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
232
+ throw new Error(`${label} must be a regular file`);
233
+ }
234
+ if (resolve(await realpath(path)) !== resolve(path)) {
235
+ throw new Error(`${label} resolves outside the Atlas store`);
236
+ }
237
+ }
238
+ async function requireMissingPath(path, message) {
239
+ try {
240
+ await lstat(path);
241
+ }
242
+ catch (error) {
243
+ if (isFileSystemError(error, "ENOENT")) {
244
+ return;
245
+ }
246
+ throw error;
247
+ }
248
+ throw new Error(message);
249
+ }
250
+ function isFileSystemError(error, code) {
251
+ return error instanceof Error && "code" in error && error.code === code;
252
+ }
@@ -0,0 +1,8 @@
1
+ export declare class StructuralWriteLock {
2
+ #private;
3
+ private constructor();
4
+ static acquire(path: string): StructuralWriteLock | undefined;
5
+ release(): void;
6
+ private static create;
7
+ }
8
+ //# sourceMappingURL=structural-write-lock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structural-write-lock.d.ts","sourceRoot":"","sources":["../../src/structural-backend/structural-write-lock.ts"],"names":[],"mappings":"AAuCA,qBAAa,mBAAmB;;IAO9B,OAAO;IAcP,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS;IAoB7D,OAAO,IAAI,IAAI;IAoBf,OAAO,CAAC,MAAM,CAAC,MAAM;CA2EtB"}
@@ -0,0 +1,415 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, constants as fileSystemConstants, fsyncSync, fstatSync, linkSync, lstatSync, openSync, readFileSync, readdirSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { currentProcessInstance, inspectProcessInstance, isProcessAlive, processStartedAfter, } from "./process-instance.js";
5
+ const OWNERSHIP_FILE_MARKER = ".owner-";
6
+ export class StructuralWriteLock {
7
+ #path;
8
+ #identity;
9
+ #ownership;
10
+ #ownershipPath;
11
+ #ownershipDescriptor;
12
+ constructor(path, identity, ownership, ownershipPath, ownershipDescriptor) {
13
+ this.#path = path;
14
+ this.#identity = identity;
15
+ this.#ownership = ownership;
16
+ this.#ownershipPath = ownershipPath;
17
+ this.#ownershipDescriptor = ownershipDescriptor;
18
+ }
19
+ static acquire(path) {
20
+ if (hasCompetingOwnershipLease(path)) {
21
+ return undefined;
22
+ }
23
+ for (let attempt = 0; attempt < 2; attempt += 1) {
24
+ const acquired = StructuralWriteLock.create(path);
25
+ if (acquired !== undefined) {
26
+ return acquired;
27
+ }
28
+ const existing = observeLock(path);
29
+ if (existing === undefined || isObservedOwnershipActive(path, existing)) {
30
+ return undefined;
31
+ }
32
+ if (!removeObservedLock(path, existing)) {
33
+ return undefined;
34
+ }
35
+ }
36
+ return undefined;
37
+ }
38
+ release() {
39
+ try {
40
+ removeObservedLock(this.#path, {
41
+ identity: this.#identity,
42
+ ownership: this.#ownership,
43
+ });
44
+ }
45
+ finally {
46
+ try {
47
+ removeObservedLock(this.#ownershipPath, {
48
+ identity: this.#identity,
49
+ ownership: this.#ownership,
50
+ });
51
+ }
52
+ finally {
53
+ if (this.#ownershipDescriptor !== undefined) {
54
+ closeSync(this.#ownershipDescriptor);
55
+ }
56
+ }
57
+ }
58
+ }
59
+ static create(path) {
60
+ const processInstance = currentProcessInstance();
61
+ const ownership = {
62
+ pid: process.pid,
63
+ token: randomUUID(),
64
+ instanceId: processInstance.id,
65
+ instanceProof: processInstance.proof,
66
+ };
67
+ const ownershipPath = ownershipFilePath(path, ownership);
68
+ let ownershipFileCreated = false;
69
+ let ownershipLeaseRetained = false;
70
+ let ownershipDescriptor;
71
+ try {
72
+ const noFollow = fileSystemConstants.O_NOFOLLOW ?? 0;
73
+ ownershipDescriptor = openSync(ownershipPath, fileSystemConstants.O_CREAT |
74
+ fileSystemConstants.O_EXCL |
75
+ fileSystemConstants.O_RDWR |
76
+ noFollow, 0o600);
77
+ ownershipFileCreated = true;
78
+ writeFileSync(ownershipDescriptor, serializeOwnership(ownership), { encoding: "utf8" });
79
+ persistOwnershipFile(ownershipDescriptor);
80
+ if (ownership.instanceProof !== "open-file") {
81
+ closeSync(ownershipDescriptor);
82
+ ownershipDescriptor = undefined;
83
+ }
84
+ if (hasCompetingOwnershipLease(path, ownershipPath)) {
85
+ return undefined;
86
+ }
87
+ // Publish only a complete owner record at the contested lock path.
88
+ try {
89
+ linkSync(ownershipPath, path);
90
+ }
91
+ catch (error) {
92
+ if (isFileSystemError(error, "EEXIST")) {
93
+ return undefined;
94
+ }
95
+ throw error;
96
+ }
97
+ const identity = lstatSync(path);
98
+ try {
99
+ persistDirectory(dirname(path));
100
+ }
101
+ catch (error) {
102
+ removeObservedLock(path, { identity, ownership });
103
+ throw error;
104
+ }
105
+ if (hasCompetingOwnershipLease(path, ownershipPath) ||
106
+ !matchesObservedLock(path, { identity, ownership })) {
107
+ removeObservedLock(path, { identity, ownership });
108
+ return undefined;
109
+ }
110
+ ownershipLeaseRetained = true;
111
+ return new StructuralWriteLock(path, identity, ownership, ownershipPath, ownershipDescriptor);
112
+ }
113
+ finally {
114
+ if (ownershipFileCreated && !ownershipLeaseRetained) {
115
+ try {
116
+ removeRegularFile(ownershipPath);
117
+ }
118
+ finally {
119
+ if (ownershipDescriptor !== undefined) {
120
+ closeSync(ownershipDescriptor);
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ function persistOwnershipFile(descriptor) {
128
+ fsyncSync(descriptor);
129
+ }
130
+ function persistDirectory(path) {
131
+ if (process.platform === "win32") {
132
+ return;
133
+ }
134
+ const descriptor = openSync(path, fileSystemConstants.O_RDONLY);
135
+ try {
136
+ fsyncSync(descriptor);
137
+ }
138
+ finally {
139
+ closeSync(descriptor);
140
+ }
141
+ }
142
+ function ownershipFilePath(path, ownership) {
143
+ if (ownership.instanceId === undefined) {
144
+ throw new Error("The structural lock owner lease requires a process instance identity");
145
+ }
146
+ if (ownership.instanceProof === undefined) {
147
+ throw new Error("The structural lock owner lease requires a process instance proof");
148
+ }
149
+ return `${path}${OWNERSHIP_FILE_MARKER}${ownership.pid}-${ownership.instanceProof}-${ownership.instanceId}-${ownership.token}`;
150
+ }
151
+ function hasCompetingOwnershipLease(lockPath, ownOwnershipPath) {
152
+ const directory = dirname(lockPath);
153
+ const prefix = `${basename(lockPath)}${OWNERSHIP_FILE_MARKER}`;
154
+ let entries;
155
+ try {
156
+ entries = readdirSync(directory);
157
+ }
158
+ catch {
159
+ return true;
160
+ }
161
+ for (const entry of entries) {
162
+ const path = join(directory, entry);
163
+ if (path === ownOwnershipPath) {
164
+ continue;
165
+ }
166
+ const ownership = parseOwnershipFileName(entry, prefix);
167
+ if (ownership === undefined) {
168
+ continue;
169
+ }
170
+ const observed = observeLock(path);
171
+ if (observed === undefined ||
172
+ observed.ownership.pid !== ownership.pid ||
173
+ observed.ownership.token !== ownership.token ||
174
+ observed.ownership.instanceId !== ownership.instanceId ||
175
+ observed.ownership.instanceProof !== ownership.instanceProof) {
176
+ if (ownership.instanceId === undefined
177
+ ? isLegacyLeasePathActive(lockPath, path, ownership.pid)
178
+ : isOwnershipActive(ownership, path)) {
179
+ return true;
180
+ }
181
+ }
182
+ else if (observed.ownership.instanceId === undefined) {
183
+ if (isLegacyLeaseActive(lockPath, observed)) {
184
+ return true;
185
+ }
186
+ if (matchesObservedLock(lockPath, observed) &&
187
+ !removeObservedLock(lockPath, observed)) {
188
+ return true;
189
+ }
190
+ }
191
+ else if (isOwnershipActive(observed.ownership, path, observed.identity)) {
192
+ return true;
193
+ }
194
+ if (!removeRegularFile(path) && pathExists(path)) {
195
+ return true;
196
+ }
197
+ }
198
+ return false;
199
+ }
200
+ function parseOwnershipFileName(name, prefix) {
201
+ if (!name.startsWith(prefix)) {
202
+ return undefined;
203
+ }
204
+ const serializedOwnership = name.slice(prefix.length);
205
+ const match = /^(\d+)-(?:(?<instanceProof>process-start|open-file)-)?(?:(?<instanceId>[0-9a-f]{64})-)?(?<token>[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/iu
206
+ .exec(serializedOwnership);
207
+ if (match === null) {
208
+ return undefined;
209
+ }
210
+ const serializedPid = match[1] ?? "";
211
+ const pid = /^\d+$/u.test(serializedPid)
212
+ ? Number.parseInt(serializedPid, 10)
213
+ : Number.NaN;
214
+ const token = match.groups?.token ?? "";
215
+ const instanceId = match.groups?.instanceId;
216
+ const instanceProof = match.groups?.instanceProof;
217
+ if (!Number.isSafeInteger(pid) ||
218
+ pid <= 0 ||
219
+ !isUuid(token) ||
220
+ (instanceProof !== undefined && instanceId === undefined)) {
221
+ return undefined;
222
+ }
223
+ return {
224
+ pid,
225
+ token,
226
+ ...(instanceId === undefined ? {} : { instanceId }),
227
+ ...(instanceProof === undefined ? {} : { instanceProof }),
228
+ };
229
+ }
230
+ function isUuid(value) {
231
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value);
232
+ }
233
+ function removeRegularFile(path) {
234
+ let identity;
235
+ try {
236
+ identity = lstatSync(path);
237
+ }
238
+ catch {
239
+ return false;
240
+ }
241
+ if (!identity.isFile() || identity.isSymbolicLink()) {
242
+ return false;
243
+ }
244
+ try {
245
+ const current = lstatSync(path);
246
+ if (current.dev !== identity.dev || current.ino !== identity.ino) {
247
+ return false;
248
+ }
249
+ unlinkSync(path);
250
+ return true;
251
+ }
252
+ catch {
253
+ return false;
254
+ }
255
+ }
256
+ function pathExists(path) {
257
+ try {
258
+ lstatSync(path);
259
+ return true;
260
+ }
261
+ catch (error) {
262
+ return !isFileSystemError(error, "ENOENT");
263
+ }
264
+ }
265
+ function observeLock(path) {
266
+ let descriptor;
267
+ try {
268
+ const identity = lstatSync(path);
269
+ if (!identity.isFile() || identity.isSymbolicLink()) {
270
+ return undefined;
271
+ }
272
+ descriptor = openSync(path, fileSystemConstants.O_RDONLY | (fileSystemConstants.O_NOFOLLOW ?? 0));
273
+ const openedIdentity = fstatSync(descriptor);
274
+ if (openedIdentity.dev !== identity.dev ||
275
+ openedIdentity.ino !== identity.ino) {
276
+ return undefined;
277
+ }
278
+ const ownership = parseOwnership(readFileSync(descriptor, "utf8"));
279
+ return ownership === undefined ? undefined : { identity: openedIdentity, ownership };
280
+ }
281
+ catch {
282
+ return undefined;
283
+ }
284
+ finally {
285
+ if (descriptor !== undefined) {
286
+ closeSync(descriptor);
287
+ }
288
+ }
289
+ }
290
+ function removeObservedLock(path, expected) {
291
+ if (!matchesObservedLock(path, expected)) {
292
+ return false;
293
+ }
294
+ try {
295
+ unlinkSync(path);
296
+ return true;
297
+ }
298
+ catch {
299
+ return false;
300
+ }
301
+ }
302
+ function matchesObservedLock(path, expected) {
303
+ const current = observeLock(path);
304
+ return current !== undefined &&
305
+ current.identity.dev === expected.identity.dev &&
306
+ current.identity.ino === expected.identity.ino &&
307
+ current.ownership.pid === expected.ownership.pid &&
308
+ current.ownership.token === expected.ownership.token &&
309
+ current.ownership.instanceId === expected.ownership.instanceId &&
310
+ current.ownership.instanceProof === expected.ownership.instanceProof;
311
+ }
312
+ function serializeOwnership(ownership) {
313
+ return `${JSON.stringify(ownership)}\n`;
314
+ }
315
+ function parseOwnership(value) {
316
+ try {
317
+ const parsed = JSON.parse(value);
318
+ const pid = typeof parsed === "object" && parsed !== null && "pid" in parsed
319
+ ? parsed.pid
320
+ : undefined;
321
+ const token = typeof parsed === "object" && parsed !== null && "token" in parsed
322
+ ? parsed.token
323
+ : undefined;
324
+ const instanceId = typeof parsed === "object" && parsed !== null && "instanceId" in parsed
325
+ ? parsed.instanceId
326
+ : undefined;
327
+ const instanceProof = typeof parsed === "object" && parsed !== null && "instanceProof" in parsed
328
+ ? parsed.instanceProof
329
+ : undefined;
330
+ if (typeof pid !== "number" ||
331
+ !Number.isSafeInteger(pid) ||
332
+ pid <= 0 ||
333
+ typeof token !== "string" ||
334
+ token.length === 0 ||
335
+ (instanceId !== undefined && !isProcessInstanceId(instanceId)) ||
336
+ (instanceProof !== undefined && !isProcessInstanceProof(instanceProof)) ||
337
+ (instanceProof !== undefined && instanceId === undefined)) {
338
+ return undefined;
339
+ }
340
+ return {
341
+ pid,
342
+ token,
343
+ ...(instanceId === undefined ? {} : { instanceId }),
344
+ ...(instanceProof === undefined ? {} : { instanceProof }),
345
+ };
346
+ }
347
+ catch {
348
+ return undefined;
349
+ }
350
+ }
351
+ function isOwnershipActive(ownership, leasePath, leaseIdentity) {
352
+ if (ownership.instanceId === undefined) {
353
+ return isProcessAlive(ownership.pid);
354
+ }
355
+ let identity;
356
+ try {
357
+ identity = leaseIdentity ?? lstatSync(leasePath);
358
+ }
359
+ catch {
360
+ return false;
361
+ }
362
+ const status = inspectProcessInstance(ownership.pid, ownership.instanceId, ownership.instanceProof ?? "process-start", {
363
+ path: leasePath,
364
+ device: identity.dev,
365
+ inode: identity.ino,
366
+ writtenAtMs: Math.max(identity.birthtimeMs, identity.ctimeMs),
367
+ });
368
+ return status === "matching" || status === "unknown";
369
+ }
370
+ function isObservedOwnershipActive(lockPath, lock) {
371
+ return lock.ownership.instanceId === undefined
372
+ ? isLegacyLeaseActive(lockPath, lock)
373
+ : isOwnershipActive(lock.ownership, lockPath, lock.identity);
374
+ }
375
+ function isLegacyLeaseActive(lockPath, lease) {
376
+ return isLegacyLeasePathActive(lockPath, lease.identity, lease.ownership.pid);
377
+ }
378
+ function isLegacyLeasePathActive(lockPath, leasePathOrIdentity, pid) {
379
+ if (!isProcessAlive(pid)) {
380
+ return false;
381
+ }
382
+ let leaseIdentity;
383
+ try {
384
+ leaseIdentity = typeof leasePathOrIdentity === "string"
385
+ ? lstatSync(leasePathOrIdentity)
386
+ : leasePathOrIdentity;
387
+ }
388
+ catch {
389
+ return false;
390
+ }
391
+ try {
392
+ const fixedIdentity = lstatSync(lockPath);
393
+ const sameLease = fixedIdentity.isFile() &&
394
+ !fixedIdentity.isSymbolicLink() &&
395
+ fixedIdentity.dev === leaseIdentity.dev &&
396
+ fixedIdentity.ino === leaseIdentity.ino;
397
+ if (!sameLease) {
398
+ return false;
399
+ }
400
+ const leaseWrittenAtMs = Math.max(leaseIdentity.birthtimeMs, leaseIdentity.ctimeMs);
401
+ return processStartedAfter(pid, leaseWrittenAtMs) !== true;
402
+ }
403
+ catch {
404
+ return false;
405
+ }
406
+ }
407
+ function isProcessInstanceId(value) {
408
+ return typeof value === "string" && /^[0-9a-f]{64}$/u.test(value);
409
+ }
410
+ function isProcessInstanceProof(value) {
411
+ return value === "process-start" || value === "open-file";
412
+ }
413
+ function isFileSystemError(error, code) {
414
+ return error instanceof Error && "code" in error && error.code === code;
415
+ }