gencow 0.1.299 → 0.2.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 (149) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/package.json +1 -1
  3. package/docs/packaging.md +14 -4
  4. package/lib/cli-artifact-guard.mjs +53 -3
  5. package/lib/cli-dev-runtime.mjs +1 -0
  6. package/lib/cli-project-runtime.mjs +26 -14
  7. package/lib/codegen-command.mjs +16 -0
  8. package/lib/coding-guardrails.mjs +2 -0
  9. package/lib/dashboard-artifact.mjs +65 -0
  10. package/lib/dashboard-assets.mjs +20 -0
  11. package/lib/db-command.mjs +121 -80
  12. package/lib/db-migration-command-steps.mjs +19 -16
  13. package/lib/db-push-command.mjs +1 -1
  14. package/lib/deploy-codegen-preflight.mjs +1 -0
  15. package/lib/dev-cloud-command.mjs +1 -1
  16. package/lib/dev-local-command.mjs +19 -56
  17. package/lib/document-local-converter.mjs +11 -0
  18. package/lib/local-dashboard-plan.mjs +60 -0
  19. package/lib/local-database-commands.mjs +127 -0
  20. package/lib/local-development-migrations.mjs +157 -0
  21. package/lib/local-drizzle-database.config.mjs +10 -0
  22. package/lib/local-runtime-features.mjs +12 -0
  23. package/lib/rag-selection.mjs +7 -0
  24. package/lib/runtime-local-worker.mjs +116 -0
  25. package/lib/runtime-mode.mjs +3 -0
  26. package/lib/standalone-codegen-adapter.mjs +91 -0
  27. package/lib/ts-codegen-import-extension.mjs +228 -19
  28. package/package.json +16 -9
  29. package/runtime/config.mjs +218 -2
  30. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  31. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  32. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  33. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  34. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  35. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  36. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  37. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  38. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  39. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  40. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  41. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  42. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  43. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  44. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  45. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  46. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  47. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  48. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  49. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  50. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  51. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  52. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  53. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  54. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  55. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  56. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  57. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  58. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  59. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  60. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  61. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  62. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  63. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  64. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  65. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  66. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  67. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  68. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  69. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  70. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  71. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  72. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  73. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  74. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  75. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  76. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  77. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  78. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  79. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  80. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  81. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  82. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  83. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  84. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  85. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  86. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  87. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  88. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  89. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  90. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  91. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  92. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  93. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  94. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  95. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  96. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  97. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  98. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  99. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  100. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  101. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  102. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  103. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  104. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  105. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  106. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  107. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  108. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  109. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  110. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  111. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  112. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  113. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  114. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  115. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  116. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  117. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  118. package/runtime/engine/composition.mjs +325 -0
  119. package/runtime/engine/document-local.mjs +504 -0
  120. package/runtime/engine/graph.json +4134 -0
  121. package/runtime/engine/index.mjs +265 -0
  122. package/runtime/engine/local-postgres-support.mjs +69 -0
  123. package/runtime/engine/local.mjs +3275 -0
  124. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  125. package/runtime/engine/rag.mjs +11 -0
  126. package/runtime/engine/search.mjs +18 -0
  127. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  128. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  129. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  130. package/runtime/framework-migrations/manifest.json +56 -0
  131. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  132. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  133. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  134. package/runtime/runtime-metadata.json +27 -0
  135. package/runtime/tooling.mjs +10399 -8951
  136. package/scripts/bundle-runtime-config.mjs +23 -0
  137. package/scripts/bundle-runtime.mjs +100 -0
  138. package/scripts/bundle-runtime.test.mjs +33 -0
  139. package/scripts/bundle-shared.mjs +3 -0
  140. package/scripts/copy-dashboard.mjs +16 -0
  141. package/scripts/pre-publish-check.mjs +23 -11
  142. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  143. package/templateFeature/tools/manifest.json +2 -1
  144. package/templateFeature/tools/tools.ts +3 -3
  145. package/runtime/server.mjs +0 -14389
  146. package/scripts/bundle-server.mjs +0 -223
  147. package/server/config.js +0 -1
  148. package/server/index.js +0 -1
  149. package/server/package.json +0 -6
