@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.1

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/README.md +45 -10
  2. package/api-operations.js +404 -0
  3. package/client.js +452 -87
  4. package/cordis.patch.yml +4 -4
  5. package/entry/SKILL.md +34 -0
  6. package/icon.png +0 -0
  7. package/index.js +35 -47
  8. package/locale/en.json +6 -6
  9. package/locale/zh.json +6 -6
  10. package/native-api.mjs +326 -0
  11. package/native-contracts.js +195 -0
  12. package/native-execution.js +184 -0
  13. package/native-runner.mjs +107 -0
  14. package/native-state.js +67 -0
  15. package/native-tools.js +241 -0
  16. package/operations.js +1260 -0
  17. package/package.json +65 -51
  18. package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
  19. package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
  20. package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
  21. package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
  22. package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
  23. package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
  24. package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
  25. package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
  26. package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
  27. package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
  28. package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
  29. package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
  30. package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
  31. package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
  32. package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
  33. package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
  34. package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
  35. package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
  36. package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
  37. package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
  38. package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
  39. package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
  40. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
  41. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
  42. package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
  43. package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
  44. package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
  45. package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
  46. package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
  47. package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
  48. package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
  49. package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
  50. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
  51. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
  52. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
  53. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
  54. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
  55. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
  56. package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
  57. package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
  58. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
  59. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
  60. package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
  61. package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
  62. package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
  63. package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
  64. package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
  65. package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
  66. package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  67. package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
  68. package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
  69. package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
  70. package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
  71. package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
  72. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
  73. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
  74. package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
  75. package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
  76. package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
  77. package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
  78. package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
  79. package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
  80. package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
  81. package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
  82. package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
  83. package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
  84. package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
  85. package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
  86. package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
  87. package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
  88. package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
  89. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
  90. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
  91. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
  92. package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
  93. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
  94. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
  95. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
  96. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
  97. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
  98. package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
  99. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
  100. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
  101. package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
  102. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
  103. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
  104. package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
  105. package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
  106. package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
  107. package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
  108. package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
  109. package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
  110. package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
  111. package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
  112. package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
  113. package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
  114. package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
  115. package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
  116. package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
  117. package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
  118. package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
  119. package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
  120. package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
  121. package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
  122. package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
  123. package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
  124. package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
  125. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
  126. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
  127. package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
  128. package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
  129. package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
  130. package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
  131. package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
  132. package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
  133. package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
  134. package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
  135. package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
  136. package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
  137. package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
  138. package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
  139. package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
  140. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
  141. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
  142. package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
  143. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
  144. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
  145. package/skills-provider.js +51 -0
  146. package/workflow-index.json +434 -0
  147. package/icon.svg +0 -4
  148. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
  149. package/skills-index.json +0 -194
