@lightdash-tools/common 0.5.0 → 0.7.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 (94) hide show
  1. package/dist/agentops/extract-yaml-project.d.ts +7 -0
  2. package/dist/agentops/extract-yaml-project.js +42 -0
  3. package/dist/agentops/formatters.d.ts +5 -0
  4. package/dist/agentops/formatters.js +47 -0
  5. package/dist/agentops/snapshots.d.ts +32 -0
  6. package/dist/agentops/snapshots.js +34 -0
  7. package/dist/agentops/types.d.ts +224 -0
  8. package/dist/agentops/types.js +430 -0
  9. package/dist/argument-validation.d.ts +25 -0
  10. package/dist/argument-validation.js +199 -0
  11. package/dist/argument-validation.test.d.ts +1 -0
  12. package/dist/argument-validation.test.js +183 -0
  13. package/dist/audit.d.ts +9 -2
  14. package/dist/audit.js +17 -2
  15. package/dist/audit.test.d.ts +1 -0
  16. package/dist/audit.test.js +73 -0
  17. package/dist/env.d.ts +8 -0
  18. package/dist/env.js +9 -1
  19. package/dist/index.d.ts +7 -1
  20. package/dist/index.js +14 -0
  21. package/dist/input-validation.d.ts +35 -0
  22. package/dist/input-validation.js +87 -0
  23. package/dist/input-validation.test.js +93 -0
  24. package/dist/operations/agent-safe.d.ts +7 -0
  25. package/dist/operations/agent-safe.js +16 -0
  26. package/dist/operations/ai-agents.d.ts +6 -0
  27. package/dist/operations/ai-agents.js +411 -0
  28. package/dist/operations/index.d.ts +5 -0
  29. package/dist/operations/index.js +16 -0
  30. package/dist/operations/parity.test.d.ts +1 -0
  31. package/dist/operations/parity.test.js +28 -0
  32. package/dist/operations/registry.d.ts +10 -0
  33. package/dist/operations/registry.js +35 -0
  34. package/dist/operations/registry.test.d.ts +1 -0
  35. package/dist/operations/registry.test.js +196 -0
  36. package/dist/operations/types.d.ts +69 -0
  37. package/dist/operations/types.js +70 -0
  38. package/dist/operations/types.test.d.ts +1 -0
  39. package/dist/operations/types.test.js +104 -0
  40. package/dist/operations/users.d.ts +6 -0
  41. package/dist/operations/users.js +60 -0
  42. package/dist/safety.d.ts +27 -2
  43. package/dist/safety.js +52 -5
  44. package/dist/safety.test.js +217 -4
  45. package/dist/types/generated/openapi-types.d.ts +35895 -10622
  46. package/dist/types/generated/openapi-types.js +0 -1
  47. package/dist/types/lightdash-api.d.ts +1 -1
  48. package/dist/types/v1/ai-agents.d.ts +112 -3
  49. package/dist/types/v1/charts.d.ts +5 -3
  50. package/dist/types/v1/dashboards.d.ts +13 -0
  51. package/dist/types/v1/index.d.ts +45 -8
  52. package/dist/types/v1/index.js +1 -1
  53. package/dist/types/v1/lightdash-api.d.ts +107 -16
  54. package/dist/types/v1/users.d.ts +4 -0
  55. package/dist/types/v2/content.d.ts +2 -0
  56. package/dist/types/v2/content.js +8 -0
  57. package/dist/types/v2/index.d.ts +11 -9
  58. package/dist/types/v2/index.js +1 -1
  59. package/package.json +16 -3
  60. package/src/agentops/extract-yaml-project.ts +42 -0
  61. package/src/agentops/formatters.ts +52 -0
  62. package/src/agentops/snapshots.ts +56 -0
  63. package/src/agentops/types.ts +599 -0
  64. package/src/argument-validation.test.ts +270 -0
  65. package/src/argument-validation.ts +240 -0
  66. package/src/audit.test.ts +87 -0
  67. package/src/audit.ts +21 -3
  68. package/src/env.ts +9 -0
  69. package/src/index.test.ts +1 -0
  70. package/src/index.ts +16 -1
  71. package/src/input-validation.test.ts +157 -1
  72. package/src/input-validation.ts +95 -0
  73. package/src/operations/agent-safe.ts +18 -0
  74. package/src/operations/ai-agents.ts +451 -0
  75. package/src/operations/index.ts +19 -0
  76. package/src/operations/parity.test.ts +35 -0
  77. package/src/operations/registry.test.ts +219 -0
  78. package/src/operations/registry.ts +44 -0
  79. package/src/operations/types.test.ts +148 -0
  80. package/src/operations/types.ts +168 -0
  81. package/src/operations/users.ts +67 -0
  82. package/src/safety.test.ts +276 -4
  83. package/src/safety.ts +72 -4
  84. package/src/types/generated/openapi-types.ts +37017 -11241
  85. package/src/types/lightdash-api.ts +39 -0
  86. package/src/types/v1/ai-agents.ts +133 -3
  87. package/src/types/v1/charts.ts +5 -3
  88. package/src/types/v1/dashboards.ts +19 -0
  89. package/src/types/v1/index.ts +51 -8
  90. package/src/types/v1/lightdash-api.ts +129 -20
  91. package/src/types/v1/users.ts +4 -0
  92. package/src/types/v2/content.ts +8 -0
  93. package/src/types/v2/index.ts +11 -9
  94. package/tsconfig.json +1 -0
