@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.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 (135) hide show
  1. package/README.md +20 -2
  2. package/cordis.patch.yml +4 -0
  3. package/icon.svg +4 -0
  4. package/index.js +35 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +37 -4
  8. package/skills/datarc-access-permissions/SKILL.md +30 -0
  9. package/skills/datarc-access-permissions/references/api.md +31 -0
  10. package/skills/datarc-access-permissions/references/write-order.md +16 -0
  11. package/skills/datarc-analysis-report/SKILL.md +125 -0
  12. package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
  13. package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  14. package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
  15. package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  16. package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  17. package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  18. package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
  19. package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
  20. package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
  21. package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  22. package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  23. package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  24. package/skills/datarc-data-search/SKILL.md +243 -0
  25. package/skills/datarc-data-search/scripts/calculate.py +116 -0
  26. package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
  27. package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
  28. package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
  29. package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  30. package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  31. package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  32. package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  33. package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  34. package/skills/datarc-dataseek-search/SKILL.md +96 -0
  35. package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  36. package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  37. package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  38. package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  39. package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  40. package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  41. package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  42. package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  43. package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  44. package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  45. package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  46. package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  47. package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
  48. package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  49. package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  50. package/skills/datarc-datasource/SKILL.md +97 -0
  51. package/skills/datarc-oauth/SKILL.md +47 -0
  52. package/skills/datarc-oauth/scripts/auth.mjs +130 -0
  53. package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
  54. package/skills/datarc-report-add-card/SKILL.md +90 -0
  55. package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
  56. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  57. package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
  58. package/skills/datarc-semantic-alias/SKILL.md +20 -0
  59. package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  60. package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
  61. package/skills/datarc-semantic-calibration/SKILL.md +20 -0
  62. package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  63. package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  64. package/skills/datarc-semantic-core/SKILL.md +12 -0
  65. package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
  66. package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
  67. package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
  68. package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
  69. package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  70. package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  71. package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
  72. package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  73. package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  74. package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  75. package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
  76. package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
  77. package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
  78. package/skills/datarc-semantic-dataset/SKILL.md +20 -0
  79. package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  80. package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  81. package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  82. package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
  83. package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  84. package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  85. package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  86. package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  87. package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  88. package/skills/datarc-semantic-prompt/SKILL.md +20 -0
  89. package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
  90. package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  91. package/skills/datarc-semantic-synonym/SKILL.md +20 -0
  92. package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  93. package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  94. package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
  95. package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  96. package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  97. package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  98. package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  99. package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  100. package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
  101. package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  102. package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  103. package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  104. package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  105. package/skills/datarc-workspace-configuration/SKILL.md +59 -0
  106. package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
  107. package/skills/datarc-workspace-configuration/references/verification.md +20 -0
  108. package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
  109. package/skills/datarc-workspace-context/SKILL.md +43 -0
  110. package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
  111. package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  112. package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
  113. package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  114. package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
  115. package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  116. package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  117. package/skills/datarc-workspace-keywords/SKILL.md +197 -0
  118. package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
  119. package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
  120. package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
  121. package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  122. package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  123. package/skills/datarc-workspace-membership/SKILL.md +29 -0
  124. package/skills/datarc-workspace-membership/references/api.md +19 -0
  125. package/skills/datarc-workspace-modeling/SKILL.md +209 -0
  126. package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
  127. package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
  128. package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
  129. package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
  130. package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  131. package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  132. package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  133. package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  134. package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  135. package/skills-index.json +194 -0
@@ -0,0 +1,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
+
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
+ }