@@ -1,830 +1,853 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { chmod, open, readFile, writeFile } from "node:fs/promises";
3
- import { dirname, resolve } from "node:path";
4
-
5
- import {
6
- canonicalArtifactValue,
7
- hashArtifactValue,
8
- sameCanonical,
9
- withoutId,
10
- } from "./canonical.mjs";
11
- import { DatarcError } from "./datarc-client.mjs";
12
-
13
- const ARTIFACT_JOURNAL = "datarc-semantic-debugging-artifact-v1";
14
-
15
- export function createCommandArtifactIdentity({
16
- command,
17
- workspaceId,
18
- request,
19
- input = request,
20
- }) {
21
- const canonicalRequest = canonicalArtifactValue(request);
22
- return {
23
- journalType: "command",
24
- command,
25
- ...(workspaceId === undefined ? {} : { workspaceId }),
26
- inputHash: hashArtifactValue(input),
27
- request: canonicalRequest,
28
- };
29
- }
30
-
31
- export function completeCommandArtifact(identity, result) {
32
- return {
33
- ...identity,
34
- status: "completed",
35
- result,
36
- resultHash: hashArtifactValue(result),
37
- };
38
- }
39
-
40
- export async function writeArtifact(path, value) {
41
- if (typeof path !== "string" || !path)
42
- throw new DatarcError("--output 需要文件路径", "INVALID_ARGUMENT");
43
- const artifact = resolve(path);
44
- try {
45
- await writeFile(artifact, `${JSON.stringify(value, null, 2)}\n`, {
46
- encoding: "utf8",
47
- flag: "wx",
48
- mode: 0o600,
49
- });
50
- await chmod(artifact, 0o600);
51
- } catch {
52
- throw new DatarcError("无法安全写入 artifact", "ARTIFACT_WRITE_FAILED", {
53
- artifact,
54
- });
55
- }
56
- return artifact;
57
- }
58
-
59
- export async function reserveArtifact(
60
- path,
61
- value,
62
- { openArtifact = open, openDirectory = open, journalId = randomUUID() } = {},
63
- ) {
64
- if (typeof path !== "string" || !path)
65
- throw new DatarcError("--output 需要文件路径", "INVALID_ARGUMENT");
66
- const artifact = resolve(path);
67
- let handle;
68
- try {
69
- handle = await openArtifact(artifact, "wx", 0o600);
70
- await handle.chmod(0o600);
71
- const reserved = {
72
- artifact,
73
- handle,
74
- offset: 0,
75
- sequence: 0,
76
- journalId,
77
- rootPlan: value.plan,
78
- previousChecksum: null,
79
- lastDurableValue: undefined,
80
- syncAmbiguous: false,
81
- failed: false,
82
- };
83
- await appendReservedArtifact(reserved, value);
84
- await syncArtifactDirectory(artifact, openDirectory);
85
- return reserved;
86
- } catch (error) {
87
- await handle?.close();
88
- if (error?.details?.reloadRequired === true) throw error;
89
- throw new DatarcError("无法安全保留 artifact", "ARTIFACT_WRITE_FAILED", {
90
- artifact,
91
- });
92
- }
93
- }
94
-
95
- export async function appendReservedArtifact(reserved, value) {
96
- if (reserved.failed)
97
- throw new DatarcError(
98
- "artifact journal is unavailable",
99
- "ARTIFACT_WRITE_FAILED",
100
- {
101
- artifact: reserved.artifact,
102
- },
103
- );
104
- if (
105
- !validateArtifactPayloadTransition(
106
- reserved.lastDurableValue,
107
- value,
108
- reserved.rootPlan,
109
- )
110
- ) {
111
- reserved.failed = true;
112
- throw new DatarcError(
113
- "artifact journal transition is invalid",
114
- "ARTIFACT_WRITE_FAILED",
115
- { artifact: reserved.artifact },
116
- );
117
- }
118
- const content = encodeArtifactRecord(reserved.sequence, value, {
119
- journalId: reserved.journalId,
120
- previousChecksum: reserved.previousChecksum,
121
- });
122
- const checksum = JSON.parse(content.toString("utf8")).checksum;
123
- let writeComplete = false;
124
- try {
125
- await writeAll(reserved.handle, content, reserved.offset);
126
- writeComplete = true;
127
- await reserved.handle.sync();
128
- reserved.offset += content.length;
129
- reserved.sequence += 1;
130
- reserved.previousChecksum = checksum;
131
- reserved.lastDurableValue = structuredClone(value);
132
- } catch {
133
- reserved.failed = true;
134
- reserved.syncAmbiguous = writeComplete;
135
- throw new DatarcError("无法安全写入 artifact", "ARTIFACT_WRITE_FAILED", {
136
- artifact: reserved.artifact,
137
- ...(writeComplete ? { reloadRequired: true } : {}),
138
- });
139
- }
140
- }
141
-
142
- export async function readJson(path) {
143
- const text = path === "-" ? await readStdin() : await readFile(path, "utf8");
144
- try {
145
- return parseJsonOrArtifactJournal(text);
146
- } catch {
147
- throw new DatarcError("输入不是有效 JSON", "INVALID_JSON");
148
- }
149
- }
150
-
151
- export function encodeArtifactRecord(
152
- sequence,
153
- payload,
154
- { journalId, previousChecksum = null } = {},
155
- ) {
156
- if (typeof journalId !== "string" || !journalId)
157
- throw new DatarcError(
158
- "artifact journal id is required",
159
- "INVALID_ARTIFACT",
160
- );
161
- const body = {
162
- journal: ARTIFACT_JOURNAL,
163
- journalId,
164
- sequence,
165
- previousChecksum,
166
- payload,
167
- };
168
- const checksum = createHash("sha256")
169
- .update(JSON.stringify(body))
170
- .digest("hex");
171
- return Buffer.from(`${JSON.stringify({ ...body, checksum })}\n`, "utf8");
172
- }
173
-
174
- export function validateArtifactPayloadTransition(previous, next, rootPlan) {
175
- return validArtifactPayloadTransition(previous, next, rootPlan);
176
- }
177
-
178
- export function validateFinalBundle(bundle) {
179
- return validFinalBundle(bundle);
180
- }
181
-
182
- export function validateRollbackBundle(bundle) {
183
- return validRollbackBundle(bundle);
184
- }
185
-
186
- function parseJsonOrArtifactJournal(text) {
187
- try {
188
- const value = JSON.parse(text);
189
- if (!isArtifactRecord(value)) return value;
190
- if (
191
- !validArtifactRecord(value, {
192
- sequence: 0,
193
- journalId: value.journalId,
194
- previousChecksum: null,
195
- }) ||
196
- !validArtifactPayloadTransition(
197
- undefined,
198
- value.payload,
199
- value.payload?.plan,
200
- )
201
- )
202
- throw new Error("invalid artifact record");
203
- return artifactPayloadReadValue(value.payload);
204
- } catch (error) {
205
- const journalValue = lastArtifactJournalValue(text);
206
- if (journalValue.found) return artifactPayloadReadValue(journalValue.value);
207
- throw error;
208
- }
209
- }
210
-
211
- function lastArtifactJournalValue(text) {
212
- let value;
213
- let expectedSequence = 0;
214
- let journalId;
215
- let previousChecksum = null;
216
- let rootPlan;
217
- let found = false;
218
- for (const line of text.split("\n")) {
219
- if (!line) continue;
220
- let record;
221
- try {
222
- record = JSON.parse(line);
223
- } catch {
224
- break;
225
- }
226
- if (
227
- !validArtifactRecord(record, {
228
- sequence: expectedSequence,
229
- journalId: journalId ?? record.journalId,
230
- previousChecksum,
231
- }) ||
232
- !validArtifactPayloadTransition(
233
- value,
234
- record.payload,
235
- rootPlan ?? record.payload?.plan,
236
- )
237
- )
238
- break;
239
- value = record.payload;
240
- journalId = record.journalId;
241
- previousChecksum = record.checksum;
242
- rootPlan ??= record.payload.plan;
243
- expectedSequence += 1;
244
- found = true;
245
- }
246
- return { found, value };
247
- }
248
-
249
- function isArtifactRecord(value) {
250
- return (
251
- value &&
252
- typeof value === "object" &&
253
- !Array.isArray(value) &&
254
- value.journal === ARTIFACT_JOURNAL
255
- );
256
- }
257
-
258
- function validArtifactRecord(
259
- record,
260
- { sequence, journalId, previousChecksum },
261
- ) {
262
- if (
263
- !isArtifactRecord(record) ||
264
- record.sequence !== sequence ||
265
- typeof record.journalId !== "string" ||
266
- !record.journalId ||
267
- record.journalId !== journalId ||
268
- record.previousChecksum !== previousChecksum ||
269
- !Object.hasOwn(record, "payload") ||
270
- typeof record.checksum !== "string"
271
- )
272
- return false;
273
- const body = {
274
- journal: record.journal,
275
- journalId: record.journalId,
276
- sequence: record.sequence,
277
- previousChecksum: record.previousChecksum,
278
- payload: record.payload,
279
- };
280
- return (
281
- createHash("sha256").update(JSON.stringify(body)).digest("hex") ===
282
- record.checksum
283
- );
284
- }
285
-
286
- function validArtifactPayloadTransition(previous, next, rootPlan) {
287
- if (isCommandArtifactPayload(previous) || isCommandArtifactPayload(next))
288
- return validCommandArtifactPayloadTransition(previous, next);
289
- return validApplyArtifactPayloadTransition(previous, next, rootPlan);
290
- }
291
-
292
- function validCommandArtifactPayloadTransition(previous, next) {
293
- const nextState = commandArtifactPayloadState(next);
294
- if (!nextState || !validCommandArtifactPayload(next)) return false;
295
- if (previous === undefined) return nextState === "reserved";
296
- const previousState = commandArtifactPayloadState(previous);
297
- if (
298
- !previousState ||
299
- !validCommandArtifactPayload(previous) ||
300
- !sameCommandArtifactIdentity(previous, next) ||
301
- previousState === "completed"
302
- )
303
- return false;
304
- if (previousState === "reserved") return nextState === "running";
305
- return nextState === "running" || nextState === "completed";
306
- }
307
-
308
- function validApplyArtifactPayloadTransition(previous, next, rootPlan) {
309
- const nextState = artifactPayloadState(next);
310
- if (
311
- !nextState ||
312
- !validPlanIdentity(rootPlan) ||
313
- !validPayloadIdentity(next) ||
314
- (next.plan !== undefined && !sameCanonical(next.plan, rootPlan))
315
- )
316
- return false;
317
- if (previous === undefined) return nextState === "reserved";
318
- const previousState = artifactPayloadState(previous);
319
- if (
320
- !previousState ||
321
- previousState === "final" ||
322
- nextState === "reserved" ||
323
- (previousState === "reserved" && nextState !== "applying") ||
324
- artifactWorkspaceId(previous) !== artifactWorkspaceId(next) ||
325
- artifactPlanHash(previous) !== artifactPlanHash(next)
326
- )
327
- return false;
328
- if (nextState === "final" && next.receipt.pendingStep !== undefined)
329
- return false;
330
- if (
331
- nextState === "final" &&
332
- next.receipt.completedSteps.length !== rootPlan.steps.length
333
- )
334
- return false;
335
- if (nextState === "final" && !validFinalBundle(next)) return false;
336
- return (
337
- validReceiptPlanBinding(next.receipt, rootPlan) &&
338
- validReceiptLineage(previous.receipt, next.receipt)
339
- );
340
- }
341
-
342
- function isCommandArtifactPayload(payload) {
343
- return (
344
- payload &&
345
- typeof payload === "object" &&
346
- !Array.isArray(payload) &&
347
- payload.journalType === "command"
348
- );
349
- }
350
-
351
- function commandArtifactPayloadState(payload) {
352
- if (!isCommandArtifactPayload(payload)) return null;
353
- return new Set(["reserved", "running", "completed"]).has(payload.status)
354
- ? payload.status
355
- : null;
356
- }
357
-
358
- function validCommandArtifactPayload(payload) {
359
- const state = commandArtifactPayloadState(payload);
360
- if (
361
- !state ||
362
- typeof payload.command !== "string" ||
363
- !payload.command.trim() ||
364
- typeof payload.inputHash !== "string" ||
365
- !/^[a-f0-9]{64}$/u.test(payload.inputHash) ||
366
- !Object.hasOwn(payload, "request") ||
367
- !payload.request ||
368
- typeof payload.request !== "object" ||
369
- Array.isArray(payload.request) ||
370
- (Object.hasOwn(payload, "workspaceId") &&
371
- !validCommandWorkspaceId(payload.workspaceId))
372
- )
373
- return false;
374
- if (state !== "completed")
375
- return (
376
- !Object.hasOwn(payload, "result") && !Object.hasOwn(payload, "resultHash")
377
- );
378
- return (
379
- Object.hasOwn(payload, "result") &&
380
- typeof payload.resultHash === "string" &&
381
- /^[a-f0-9]{64}$/u.test(payload.resultHash) &&
382
- payload.resultHash === hashArtifactValue(payload.result)
383
- );
384
- }
385
-
386
- function validCommandWorkspaceId(value) {
387
- return (
388
- (typeof value === "string" && Boolean(value.trim())) ||
389
- (typeof value === "number" && Number.isFinite(value))
390
- );
391
- }
392
-
393
- function sameCommandArtifactIdentity(previous, next) {
394
- return (
395
- previous.command === next.command &&
396
- previous.inputHash === next.inputHash &&
397
- Object.hasOwn(previous, "workspaceId") ===
398
- Object.hasOwn(next, "workspaceId") &&
399
- previous.workspaceId === next.workspaceId &&
400
- sameCanonical(previous.request, next.request)
401
- );
402
- }
403
-
404
- function artifactPayloadReadValue(payload) {
405
- return isCommandArtifactPayload(payload) && payload.status === "completed"
406
- ? payload.result
407
- : payload;
408
- }
409
-
410
- function validFinalBundle(bundle) {
411
- if (!bundle || typeof bundle !== "object" || Array.isArray(bundle))
412
- return false;
413
- const plan = bundle.plan;
414
- const receipt = bundle.receipt;
415
- return Boolean(
416
- !hasNonFinalMarker(bundle) &&
417
- validFinalBaseline(bundle.baseline) &&
418
- validTimestamp(bundle.mutationStartedAt) &&
419
- validPlanIdentity(plan) &&
420
- validReceiptShape(receipt) &&
421
- !hasNonFinalMarker(receipt) &&
422
- validEnvelopeHash(plan, "planHash") &&
423
- validEnvelopeHash(receipt, "receiptHash") &&
424
- plan.workspaceId === receipt.workspaceId &&
425
- plan.planHash === receipt.planHash &&
426
- receipt.pendingStep === undefined &&
427
- receipt.completedSteps.length === plan.steps.length &&
428
- receipt.completedSteps.every(
429
- (step) => step.state === undefined && !hasNonFinalMarker(step),
430
- ) &&
431
- validReceiptPlanBinding(receipt, plan),
432
- );
433
- }
434
-
435
- function validRollbackBundle(bundle) {
436
- if (!bundle || typeof bundle !== "object" || Array.isArray(bundle))
437
- return false;
438
- const allowed = new Set([
439
- "baseline",
440
- "mutationStartedAt",
441
- "plan",
442
- "receipt",
443
- "status",
444
- ]);
445
- if (
446
- Object.keys(bundle).some((field) => !allowed.has(field)) ||
447
- (bundle.status !== undefined && bundle.status !== "applying") ||
448
- ["partial", "uncertain", "reloadRequired"].some((field) =>
449
- Object.hasOwn(bundle, field),
450
- ) ||
451
- !validFinalBaseline(bundle.baseline) ||
452
- !validTimestamp(bundle.mutationStartedAt)
453
- )
454
- return false;
455
- const plan = bundle.plan;
456
- const receipt = bundle.receipt;
457
- return Boolean(
458
- validPlanIdentity(plan) &&
459
- validReceiptShape(receipt) &&
460
- validEnvelopeHash(plan, "planHash") &&
461
- validEnvelopeHash(receipt, "receiptHash") &&
462
- plan.workspaceId === receipt.workspaceId &&
463
- plan.planHash === receipt.planHash &&
464
- !hasNonFinalMarker(receipt) &&
465
- (bundle.status === "applying" ||
466
- (receipt.pendingStep === undefined &&
467
- receipt.completedSteps.length === plan.steps.length &&
468
- receipt.completedSteps.every(
469
- (step) => step.state === undefined && !hasNonFinalMarker(step),
470
- ))) &&
471
- validReceiptPlanBinding(receipt, plan),
472
- );
473
- }
474
-
475
- function validFinalBaseline(baseline) {
476
- return Boolean(
477
- baseline &&
478
- typeof baseline === "object" &&
479
- !Array.isArray(baseline) &&
480
- Array.isArray(baseline.baselineTaskUids) &&
481
- validTimestamp(baseline.capturedAt),
482
- );
483
- }
484
-
485
- function validTimestamp(value) {
486
- return (
487
- typeof value === "string" &&
488
- value.trim() &&
489
- Number.isFinite(Date.parse(value))
490
- );
491
- }
492
-
493
- function hasNonFinalMarker(value) {
494
- return ["status", "partial", "uncertain", "reloadRequired"].some((field) =>
495
- Object.hasOwn(value ?? {}, field),
496
- );
497
- }
498
-
499
- function validEnvelopeHash(value, field) {
500
- if (typeof value?.[field] !== "string" || !value[field]) return false;
501
- const body = structuredClone(value);
502
- delete body[field];
503
- return value[field] === hashArtifactValue(body);
504
- }
505
-
506
- function artifactPayloadState(payload) {
507
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
508
- return null;
509
- if (payload.status === "reserved") return "reserved";
510
- if (payload.status === "applying") return "applying";
511
- if (payload.status === undefined && payload.receipt) return "final";
512
- return null;
513
- }
514
-
515
- function validPayloadIdentity(payload) {
516
- const state = artifactPayloadState(payload);
517
- const plan = payload.plan;
518
- const receipt = payload.receipt;
519
- if (state === "reserved")
520
- return validPlanIdentity(plan) && receipt === undefined;
521
- if (!validReceiptShape(receipt)) return false;
522
- if (plan !== undefined && !validPlanIdentity(plan)) return false;
523
- return (
524
- (plan === undefined || plan.workspaceId === receipt.workspaceId) &&
525
- (plan === undefined || plan.planHash === receipt.planHash)
526
- );
527
- }
528
-
529
- function validPlanIdentity(plan) {
530
- return (
531
- plan &&
532
- typeof plan === "object" &&
533
- !Array.isArray(plan) &&
534
- plan.workspaceId !== undefined &&
535
- typeof plan.planHash === "string" &&
536
- plan.planHash &&
537
- Array.isArray(plan.steps)
538
- );
539
- }
540
-
541
- function validReceiptShape(receipt) {
542
- return (
543
- receipt &&
544
- typeof receipt === "object" &&
545
- !Array.isArray(receipt) &&
546
- receipt.workspaceId !== undefined &&
547
- typeof receipt.planHash === "string" &&
548
- receipt.planHash &&
549
- Array.isArray(receipt.completedSteps) &&
550
- !Object.hasOwn(receipt, "pendingSteps") &&
551
- (receipt.pendingStep === undefined ||
552
- (receipt.pendingStep &&
553
- typeof receipt.pendingStep === "object" &&
554
- !Array.isArray(receipt.pendingStep)))
555
- );
556
- }
557
-
558
- function validReceiptPlanBinding(receipt, plan) {
559
- if (receipt.completedSteps.length > plan.steps.length) return false;
560
- if (
561
- !receipt.completedSteps.every((step, index) =>
562
- validBoundReceiptStep(step, plan.steps[index], index, false),
563
- )
564
- )
565
- return false;
566
- if (receipt.pendingStep === undefined) return true;
567
- const pendingIndex = receipt.completedSteps.length;
568
- return (
569
- pendingIndex < plan.steps.length &&
570
- validBoundReceiptStep(
571
- receipt.pendingStep,
572
- plan.steps[pendingIndex],
573
- pendingIndex,
574
- true,
575
- )
576
- );
577
- }
578
-
579
- function validBoundReceiptStep(actual, planned, index, pending) {
580
- const generatedIdentity = hasResolvedGeneratedIdentity(actual, planned);
581
- if (
582
- !actual ||
583
- !planned ||
584
- actual.planStepIndex !== index ||
585
- actual.planStepHash !== hashArtifactValue(planned) ||
586
- !sameCanonical(stepStaticBody(actual), stepStaticBody(planned)) ||
587
- !validRuntimeEndpoint(actual, planned)
588
- )
589
- return false;
590
- const allowedStates = plannedPossibleStates(planned);
591
- if (pending)
592
- return (
593
- actual.state === "uncertain" &&
594
- actual.operation === planned.operation &&
595
- actual.endpoint === planned.endpoint &&
596
- sameCanonical(actual.after, planned.after) &&
597
- sameCanonical(
598
- actual.possibleAfter,
599
- uniqueCanonicalStates(allowedStates),
600
- ) &&
601
- actual.identityResolved === (planned.before !== null) &&
602
- actual.rollbackRecreate === undefined
603
- );
604
- if (actual.state === undefined)
605
- return (
606
- actual.operation === planned.operation &&
607
- runtimeStateMatches(actual.after, planned.after, generatedIdentity) &&
608
- actual.possibleAfter === undefined &&
609
- actual.identityResolved === undefined &&
610
- actual.rollbackRecreate === undefined
611
- );
612
- if (!new Set(["uncertain", "verified"]).has(actual.state)) return false;
613
- if (
614
- !validPartialOperation(actual, planned) ||
615
- !allowedStates.some((state) =>
616
- runtimeStateMatches(actual.after, state, generatedIdentity),
617
- ) ||
618
- !validPartialPossibleAfter(
619
- actual.possibleAfter,
620
- allowedStates,
621
- generatedIdentity,
622
- ) ||
623
- !validPartialIdentity(actual, planned)
624
- )
625
- return false;
626
- return (
627
- actual.rollbackRecreate === undefined ||
628
- (actual.rollbackRecreate === true && planned.operation === "REPLACE")
629
- );
630
- }
631
-
632
- function stepStaticBody(step) {
633
- const result = structuredClone(step);
634
- for (const field of [
635
- "after",
636
- "endpoint",
637
- "identityResolved",
638
- "operation",
639
- "planStepHash",
640
- "planStepIndex",
641
- "possibleAfter",
642
- "rollbackRecreate",
643
- "state",
644
- ])
645
- delete result[field];
646
- return result;
647
- }
648
-
649
- function validRuntimeEndpoint(actual, planned) {
650
- if (actual.endpoint === planned.endpoint) return true;
651
- return hasResolvedGeneratedIdentity(actual, planned);
652
- }
653
-
654
- function hasResolvedGeneratedIdentity(actual, planned) {
655
- if (!new Set(["POST", "REPLACE"]).has(planned.operation)) return false;
656
- if (planned.after?.id !== undefined) return false;
657
- const id = actual.after?.id;
658
- if (
659
- planned.kind === "semantic_calibration" &&
660
- planned.operation === "POST" &&
661
- planned.before !== null &&
662
- id !== undefined &&
663
- actual.endpoint === planned.endpoint
664
- )
665
- return true;
666
- return (
667
- id !== undefined &&
668
- planned.endpoint.endsWith("/") &&
669
- actual.endpoint === `${planned.endpoint}${id}/`
670
- );
671
- }
672
-
673
- function validPartialOperation(actual, planned) {
674
- return (
675
- actual.operation === planned.operation ||
676
- (planned.kind === "semantic_calibration" &&
677
- planned.operation === "REPLACE" &&
678
- actual.operation === "DELETE")
679
- );
680
- }
681
-
682
- function validPartialIdentity(actual, planned) {
683
- const expected =
684
- planned.before !== null || actual.endpoint !== planned.endpoint;
685
- if (actual.identityResolved === expected) return true;
686
- return (
687
- actual.identityResolved === false &&
688
- planned.kind === "semantic_calibration" &&
689
- planned.operation === "REPLACE" &&
690
- actual.operation === "REPLACE" &&
691
- actual.endpoint === planned.endpoint &&
692
- actual.state === "uncertain" &&
693
- actual.rollbackRecreate === true &&
694
- sameCanonical(actual.after, planned.after) &&
695
- sameCanonical(actual.possibleAfter, [null, withoutId(planned.after)])
696
- );
697
- }
698
-
699
- function validPartialPossibleAfter(
700
- actualStates,
701
- allowedStates,
702
- generatedIdentity,
703
- ) {
704
- if (!Array.isArray(actualStates) || actualStates.length === 0) return false;
705
- let previousIndex = -1;
706
- for (const actual of actualStates) {
707
- const index = allowedStates.findIndex(
708
- (allowed, candidateIndex) =>
709
- candidateIndex > previousIndex &&
710
- runtimeStateMatches(actual, allowed, generatedIdentity),
711
- );
712
- if (index === -1) return false;
713
- previousIndex = index;
714
- }
715
- return true;
716
- }
717
-
718
- function plannedPossibleStates(step) {
719
- if (step.kind === "semantic_calibration" && step.operation === "POST")
720
- return step.before === null
721
- ? [null, withoutId(step.after)]
722
- : [withoutId(step.before), withoutId(step.after)];
723
- if (step.operation === "REPLACE")
724
- return [withoutId(step.before), null, withoutId(step.after)];
725
- if (step.kind === "knowledge" && step.before === null && !step.after.active)
726
- return [null, { ...step.after, active: true }, step.after];
727
- return [step.before, step.after];
728
- }
729
-
730
- function uniqueCanonicalStates(states) {
731
- const seen = new Set();
732
- return states.filter((state) => {
733
- const key = JSON.stringify(canonicalArtifactValue(state));
734
- if (seen.has(key)) return false;
735
- seen.add(key);
736
- return true;
737
- });
738
- }
739
-
740
- function runtimeStateMatches(actual, expected, generatedIdentity = false) {
741
- if (actual === null || expected === null) return actual === expected;
742
- if (
743
- !actual ||
744
- !expected ||
745
- typeof actual !== "object" ||
746
- typeof expected !== "object"
747
- )
748
- return sameCanonical(actual, expected);
749
- const normalized = structuredClone(actual);
750
- if (generatedIdentity && !Object.hasOwn(expected, "id")) delete normalized.id;
751
- return sameCanonical(normalized, expected);
752
- }
753
-
754
- function artifactWorkspaceId(payload) {
755
- return payload.receipt?.workspaceId ?? payload.plan?.workspaceId;
756
- }
757
-
758
- function artifactPlanHash(payload) {
759
- return payload.receipt?.planHash ?? payload.plan?.planHash;
760
- }
761
-
762
- function validReceiptLineage(previous, next) {
763
- if (!validReceiptShape(next)) return false;
764
- if (previous === undefined) return next.completedSteps.length === 0;
765
- if (!validReceiptShape(previous)) return false;
766
- if (
767
- next.completedSteps.length < previous.completedSteps.length ||
768
- !previous.completedSteps.every((step, index) =>
769
- sameCanonical(step, next.completedSteps[index]),
770
- )
771
- )
772
- return false;
773
- const growth = next.completedSteps.length - previous.completedSteps.length;
774
- if (growth > 1) return false;
775
- if (previous.pendingStep === undefined) return growth === 0;
776
- if (growth === 0)
777
- return (
778
- next.pendingStep !== undefined &&
779
- sameCanonical(previous.pendingStep, next.pendingStep)
780
- );
781
- return (
782
- next.pendingStep === undefined &&
783
- sameStepLineage(
784
- previous.pendingStep,
785
- next.completedSteps[next.completedSteps.length - 1],
786
- )
787
- );
788
- }
789
-
790
- function sameStepLineage(pending, completed) {
791
- return (
792
- pending?.planStepIndex === completed?.planStepIndex &&
793
- pending?.planStepHash === completed?.planStepHash
794
- );
795
- }
796
-
797
- async function syncArtifactDirectory(artifact, openDirectory) {
798
- let handle;
799
- try {
800
- handle = await openDirectory(dirname(artifact), "r");
801
- await handle.sync();
802
- } finally {
803
- await handle?.close();
804
- }
805
- }
806
-
807
- async function writeAll(handle, content, position) {
808
- let offset = 0;
809
- while (offset < content.length) {
810
- const { bytesWritten } = await handle.write(
811
- content,
812
- offset,
813
- content.length - offset,
814
- position + offset,
815
- );
816
- if (
817
- !Number.isInteger(bytesWritten) ||
818
- bytesWritten <= 0 ||
819
- bytesWritten > content.length - offset
820
- )
821
- throw new Error("artifact write made no progress");
822
- offset += bytesWritten;
823
- }
824
- }
825
-
826
- async function readStdin() {
827
- const chunks = [];
828
- for await (const chunk of process.stdin) chunks.push(chunk);
829
- return Buffer.concat(chunks).toString("utf8");
830
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmod, open, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+
5
+ import {
6
+ canonicalArtifactValue,
7
+ hashArtifactValue,
8
+ sameCanonical,
9
+ withoutId,
10
+ } from "./canonical.mjs";
11
+ import { DatarcError } from "./datarc-client.mjs";
12
+
13
+ const ARTIFACT_JOURNAL = "datarc-semantic-debugging-artifact-v1";
14
+ let directorySyncWarningEmitted = false;
15
+
16
+ export function createCommandArtifactIdentity({
17
+ command,
18
+ workspaceId,
19
+ request,
20
+ input = request,
21
+ }) {
22
+ const canonicalRequest = canonicalArtifactValue(request);
23
+ return {
24
+ journalType: "command",
25
+ command,
26
+ ...(workspaceId === undefined ? {} : { workspaceId }),
27
+ inputHash: hashArtifactValue(input),
28
+ request: canonicalRequest,
29
+ };
30
+ }
31
+
32
+ export function completeCommandArtifact(identity, result) {
33
+ return {
34
+ ...identity,
35
+ status: "completed",
36
+ result,
37
+ resultHash: hashArtifactValue(result),
38
+ };
39
+ }
40
+
41
+ export async function writeArtifact(path, value) {
42
+ if (typeof path !== "string" || !path)
43
+ throw new DatarcError("--output 需要文件路径", "INVALID_ARGUMENT");
44
+ const artifact = resolve(path);
45
+ try {
46
+ await writeFile(artifact, `${JSON.stringify(value, null, 2)}\n`, {
47
+ encoding: "utf8",
48
+ flag: "wx",
49
+ mode: 0o600,
50
+ });
51
+ await chmod(artifact, 0o600);
52
+ } catch {
53
+ throw new DatarcError("无法安全写入 artifact", "ARTIFACT_WRITE_FAILED", {
54
+ artifact,
55
+ });
56
+ }
57
+ return artifact;
58
+ }
59
+
60
+ export async function reserveArtifact(
61
+ path,
62
+ value,
63
+ { openArtifact = open, openDirectory = open, journalId = randomUUID() } = {},
64
+ ) {
65
+ if (typeof path !== "string" || !path)
66
+ throw new DatarcError("--output 需要文件路径", "INVALID_ARGUMENT");
67
+ const artifact = resolve(path);
68
+ let handle;
69
+ try {
70
+ handle = await openArtifact(artifact, "wx", 0o600);
71
+ await handle.chmod(0o600);
72
+ const reserved = {
73
+ artifact,
74
+ handle,
75
+ offset: 0,
76
+ sequence: 0,
77
+ journalId,
78
+ rootPlan: value.plan,
79
+ previousChecksum: null,
80
+ lastDurableValue: undefined,
81
+ syncAmbiguous: false,
82
+ failed: false,
83
+ };
84
+ await appendReservedArtifact(reserved, value);
85
+ await syncArtifactDirectory(artifact, openDirectory);
86
+ return reserved;
87
+ } catch (error) {
88
+ await handle?.close();
89
+ if (error?.details?.reloadRequired === true) throw error;
90
+ throw new DatarcError("无法安全保留 artifact", "ARTIFACT_WRITE_FAILED", {
91
+ artifact,
92
+ });
93
+ }
94
+ }
95
+
96
+ export async function appendReservedArtifact(reserved, value) {
97
+ if (reserved.failed)
98
+ throw new DatarcError(
99
+ "artifact journal is unavailable",
100
+ "ARTIFACT_WRITE_FAILED",
101
+ {
102
+ artifact: reserved.artifact,
103
+ },
104
+ );
105
+ if (
106
+ !validateArtifactPayloadTransition(
107
+ reserved.lastDurableValue,
108
+ value,
109
+ reserved.rootPlan,
110
+ )
111
+ ) {
112
+ reserved.failed = true;
113
+ throw new DatarcError(
114
+ "artifact journal transition is invalid",
115
+ "ARTIFACT_WRITE_FAILED",
116
+ { artifact: reserved.artifact },
117
+ );
118
+ }
119
+ const content = encodeArtifactRecord(reserved.sequence, value, {
120
+ journalId: reserved.journalId,
121
+ previousChecksum: reserved.previousChecksum,
122
+ });
123
+ const checksum = JSON.parse(content.toString("utf8")).checksum;
124
+ let writeComplete = false;
125
+ try {
126
+ await writeAll(reserved.handle, content, reserved.offset);
127
+ writeComplete = true;
128
+ await reserved.handle.sync();
129
+ reserved.offset += content.length;
130
+ reserved.sequence += 1;
131
+ reserved.previousChecksum = checksum;
132
+ reserved.lastDurableValue = structuredClone(value);
133
+ } catch {
134
+ reserved.failed = true;
135
+ reserved.syncAmbiguous = writeComplete;
136
+ throw new DatarcError("无法安全写入 artifact", "ARTIFACT_WRITE_FAILED", {
137
+ artifact: reserved.artifact,
138
+ ...(writeComplete ? { reloadRequired: true } : {}),
139
+ });
140
+ }
141
+ }
142
+
143
+ export async function readJson(path) {
144
+ const text = path === "-" ? await readStdin() : await readFile(path, "utf8");
145
+ try {
146
+ return parseJsonOrArtifactJournal(text);
147
+ } catch {
148
+ throw new DatarcError("输入不是有效 JSON", "INVALID_JSON");
149
+ }
150
+ }
151
+
152
+ export function encodeArtifactRecord(
153
+ sequence,
154
+ payload,
155
+ { journalId, previousChecksum = null } = {},
156
+ ) {
157
+ if (typeof journalId !== "string" || !journalId)
158
+ throw new DatarcError(
159
+ "artifact journal id is required",
160
+ "INVALID_ARTIFACT",
161
+ );
162
+ const body = {
163
+ journal: ARTIFACT_JOURNAL,
164
+ journalId,
165
+ sequence,
166
+ previousChecksum,
167
+ payload,
168
+ };
169
+ const checksum = createHash("sha256")
170
+ .update(JSON.stringify(body))
171
+ .digest("hex");
172
+ return Buffer.from(`${JSON.stringify({ ...body, checksum })}\n`, "utf8");
173
+ }
174
+
175
+ export function validateArtifactPayloadTransition(previous, next, rootPlan) {
176
+ return validArtifactPayloadTransition(previous, next, rootPlan);
177
+ }
178
+
179
+ export function validateFinalBundle(bundle) {
180
+ return validFinalBundle(bundle);
181
+ }
182
+
183
+ export function validateRollbackBundle(bundle) {
184
+ return validRollbackBundle(bundle);
185
+ }
186
+
187
+ function parseJsonOrArtifactJournal(text) {
188
+ try {
189
+ const value = JSON.parse(text);
190
+ if (!isArtifactRecord(value)) return value;
191
+ if (
192
+ !validArtifactRecord(value, {
193
+ sequence: 0,
194
+ journalId: value.journalId,
195
+ previousChecksum: null,
196
+ }) ||
197
+ !validArtifactPayloadTransition(
198
+ undefined,
199
+ value.payload,
200
+ value.payload?.plan,
201
+ )
202
+ )
203
+ throw new Error("invalid artifact record");
204
+ return artifactPayloadReadValue(value.payload);
205
+ } catch (error) {
206
+ const journalValue = lastArtifactJournalValue(text);
207
+ if (journalValue.found) return artifactPayloadReadValue(journalValue.value);
208
+ throw error;
209
+ }
210
+ }
211
+
212
+ function lastArtifactJournalValue(text) {
213
+ let value;
214
+ let expectedSequence = 0;
215
+ let journalId;
216
+ let previousChecksum = null;
217
+ let rootPlan;
218
+ let found = false;
219
+ for (const line of text.split("\n")) {
220
+ if (!line) continue;
221
+ let record;
222
+ try {
223
+ record = JSON.parse(line);
224
+ } catch {
225
+ break;
226
+ }
227
+ if (
228
+ !validArtifactRecord(record, {
229
+ sequence: expectedSequence,
230
+ journalId: journalId ?? record.journalId,
231
+ previousChecksum,
232
+ }) ||
233
+ !validArtifactPayloadTransition(
234
+ value,
235
+ record.payload,
236
+ rootPlan ?? record.payload?.plan,
237
+ )
238
+ )
239
+ break;
240
+ value = record.payload;
241
+ journalId = record.journalId;
242
+ previousChecksum = record.checksum;
243
+ rootPlan ??= record.payload.plan;
244
+ expectedSequence += 1;
245
+ found = true;
246
+ }
247
+ return { found, value };
248
+ }
249
+
250
+ function isArtifactRecord(value) {
251
+ return (
252
+ value &&
253
+ typeof value === "object" &&
254
+ !Array.isArray(value) &&
255
+ value.journal === ARTIFACT_JOURNAL
256
+ );
257
+ }
258
+
259
+ function validArtifactRecord(
260
+ record,
261
+ { sequence, journalId, previousChecksum },
262
+ ) {
263
+ if (
264
+ !isArtifactRecord(record) ||
265
+ record.sequence !== sequence ||
266
+ typeof record.journalId !== "string" ||
267
+ !record.journalId ||
268
+ record.journalId !== journalId ||
269
+ record.previousChecksum !== previousChecksum ||
270
+ !Object.hasOwn(record, "payload") ||
271
+ typeof record.checksum !== "string"
272
+ )
273
+ return false;
274
+ const body = {
275
+ journal: record.journal,
276
+ journalId: record.journalId,
277
+ sequence: record.sequence,
278
+ previousChecksum: record.previousChecksum,
279
+ payload: record.payload,
280
+ };
281
+ return (
282
+ createHash("sha256").update(JSON.stringify(body)).digest("hex") ===
283
+ record.checksum
284
+ );
285
+ }
286
+
287
+ function validArtifactPayloadTransition(previous, next, rootPlan) {
288
+ if (isCommandArtifactPayload(previous) || isCommandArtifactPayload(next))
289
+ return validCommandArtifactPayloadTransition(previous, next);
290
+ return validApplyArtifactPayloadTransition(previous, next, rootPlan);
291
+ }
292
+
293
+ function validCommandArtifactPayloadTransition(previous, next) {
294
+ const nextState = commandArtifactPayloadState(next);
295
+ if (!nextState || !validCommandArtifactPayload(next)) return false;
296
+ if (previous === undefined) return nextState === "reserved";
297
+ const previousState = commandArtifactPayloadState(previous);
298
+ if (
299
+ !previousState ||
300
+ !validCommandArtifactPayload(previous) ||
301
+ !sameCommandArtifactIdentity(previous, next) ||
302
+ previousState === "completed"
303
+ )
304
+ return false;
305
+ if (previousState === "reserved") return nextState === "running";
306
+ return nextState === "running" || nextState === "completed";
307
+ }
308
+
309
+ function validApplyArtifactPayloadTransition(previous, next, rootPlan) {
310
+ const nextState = artifactPayloadState(next);
311
+ if (
312
+ !nextState ||
313
+ !validPlanIdentity(rootPlan) ||
314
+ !validPayloadIdentity(next) ||
315
+ (next.plan !== undefined && !sameCanonical(next.plan, rootPlan))
316
+ )
317
+ return false;
318
+ if (previous === undefined) return nextState === "reserved";
319
+ const previousState = artifactPayloadState(previous);
320
+ if (
321
+ !previousState ||
322
+ previousState === "final" ||
323
+ nextState === "reserved" ||
324
+ (previousState === "reserved" && nextState !== "applying") ||
325
+ artifactWorkspaceId(previous) !== artifactWorkspaceId(next) ||
326
+ artifactPlanHash(previous) !== artifactPlanHash(next)
327
+ )
328
+ return false;
329
+ if (nextState === "final" && next.receipt.pendingStep !== undefined)
330
+ return false;
331
+ if (
332
+ nextState === "final" &&
333
+ next.receipt.completedSteps.length !== rootPlan.steps.length
334
+ )
335
+ return false;
336
+ if (nextState === "final" && !validFinalBundle(next)) return false;
337
+ return (
338
+ validReceiptPlanBinding(next.receipt, rootPlan) &&
339
+ validReceiptLineage(previous.receipt, next.receipt)
340
+ );
341
+ }
342
+
343
+ function isCommandArtifactPayload(payload) {
344
+ return (
345
+ payload &&
346
+ typeof payload === "object" &&
347
+ !Array.isArray(payload) &&
348
+ payload.journalType === "command"
349
+ );
350
+ }
351
+
352
+ function commandArtifactPayloadState(payload) {
353
+ if (!isCommandArtifactPayload(payload)) return null;
354
+ return new Set(["reserved", "running", "completed"]).has(payload.status)
355
+ ? payload.status
356
+ : null;
357
+ }
358
+
359
+ function validCommandArtifactPayload(payload) {
360
+ const state = commandArtifactPayloadState(payload);
361
+ if (
362
+ !state ||
363
+ typeof payload.command !== "string" ||
364
+ !payload.command.trim() ||
365
+ typeof payload.inputHash !== "string" ||
366
+ !/^[a-f0-9]{64}$/u.test(payload.inputHash) ||
367
+ !Object.hasOwn(payload, "request") ||
368
+ !payload.request ||
369
+ typeof payload.request !== "object" ||
370
+ Array.isArray(payload.request) ||
371
+ (Object.hasOwn(payload, "workspaceId") &&
372
+ !validCommandWorkspaceId(payload.workspaceId))
373
+ )
374
+ return false;
375
+ if (state !== "completed")
376
+ return (
377
+ !Object.hasOwn(payload, "result") && !Object.hasOwn(payload, "resultHash")
378
+ );
379
+ return (
380
+ Object.hasOwn(payload, "result") &&
381
+ typeof payload.resultHash === "string" &&
382
+ /^[a-f0-9]{64}$/u.test(payload.resultHash) &&
383
+ payload.resultHash === hashArtifactValue(payload.result)
384
+ );
385
+ }
386
+
387
+ function validCommandWorkspaceId(value) {
388
+ return (
389
+ (typeof value === "string" && Boolean(value.trim())) ||
390
+ (typeof value === "number" && Number.isFinite(value))
391
+ );
392
+ }
393
+
394
+ function sameCommandArtifactIdentity(previous, next) {
395
+ return (
396
+ previous.command === next.command &&
397
+ previous.inputHash === next.inputHash &&
398
+ Object.hasOwn(previous, "workspaceId") ===
399
+ Object.hasOwn(next, "workspaceId") &&
400
+ previous.workspaceId === next.workspaceId &&
401
+ sameCanonical(previous.request, next.request)
402
+ );
403
+ }
404
+
405
+ function artifactPayloadReadValue(payload) {
406
+ return isCommandArtifactPayload(payload) && payload.status === "completed"
407
+ ? payload.result
408
+ : payload;
409
+ }
410
+
411
+ function validFinalBundle(bundle) {
412
+ if (!bundle || typeof bundle !== "object" || Array.isArray(bundle))
413
+ return false;
414
+ const plan = bundle.plan;
415
+ const receipt = bundle.receipt;
416
+ return Boolean(
417
+ !hasNonFinalMarker(bundle) &&
418
+ validFinalBaseline(bundle.baseline) &&
419
+ validTimestamp(bundle.mutationStartedAt) &&
420
+ validPlanIdentity(plan) &&
421
+ validReceiptShape(receipt) &&
422
+ !hasNonFinalMarker(receipt) &&
423
+ validEnvelopeHash(plan, "planHash") &&
424
+ validEnvelopeHash(receipt, "receiptHash") &&
425
+ plan.workspaceId === receipt.workspaceId &&
426
+ plan.planHash === receipt.planHash &&
427
+ receipt.pendingStep === undefined &&
428
+ receipt.completedSteps.length === plan.steps.length &&
429
+ receipt.completedSteps.every(
430
+ (step) => step.state === undefined && !hasNonFinalMarker(step),
431
+ ) &&
432
+ validReceiptPlanBinding(receipt, plan),
433
+ );
434
+ }
435
+
436
+ function validRollbackBundle(bundle) {
437
+ if (!bundle || typeof bundle !== "object" || Array.isArray(bundle))
438
+ return false;
439
+ const allowed = new Set([
440
+ "baseline",
441
+ "mutationStartedAt",
442
+ "plan",
443
+ "receipt",
444
+ "status",
445
+ ]);
446
+ if (
447
+ Object.keys(bundle).some((field) => !allowed.has(field)) ||
448
+ (bundle.status !== undefined && bundle.status !== "applying") ||
449
+ ["partial", "uncertain", "reloadRequired"].some((field) =>
450
+ Object.hasOwn(bundle, field),
451
+ ) ||
452
+ !validFinalBaseline(bundle.baseline) ||
453
+ !validTimestamp(bundle.mutationStartedAt)
454
+ )
455
+ return false;
456
+ const plan = bundle.plan;
457
+ const receipt = bundle.receipt;
458
+ return Boolean(
459
+ validPlanIdentity(plan) &&
460
+ validReceiptShape(receipt) &&
461
+ validEnvelopeHash(plan, "planHash") &&
462
+ validEnvelopeHash(receipt, "receiptHash") &&
463
+ plan.workspaceId === receipt.workspaceId &&
464
+ plan.planHash === receipt.planHash &&
465
+ !hasNonFinalMarker(receipt) &&
466
+ (bundle.status === "applying" ||
467
+ (receipt.pendingStep === undefined &&
468
+ receipt.completedSteps.length === plan.steps.length &&
469
+ receipt.completedSteps.every(
470
+ (step) => step.state === undefined && !hasNonFinalMarker(step),
471
+ ))) &&
472
+ validReceiptPlanBinding(receipt, plan),
473
+ );
474
+ }
475
+
476
+ function validFinalBaseline(baseline) {
477
+ return Boolean(
478
+ baseline &&
479
+ typeof baseline === "object" &&
480
+ !Array.isArray(baseline) &&
481
+ Array.isArray(baseline.baselineTaskUids) &&
482
+ validTimestamp(baseline.capturedAt),
483
+ );
484
+ }
485
+
486
+ function validTimestamp(value) {
487
+ return (
488
+ typeof value === "string" &&
489
+ value.trim() &&
490
+ Number.isFinite(Date.parse(value))
491
+ );
492
+ }
493
+
494
+ function hasNonFinalMarker(value) {
495
+ return ["status", "partial", "uncertain", "reloadRequired"].some((field) =>
496
+ Object.hasOwn(value ?? {}, field),
497
+ );
498
+ }
499
+
500
+ function validEnvelopeHash(value, field) {
501
+ if (typeof value?.[field] !== "string" || !value[field]) return false;
502
+ const body = structuredClone(value);
503
+ delete body[field];
504
+ return value[field] === hashArtifactValue(body);
505
+ }
506
+
507
+ function artifactPayloadState(payload) {
508
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
509
+ return null;
510
+ if (payload.status === "reserved") return "reserved";
511
+ if (payload.status === "applying") return "applying";
512
+ if (payload.status === undefined && payload.receipt) return "final";
513
+ return null;
514
+ }
515
+
516
+ function validPayloadIdentity(payload) {
517
+ const state = artifactPayloadState(payload);
518
+ const plan = payload.plan;
519
+ const receipt = payload.receipt;
520
+ if (state === "reserved")
521
+ return validPlanIdentity(plan) && receipt === undefined;
522
+ if (!validReceiptShape(receipt)) return false;
523
+ if (plan !== undefined && !validPlanIdentity(plan)) return false;
524
+ return (
525
+ (plan === undefined || plan.workspaceId === receipt.workspaceId) &&
526
+ (plan === undefined || plan.planHash === receipt.planHash)
527
+ );
528
+ }
529
+
530
+ function validPlanIdentity(plan) {
531
+ return (
532
+ plan &&
533
+ typeof plan === "object" &&
534
+ !Array.isArray(plan) &&
535
+ plan.workspaceId !== undefined &&
536
+ typeof plan.planHash === "string" &&
537
+ plan.planHash &&
538
+ Array.isArray(plan.steps)
539
+ );
540
+ }
541
+
542
+ function validReceiptShape(receipt) {
543
+ return (
544
+ receipt &&
545
+ typeof receipt === "object" &&
546
+ !Array.isArray(receipt) &&
547
+ receipt.workspaceId !== undefined &&
548
+ typeof receipt.planHash === "string" &&
549
+ receipt.planHash &&
550
+ Array.isArray(receipt.completedSteps) &&
551
+ !Object.hasOwn(receipt, "pendingSteps") &&
552
+ (receipt.pendingStep === undefined ||
553
+ (receipt.pendingStep &&
554
+ typeof receipt.pendingStep === "object" &&
555
+ !Array.isArray(receipt.pendingStep)))
556
+ );
557
+ }
558
+
559
+ function validReceiptPlanBinding(receipt, plan) {
560
+ if (receipt.completedSteps.length > plan.steps.length) return false;
561
+ if (
562
+ !receipt.completedSteps.every((step, index) =>
563
+ validBoundReceiptStep(step, plan.steps[index], index, false),
564
+ )
565
+ )
566
+ return false;
567
+ if (receipt.pendingStep === undefined) return true;
568
+ const pendingIndex = receipt.completedSteps.length;
569
+ return (
570
+ pendingIndex < plan.steps.length &&
571
+ validBoundReceiptStep(
572
+ receipt.pendingStep,
573
+ plan.steps[pendingIndex],
574
+ pendingIndex,
575
+ true,
576
+ )
577
+ );
578
+ }
579
+
580
+ function validBoundReceiptStep(actual, planned, index, pending) {
581
+ const generatedIdentity = hasResolvedGeneratedIdentity(actual, planned);
582
+ if (
583
+ !actual ||
584
+ !planned ||
585
+ actual.planStepIndex !== index ||
586
+ actual.planStepHash !== hashArtifactValue(planned) ||
587
+ !sameCanonical(stepStaticBody(actual), stepStaticBody(planned)) ||
588
+ !validRuntimeEndpoint(actual, planned)
589
+ )
590
+ return false;
591
+ const allowedStates = plannedPossibleStates(planned);
592
+ if (pending)
593
+ return (
594
+ actual.state === "uncertain" &&
595
+ actual.operation === planned.operation &&
596
+ actual.endpoint === planned.endpoint &&
597
+ sameCanonical(actual.after, planned.after) &&
598
+ sameCanonical(
599
+ actual.possibleAfter,
600
+ uniqueCanonicalStates(allowedStates),
601
+ ) &&
602
+ actual.identityResolved === (planned.before !== null) &&
603
+ actual.rollbackRecreate === undefined
604
+ );
605
+ if (actual.state === undefined)
606
+ return (
607
+ actual.operation === planned.operation &&
608
+ runtimeStateMatches(actual.after, planned.after, generatedIdentity) &&
609
+ actual.possibleAfter === undefined &&
610
+ actual.identityResolved === undefined &&
611
+ actual.rollbackRecreate === undefined
612
+ );
613
+ if (!new Set(["uncertain", "verified"]).has(actual.state)) return false;
614
+ if (
615
+ !validPartialOperation(actual, planned) ||
616
+ !allowedStates.some((state) =>
617
+ runtimeStateMatches(actual.after, state, generatedIdentity),
618
+ ) ||
619
+ !validPartialPossibleAfter(
620
+ actual.possibleAfter,
621
+ allowedStates,
622
+ generatedIdentity,
623
+ ) ||
624
+ !validPartialIdentity(actual, planned)
625
+ )
626
+ return false;
627
+ return (
628
+ actual.rollbackRecreate === undefined ||
629
+ (actual.rollbackRecreate === true && planned.operation === "REPLACE")
630
+ );
631
+ }
632
+
633
+ function stepStaticBody(step) {
634
+ const result = structuredClone(step);
635
+ for (const field of [
636
+ "after",
637
+ "endpoint",
638
+ "identityResolved",
639
+ "operation",
640
+ "planStepHash",
641
+ "planStepIndex",
642
+ "possibleAfter",
643
+ "rollbackRecreate",
644
+ "state",
645
+ ])
646
+ delete result[field];
647
+ return result;
648
+ }
649
+
650
+ function validRuntimeEndpoint(actual, planned) {
651
+ if (actual.endpoint === planned.endpoint) return true;
652
+ return hasResolvedGeneratedIdentity(actual, planned);
653
+ }
654
+
655
+ function hasResolvedGeneratedIdentity(actual, planned) {
656
+ if (!new Set(["POST", "REPLACE"]).has(planned.operation)) return false;
657
+ if (planned.after?.id !== undefined) return false;
658
+ const id = actual.after?.id;
659
+ if (
660
+ planned.kind === "semantic_calibration" &&
661
+ planned.operation === "POST" &&
662
+ planned.before !== null &&
663
+ id !== undefined &&
664
+ actual.endpoint === planned.endpoint
665
+ )
666
+ return true;
667
+ return (
668
+ id !== undefined &&
669
+ planned.endpoint.endsWith("/") &&
670
+ actual.endpoint === `${planned.endpoint}${id}/`
671
+ );
672
+ }
673
+
674
+ function validPartialOperation(actual, planned) {
675
+ return (
676
+ actual.operation === planned.operation ||
677
+ (planned.kind === "semantic_calibration" &&
678
+ planned.operation === "REPLACE" &&
679
+ actual.operation === "DELETE")
680
+ );
681
+ }
682
+
683
+ function validPartialIdentity(actual, planned) {
684
+ const expected =
685
+ planned.before !== null || actual.endpoint !== planned.endpoint;
686
+ if (actual.identityResolved === expected) return true;
687
+ return (
688
+ actual.identityResolved === false &&
689
+ planned.kind === "semantic_calibration" &&
690
+ planned.operation === "REPLACE" &&
691
+ actual.operation === "REPLACE" &&
692
+ actual.endpoint === planned.endpoint &&
693
+ actual.state === "uncertain" &&
694
+ actual.rollbackRecreate === true &&
695
+ sameCanonical(actual.after, planned.after) &&
696
+ sameCanonical(actual.possibleAfter, [null, withoutId(planned.after)])
697
+ );
698
+ }
699
+
700
+ function validPartialPossibleAfter(
701
+ actualStates,
702
+ allowedStates,
703
+ generatedIdentity,
704
+ ) {
705
+ if (!Array.isArray(actualStates) || actualStates.length === 0) return false;
706
+ let previousIndex = -1;
707
+ for (const actual of actualStates) {
708
+ const index = allowedStates.findIndex(
709
+ (allowed, candidateIndex) =>
710
+ candidateIndex > previousIndex &&
711
+ runtimeStateMatches(actual, allowed, generatedIdentity),
712
+ );
713
+ if (index === -1) return false;
714
+ previousIndex = index;
715
+ }
716
+ return true;
717
+ }
718
+
719
+ function plannedPossibleStates(step) {
720
+ if (step.kind === "semantic_calibration" && step.operation === "POST")
721
+ return step.before === null
722
+ ? [null, withoutId(step.after)]
723
+ : [withoutId(step.before), withoutId(step.after)];
724
+ if (step.operation === "REPLACE")
725
+ return [withoutId(step.before), null, withoutId(step.after)];
726
+ if (step.kind === "knowledge" && step.before === null && !step.after.active)
727
+ return [null, { ...step.after, active: true }, step.after];
728
+ return [step.before, step.after];
729
+ }
730
+
731
+ function uniqueCanonicalStates(states) {
732
+ const seen = new Set();
733
+ return states.filter((state) => {
734
+ const key = JSON.stringify(canonicalArtifactValue(state));
735
+ if (seen.has(key)) return false;
736
+ seen.add(key);
737
+ return true;
738
+ });
739
+ }
740
+
741
+ function runtimeStateMatches(actual, expected, generatedIdentity = false) {
742
+ if (actual === null || expected === null) return actual === expected;
743
+ if (
744
+ !actual ||
745
+ !expected ||
746
+ typeof actual !== "object" ||
747
+ typeof expected !== "object"
748
+ )
749
+ return sameCanonical(actual, expected);
750
+ const normalized = structuredClone(actual);
751
+ if (generatedIdentity && !Object.hasOwn(expected, "id")) delete normalized.id;
752
+ return sameCanonical(normalized, expected);
753
+ }
754
+
755
+ function artifactWorkspaceId(payload) {
756
+ return payload.receipt?.workspaceId ?? payload.plan?.workspaceId;
757
+ }
758
+
759
+ function artifactPlanHash(payload) {
760
+ return payload.receipt?.planHash ?? payload.plan?.planHash;
761
+ }
762
+
763
+ function validReceiptLineage(previous, next) {
764
+ if (!validReceiptShape(next)) return false;
765
+ if (previous === undefined) return next.completedSteps.length === 0;
766
+ if (!validReceiptShape(previous)) return false;
767
+ if (
768
+ next.completedSteps.length < previous.completedSteps.length ||
769
+ !previous.completedSteps.every((step, index) =>
770
+ sameCanonical(step, next.completedSteps[index]),
771
+ )
772
+ )
773
+ return false;
774
+ const growth = next.completedSteps.length - previous.completedSteps.length;
775
+ if (growth > 1) return false;
776
+ if (previous.pendingStep === undefined) return growth === 0;
777
+ if (growth === 0)
778
+ return (
779
+ next.pendingStep !== undefined &&
780
+ sameCanonical(previous.pendingStep, next.pendingStep)
781
+ );
782
+ return (
783
+ next.pendingStep === undefined &&
784
+ sameStepLineage(
785
+ previous.pendingStep,
786
+ next.completedSteps[next.completedSteps.length - 1],
787
+ )
788
+ );
789
+ }
790
+
791
+ function sameStepLineage(pending, completed) {
792
+ return (
793
+ pending?.planStepIndex === completed?.planStepIndex &&
794
+ pending?.planStepHash === completed?.planStepHash
795
+ );
796
+ }
797
+
798
+ async function syncArtifactDirectory(artifact, openDirectory) {
799
+ let handle;
800
+ try {
801
+ handle = await openDirectory(dirname(artifact), "r");
802
+ try {
803
+ await handle.sync();
804
+ } catch (error) {
805
+ // reserveArtifact has already completed its exclusive file write and fsync.
806
+ // Only the native Windows directory-fsync limitation may lose this extra
807
+ // directory-entry durability guarantee; all other I/O errors stay fatal.
808
+ if (
809
+ process.platform !== "win32" ||
810
+ openDirectory !== open ||
811
+ error?.code !== "EPERM" ||
812
+ error?.errno !== -4048 ||
813
+ error?.syscall !== "fsync" ||
814
+ !(await handle.stat()).isDirectory()
815
+ )
816
+ throw error;
817
+ if (!directorySyncWarningEmitted) {
818
+ directorySyncWarningEmitted = true;
819
+ process.emitWarning(
820
+ "Windows已同步工件文件,但不支持目录项fsync;目录项的断电持久性无法保证。请保留并核对工件,不要自动重放写入。",
821
+ { code: "DATARC_DIRECTORY_SYNC_UNAVAILABLE" },
822
+ );
823
+ }
824
+ }
825
+ } finally {
826
+ await handle?.close();
827
+ }
828
+ }
829
+
830
+ async function writeAll(handle, content, position) {
831
+ let offset = 0;
832
+ while (offset < content.length) {
833
+ const { bytesWritten } = await handle.write(
834
+ content,
835
+ offset,
836
+ content.length - offset,
837
+ position + offset,
838
+ );
839
+ if (
840
+ !Number.isInteger(bytesWritten) ||
841
+ bytesWritten <= 0 ||
842
+ bytesWritten > content.length - offset
843
+ )
844
+ throw new Error("artifact write made no progress");
845
+ offset += bytesWritten;
846
+ }
847
+ }
848
+
849
+ async function readStdin() {
850
+ const chunks = [];
851
+ for await (const chunk of process.stdin) chunks.push(chunk);
852
+ return Buffer.concat(chunks).toString("utf8");
853
+ }