@@ -0,0 +1,430 @@
1
+ "use strict";
2
+ /**
3
+ * AgentOps bundle and evaluation gate YAML types (RFC Phase 2).
4
+ * Kubernetes-style documents with apiVersion, kind, metadata, and spec.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.GateExitCode = exports.lightdashAiEvaluationGateSchema = exports.gatePolicySchema = exports.lightdashAiAgentBundleSchema = void 0;
8
+ exports.parseDocumentYaml = parseDocumentYaml;
9
+ exports.parseLightdashAiAgentBundle = parseLightdashAiAgentBundle;
10
+ exports.parseLightdashAiEvaluationGate = parseLightdashAiEvaluationGate;
11
+ exports.normalizeEvaluationPrompt = normalizeEvaluationPrompt;
12
+ exports.computeBundleDiff = computeBundleDiff;
13
+ exports.detectBundleDrift = detectBundleDrift;
14
+ exports.getLightdashAiAgentBundleJsonSchema = getLightdashAiAgentBundleJsonSchema;
15
+ exports.getLightdashAiEvaluationGateJsonSchema = getLightdashAiEvaluationGateJsonSchema;
16
+ exports.evaluateGatePolicy = evaluateGatePolicy;
17
+ const yaml_1 = require("yaml");
18
+ const zod_1 = require("zod");
19
+ // ─── Shared metadata ─────────────────────────────────────────────────────────
20
+ const metadataSchema = zod_1.z.object({
21
+ name: zod_1.z.string().min(1),
22
+ labels: zod_1.z.record(zod_1.z.string(), zod_1.z.string()).optional(),
23
+ annotations: zod_1.z.record(zod_1.z.string(), zod_1.z.string()).optional(),
24
+ });
25
+ // ─── Bundle schemas ────────────────────────────────────────────────────────────
26
+ const bundleEvaluationPromptSchema = zod_1.z.union([
27
+ zod_1.z.object({
28
+ prompt: zod_1.z.string().min(1),
29
+ expectedResponse: zod_1.z.string().nullable().optional(),
30
+ }),
31
+ zod_1.z.object({
32
+ threadUuid: zod_1.z.string().uuid(),
33
+ promptUuid: zod_1.z.string().uuid(),
34
+ expectedResponse: zod_1.z.string().nullable().optional(),
35
+ }),
36
+ ]);
37
+ const bundleEvaluationSchema = zod_1.z.object({
38
+ key: zod_1.z.string().min(1),
39
+ uuid: zod_1.z.string().uuid().optional(),
40
+ title: zod_1.z.string().min(1),
41
+ description: zod_1.z.string().nullable().optional(),
42
+ prompts: zod_1.z.array(bundleEvaluationPromptSchema).min(1),
43
+ });
44
+ const bundleAgentSchema = zod_1.z.object({
45
+ key: zod_1.z.string().min(1),
46
+ uuid: zod_1.z.string().uuid().optional(),
47
+ name: zod_1.z.string().min(1),
48
+ description: zod_1.z.string().nullable().optional(),
49
+ instruction: zod_1.z.string().nullable().optional(),
50
+ tags: zod_1.z.array(zod_1.z.string()).nullable().optional(),
51
+ enableDataAccess: zod_1.z.boolean().optional(),
52
+ enableSelfImprovement: zod_1.z.boolean().optional(),
53
+ evaluations: zod_1.z.array(bundleEvaluationSchema).optional().default([]),
54
+ });
55
+ exports.lightdashAiAgentBundleSchema = zod_1.z.object({
56
+ apiVersion: zod_1.z.literal('lightdash.ai/v1alpha1'),
57
+ kind: zod_1.z.literal('LightdashAiAgentBundle'),
58
+ metadata: metadataSchema,
59
+ spec: zod_1.z.object({
60
+ projectUuid: zod_1.z.string().uuid(),
61
+ agents: zod_1.z.array(bundleAgentSchema).min(1),
62
+ }),
63
+ });
64
+ // ─── Gate schemas ──────────────────────────────────────────────────────────────
65
+ exports.gatePolicySchema = zod_1.z.object({
66
+ minPassRate: zod_1.z.number().min(0).max(1).optional(),
67
+ maxFailedAssessments: zod_1.z.number().int().min(0).optional(),
68
+ minPassedAssessments: zod_1.z.number().int().min(0).optional(),
69
+ requireAllPassed: zod_1.z.boolean().optional(),
70
+ });
71
+ exports.lightdashAiEvaluationGateSchema = zod_1.z.object({
72
+ apiVersion: zod_1.z.literal('lightdash.ai/v1alpha1'),
73
+ kind: zod_1.z.literal('LightdashAiEvaluationGate'),
74
+ metadata: metadataSchema,
75
+ spec: zod_1.z.object({
76
+ projectUuid: zod_1.z.string().uuid(),
77
+ agentUuid: zod_1.z.string().uuid(),
78
+ evaluationUuid: zod_1.z.string().uuid(),
79
+ policy: exports.gatePolicySchema,
80
+ runUuid: zod_1.z.string().uuid().optional(),
81
+ triggerRun: zod_1.z.boolean().optional().default(false),
82
+ }),
83
+ });
84
+ // ─── Gate exit codes (RFC Phase 2) ─────────────────────────────────────────────
85
+ exports.GateExitCode = {
86
+ PASSED: 0,
87
+ ERROR: 1,
88
+ INVALID: 2,
89
+ POLICY_FAILED: 3,
90
+ TIMEOUT: 4,
91
+ RUN_FAILED: 5,
92
+ RUN_IN_PROGRESS: 6,
93
+ };
94
+ // ─── Parsing & validation ──────────────────────────────────────────────────────
95
+ function formatZodError(error) {
96
+ return error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');
97
+ }
98
+ function parseDocumentYaml(content) {
99
+ const parsed = (0, yaml_1.parse)(content);
100
+ if (parsed === null || typeof parsed !== 'object') {
101
+ throw new Error('YAML document must be a mapping object');
102
+ }
103
+ return parsed;
104
+ }
105
+ function parseLightdashAiAgentBundle(content) {
106
+ const doc = parseDocumentYaml(content);
107
+ const result = exports.lightdashAiAgentBundleSchema.safeParse(doc);
108
+ if (!result.success) {
109
+ throw new Error(`Invalid LightdashAiAgentBundle: ${formatZodError(result.error)}`);
110
+ }
111
+ return result.data;
112
+ }
113
+ function parseLightdashAiEvaluationGate(content) {
114
+ const doc = parseDocumentYaml(content);
115
+ const result = exports.lightdashAiEvaluationGateSchema.safeParse(doc);
116
+ if (!result.success) {
117
+ throw new Error(`Invalid LightdashAiEvaluationGate: ${formatZodError(result.error)}`);
118
+ }
119
+ return result.data;
120
+ }
121
+ // ─── Prompt normalization ──────────────────────────────────────────────────────
122
+ function normalizeEvaluationPrompt(prompt) {
123
+ var _a, _b;
124
+ if ('prompt' in prompt) {
125
+ return {
126
+ type: 'string',
127
+ prompt: prompt.prompt,
128
+ expectedResponse: (_a = prompt.expectedResponse) !== null && _a !== void 0 ? _a : null,
129
+ };
130
+ }
131
+ return {
132
+ type: 'thread',
133
+ threadUuid: prompt.threadUuid,
134
+ promptUuid: prompt.promptUuid,
135
+ expectedResponse: (_b = prompt.expectedResponse) !== null && _b !== void 0 ? _b : null,
136
+ };
137
+ }
138
+ function promptsEqual(a, b) {
139
+ return JSON.stringify(a) === JSON.stringify(b);
140
+ }
141
+ function agentFieldsToCompare(agent) {
142
+ const fields = ['name', 'description', 'instruction', 'tags'];
143
+ if (agent.enableDataAccess !== undefined) {
144
+ fields.push('enableDataAccess');
145
+ }
146
+ if (agent.enableSelfImprovement !== undefined) {
147
+ fields.push('enableSelfImprovement');
148
+ }
149
+ return fields;
150
+ }
151
+ /** API defaults omitted bundle booleans to false when the bundle explicitly sets them. */
152
+ function normalizeAgentBooleanFlag(value) {
153
+ return value !== null && value !== void 0 ? value : false;
154
+ }
155
+ function normalizeTags(tags) {
156
+ if (tags == null || tags.length === 0) {
157
+ return null;
158
+ }
159
+ return tags;
160
+ }
161
+ function pickAgentFields(agent) {
162
+ return {
163
+ name: agent.name,
164
+ description: agent.description,
165
+ instruction: agent.instruction,
166
+ tags: normalizeTags(agent.tags),
167
+ enableDataAccess: normalizeAgentBooleanFlag(agent.enableDataAccess),
168
+ enableSelfImprovement: normalizeAgentBooleanFlag(agent.enableSelfImprovement),
169
+ };
170
+ }
171
+ function desiredAgentToSnapshot(agent, uuid) {
172
+ var _a, _b, _c;
173
+ return Object.assign(Object.assign({ uuid, name: agent.name, description: (_a = agent.description) !== null && _a !== void 0 ? _a : null, instruction: (_b = agent.instruction) !== null && _b !== void 0 ? _b : null, tags: normalizeTags((_c = agent.tags) !== null && _c !== void 0 ? _c : null) }, (agent.enableDataAccess !== undefined ? { enableDataAccess: agent.enableDataAccess } : {})), (agent.enableSelfImprovement !== undefined
174
+ ? { enableSelfImprovement: agent.enableSelfImprovement }
175
+ : {}));
176
+ }
177
+ function evaluationToSnapshot(evalSpec, evalUuid) {
178
+ var _a;
179
+ return {
180
+ evalUuid,
181
+ title: evalSpec.title,
182
+ description: (_a = evalSpec.description) !== null && _a !== void 0 ? _a : null,
183
+ prompts: evalSpec.prompts.map(normalizeEvaluationPrompt),
184
+ };
185
+ }
186
+ function findAgentMatch(desired, current) {
187
+ if (desired.uuid) {
188
+ const byUuid = current.agents.find((a) => a.agent.uuid === desired.uuid);
189
+ if (byUuid)
190
+ return byUuid;
191
+ }
192
+ return current.agents.find((a) => a.agent.name === desired.name);
193
+ }
194
+ function findEvaluationMatch(desired, evaluations) {
195
+ if (desired.uuid) {
196
+ const byUuid = evaluations.find((e) => e.evalUuid === desired.uuid);
197
+ if (byUuid)
198
+ return byUuid;
199
+ }
200
+ return evaluations.find((e) => e.title === desired.title);
201
+ }
202
+ // ─── Diff computation ──────────────────────────────────────────────────────────
203
+ function computeBundleDiff(bundle, current) {
204
+ const changes = [];
205
+ const matchedAgentUuids = new Set();
206
+ for (const desiredAgent of bundle.spec.agents) {
207
+ const match = findAgentMatch(desiredAgent, current);
208
+ const agentPath = `spec.agents.${desiredAgent.key}`;
209
+ if (!match) {
210
+ changes.push({
211
+ resourceType: 'agent',
212
+ operation: 'create',
213
+ key: desiredAgent.key,
214
+ path: agentPath,
215
+ });
216
+ for (const desiredEval of desiredAgent.evaluations) {
217
+ changes.push({
218
+ resourceType: 'evaluation',
219
+ operation: 'create',
220
+ key: desiredEval.key,
221
+ agentKey: desiredAgent.key,
222
+ path: `${agentPath}.evaluations.${desiredEval.key}`,
223
+ });
224
+ }
225
+ continue;
226
+ }
227
+ matchedAgentUuids.add(match.agent.uuid);
228
+ const agentUuid = match.agent.uuid;
229
+ const desiredSnapshot = desiredAgentToSnapshot(desiredAgent, agentUuid);
230
+ const fieldDiffs = {};
231
+ for (const field of agentFieldsToCompare(desiredAgent)) {
232
+ const fromVal = pickAgentFields(match.agent)[field];
233
+ const toVal = pickAgentFields(desiredSnapshot)[field];
234
+ if (JSON.stringify(fromVal) !== JSON.stringify(toVal)) {
235
+ fieldDiffs[field] = { from: fromVal, to: toVal };
236
+ }
237
+ }
238
+ if (Object.keys(fieldDiffs).length > 0) {
239
+ changes.push({
240
+ resourceType: 'agent',
241
+ operation: 'update',
242
+ key: desiredAgent.key,
243
+ agentUuid,
244
+ path: agentPath,
245
+ fields: fieldDiffs,
246
+ });
247
+ }
248
+ else {
249
+ changes.push({
250
+ resourceType: 'agent',
251
+ operation: 'noop',
252
+ key: desiredAgent.key,
253
+ agentUuid,
254
+ path: agentPath,
255
+ });
256
+ }
257
+ for (const desiredEval of desiredAgent.evaluations) {
258
+ const evalMatch = findEvaluationMatch(desiredEval, match.evaluations);
259
+ const evalPath = `${agentPath}.evaluations.${desiredEval.key}`;
260
+ if (!evalMatch) {
261
+ changes.push({
262
+ resourceType: 'evaluation',
263
+ operation: 'create',
264
+ key: desiredEval.key,
265
+ agentKey: desiredAgent.key,
266
+ agentUuid,
267
+ path: evalPath,
268
+ });
269
+ continue;
270
+ }
271
+ const desiredEvalSnapshot = evaluationToSnapshot(desiredEval, evalMatch.evalUuid);
272
+ const evalFieldDiffs = {};
273
+ if (evalMatch.title !== desiredEvalSnapshot.title) {
274
+ evalFieldDiffs.title = { from: evalMatch.title, to: desiredEvalSnapshot.title };
275
+ }
276
+ if (evalMatch.description !== desiredEvalSnapshot.description) {
277
+ evalFieldDiffs.description = {
278
+ from: evalMatch.description,
279
+ to: desiredEvalSnapshot.description,
280
+ };
281
+ }
282
+ if (!promptsEqual(evalMatch.prompts, desiredEvalSnapshot.prompts)) {
283
+ evalFieldDiffs.prompts = { from: evalMatch.prompts, to: desiredEvalSnapshot.prompts };
284
+ }
285
+ if (Object.keys(evalFieldDiffs).length > 0) {
286
+ changes.push({
287
+ resourceType: 'evaluation',
288
+ operation: 'update',
289
+ key: desiredEval.key,
290
+ agentKey: desiredAgent.key,
291
+ agentUuid,
292
+ evaluationUuid: evalMatch.evalUuid,
293
+ path: evalPath,
294
+ fields: evalFieldDiffs,
295
+ });
296
+ }
297
+ else {
298
+ changes.push({
299
+ resourceType: 'evaluation',
300
+ operation: 'noop',
301
+ key: desiredEval.key,
302
+ agentKey: desiredAgent.key,
303
+ agentUuid,
304
+ evaluationUuid: evalMatch.evalUuid,
305
+ path: evalPath,
306
+ });
307
+ }
308
+ }
309
+ for (const existingEval of match.evaluations) {
310
+ const isDesired = desiredAgent.evaluations.some((e) => (e.uuid != null && e.uuid === existingEval.evalUuid) || e.title === existingEval.title);
311
+ if (!isDesired) {
312
+ changes.push({
313
+ resourceType: 'evaluation',
314
+ operation: 'delete',
315
+ key: existingEval.evalUuid,
316
+ agentKey: desiredAgent.key,
317
+ agentUuid,
318
+ path: `${agentPath}.evaluations[${existingEval.evalUuid}]`,
319
+ });
320
+ }
321
+ }
322
+ }
323
+ for (const { agent, evaluations } of current.agents) {
324
+ const isDesired = bundle.spec.agents.some((a) => a.uuid === agent.uuid || a.name === agent.name);
325
+ if (!isDesired && !matchedAgentUuids.has(agent.uuid)) {
326
+ for (const evalItem of evaluations) {
327
+ changes.push({
328
+ resourceType: 'evaluation',
329
+ operation: 'delete',
330
+ key: evalItem.evalUuid,
331
+ agentUuid: agent.uuid,
332
+ path: `agents[${agent.uuid}].evaluations[${evalItem.evalUuid}]`,
333
+ });
334
+ }
335
+ changes.push({
336
+ resourceType: 'agent',
337
+ operation: 'delete',
338
+ key: agent.uuid,
339
+ path: `agents[${agent.uuid}]`,
340
+ });
341
+ }
342
+ }
343
+ const summary = {
344
+ creates: changes.filter((c) => c.operation === 'create').length,
345
+ updates: changes.filter((c) => c.operation === 'update').length,
346
+ deletes: changes.filter((c) => c.operation === 'delete').length,
347
+ noops: changes.filter((c) => c.operation === 'noop').length,
348
+ };
349
+ return {
350
+ bundleName: bundle.metadata.name,
351
+ projectUuid: bundle.spec.projectUuid,
352
+ changes,
353
+ hasDrift: summary.creates + summary.updates + summary.deletes > 0,
354
+ summary,
355
+ };
356
+ }
357
+ function detectBundleDrift(bundle, current) {
358
+ const diff = computeBundleDiff(bundle, current);
359
+ return { hasDrift: diff.hasDrift, diff };
360
+ }
361
+ // ─── Gate policy evaluation ────────────────────────────────────────────────────
362
+ function getLightdashAiAgentBundleJsonSchema() {
363
+ return zod_1.z.toJSONSchema(exports.lightdashAiAgentBundleSchema);
364
+ }
365
+ function getLightdashAiEvaluationGateJsonSchema() {
366
+ return zod_1.z.toJSONSchema(exports.lightdashAiEvaluationGateSchema);
367
+ }
368
+ function evaluateGatePolicy(policy, run) {
369
+ const reasons = [];
370
+ const totalAssessments = run.passedAssessments + run.failedAssessments;
371
+ const passRate = totalAssessments > 0 ? run.passedAssessments / totalAssessments : null;
372
+ if (run.status === 'failed') {
373
+ return {
374
+ exitCode: exports.GateExitCode.RUN_FAILED,
375
+ passed: false,
376
+ reasons: ['Evaluation run failed'],
377
+ metrics: {
378
+ passedAssessments: run.passedAssessments,
379
+ failedAssessments: run.failedAssessments,
380
+ totalAssessments,
381
+ passRate,
382
+ runStatus: run.status,
383
+ },
384
+ };
385
+ }
386
+ if (run.status === 'pending' || run.status === 'running') {
387
+ return {
388
+ exitCode: exports.GateExitCode.RUN_IN_PROGRESS,
389
+ passed: false,
390
+ reasons: [`Evaluation run is ${run.status}`],
391
+ metrics: {
392
+ passedAssessments: run.passedAssessments,
393
+ failedAssessments: run.failedAssessments,
394
+ totalAssessments,
395
+ passRate,
396
+ runStatus: run.status,
397
+ },
398
+ };
399
+ }
400
+ if (policy.minPassRate != null) {
401
+ if (passRate === null) {
402
+ reasons.push('minPassRate requires at least one assessment');
403
+ }
404
+ else if (passRate < policy.minPassRate) {
405
+ reasons.push(`pass rate ${passRate.toFixed(4)} < minPassRate ${policy.minPassRate}`);
406
+ }
407
+ }
408
+ if (policy.maxFailedAssessments != null && run.failedAssessments > policy.maxFailedAssessments) {
409
+ reasons.push(`failed assessments ${run.failedAssessments} > maxFailedAssessments ${policy.maxFailedAssessments}`);
410
+ }
411
+ if (policy.minPassedAssessments != null && run.passedAssessments < policy.minPassedAssessments) {
412
+ reasons.push(`passed assessments ${run.passedAssessments} < minPassedAssessments ${policy.minPassedAssessments}`);
413
+ }
414
+ if (policy.requireAllPassed === true && run.failedAssessments > 0) {
415
+ reasons.push(`requireAllPassed: ${run.failedAssessments} failed assessment(s)`);
416
+ }
417
+ const passed = reasons.length === 0;
418
+ return {
419
+ exitCode: passed ? exports.GateExitCode.PASSED : exports.GateExitCode.POLICY_FAILED,
420
+ passed,
421
+ reasons,
422
+ metrics: {
423
+ passedAssessments: run.passedAssessments,
424
+ failedAssessments: run.failedAssessments,
425
+ totalAssessments,
426
+ passRate,
427
+ runStatus: run.status,
428
+ },
429
+ };
430
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Descriptor-driven argument validation for CLI and MCP tools (RFC Phase 0).
3
+ * Validates known resource identifier keys with semantic type rules.
4
+ */
5
+ /** Object keys whose string values are treated as resource identifiers. */
6
+ export declare const RESOURCE_ID_KEYS: Set<string>;
7
+ export type ArgumentSource = 'body' | 'option' | 'positional';
8
+ export type ArgumentSemanticType = 'boolean' | 'fingerprint' | 'free-text' | 'json' | 'number' | 'slug' | 'uuid-or-slug' | 'uuid';
9
+ /** Per-argument validation metadata supplied by CLI/MCP command definitions. */
10
+ export interface ArgumentDescriptor {
11
+ name: string;
12
+ source: ArgumentSource;
13
+ semanticType: ArgumentSemanticType;
14
+ required?: boolean;
15
+ }
16
+ /**
17
+ * Validates tool arguments against explicit descriptors.
18
+ * Identifier semantic types (`uuid`, `slug`, `fingerprint`) receive strict validation.
19
+ */
20
+ export declare function validateArguments(args: Record<string, unknown>, descriptors: ArgumentDescriptor[]): void;
21
+ /**
22
+ * Recursively walks an object (and nested arrays/objects) and validates any
23
+ * string value under a key in {@link RESOURCE_ID_KEYS}.
24
+ */
25
+ export declare function validateResourceIdsInObject(obj: unknown): void;
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ /**
3
+ * Descriptor-driven argument validation for CLI and MCP tools (RFC Phase 0).
4
+ * Validates known resource identifier keys with semantic type rules.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.RESOURCE_ID_KEYS = void 0;
8
+ exports.validateArguments = validateArguments;
9
+ exports.validateResourceIdsInObject = validateResourceIdsInObject;
10
+ const input_validation_1 = require("./input-validation");
11
+ /** Object keys whose string values are treated as resource identifiers. */
12
+ exports.RESOURCE_ID_KEYS = new Set([
13
+ 'project',
14
+ 'projectUuid',
15
+ 'projectUuids',
16
+ 'projects',
17
+ 'agentUuid',
18
+ 'threadUuid',
19
+ 'messageUuid',
20
+ 'promptUuid',
21
+ 'evalUuid',
22
+ 'runUuid',
23
+ 'artifactUuid',
24
+ 'versionUuid',
25
+ 'mcpServerUuid',
26
+ 'toolCallId',
27
+ 'fingerprint',
28
+ 'savedQueryUuid',
29
+ 'slug',
30
+ 'userUuid',
31
+ 'groupUuid',
32
+ 'spaceUuid',
33
+ 'spaceUuids',
34
+ 'parentSpaceUuid',
35
+ 'roleUuid',
36
+ 'dashboardUuid',
37
+ 'schedulerUuid',
38
+ 'organizationUuid',
39
+ 'chartUuid',
40
+ ]);
41
+ /** Keys that accept OpenAPI UuidOrSlug (UUID or slug), not UUID-only. */
42
+ const UUID_OR_SLUG_KEYS = new Set(['dashboardUuid', 'chartUuid']);
43
+ function isMissing(value) {
44
+ return value === undefined || value === null;
45
+ }
46
+ function requireString(value, name, label) {
47
+ if (typeof value !== 'string') {
48
+ throw new Error(`Argument '${name}' must be a string ${label}`);
49
+ }
50
+ return value;
51
+ }
52
+ function validateUuidArgument(value, name) {
53
+ (0, input_validation_1.validateUuid)(requireString(value, name, 'UUID'));
54
+ }
55
+ function validateSlugArgument(value, name) {
56
+ (0, input_validation_1.validateSlug)(requireString(value, name, 'slug'));
57
+ }
58
+ function validateFingerprintArgument(value, name) {
59
+ (0, input_validation_1.validateFingerprint)(requireString(value, name, 'fingerprint'));
60
+ }
61
+ function validateFreeTextArgument(value, _name) {
62
+ if (typeof value === 'string') {
63
+ (0, input_validation_1.rejectControlChars)(value);
64
+ }
65
+ }
66
+ function validateJsonArgument(value, name) {
67
+ if (typeof value !== 'string') {
68
+ return;
69
+ }
70
+ (0, input_validation_1.rejectControlChars)(value);
71
+ try {
72
+ JSON.parse(value);
73
+ }
74
+ catch (_a) {
75
+ throw new Error(`Argument '${name}' must be valid JSON`);
76
+ }
77
+ }
78
+ function validateBooleanArgument(value, name) {
79
+ if (typeof value !== 'boolean') {
80
+ throw new Error(`Argument '${name}' must be a boolean`);
81
+ }
82
+ }
83
+ function validateNumberArgument(value, name) {
84
+ if (typeof value !== 'number' || Number.isNaN(value)) {
85
+ throw new Error(`Argument '${name}' must be a number`);
86
+ }
87
+ }
88
+ function validateUuidOrSlugArgument(value, name) {
89
+ (0, input_validation_1.validateUuidOrSlug)(requireString(value, name, 'UUID or slug'));
90
+ }
91
+ function validateBySemanticType(value, semanticType, name) {
92
+ switch (semanticType) {
93
+ case 'boolean':
94
+ validateBooleanArgument(value, name);
95
+ break;
96
+ case 'fingerprint':
97
+ validateFingerprintArgument(value, name);
98
+ break;
99
+ case 'free-text':
100
+ validateFreeTextArgument(value, name);
101
+ break;
102
+ case 'json':
103
+ validateJsonArgument(value, name);
104
+ break;
105
+ case 'number':
106
+ validateNumberArgument(value, name);
107
+ break;
108
+ case 'slug':
109
+ validateSlugArgument(value, name);
110
+ break;
111
+ case 'uuid':
112
+ validateUuidArgument(value, name);
113
+ break;
114
+ case 'uuid-or-slug':
115
+ validateUuidOrSlugArgument(value, name);
116
+ break;
117
+ default: {
118
+ const exhaustive = semanticType;
119
+ throw new Error(`Unknown semantic type: ${exhaustive}`);
120
+ }
121
+ }
122
+ }
123
+ function validateResourceIdValue(key, value) {
124
+ if (key === 'slug') {
125
+ (0, input_validation_1.validateSlug)(value);
126
+ return;
127
+ }
128
+ if (key === 'fingerprint' || key === 'toolCallId') {
129
+ (0, input_validation_1.validateFingerprint)(value);
130
+ return;
131
+ }
132
+ if (UUID_OR_SLUG_KEYS.has(key)) {
133
+ (0, input_validation_1.validateUuidOrSlug)(value);
134
+ return;
135
+ }
136
+ (0, input_validation_1.validateUuid)(value);
137
+ }
138
+ function validateResourceIdValues(key, value) {
139
+ if (typeof value === 'string') {
140
+ validateResourceIdValue(key, value);
141
+ return;
142
+ }
143
+ if (Array.isArray(value)) {
144
+ for (const item of value) {
145
+ if (typeof item !== 'string') {
146
+ throw new Error(`Argument '${key}' must be a string or string array`);
147
+ }
148
+ validateResourceIdValue(key, item);
149
+ }
150
+ }
151
+ }
152
+ /**
153
+ * Validates tool arguments against explicit descriptors.
154
+ * Identifier semantic types (`uuid`, `slug`, `fingerprint`) receive strict validation.
155
+ */
156
+ function validateArguments(args, descriptors) {
157
+ for (const descriptor of descriptors) {
158
+ const value = args[descriptor.name];
159
+ if (isMissing(value)) {
160
+ if (descriptor.required) {
161
+ throw new Error(`Required argument '${descriptor.name}' is missing`);
162
+ }
163
+ continue;
164
+ }
165
+ if (Array.isArray(value)) {
166
+ for (const item of value) {
167
+ validateBySemanticType(item, descriptor.semanticType, descriptor.name);
168
+ }
169
+ }
170
+ else {
171
+ validateBySemanticType(value, descriptor.semanticType, descriptor.name);
172
+ }
173
+ }
174
+ }
175
+ /**
176
+ * Recursively walks an object (and nested arrays/objects) and validates any
177
+ * string value under a key in {@link RESOURCE_ID_KEYS}.
178
+ */
179
+ function validateResourceIdsInObject(obj) {
180
+ if (obj === null || obj === undefined) {
181
+ return;
182
+ }
183
+ if (Array.isArray(obj)) {
184
+ for (const item of obj) {
185
+ validateResourceIdsInObject(item);
186
+ }
187
+ return;
188
+ }
189
+ if (typeof obj !== 'object') {
190
+ return;
191
+ }
192
+ const record = obj;
193
+ for (const [key, value] of Object.entries(record)) {
194
+ if (exports.RESOURCE_ID_KEYS.has(key)) {
195
+ validateResourceIdValues(key, value);
196
+ }
197
+ validateResourceIdsInObject(value);
198
+ }
199
+ }
@@ -0,0 +1 @@
1
+ export {};