@@ -0,0 +1,9 @@
1
+ import {
2
+ runtimePostgresClient,
3
+ runtimePostgresCodecs
4
+ } from "./chunk-F3G4UGV4.mjs";
5
+ import "./chunk-KX2PRQPS.mjs";
6
+ export {
7
+ runtimePostgresClient,
8
+ runtimePostgresCodecs
9
+ };
@@ -0,0 +1,74 @@
1
+ import {
2
+ RuntimeDiagnosticError
3
+ } from "./chunk-AEBW7XZJ.mjs";
4
+
5
+ // ../runtime/dist/workflow/provider-retry.js
6
+ var issued = /* @__PURE__ */ new WeakMap();
7
+ var codes = /* @__PURE__ */ new Set([
8
+ "AI_ADMISSION_UNAVAILABLE",
9
+ "AI_TIER_QUEUE_WAIT_EXCEEDED",
10
+ "AI_PROVIDER_ROUTING_UNAVAILABLE"
11
+ ]);
12
+ function isRuntimeWorkflowProviderRetryCode(code) {
13
+ return codes.has(code);
14
+ }
15
+ function issueRuntimeWorkflowProviderRetry(diagnostic, providerCode, retryDelayMs) {
16
+ if (!isRuntimeWorkflowProviderRetryCode(providerCode) || retryDelayMs !== null && (!Number.isSafeInteger(retryDelayMs) || retryDelayMs < 0))
17
+ throw new TypeError("RUNTIME_WORKFLOW_PROVIDER_RETRY_INVALID");
18
+ const error = new RuntimeDiagnosticError(diagnostic);
19
+ issued.set(error, Object.freeze({ errorCode: providerCode, retryDelayMs }));
20
+ return error;
21
+ }
22
+ function runtimeWorkflowProviderRetry(error) {
23
+ return error && (typeof error === "object" || typeof error === "function") ? issued.get(error) : void 0;
24
+ }
25
+
26
+ // ../runtime/dist/rag/ingest-errors.js
27
+ var actions = {
28
+ RAG_EMBEDDING_REQUEST_INVALID: "Restore the trusted app-bound embedding supplier and its bounded input contract before same-job retry. No provider call was made by this rejected batch; committed conversion/index data is preserved. Do not edit framework rows or start replacement work.",
29
+ RAG_EMBEDDING_ADMISSION_REJECTED: "The trusted embedding gateway refused this batch before provider execution. Wait for the existing gateway admission/routing condition to clear, inspect this same rag_ingest_jobs.get/workflows.get identity, then use its same-run retry control. Committed conversion/index data is preserved; do not start replacement work or blindly retry an unknown outcome.",
30
+ RAG_CONVERSION_OUTCOME_UNKNOWN: "Inspect this same rag_ingest_jobs.get/workflows.get identity and any committed conversion artifact before resuming. External work may have been accepted; do not blindly repeat conversion or admit a replacement owner. Resume only after the existing provider outcome establishes a safe precondition.",
31
+ RAG_EMBEDDING_PROVIDER_UNAVAILABLE: "Restore the trusted app-bound embedding capability and inspect this same rag_ingest_jobs.get/workflows.get identity before resuming. Converted artifacts/index may already be committed; do not restart conversion under replacement work.",
32
+ RAG_INGEST_EXTERNAL_STATE_UNAVAILABLE: "Use an explicit basic conversion mode for this Runtime ingestion path until its durable external submission authority is available. No converter/provider call was admitted by this stage. Preserve and inspect this same job; do not bypass consent or blindly redispatch external work.",
33
+ RAG_EMBEDDING_OUTCOME_UNKNOWN: "Inspect this same rag_ingest_jobs.get/workflows.get identity and any committed embedding receipts before resuming. Provider work may have been accepted; do not blindly repeat paid embedding calls."
34
+ };
35
+ function isRagIngestErrorCode(code) {
36
+ return Object.hasOwn(actions, code);
37
+ }
38
+ function ragIngestError(code, correlationId, dataImpact = "unknown") {
39
+ return new RuntimeDiagnosticError({
40
+ code,
41
+ stage: "workflow",
42
+ capability: "application",
43
+ servingStarted: "unchanged",
44
+ dataImpact,
45
+ retryable: false,
46
+ retryPrecondition: "Restore the same canonical owner's capability and verify prior committed/provider effects before explicit resumption.",
47
+ nextAction: actions[code],
48
+ correlationId
49
+ });
50
+ }
51
+ function ragEmbeddingGatewayRetryError(correlationId, providerCode, retryDelayMs) {
52
+ const wait = retryDelayMs === null ? "the configured same-run Workflow backoff" : `the gateway-requested ${retryDelayMs} ms provider delay`;
53
+ const diagnostic = {
54
+ code: providerCode,
55
+ stage: "workflow",
56
+ capability: "application",
57
+ servingStarted: "unchanged",
58
+ dataImpact: "committed",
59
+ retryable: true,
60
+ retryPrecondition: `Wait for ${wait}; the existing Workflow retry budget and committed RAG checkpoints remain authoritative.`,
61
+ nextAction: `The trusted embedding gateway returned ${providerCode} before provider execution. Wait for ${wait}, inspect the same rag_ingest_jobs.get/workflows.get identity, and preserve committed source/index data. The canonical Workflow owner alone decides whether this run is scheduled to retry; do not start replacement work or blindly repeat provider calls.`,
62
+ correlationId,
63
+ ...retryDelayMs !== null && retryDelayMs >= 1e3 && retryDelayMs <= 6e4 ? { retryAfterSeconds: Math.ceil(retryDelayMs / 1e3) } : {}
64
+ };
65
+ return issueRuntimeWorkflowProviderRetry(diagnostic, providerCode, retryDelayMs);
66
+ }
67
+
68
+ export {
69
+ isRuntimeWorkflowProviderRetryCode,
70
+ runtimeWorkflowProviderRetry,
71
+ isRagIngestErrorCode,
72
+ ragIngestError,
73
+ ragEmbeddingGatewayRetryError
74
+ };
@@ -0,0 +1,215 @@
1
+ import {
2
+ assertRuntimeHost
3
+ } from "./chunk-DPWXSMWO.mjs";
4
+ import {
5
+ filesystemRootOwnerFilename
6
+ } from "./chunk-N4LTCKJP.mjs";
7
+ import {
8
+ RuntimeDiagnosticError,
9
+ runtimeDiagnostic
10
+ } from "./chunk-AEBW7XZJ.mjs";
11
+
12
+ // ../runtime/dist/scheduler/activation.js
13
+ function createRuntimeJobActivation() {
14
+ let active = false;
15
+ const listeners = /* @__PURE__ */ new Set();
16
+ return Object.freeze({
17
+ gate: Object.freeze({
18
+ isActive: () => active,
19
+ subscribe(listener) {
20
+ listeners.add(listener);
21
+ return () => {
22
+ listeners.delete(listener);
23
+ };
24
+ }
25
+ }),
26
+ activate() {
27
+ if (active)
28
+ return;
29
+ active = true;
30
+ for (const listener of [...listeners])
31
+ listener();
32
+ }
33
+ });
34
+ }
35
+
36
+ // ../runtime/dist/local/project-identity.js
37
+ import { randomUUID } from "node:crypto";
38
+ import { constants } from "node:fs";
39
+ import { link, lstat, mkdir, open, realpath, unlink } from "node:fs/promises";
40
+ import { resolve } from "node:path";
41
+ var identityFilename = "runtime-project-identity.json";
42
+ var maxBytes = 4096;
43
+ function hasPrivateMode(mode) {
44
+ return process.platform === "win32" || (mode & 511) === 384;
45
+ }
46
+ function failure(conflict = false) {
47
+ return new RuntimeDiagnosticError({
48
+ code: conflict ? "RUNTIME_PROJECT_IDENTITY_CONFLICT" : "RUNTIME_PROJECT_IDENTITY_UNAVAILABLE",
49
+ stage: "startup",
50
+ capability: "application",
51
+ servingStarted: false,
52
+ dataImpact: "none",
53
+ retryable: false,
54
+ correlationId: randomUUID(),
55
+ retryPrecondition: conflict ? "Select the original project and its matching storage root before restarting." : "Restore project directory access and safe owner permissions; restore an existing identity record only if it is damaged.",
56
+ nextAction: conflict ? "Run `pnpm exec gencow dev --local` from the original app workspace with its dedicated storage root. Preserve identity records, storage owner markers and signing keys; do not rebind or copy another app's private storage." : "Check project directory access and permissions on any existing identity records. A new workspace creates its identity automatically. Restore a damaged existing record from its original backup; do not delete or regenerate it. Then run `pnpm exec gencow dev --local`."
57
+ });
58
+ }
59
+ function storagePermissionsFailure() {
60
+ return new RuntimeDiagnosticError({
61
+ code: "RUNTIME_STORAGE_DIRECTORY_PERMISSIONS_UNSAFE",
62
+ stage: "startup",
63
+ capability: "storage",
64
+ servingStarted: false,
65
+ dataImpact: "none",
66
+ retryable: false,
67
+ correlationId: randomUUID(),
68
+ retryPrecondition: "Remove group and other write permissions from the configured filesystem storage directory before restarting.",
69
+ nextAction: "The configured filesystem storage directory is group- or world-writable. For the default storage path, run `chmod 700 -- .gencow/uploads` from the app workspace; for a custom storage path, apply the same permissions to that configured directory. Then run `pnpm exec gencow dev --local`. Preserve stored files and existing identity records."
70
+ });
71
+ }
72
+ function absent(error) {
73
+ return !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
74
+ }
75
+ async function readIdentity(path, publicationRace = false) {
76
+ for (let attempt = 0; attempt < 100; attempt++) {
77
+ let handle;
78
+ try {
79
+ const before = await lstat(path);
80
+ if (publicationRace && before.nlink === 2 && attempt < 99) {
81
+ await new Promise((done) => setTimeout(done, 10));
82
+ continue;
83
+ }
84
+ if (!before.isFile() || before.nlink !== 1 || before.size > maxBytes || !hasPrivateMode(before.mode) || process.getuid && before.uid !== process.getuid())
85
+ throw failure();
86
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
87
+ const opened = await handle.stat();
88
+ if (opened.dev !== before.dev || opened.ino !== before.ino)
89
+ throw failure();
90
+ const buffer = Buffer.alloc(maxBytes + 1);
91
+ let length = 0;
92
+ while (length < buffer.length) {
93
+ const result = await handle.read(buffer, length, buffer.length - length, length);
94
+ if (!result.bytesRead)
95
+ break;
96
+ length += result.bytesRead;
97
+ }
98
+ if (length > maxBytes)
99
+ throw failure();
100
+ const value = JSON.parse(buffer.subarray(0, length).toString("utf8"));
101
+ const after = await lstat(path);
102
+ if (after.dev !== before.dev || after.ino !== before.ino || after.nlink !== 1 || after.size !== length || !hasPrivateMode(after.mode))
103
+ throw failure();
104
+ if (!value || typeof value !== "object" || !("version" in value) || value.version !== 1 || !("appId" in value) || typeof value.appId !== "string" || !value.appId.trim() || value.appId.includes("\0"))
105
+ throw failure();
106
+ return value.appId;
107
+ } catch (error) {
108
+ if (absent(error))
109
+ return void 0;
110
+ if (runtimeDiagnostic(error))
111
+ throw error;
112
+ throw failure();
113
+ } finally {
114
+ await handle?.close();
115
+ }
116
+ }
117
+ throw failure();
118
+ }
119
+ async function resolveRuntimeProjectIdentity(input) {
120
+ assertRuntimeHost();
121
+ const project = await realpath(input.projectDir).catch(() => {
122
+ throw failure();
123
+ });
124
+ const directory = resolve(project, ".gencow");
125
+ const identityPath = resolve(directory, identityFilename);
126
+ try {
127
+ await mkdir(directory, { mode: 448 });
128
+ } catch (error) {
129
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
130
+ throw failure();
131
+ }
132
+ const owner = await lstat(directory).catch(() => {
133
+ throw failure();
134
+ });
135
+ const assertDirectory = async () => {
136
+ const current = await lstat(directory);
137
+ if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== owner.dev || current.ino !== owner.ino || process.getuid && current.uid !== process.getuid())
138
+ throw failure();
139
+ };
140
+ try {
141
+ await assertDirectory();
142
+ const existing = await readIdentity(identityPath, true);
143
+ let storageIdentity;
144
+ if (input.storageDirectory) {
145
+ try {
146
+ const storageOwner = await lstat(input.storageDirectory);
147
+ if (!storageOwner.isDirectory() || storageOwner.isSymbolicLink() || process.getuid && storageOwner.uid !== process.getuid())
148
+ throw failure();
149
+ if (process.platform !== "win32" && (storageOwner.mode & 18) !== 0)
150
+ throw storagePermissionsFailure();
151
+ storageIdentity = await readIdentity(resolve(input.storageDirectory, filesystemRootOwnerFilename));
152
+ } catch (error) {
153
+ if (!absent(error))
154
+ throw error;
155
+ }
156
+ }
157
+ if (existing) {
158
+ if (storageIdentity && storageIdentity !== existing)
159
+ throw failure(true);
160
+ await assertDirectory();
161
+ return existing;
162
+ }
163
+ const legacyIds = [
164
+ resolve(input.sourceRoot),
165
+ ...input.artifactRoot ? [resolve(input.artifactRoot)] : []
166
+ ];
167
+ if (storageIdentity && !legacyIds.includes(storageIdentity))
168
+ throw failure(true);
169
+ const appId = storageIdentity ?? resolve(input.sourceRoot);
170
+ const temporary = resolve(directory, `${identityFilename}.tmp-${randomUUID()}`);
171
+ let handle;
172
+ try {
173
+ handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
174
+ await handle.writeFile(JSON.stringify({ version: 1, appId }));
175
+ await handle.sync();
176
+ await handle.close();
177
+ handle = void 0;
178
+ await assertDirectory();
179
+ try {
180
+ await link(temporary, identityPath);
181
+ } catch (error) {
182
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
183
+ throw error;
184
+ }
185
+ } finally {
186
+ await handle?.close();
187
+ await unlink(temporary).catch((error) => {
188
+ if (!absent(error))
189
+ throw error;
190
+ });
191
+ }
192
+ if (process.platform !== "win32") {
193
+ const directoryHandle = await open(directory, constants.O_RDONLY | constants.O_NOFOLLOW);
194
+ try {
195
+ await directoryHandle.sync();
196
+ } finally {
197
+ await directoryHandle.close();
198
+ }
199
+ }
200
+ await assertDirectory();
201
+ const winner = await readIdentity(identityPath, true);
202
+ if (!winner || storageIdentity && winner !== storageIdentity)
203
+ throw failure(true);
204
+ return winner;
205
+ } catch (error) {
206
+ if (runtimeDiagnostic(error))
207
+ throw error;
208
+ throw failure();
209
+ }
210
+ }
211
+
212
+ export {
213
+ createRuntimeJobActivation,
214
+ resolveRuntimeProjectIdentity
215
+ };
@@ -0,0 +1,114 @@
1
+ // ../runtime/dist/workflow/store-sql.js
2
+ import { sql as sql2 } from "drizzle-orm";
3
+
4
+ // ../runtime/dist/workflow/source-timing.js
5
+ import { sql } from "drizzle-orm";
6
+ function age(origin) {
7
+ return sql`CASE WHEN isfinite(${origin}) AND ${origin}<=statement_timestamp()
8
+ THEN (EXTRACT(EPOCH FROM (statement_timestamp()-${origin}))*1000)::double precision
9
+ ELSE NULL::double precision END`;
10
+ }
11
+ function numericAge(value) {
12
+ if (value == null || typeof value === "string" && !value.trim())
13
+ return null;
14
+ const parsed = Number(value);
15
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
16
+ }
17
+ function createWorkflowSourceTimingRead(_claim, observer) {
18
+ if (!observer)
19
+ return void 0;
20
+ const readStarted = performance.now();
21
+ let row;
22
+ return {
23
+ columns: sql`,${age(sql`created_at`)} AS source_age_ms,
24
+ ${age(sql`active_started_at`)} AS attempt_age_ms`,
25
+ capture(value) {
26
+ row = value;
27
+ },
28
+ publish() {
29
+ const readSettled = performance.now();
30
+ const sourceAgeMs = numericAge(row?.source_age_ms);
31
+ const attemptAgeMs = numericAge(row?.attempt_age_ms);
32
+ try {
33
+ observer(sourceAgeMs === null || attemptAgeMs === null ? null : Object.freeze({
34
+ sourceAgeMs,
35
+ attemptAgeMs,
36
+ readStarted,
37
+ readSettled
38
+ }));
39
+ } catch {
40
+ }
41
+ }
42
+ };
43
+ }
44
+
45
+ // ../runtime/dist/workflow/store-sql.js
46
+ function workflowRows(result) {
47
+ if (Array.isArray(result))
48
+ return result;
49
+ return result?.rows ?? [];
50
+ }
51
+ function workflowJson(value) {
52
+ return sql2`${JSON.stringify(value)}::jsonb`;
53
+ }
54
+ var WorkflowLeaseLostError = class extends Error {
55
+ constructor() {
56
+ super("RUNTIME_WORKFLOW_LEASE_LOST");
57
+ this.name = "WorkflowLeaseLostError";
58
+ }
59
+ };
60
+ function workflowOwnedFence(claim) {
61
+ return sql2`id=${claim.id} AND workflow_name=${claim.name} AND status='running'
62
+ AND lease_owner=${claim.owner} AND lease_epoch=${claim.epoch}
63
+ AND lease_expires_at>clock_timestamp() AND completed_at IS NULL`;
64
+ }
65
+ function workflowLiveFence(claim) {
66
+ return sql2`${workflowOwnedFence(claim)} AND cancel_requested_at IS NULL
67
+ AND (active_deadline_at IS NULL OR active_deadline_at>clock_timestamp())
68
+ AND (lifecycle_deadline_at IS NULL OR lifecycle_deadline_at>clock_timestamp())`;
69
+ }
70
+ async function assertLiveWorkflowLease(db, claim, timing) {
71
+ const rows = workflowRows(await db.execute(sql2`SELECT LEAST(lease_expires_at,active_deadline_at,lifecycle_deadline_at)::text AS deadline${timing?.columns ?? sql2``}
72
+ FROM _gencow_workflow_runs_v2 WHERE ${workflowLiveFence(claim)} FOR UPDATE`));
73
+ if (!rows.length)
74
+ throw new WorkflowLeaseLostError();
75
+ timing?.capture(rows[0]);
76
+ return rows[0].deadline;
77
+ }
78
+ async function flushWorkflowDeferredWrites(tx) {
79
+ await tx.execute(sql2`SET CONSTRAINTS ALL IMMEDIATE`);
80
+ }
81
+ async function assertWorkflowClaimDeadline(db, deadline) {
82
+ await flushWorkflowDeferredWrites(db);
83
+ const rows = workflowRows(await db.execute(sql2`SELECT 1 WHERE ${deadline}::timestamptz>clock_timestamp()`));
84
+ if (!rows.length)
85
+ throw new WorkflowLeaseLostError();
86
+ }
87
+ async function withWorkflowLease(db, claim, run, assertLocal = () => {
88
+ }, onTiming) {
89
+ const timing = createWorkflowSourceTimingRead(claim, onTiming);
90
+ const result = await db.transaction(async (tx) => {
91
+ assertLocal();
92
+ await assertLiveWorkflowLease(tx, claim, timing);
93
+ const result2 = await run(tx);
94
+ await flushWorkflowDeferredWrites(tx);
95
+ await assertLiveWorkflowLease(tx, claim);
96
+ assertLocal();
97
+ return result2;
98
+ });
99
+ timing?.publish();
100
+ return result;
101
+ }
102
+
103
+ export {
104
+ createWorkflowSourceTimingRead,
105
+ workflowRows,
106
+ workflowJson,
107
+ WorkflowLeaseLostError,
108
+ workflowOwnedFence,
109
+ workflowLiveFence,
110
+ assertLiveWorkflowLease,
111
+ flushWorkflowDeferredWrites,
112
+ assertWorkflowClaimDeadline,
113
+ withWorkflowLease
114
+ };