@fabricorg/experiments 0.11.1 → 0.13.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.
package/dist/bin/fx.js CHANGED
@@ -4,12 +4,12 @@ import { resolve, join, basename, dirname, extname } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { mkdir, writeFile, readFile, copyFile, access, readdir, stat, rename, chmod, unlink } from 'fs/promises';
6
6
  import { parse, stringify } from 'yaml';
7
- import { randomUUID, webcrypto, createHash } from 'crypto';
7
+ import { randomUUID, webcrypto, randomBytes, createHash } from 'crypto';
8
8
  import { createServer } from 'http';
9
9
  import { createRequire } from 'module';
10
10
  import { createTargetPackRegistry, builtinTargetPacks, doctorTargetPack, runTargetPack, createWorkspaceContext, deleteEphemeralLakebaseBranch, createEphemeralLakebaseBranch, toLakebaseBranchId } from '@fabricorg/databricks-testkit';
11
11
  import { XMLParser } from 'fast-xml-parser';
12
- import { execFile } from 'child_process';
12
+ import { execFile, spawn } from 'child_process';
13
13
  import { homedir } from 'os';
14
14
  import { promisify } from 'util';
15
15
  import { stdin, stderr } from 'process';
@@ -20,6 +20,10 @@ var __export = (target, all) => {
20
20
  __defProp(target, name, { get: all[name], enumerable: true });
21
21
  };
22
22
 
23
+ // package.json
24
+ var package_default = {
25
+ version: "0.13.0"};
26
+
23
27
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
24
28
  var external_exports = {};
25
29
  __export(external_exports, {
@@ -4302,26 +4306,55 @@ var ExperimentSpecBase = external_exports.object({
4302
4306
  isGuardrail: external_exports.boolean().optional()
4303
4307
  })
4304
4308
  ).optional()
4305
- });
4306
- var ExperimentSpec = ExperimentSpecBase.refine(
4307
- (s) => s.holdback === void 0 || s.sampleRate === void 0,
4308
- { message: "Use either `sampleRate` or `holdback`, not both.", path: ["holdback"] }
4309
- ).refine((s) => s.divertTo === void 0 || s.variants.some((v) => v.key === s.divertTo), {
4310
- message: "`divertTo` must reference an existing variant key.",
4311
- path: ["divertTo"]
4312
- }).refine(
4313
- (s) => {
4314
- const withWeight = s.variants.filter((v) => v.weight !== void 0);
4315
- if (withWeight.length === 0) return true;
4316
- if (withWeight.length !== s.variants.length) return false;
4317
- const sum = withWeight.reduce((acc, v) => acc + (v.weight ?? 0), 0);
4318
- return sum === 1e4;
4319
- },
4320
- {
4321
- message: "When variant weights are set, all variants must have weights summing to 10000.",
4322
- path: ["variants"]
4309
+ }).strict();
4310
+ function validateExperimentSpec(spec, ctx) {
4311
+ if (spec.holdback !== void 0 && spec.sampleRate !== void 0) {
4312
+ ctx.addIssue({
4313
+ code: external_exports.ZodIssueCode.custom,
4314
+ message: "Use either `sampleRate` or `holdback`, not both.",
4315
+ path: ["holdback"]
4316
+ });
4323
4317
  }
4324
- );
4318
+ const variantKeys = spec.variants.map((variant) => variant.key);
4319
+ if (new Set(variantKeys).size !== variantKeys.length) {
4320
+ ctx.addIssue({
4321
+ code: external_exports.ZodIssueCode.custom,
4322
+ message: "Variant keys must be unique.",
4323
+ path: ["variants"]
4324
+ });
4325
+ }
4326
+ if (spec.divertTo !== void 0 && !variantKeys.includes(spec.divertTo)) {
4327
+ ctx.addIssue({
4328
+ code: external_exports.ZodIssueCode.custom,
4329
+ message: "divertTo must reference an existing variant key.",
4330
+ path: ["divertTo"]
4331
+ });
4332
+ }
4333
+ const withWeight = spec.variants.filter((variant) => variant.weight !== void 0);
4334
+ if (withWeight.length > 0 && (withWeight.length !== spec.variants.length || withWeight.reduce((sum, variant) => sum + (variant.weight ?? 0), 0) !== 1e4)) {
4335
+ ctx.addIssue({
4336
+ code: external_exports.ZodIssueCode.custom,
4337
+ message: "Variant weights must sum to 10000 and be declared for every variant.",
4338
+ path: ["variants"]
4339
+ });
4340
+ }
4341
+ const metricKeys = (spec.metrics ?? []).map((metric) => metric.key);
4342
+ if (new Set(metricKeys).size !== metricKeys.length) {
4343
+ ctx.addIssue({
4344
+ code: external_exports.ZodIssueCode.custom,
4345
+ message: "Metric keys must be unique.",
4346
+ path: ["metrics"]
4347
+ });
4348
+ }
4349
+ if (spec.environmentIds && new Set(spec.environmentIds).size !== spec.environmentIds.length) {
4350
+ ctx.addIssue({
4351
+ code: external_exports.ZodIssueCode.custom,
4352
+ message: "Environment IDs must be unique.",
4353
+ path: ["environmentIds"]
4354
+ });
4355
+ }
4356
+ }
4357
+ var ExperimentSpec = ExperimentSpecBase.superRefine(validateExperimentSpec);
4325
4358
  external_exports.object({
4326
4359
  experimentId: ExperimentId,
4327
4360
  subjectId: external_exports.string().min(1),
@@ -4503,6 +4536,7 @@ var ActionId = external_exports.enum([
4503
4536
  "experiment.resume",
4504
4537
  "experiment.kill",
4505
4538
  "experiment.declare_winner",
4539
+ "experiment.archive",
4506
4540
  "experiment.update",
4507
4541
  "experiment.guardrail_breach",
4508
4542
  "experiment.workspace_resource_upsert",
@@ -4512,7 +4546,7 @@ var ActionId = external_exports.enum([
4512
4546
  var CreateExperimentInput = ExperimentSpecBase.extend({
4513
4547
  ownerId: external_exports.string().min(1),
4514
4548
  tenantId: external_exports.string().min(1).default("default")
4515
- });
4549
+ }).superRefine(validateExperimentSpec);
4516
4550
  var ExperimentRef = external_exports.object({
4517
4551
  experimentId: ExperimentId,
4518
4552
  tenantId: external_exports.string().min(1).default("default")
@@ -4534,6 +4568,7 @@ var DeclareWinnerInput = ExperimentRef.extend({
4534
4568
  winningVariant: VariantKey,
4535
4569
  justification: external_exports.string().min(1).max(2e3)
4536
4570
  });
4571
+ var ArchiveInput = ExperimentRef;
4537
4572
  var UpdateExperimentInput = ExperimentRef.extend({
4538
4573
  spec: ExperimentSpec
4539
4574
  });
@@ -5186,7 +5221,9 @@ var experimentStateMachine = {
5186
5221
  { from: "paused", to: "running", causedByAction: "experiment.resume" },
5187
5222
  { from: "running", to: "killed", causedByAction: "experiment.kill" },
5188
5223
  { from: "paused", to: "killed", causedByAction: "experiment.kill" },
5189
- { from: "running", to: "concluded", causedByAction: "experiment.declare_winner" }
5224
+ { from: "running", to: "concluded", causedByAction: "experiment.declare_winner" },
5225
+ { from: "killed", to: "archived", causedByAction: "experiment.archive" },
5226
+ { from: "concluded", to: "archived", causedByAction: "experiment.archive" }
5190
5227
  ]
5191
5228
  };
5192
5229
  var separationOfDuties = {
@@ -5244,7 +5281,7 @@ async function executeGovernedExperimentAction(definition, parameters, ctx) {
5244
5281
  for (const policyId of definition.policies ?? []) {
5245
5282
  const policy = policiesById.get(policyId);
5246
5283
  if (!policy) {
5247
- return { success: false, error: `Required policy is not registered: ${policyId}` };
5284
+ return failure(`Required policy is not registered: ${policyId}`, "INTERNAL");
5248
5285
  }
5249
5286
  policyOutcomes.push(
5250
5287
  await policy.evaluate({
@@ -5266,10 +5303,10 @@ async function executeGovernedExperimentAction(definition, parameters, ctx) {
5266
5303
  });
5267
5304
  const blocked = policyOutcomes.find((policy) => policy.result === "block");
5268
5305
  if (blocked) {
5269
- return {
5270
- success: false,
5271
- error: `Policy ${blocked.policyId} blocked ${definition.actionId}: ${blocked.reason ?? "denied"}`
5272
- };
5306
+ return failure(
5307
+ `Policy ${blocked.policyId} blocked ${definition.actionId}: ${blocked.reason ?? "denied"}`,
5308
+ "POLICY_DENIED"
5309
+ );
5273
5310
  }
5274
5311
  }
5275
5312
  if (definition.stateMachine) {
@@ -5279,11 +5316,11 @@ async function executeGovernedExperimentAction(definition, parameters, ctx) {
5279
5316
  actionId: definition.actionId,
5280
5317
  error: transitionError
5281
5318
  });
5282
- return { success: false, error: transitionError };
5319
+ return failure(transitionError, "ILLEGAL_TRANSITION");
5283
5320
  }
5284
5321
  }
5285
5322
  if (!definition.handler) {
5286
- return { success: false, error: `Action ${definition.actionId} has no handler` };
5323
+ return failure(`Action ${definition.actionId} has no handler`, "INTERNAL");
5287
5324
  }
5288
5325
  return definition.handler(ctx, parameters);
5289
5326
  }
@@ -5292,9 +5329,7 @@ async function validateCurrentTransition(definition, parameters, ctx) {
5292
5329
  if (!binding) return null;
5293
5330
  const entityId = binding.getEntityId(parameters);
5294
5331
  if (!entityId) return `Action ${definition.actionId} did not identify an experiment`;
5295
- const params = actionParams({ parameters });
5296
- const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
5297
- const experiment = await ctx.db.store.getExperiment(tenantId, entityId);
5332
+ const experiment = await ctx.db.store.getExperiment(ctx.tenantId, entityId);
5298
5333
  if (!experiment) return null;
5299
5334
  const target = typeof binding.targetState === "function" ? binding.targetState(parameters) : binding.targetState;
5300
5335
  const valid = experimentStateMachine.transitions.some(
@@ -5304,8 +5339,7 @@ async function validateCurrentTransition(definition, parameters, ctx) {
5304
5339
  }
5305
5340
  async function findExperiment(ctx, params) {
5306
5341
  if (typeof params.experimentId !== "string") return null;
5307
- const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
5308
- return ctx.db.store.getExperiment(tenantId, params.experimentId);
5342
+ return ctx.db.store.getExperiment(ctx.tenantId, params.experimentId);
5309
5343
  }
5310
5344
  function actionParams(ctx) {
5311
5345
  return isRecord(ctx.parameters) ? ctx.parameters : {};
@@ -5324,7 +5358,7 @@ async function appendGovernanceEvent(ctx, parameters, type, payload) {
5324
5358
  await ctx.db.store.appendEvent({
5325
5359
  id: randomUUID(),
5326
5360
  type,
5327
- tenantId: typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId,
5361
+ tenantId: ctx.tenantId,
5328
5362
  experimentId: typeof params.experimentId === "string" ? params.experimentId : "*",
5329
5363
  actorId: ctx.actorId,
5330
5364
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5339,6 +5373,31 @@ async function appendGovernanceEvent(ctx, parameters, type, payload) {
5339
5373
  function isRecord(value) {
5340
5374
  return value !== null && typeof value === "object" && !Array.isArray(value);
5341
5375
  }
5376
+ function failure(error, code) {
5377
+ return { success: false, error, code };
5378
+ }
5379
+ function bindTrustedActionParameters(actionId, parameters, context) {
5380
+ if (!isRecord2(parameters)) return parameters;
5381
+ const bound = { ...parameters, tenantId: context.tenantId };
5382
+ switch (actionId) {
5383
+ case "experiment.create":
5384
+ bound.ownerId = context.actorId;
5385
+ break;
5386
+ case "experiment.approve":
5387
+ bound.approverId = context.actorId;
5388
+ break;
5389
+ case "experiment.environment_publish":
5390
+ bound.publishedBy = context.actorId;
5391
+ break;
5392
+ case "experiment.environment_promote":
5393
+ bound.promotedBy = context.actorId;
5394
+ break;
5395
+ }
5396
+ return bound;
5397
+ }
5398
+ function isRecord2(value) {
5399
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5400
+ }
5342
5401
  var Invoker = class {
5343
5402
  constructor(services) {
5344
5403
  this.services = services;
@@ -5359,32 +5418,48 @@ var Invoker = class {
5359
5418
  async invoke(actionId, params, options = {}) {
5360
5419
  const def = this.registry.get(actionId);
5361
5420
  if (!def) {
5362
- return { success: false, error: `Unknown action: ${actionId}` };
5421
+ return failure2(`Unknown action: ${actionId}`, "NOT_FOUND");
5363
5422
  }
5364
5423
  const parsed = def.schema.safeParse(params);
5365
5424
  if (!parsed.success) {
5366
- return {
5367
- success: false,
5368
- error: `Validation failed: ${JSON.stringify(parsed.error.issues)}`
5369
- };
5425
+ return failure2(
5426
+ `Validation failed: ${JSON.stringify(parsed.error.issues)}`,
5427
+ "VALIDATION_FAILED"
5428
+ );
5370
5429
  }
5371
5430
  const ctx = {
5372
5431
  actionInvocationId: (this.services.uuid ?? randomUUID)(),
5373
- tenantId: options.tenantId ?? "default",
5432
+ tenantId: options.tenantId ?? stringField(parsed.data, "tenantId") ?? "default",
5374
5433
  spaceId: options.spaceId ?? "default",
5375
- actorId: options.actorId ?? "system",
5434
+ actorId: options.actorId ?? serializedActorId(actionId, parsed.data) ?? "system",
5376
5435
  actorType: options.actorType ?? "system",
5377
5436
  correlationId: options.correlationId ?? (this.services.uuid ?? randomUUID)(),
5378
5437
  db: this.services
5379
5438
  };
5380
5439
  try {
5381
- return await executeGovernedExperimentAction(def, parsed.data, ctx);
5440
+ const trustedParameters = bindTrustedActionParameters(actionId, parsed.data, ctx);
5441
+ return await executeGovernedExperimentAction(def, trustedParameters, ctx);
5382
5442
  } catch (e) {
5383
5443
  const err = e;
5384
- return { success: false, error: err.message ?? String(e) };
5444
+ return failure2(err.message ?? String(e), err.code ?? "INTERNAL");
5385
5445
  }
5386
5446
  }
5387
5447
  };
5448
+ function failure2(error, code) {
5449
+ return { success: false, error, code };
5450
+ }
5451
+ function serializedActorId(actionId, parameters) {
5452
+ if (actionId === "experiment.create") return stringField(parameters, "ownerId");
5453
+ if (actionId === "experiment.approve") return stringField(parameters, "approverId");
5454
+ if (actionId === "experiment.environment_publish") return stringField(parameters, "publishedBy");
5455
+ if (actionId === "experiment.environment_promote") return stringField(parameters, "promotedBy");
5456
+ return void 0;
5457
+ }
5458
+ function stringField(value, key) {
5459
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
5460
+ const field = value[key];
5461
+ return typeof field === "string" && field.length > 0 ? field : void 0;
5462
+ }
5388
5463
  function requireResourceStore(store) {
5389
5464
  if (!store.getResource || !store.listResources || !store.putResource) {
5390
5465
  throw new Error("Control-plane store does not support workspace resources");
@@ -5406,13 +5481,13 @@ var upsertWorkspaceResource = {
5406
5481
  mutatesDomain: true,
5407
5482
  async handler(ctx, params) {
5408
5483
  const input = UpsertWorkspaceResourceInput.parse(params);
5409
- const resource = WorkspaceResource.parse({ ...input.resource, tenantId: input.tenantId });
5484
+ const resource = WorkspaceResource.parse({ ...input.resource, tenantId: ctx.tenantId });
5410
5485
  const store = requireResourceStore(ctx.db.store);
5411
5486
  await store.put(resource);
5412
5487
  await ctx.db.store.appendEvent({
5413
5488
  id: randomUUID(),
5414
5489
  type: "workspace_resource.upserted",
5415
- tenantId: input.tenantId,
5490
+ tenantId: ctx.tenantId,
5416
5491
  experimentId: `workspace:${resource.kind}:${resource.id}`,
5417
5492
  actorId: ctx.actorId,
5418
5493
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5441,26 +5516,26 @@ var publishEnvironment = {
5441
5516
  if (!store.nextVersion)
5442
5517
  throw new Error("Control-plane store does not support resource versions");
5443
5518
  const environment = Environment.parse(
5444
- await store.get(input.tenantId, "environment", input.environmentId)
5519
+ await store.get(ctx.tenantId, "environment", input.environmentId)
5445
5520
  );
5446
- const features = (await store.list(input.tenantId, "feature")).filter((resource) => resource.kind === "feature").filter((feature) => feature.projectId === environment.projectId && !feature.archived);
5521
+ const features = (await store.list(ctx.tenantId, "feature")).filter((resource) => resource.kind === "feature").filter((feature) => feature.projectId === environment.projectId && !feature.archived);
5447
5522
  const featureIds = new Set(features.map((feature) => feature.id));
5448
- const rules = (await store.list(input.tenantId, "rule")).filter((resource) => resource.kind === "rule").filter(
5523
+ const rules = (await store.list(ctx.tenantId, "rule")).filter((resource) => resource.kind === "rule").filter(
5449
5524
  (rule) => rule.environmentId === environment.id && featureIds.has(rule.featureId) && rule.enabled
5450
5525
  ).sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
5451
5526
  const snapshot = { features, rules };
5452
5527
  const resourceHash = createHash("sha256").update(stableJson(snapshot)).digest("hex");
5453
- const version = await store.nextVersion(input.tenantId, `environment:${environment.id}`);
5528
+ const version = await store.nextVersion(ctx.tenantId, `environment:${environment.id}`);
5454
5529
  const publication = {
5455
5530
  id: randomUUID(),
5456
5531
  kind: "publication",
5457
- tenantId: input.tenantId,
5532
+ tenantId: ctx.tenantId,
5458
5533
  environmentId: environment.id,
5459
5534
  version,
5460
5535
  status: "published",
5461
5536
  resourceHash,
5462
- manifestVersion: await ctx.db.store.currentManifestVersion(input.tenantId),
5463
- publishedBy: input.publishedBy,
5537
+ manifestVersion: await ctx.db.store.currentManifestVersion(ctx.tenantId),
5538
+ publishedBy: ctx.actorId,
5464
5539
  publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
5465
5540
  snapshot
5466
5541
  };
@@ -5468,7 +5543,7 @@ var publishEnvironment = {
5468
5543
  await ctx.db.store.appendEvent({
5469
5544
  id: randomUUID(),
5470
5545
  type: "environment.published",
5471
- tenantId: input.tenantId,
5546
+ tenantId: ctx.tenantId,
5472
5547
  experimentId: `workspace:environment:${environment.id}`,
5473
5548
  actorId: ctx.actorId,
5474
5549
  at: publication.publishedAt,
@@ -5498,10 +5573,10 @@ var promoteEnvironment = {
5498
5573
  const input = PromoteEnvironmentInput.parse(params);
5499
5574
  const store = requireResourceStore(ctx.db.store);
5500
5575
  const source = Environment.parse(
5501
- await store.get(input.tenantId, "environment", input.sourceEnvironmentId)
5576
+ await store.get(ctx.tenantId, "environment", input.sourceEnvironmentId)
5502
5577
  );
5503
5578
  const target = Environment.parse(
5504
- await store.get(input.tenantId, "environment", input.targetEnvironmentId)
5579
+ await store.get(ctx.tenantId, "environment", input.targetEnvironmentId)
5505
5580
  );
5506
5581
  if (source.projectId !== target.projectId) {
5507
5582
  throw new Error("Source and target environments must belong to the same project");
@@ -5509,12 +5584,12 @@ var promoteEnvironment = {
5509
5584
  if (target.rank <= source.rank) {
5510
5585
  throw new Error("Promotions must move to a higher-ranked environment");
5511
5586
  }
5512
- const publications = (await store.list(input.tenantId, "publication")).filter(
5587
+ const publications = (await store.list(ctx.tenantId, "publication")).filter(
5513
5588
  (resource) => resource.kind === "publication" && resource.environmentId === source.id
5514
5589
  ).sort((a, b) => b.version - a.version);
5515
5590
  const sourcePublication = publications[0];
5516
5591
  if (!sourcePublication) throw new Error("Source environment has no published version");
5517
- const currentTargetRules = (await store.list(input.tenantId, "rule")).filter(
5592
+ const currentTargetRules = (await store.list(ctx.tenantId, "rule")).filter(
5518
5593
  (resource) => resource.kind === "rule" && resource.environmentId === target.id && resource.enabled
5519
5594
  );
5520
5595
  const at = (/* @__PURE__ */ new Date()).toISOString();
@@ -5532,7 +5607,7 @@ var promoteEnvironment = {
5532
5607
  await ctx.db.store.appendEvent({
5533
5608
  id: randomUUID(),
5534
5609
  type: "environment.promoted",
5535
- tenantId: input.tenantId,
5610
+ tenantId: ctx.tenantId,
5536
5611
  experimentId: `workspace:environment:${target.id}`,
5537
5612
  actorId: ctx.actorId,
5538
5613
  at,
@@ -5599,7 +5674,7 @@ var createExperiment = {
5599
5674
  async handler(ctx, params) {
5600
5675
  const input = params;
5601
5676
  const store = ctx.db.store;
5602
- const tenantId = input.tenantId ?? ctx.tenantId;
5677
+ const tenantId = ctx.tenantId;
5603
5678
  const existing = await store.getExperiment(tenantId, input.id);
5604
5679
  if (existing) {
5605
5680
  return { success: true, data: { experimentId: existing.id, idempotent: true } };
@@ -5646,7 +5721,7 @@ var createExperiment = {
5646
5721
  metadata: input.metadata,
5647
5722
  approval: null,
5648
5723
  killReason: null,
5649
- ownerId: input.ownerId,
5724
+ ownerId: ctx.actorId,
5650
5725
  tenantId,
5651
5726
  projectId: input.projectId,
5652
5727
  propertyId: input.propertyId,
@@ -5685,7 +5760,7 @@ function lifecycle(actionId, schema, evt, fn, options = {}) {
5685
5760
  async handler(ctx, params) {
5686
5761
  const p = params;
5687
5762
  const store = ctx.db.store;
5688
- const e = await loadExperiment(store, p.tenantId, p.experimentId);
5763
+ const e = await loadExperiment(store, ctx.tenantId, p.experimentId);
5689
5764
  options.policy?.(e, p, ctx);
5690
5765
  const updated = fn(e, p);
5691
5766
  await store.putExperiment(updated);
@@ -5783,6 +5858,13 @@ var declareWinner = lifecycle(
5783
5858
  },
5784
5859
  { targetState: "concluded" }
5785
5860
  );
5861
+ var archive = lifecycle(
5862
+ "experiment.archive",
5863
+ ArchiveInput,
5864
+ "experiment.archived",
5865
+ (experiment) => transition(experiment, "archive"),
5866
+ { targetState: "archived" }
5867
+ );
5786
5868
  var update = {
5787
5869
  actionId: "experiment.update",
5788
5870
  namespace: NAMESPACE,
@@ -5795,7 +5877,7 @@ var update = {
5795
5877
  async handler(ctx, params) {
5796
5878
  const p = params;
5797
5879
  const store = ctx.db.store;
5798
- const e = await loadExperiment(store, p.tenantId, p.experimentId);
5880
+ const e = await loadExperiment(store, ctx.tenantId, p.experimentId);
5799
5881
  const liveStates = /* @__PURE__ */ new Set(["running", "paused", "concluded"]);
5800
5882
  if (liveStates.has(e.state)) {
5801
5883
  const curKeys = new Set(e.variants.map((v) => v.key));
@@ -5858,7 +5940,7 @@ var guardrailBreach = {
5858
5940
  async handler(ctx, params) {
5859
5941
  const p = params;
5860
5942
  const store = ctx.db.store;
5861
- const e = await loadExperiment(store, p.tenantId, p.experimentId);
5943
+ const e = await loadExperiment(store, ctx.tenantId, p.experimentId);
5862
5944
  await store.appendEvent(
5863
5945
  event("guardrail.breached", e, ctx, {
5864
5946
  guardrailKey: p.guardrailKey,
@@ -5896,6 +5978,7 @@ var experimentActions = [
5896
5978
  resume,
5897
5979
  kill,
5898
5980
  declareWinner,
5981
+ archive,
5899
5982
  update,
5900
5983
  guardrailBreach,
5901
5984
  ...workspaceActions
@@ -6680,187 +6763,6 @@ async function cmdKill(experimentId, options) {
6680
6763
  );
6681
6764
  return 0;
6682
6765
  }
6683
- async function cmdDev(options = {}) {
6684
- const ws = await loadWorkspace();
6685
- const port = options.port ?? Number(process.env.FX_DEV_PORT ?? 8787);
6686
- const tenantId = options.tenantId ?? "default";
6687
- const manifest = await ws.module.publishManifest(tenantId);
6688
- await writeFile(ws.manifestFile, JSON.stringify(manifest, null, 2), "utf8");
6689
- const server = createServer(async (req, res) => {
6690
- try {
6691
- const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
6692
- res.setHeader("access-control-allow-origin", "*");
6693
- res.setHeader("access-control-allow-headers", "content-type");
6694
- res.setHeader("access-control-allow-methods", "GET,POST,OPTIONS");
6695
- if (req.method === "OPTIONS") {
6696
- res.statusCode = 204;
6697
- res.end();
6698
- return;
6699
- }
6700
- if (req.method === "GET" && url.pathname === "/manifest") {
6701
- const m = await ws.module.publishManifest(tenantId);
6702
- res.setHeader("content-type", "application/json");
6703
- res.setHeader("cache-control", "no-store");
6704
- res.end(JSON.stringify(m));
6705
- log(`GET /manifest \u2192 v${m.manifestVersion} (${m.experiments.length} exps)`);
6706
- return;
6707
- }
6708
- if (req.method === "POST" && url.pathname === "/v1/exposure") {
6709
- const body = await readJson(req);
6710
- const parsed = Exposure.safeParse({
6711
- experimentId: body.experimentId,
6712
- subjectId: body.subjectId,
6713
- variantKey: body.variantKey,
6714
- tenantId: body.tenantId ?? tenantId,
6715
- manifestVersion: body.manifestVersion ?? 0,
6716
- at: body.at ?? (/* @__PURE__ */ new Date()).toISOString(),
6717
- failure: body.failure ?? null
6718
- });
6719
- if (!parsed.success) {
6720
- res.statusCode = 400;
6721
- res.setHeader("content-type", "application/json");
6722
- res.end(JSON.stringify({ error: "invalid exposure", issues: parsed.error.issues }));
6723
- log(
6724
- `POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
6725
- );
6726
- return;
6727
- }
6728
- await ws.warehouse.recordExposures([parsed.data]);
6729
- res.statusCode = 204;
6730
- res.end();
6731
- log(
6732
- `POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`
6733
- );
6734
- return;
6735
- }
6736
- if (req.method === "POST" && url.pathname === "/v1/conversion") {
6737
- const body = await readJson(req);
6738
- const parsed = ConversionEvent.safeParse({
6739
- ...body,
6740
- tenantId: body.tenantId ?? tenantId,
6741
- at: body.at ?? (/* @__PURE__ */ new Date()).toISOString()
6742
- });
6743
- if (!parsed.success) {
6744
- res.statusCode = 400;
6745
- res.setHeader("content-type", "application/json");
6746
- res.end(JSON.stringify({ error: "invalid conversion", issues: parsed.error.issues }));
6747
- log(
6748
- `POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
6749
- );
6750
- return;
6751
- }
6752
- await ws.warehouse.recordConversions([parsed.data]);
6753
- res.statusCode = 204;
6754
- res.end();
6755
- log(`POST /v1/conversion ${parsed.data.eventName} ${parsed.data.subjectId}`);
6756
- return;
6757
- }
6758
- if (req.method === "GET" && url.pathname === "/healthz") {
6759
- res.setHeader("content-type", "application/json");
6760
- res.end(JSON.stringify({ ok: true, port, tenantId }));
6761
- return;
6762
- }
6763
- res.statusCode = 404;
6764
- res.end("not found");
6765
- } catch (e) {
6766
- const err = e;
6767
- res.statusCode = 500;
6768
- res.end(`error: ${err.message}`);
6769
- log(`ERR ${err.message}`);
6770
- }
6771
- });
6772
- try {
6773
- await new Promise((resolveStart, rejectStart) => {
6774
- server.once("error", rejectStart);
6775
- server.listen(port, "127.0.0.1", () => {
6776
- server.off("error", rejectStart);
6777
- resolveStart();
6778
- });
6779
- });
6780
- } catch (e) {
6781
- const err = e;
6782
- if (err.code === "EADDRINUSE") {
6783
- process.stderr.write(
6784
- `fx dev: port ${port} is already in use.
6785
-
6786
- Another fx dev server may already be running. Either stop that process or choose another port:
6787
-
6788
- fx dev --port ${port + 1}
6789
-
6790
- To find the process on Linux/macOS:
6791
-
6792
- lsof -nP -iTCP:${port} -sTCP:LISTEN
6793
- `
6794
- );
6795
- return 1;
6796
- }
6797
- throw e;
6798
- }
6799
- log(`fx dev \u2014 listening on http://127.0.0.1:${port}`);
6800
- log(" GET /manifest");
6801
- log(" POST /v1/exposure");
6802
- log(" POST /v1/conversion");
6803
- log(` workspace=${ws.root}`);
6804
- await new Promise((resolveStop) => {
6805
- const stop = () => {
6806
- log("shutting down\u2026");
6807
- server.close(() => resolveStop());
6808
- };
6809
- process.once("SIGINT", stop);
6810
- process.once("SIGTERM", stop);
6811
- });
6812
- return 0;
6813
- }
6814
- function log(msg) {
6815
- const t = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
6816
- process.stdout.write(`[${t}] ${msg}
6817
- `);
6818
- }
6819
- function readJson(req) {
6820
- return new Promise((resolveBody, reject) => {
6821
- const chunks = [];
6822
- req.on("data", (c) => chunks.push(c));
6823
- req.on("end", () => {
6824
- try {
6825
- const raw = Buffer.concat(chunks).toString("utf8");
6826
- resolveBody(raw.length === 0 ? {} : JSON.parse(raw));
6827
- } catch (e) {
6828
- reject(e);
6829
- }
6830
- });
6831
- req.on("error", reject);
6832
- });
6833
- }
6834
- async function cmdPlan(dir, options = {}) {
6835
- try {
6836
- const ws = await loadWorkspace();
6837
- const specs = (await loadExperimentDir(resolve(dir))).map((s) => s.spec);
6838
- const tenantId = options.tenantId ?? "default";
6839
- const current = await ws.module.store.listExperiments(tenantId);
6840
- const p = plan({
6841
- specs,
6842
- current,
6843
- tenantId,
6844
- ownerId: options.ownerId ?? "cli",
6845
- approverId: options.approverId ?? "cli-reviewer",
6846
- allowDeletes: options.allowDeletes
6847
- });
6848
- if (options.json) {
6849
- process.stdout.write(`${JSON.stringify(p, null, 2)}
6850
- `);
6851
- } else {
6852
- process.stdout.write(formatPlan(p));
6853
- process.stdout.write("\n");
6854
- }
6855
- if (p.blocked.length > 0) return 2;
6856
- const hasChanges = p.diffs.some((d) => d.kind !== "noop");
6857
- return hasChanges ? 2 : 0;
6858
- } catch (e) {
6859
- process.stderr.write(`fx plan: ${e.message}
6860
- `);
6861
- return 1;
6862
- }
6863
- }
6864
6766
 
6865
6767
  // ../manifest-signing/dist/index.js
6866
6768
  function canonicalSignedPayload(m) {
@@ -6878,6 +6780,12 @@ function canonicalSignedPayload(m) {
6878
6780
  function canonicalSignedBytes(m) {
6879
6781
  return new TextEncoder().encode(canonicalSignedPayload(m));
6880
6782
  }
6783
+ async function getSubtle() {
6784
+ if (globalThis.crypto?.subtle) return globalThis.crypto.subtle;
6785
+ const nodeCryptoSpecifier = "node:crypto";
6786
+ const { webcrypto: webcrypto2 } = await import(nodeCryptoSpecifier);
6787
+ return webcrypto2.subtle;
6788
+ }
6881
6789
  async function sha256(data) {
6882
6790
  const subtle = await getSubtle();
6883
6791
  const buf = await subtle.digest("SHA-256", data);
@@ -6888,13 +6796,8 @@ function hexEncode(bytes) {
6888
6796
  for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
6889
6797
  return s;
6890
6798
  }
6891
- async function getSubtle() {
6892
- if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
6893
- const { webcrypto: webcrypto2 } = await import('crypto');
6894
- return webcrypto2.subtle;
6895
- }
6896
6799
  async function signManifest(manifest, key) {
6897
- const subtle = await getSubtle2();
6800
+ const subtle = await getSubtle();
6898
6801
  const payload = canonicalSignedBytes(manifest);
6899
6802
  const signedHash = await sha256(payload);
6900
6803
  const pkcs8 = ed25519PrivateKeyToPkcs8(hexDecode(key.privateKeyHex));
@@ -6913,11 +6816,6 @@ async function signManifest(manifest, key) {
6913
6816
  signedHash: hexEncode(signedHash)
6914
6817
  };
6915
6818
  }
6916
- async function getSubtle2() {
6917
- if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
6918
- const { webcrypto: webcrypto2 } = await import('crypto');
6919
- return webcrypto2.subtle;
6920
- }
6921
6819
  function hexDecode(hex) {
6922
6820
  if (hex.length % 2 !== 0) throw new Error("hexDecode: odd length");
6923
6821
  const out = new Uint8Array(hex.length / 2);
@@ -6949,8 +6847,34 @@ function ed25519PrivateKeyToPkcs8(seed) {
6949
6847
  out.set(seed, prefix.length);
6950
6848
  return out;
6951
6849
  }
6850
+ function jwksFromKeys(keys) {
6851
+ return {
6852
+ keys: keys.map((k) => ({
6853
+ kid: k.keyId,
6854
+ kty: "OKP",
6855
+ crv: "Ed25519",
6856
+ x: hexToBase64Url(k.publicKeyHex),
6857
+ alg: "EdDSA",
6858
+ use: "sig",
6859
+ status: k.status
6860
+ }))
6861
+ };
6862
+ }
6863
+ function hexToBytes(hex) {
6864
+ const out = new Uint8Array(hex.length / 2);
6865
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
6866
+ return out;
6867
+ }
6868
+ function hexToBase64Url(hex) {
6869
+ return bytesToBase64Url(hexToBytes(hex));
6870
+ }
6871
+ function bytesToBase64Url(bytes) {
6872
+ let s = "";
6873
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
6874
+ return btoa(s).replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
6875
+ }
6952
6876
  async function generateKeypair(keyId) {
6953
- const subtle = await getSubtle4();
6877
+ const subtle = await getSubtle();
6954
6878
  const kp = await subtle.generateKey({ name: "Ed25519" }, true, [
6955
6879
  "sign",
6956
6880
  "verify"
@@ -6964,13 +6888,6 @@ async function generateKeypair(keyId) {
6964
6888
  keyId
6965
6889
  };
6966
6890
  }
6967
- async function getSubtle4() {
6968
- if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
6969
- const { webcrypto: webcrypto2 } = await import('crypto');
6970
- return webcrypto2.subtle;
6971
- }
6972
-
6973
- // src/commands/publish.ts
6974
6891
  async function cmdPublish(options = {}) {
6975
6892
  const ws = await loadWorkspace();
6976
6893
  const tenantId = options.tenantId ?? "default";
@@ -7021,6 +6938,23 @@ async function cmdPublish(options = {}) {
7021
6938
  const out = resolve(options.staticDir);
7022
6939
  await mkdir(out, { recursive: true });
7023
6940
  await writeFile(join(out, "manifest.json"), JSON.stringify(signed), "utf8");
6941
+ const tenantPath = encodeURIComponent(manifest.tenantId);
6942
+ const jwksDirectory = join(out, ".well-known", "jwks");
6943
+ const revocationsDirectory = join(out, ".well-known", "revocations");
6944
+ await mkdir(jwksDirectory, { recursive: true });
6945
+ await mkdir(revocationsDirectory, { recursive: true });
6946
+ await writeFile(
6947
+ join(jwksDirectory, tenantPath),
6948
+ JSON.stringify(
6949
+ jwksFromKeys([{ keyId: key.keyId, publicKeyHex: key.publicKeyHex, status: "active" }])
6950
+ ),
6951
+ "utf8"
6952
+ );
6953
+ await writeFile(
6954
+ join(revocationsDirectory, tenantPath),
6955
+ JSON.stringify({ versions: [] }),
6956
+ "utf8"
6957
+ );
7024
6958
  const tagLoader = await locateTagLoaderBundle();
7025
6959
  if (tagLoader) {
7026
6960
  await copyFile(tagLoader.js, join(out, "experiments.tag.global.js"));
@@ -7028,7 +6962,7 @@ async function cmdPublish(options = {}) {
7028
6962
  await copyFile(tagLoader.map, join(out, "experiments.tag.global.js.map"));
7029
6963
  }
7030
6964
  process.stdout.write(
7031
- `Static export written to ${out} (manifest.json + experiments.tag.global.js)
6965
+ `Static export written to ${out} (signed manifest, JWKS, revocations + experiments.tag.global.js)
7032
6966
  `
7033
6967
  );
7034
6968
  } else {
@@ -7071,17 +7005,233 @@ async function loadOrCreateKey(fxDir, keyId) {
7071
7005
  return kp;
7072
7006
  }
7073
7007
  }
7074
- async function cmdImportMojito(inputDir, options = {}) {
7075
- const root = resolve(inputDir);
7076
- const outDir = resolve(options.outputDir ?? join(root, "converted"));
7077
- await mkdir(outDir, { recursive: true });
7078
- const waves = await findWaves(root);
7079
- if (waves.length === 0) {
7080
- process.stderr.write(`No Mojito waves found under ${root}.
7081
- `);
7082
- return 1;
7083
- }
7084
- const results = [];
7008
+
7009
+ // src/commands/dev.ts
7010
+ async function cmdDev(options = {}) {
7011
+ const ws = await loadWorkspace();
7012
+ const port = options.port ?? Number(process.env.FX_DEV_PORT ?? 8787);
7013
+ const tenantId = options.tenantId ?? "default";
7014
+ const key = await loadOrCreateKey(ws.fxDir, "dev-default");
7015
+ const manifest = await signedManifest(ws.module.publishManifest.bind(ws.module), tenantId, key);
7016
+ await writeFile(ws.manifestFile, JSON.stringify(manifest, null, 2), "utf8");
7017
+ const server = createServer(async (req, res) => {
7018
+ try {
7019
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
7020
+ res.setHeader("access-control-allow-origin", "*");
7021
+ res.setHeader("access-control-allow-headers", "content-type");
7022
+ res.setHeader("access-control-allow-methods", "GET,POST,OPTIONS");
7023
+ if (req.method === "OPTIONS") {
7024
+ res.statusCode = 204;
7025
+ res.end();
7026
+ return;
7027
+ }
7028
+ if (req.method === "GET" && url.pathname === "/manifest") {
7029
+ const m = await signedManifest(ws.module.publishManifest.bind(ws.module), tenantId, key);
7030
+ res.setHeader("content-type", "application/json");
7031
+ res.setHeader("cache-control", "no-store");
7032
+ res.end(JSON.stringify(m));
7033
+ log(`GET /manifest \u2192 v${m.manifestVersion} (${m.experiments.length} exps)`);
7034
+ return;
7035
+ }
7036
+ const tenantPath = encodeURIComponent(tenantId);
7037
+ if (req.method === "GET" && url.pathname === `/.well-known/jwks/${tenantPath}`) {
7038
+ res.setHeader("content-type", "application/json");
7039
+ res.setHeader("cache-control", "no-store");
7040
+ res.end(
7041
+ JSON.stringify(
7042
+ jwksFromKeys([{ keyId: key.keyId, publicKeyHex: key.publicKeyHex, status: "active" }])
7043
+ )
7044
+ );
7045
+ return;
7046
+ }
7047
+ if (req.method === "GET" && url.pathname === `/.well-known/revocations/${tenantPath}`) {
7048
+ res.setHeader("content-type", "application/json");
7049
+ res.setHeader("cache-control", "no-store");
7050
+ res.end(JSON.stringify({ versions: [] }));
7051
+ return;
7052
+ }
7053
+ if (req.method === "POST" && url.pathname === "/v1/exposure") {
7054
+ const body = await readJson(req);
7055
+ const parsed = Exposure.safeParse({
7056
+ experimentId: body.experimentId,
7057
+ subjectId: body.subjectId,
7058
+ variantKey: body.variantKey,
7059
+ tenantId: body.tenantId ?? tenantId,
7060
+ manifestVersion: body.manifestVersion ?? 0,
7061
+ at: body.at ?? (/* @__PURE__ */ new Date()).toISOString(),
7062
+ failure: body.failure ?? null
7063
+ });
7064
+ if (!parsed.success) {
7065
+ res.statusCode = 400;
7066
+ res.setHeader("content-type", "application/json");
7067
+ res.end(JSON.stringify({ error: "invalid exposure", issues: parsed.error.issues }));
7068
+ log(
7069
+ `POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
7070
+ );
7071
+ return;
7072
+ }
7073
+ await ws.warehouse.recordExposures([parsed.data]);
7074
+ res.statusCode = 204;
7075
+ res.end();
7076
+ log(
7077
+ `POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`
7078
+ );
7079
+ return;
7080
+ }
7081
+ if (req.method === "POST" && url.pathname === "/v1/conversion") {
7082
+ const body = await readJson(req);
7083
+ const parsed = ConversionEvent.safeParse({
7084
+ ...body,
7085
+ tenantId: body.tenantId ?? tenantId,
7086
+ at: body.at ?? (/* @__PURE__ */ new Date()).toISOString()
7087
+ });
7088
+ if (!parsed.success) {
7089
+ res.statusCode = 400;
7090
+ res.setHeader("content-type", "application/json");
7091
+ res.end(JSON.stringify({ error: "invalid conversion", issues: parsed.error.issues }));
7092
+ log(
7093
+ `POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
7094
+ );
7095
+ return;
7096
+ }
7097
+ await ws.warehouse.recordConversions([parsed.data]);
7098
+ res.statusCode = 204;
7099
+ res.end();
7100
+ log(`POST /v1/conversion ${parsed.data.eventName} ${parsed.data.subjectId}`);
7101
+ return;
7102
+ }
7103
+ if (req.method === "GET" && url.pathname === "/healthz") {
7104
+ res.setHeader("content-type", "application/json");
7105
+ res.end(JSON.stringify({ ok: true, port, tenantId }));
7106
+ return;
7107
+ }
7108
+ res.statusCode = 404;
7109
+ res.end("not found");
7110
+ } catch (e) {
7111
+ const err = e;
7112
+ res.statusCode = 500;
7113
+ res.end(`error: ${err.message}`);
7114
+ log(`ERR ${err.message}`);
7115
+ }
7116
+ });
7117
+ try {
7118
+ await new Promise((resolveStart, rejectStart) => {
7119
+ server.once("error", rejectStart);
7120
+ server.listen(port, "127.0.0.1", () => {
7121
+ server.off("error", rejectStart);
7122
+ resolveStart();
7123
+ });
7124
+ });
7125
+ } catch (e) {
7126
+ const err = e;
7127
+ if (err.code === "EADDRINUSE") {
7128
+ process.stderr.write(
7129
+ `fx dev: port ${port} is already in use.
7130
+
7131
+ Another fx dev server may already be running. Either stop that process or choose another port:
7132
+
7133
+ fx dev --port ${port + 1}
7134
+
7135
+ To find the process on Linux/macOS:
7136
+
7137
+ lsof -nP -iTCP:${port} -sTCP:LISTEN
7138
+ `
7139
+ );
7140
+ return 1;
7141
+ }
7142
+ throw e;
7143
+ }
7144
+ log(`fx dev \u2014 listening on http://127.0.0.1:${port}`);
7145
+ log(" GET /manifest");
7146
+ log(` GET /.well-known/jwks/${encodeURIComponent(tenantId)}`);
7147
+ log(` GET /.well-known/revocations/${encodeURIComponent(tenantId)}`);
7148
+ log(" POST /v1/exposure");
7149
+ log(" POST /v1/conversion");
7150
+ log(` workspace=${ws.root}`);
7151
+ await new Promise((resolveStop) => {
7152
+ const stop = () => {
7153
+ log("shutting down\u2026");
7154
+ server.close(() => resolveStop());
7155
+ };
7156
+ process.once("SIGINT", stop);
7157
+ process.once("SIGTERM", stop);
7158
+ });
7159
+ return 0;
7160
+ }
7161
+ async function signedManifest(publish, tenantId, key) {
7162
+ const manifest = await publish(tenantId);
7163
+ const signature = await signManifest(
7164
+ {
7165
+ schemaVersion: manifest.schemaVersion,
7166
+ manifestVersion: manifest.manifestVersion,
7167
+ tenantId: manifest.tenantId,
7168
+ contentHash: manifest.contentHash
7169
+ },
7170
+ { keyId: key.keyId, privateKeyHex: key.privateKeyHex }
7171
+ );
7172
+ return { ...manifest, signature };
7173
+ }
7174
+ function log(msg) {
7175
+ const t = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
7176
+ process.stdout.write(`[${t}] ${msg}
7177
+ `);
7178
+ }
7179
+ function readJson(req) {
7180
+ return new Promise((resolveBody, reject) => {
7181
+ const chunks = [];
7182
+ req.on("data", (c) => chunks.push(c));
7183
+ req.on("end", () => {
7184
+ try {
7185
+ const raw = Buffer.concat(chunks).toString("utf8");
7186
+ resolveBody(raw.length === 0 ? {} : JSON.parse(raw));
7187
+ } catch (e) {
7188
+ reject(e);
7189
+ }
7190
+ });
7191
+ req.on("error", reject);
7192
+ });
7193
+ }
7194
+ async function cmdPlan(dir, options = {}) {
7195
+ try {
7196
+ const ws = await loadWorkspace();
7197
+ const specs = (await loadExperimentDir(resolve(dir))).map((s) => s.spec);
7198
+ const tenantId = options.tenantId ?? "default";
7199
+ const current = await ws.module.store.listExperiments(tenantId);
7200
+ const p = plan({
7201
+ specs,
7202
+ current,
7203
+ tenantId,
7204
+ ownerId: options.ownerId ?? "cli",
7205
+ approverId: options.approverId ?? "cli-reviewer",
7206
+ allowDeletes: options.allowDeletes
7207
+ });
7208
+ if (options.json) {
7209
+ process.stdout.write(`${JSON.stringify(p, null, 2)}
7210
+ `);
7211
+ } else {
7212
+ process.stdout.write(formatPlan(p));
7213
+ process.stdout.write("\n");
7214
+ }
7215
+ if (p.blocked.length > 0) return 2;
7216
+ const hasChanges = p.diffs.some((d) => d.kind !== "noop");
7217
+ return hasChanges ? 2 : 0;
7218
+ } catch (e) {
7219
+ process.stderr.write(`fx plan: ${e.message}
7220
+ `);
7221
+ return 1;
7222
+ }
7223
+ }
7224
+ async function cmdImportMojito(inputDir, options = {}) {
7225
+ const root = resolve(inputDir);
7226
+ const outDir = resolve(options.outputDir ?? join(root, "converted"));
7227
+ await mkdir(outDir, { recursive: true });
7228
+ const waves = await findWaves(root);
7229
+ if (waves.length === 0) {
7230
+ process.stderr.write(`No Mojito waves found under ${root}.
7231
+ `);
7232
+ return 1;
7233
+ }
7234
+ const results = [];
7085
7235
  for (const waveDir of waves) {
7086
7236
  try {
7087
7237
  const r = await convertWave(waveDir, outDir);
@@ -7584,6 +7734,15 @@ var TestRunListInput = external_exports.object({
7584
7734
  var TestRunListResponse = external_exports.object({
7585
7735
  runs: external_exports.array(TestRun.omit({ cases: true }))
7586
7736
  });
7737
+ var HarnessOperatorDefinition = external_exports.object({
7738
+ name: external_exports.enum(["quality-status", "srm-watcher", "analyst"]),
7739
+ kind: external_exports.literal("job"),
7740
+ description: external_exports.string(),
7741
+ mutates: external_exports.boolean()
7742
+ });
7743
+ var HarnessOperatorListResponse = external_exports.array(HarnessOperatorDefinition);
7744
+ var HarnessJobInput = external_exports.record(external_exports.unknown()).default({});
7745
+ var HarnessJobResponse = external_exports.record(external_exports.unknown());
7587
7746
  var endpoints = {
7588
7747
  "tenants.me": {
7589
7748
  method: "GET",
@@ -7896,6 +8055,22 @@ var endpoints = {
7896
8055
  response: TestRun,
7897
8056
  mutates: false,
7898
8057
  requiresRole: "viewer"
8058
+ },
8059
+ "harness.definitions": {
8060
+ method: "GET",
8061
+ path: "/v1/orgs/:orgId/harness/admin/agents",
8062
+ params: Empty,
8063
+ response: HarnessOperatorListResponse,
8064
+ mutates: false,
8065
+ requiresRole: "viewer"
8066
+ },
8067
+ "harness.invokeJob": {
8068
+ method: "POST",
8069
+ path: "/v1/orgs/:orgId/harness/jobs/:jobName",
8070
+ params: HarnessJobInput,
8071
+ response: HarnessJobResponse,
8072
+ mutates: true,
8073
+ requiresRole: "experimenter"
7899
8074
  }
7900
8075
  };
7901
8076
  function buildPath(template, pathParams) {
@@ -7953,6 +8128,7 @@ var ApiClient = class {
7953
8128
  method: def.method,
7954
8129
  headers: {
7955
8130
  accept: "application/json",
8131
+ ...this.opts.headers ?? {},
7956
8132
  // Hosted Fabric API keys use their own header so upstream auth
7957
8133
  // middleware cannot mistake them for OAuth bearer credentials.
7958
8134
  ...this.opts.apiKey ? { "x-api-key": this.opts.apiKey } : {},
@@ -8081,6 +8257,10 @@ var ApiClient = class {
8081
8257
  get: (runId, orgId) => this.call("testRuns.get", {}, orgId ? { orgId, runId } : { runId }),
8082
8258
  create: (params, orgId) => this.call("testRuns.create", params, orgId ? { orgId } : void 0)
8083
8259
  };
8260
+ harness = {
8261
+ definitions: (orgId) => this.call("harness.definitions", {}, orgId ? { orgId } : void 0),
8262
+ invokeJob: (jobName, params = {}, orgId) => this.call("harness.invokeJob", params, orgId ? { orgId, jobName } : { jobName })
8263
+ };
8084
8264
  };
8085
8265
  async function safeJson(r) {
8086
8266
  try {
@@ -8277,9 +8457,11 @@ var FILES = {
8277
8457
  2
8278
8458
  )}
8279
8459
  `,
8280
- "cucumber.mjs": `export default {
8460
+ "cucumber.mjs": `process.env.DBX_TEST_PROFILE ??= 'local';
8461
+
8462
+ export default {
8281
8463
  paths: ['features/**/*.feature'],
8282
- import: ['features/support/steps.ts'],
8464
+ import: ['cucumber-register.mjs'],
8283
8465
  format: [
8284
8466
  'progress',
8285
8467
  ['junit', 'reports/bdd-junit.xml'],
@@ -8288,6 +8470,11 @@ var FILES = {
8288
8470
  ['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json'],
8289
8471
  ],
8290
8472
  };
8473
+ `,
8474
+ "cucumber-register.mjs": `import { register } from 'tsx/esm/api';
8475
+
8476
+ register();
8477
+ await import('./features/support/steps.ts');
8291
8478
  `,
8292
8479
  "features/support/steps.ts": `import '@fabricorg/databricks-bdd/steps';
8293
8480
  `,
@@ -8771,7 +8958,7 @@ function normalizeTestEvidence(value, options = {}) {
8771
8958
  if (kind === "databricks-bdd") {
8772
8959
  const cases = arrayOfRecords(evidence.scenarios).map((scenario, index) => {
8773
8960
  const failures = arrayOfRecords(scenario.failures);
8774
- const statementId = failures.find((failure) => typeof failure.statementId === "string")?.statementId;
8961
+ const statementId = failures.find((failure3) => typeof failure3.statementId === "string")?.statementId;
8775
8962
  return {
8776
8963
  id: `${scenario.uri ?? "scenario"}:${index}`,
8777
8964
  name: String(scenario.name ?? `Scenario ${index + 1}`),
@@ -8918,14 +9105,14 @@ function parseEvidenceText(text) {
8918
9105
  const suites = collectSuites(parsed.testsuites ?? parsed.testsuite);
8919
9106
  const cases = suites.flatMap(
8920
9107
  (suite, suiteIndex) => asRecords(suite.testcase).map((testCase, caseIndex) => {
8921
- const failure = testCase.failure ?? testCase.error;
9108
+ const failure3 = testCase.failure ?? testCase.error;
8922
9109
  const skipped = testCase.skipped;
8923
- const error = xmlText(failure);
9110
+ const error = xmlText(failure3);
8924
9111
  return {
8925
9112
  id: `${suite["@_name"] ?? suiteIndex}:${testCase["@_name"] ?? caseIndex}`,
8926
9113
  name: String(testCase["@_name"] ?? `Test ${caseIndex + 1}`),
8927
9114
  uri: String(testCase["@_classname"] ?? suite["@_name"] ?? ""),
8928
- status: failure ? "failed" : skipped ? "skipped" : "passed",
9115
+ status: failure3 ? "failed" : skipped ? "skipped" : "passed",
8929
9116
  durationMs: Math.round(Number(testCase["@_time"] ?? 0) * 1e3),
8930
9117
  ...error ? { error } : {}
8931
9118
  };
@@ -9318,6 +9505,158 @@ function symbol(status) {
9318
9505
  function objectOf2(value) {
9319
9506
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
9320
9507
  }
9508
+ async function cmdHarness(action, jobName, options) {
9509
+ const client = new ApiClient({
9510
+ baseUrl: options.apiUrl,
9511
+ apiKey: options.apiKey,
9512
+ bearerToken: options.bearerToken,
9513
+ defaultOrgId: options.tenantId,
9514
+ fetchImpl: options.fetchImpl
9515
+ });
9516
+ if (action === "list" || action === "doctor") {
9517
+ const definitions = await client.harness.definitions();
9518
+ if (options.json) process.stdout.write(`${JSON.stringify(definitions, null, 2)}
9519
+ `);
9520
+ else {
9521
+ for (const item of definitions) {
9522
+ process.stdout.write(
9523
+ `${item.name.padEnd(16)} ${item.mutates ? "controlled write" : "read only"} ${item.description}
9524
+ `
9525
+ );
9526
+ }
9527
+ if (action === "doctor") {
9528
+ process.stdout.write(
9529
+ `Harness operator ready: ${definitions.length} jobs \xB7 tenant ${options.tenantId}
9530
+ `
9531
+ );
9532
+ }
9533
+ }
9534
+ return definitions.length > 0 ? 0 : 1;
9535
+ }
9536
+ if (action === "run") {
9537
+ if (!jobName) throw new Error("Usage: fx harness run <job> [--input <json>]");
9538
+ const output = await client.harness.invokeJob(jobName, parseInput(options.input));
9539
+ process.stdout.write(`${JSON.stringify(output, null, 2)}
9540
+ `);
9541
+ return 0;
9542
+ }
9543
+ if (action === "fiber") return runFiberThroughBridge(options);
9544
+ throw new Error(`Unknown harness action: ${action}`);
9545
+ }
9546
+ async function createHarnessCredentialBridge(options) {
9547
+ const remote = `${options.apiUrl.replace(/\/+$/, "")}/v1/orgs/${encodeURIComponent(options.tenantId)}/harness`;
9548
+ const bridgeToken = randomBytes(24).toString("base64url");
9549
+ const server = createServer((request, response) => {
9550
+ void proxyHarnessRequest(request, response, remote, bridgeToken, options);
9551
+ });
9552
+ await new Promise((resolve11, reject) => {
9553
+ server.once("error", reject);
9554
+ server.listen(0, "127.0.0.1", resolve11);
9555
+ });
9556
+ const address = server.address();
9557
+ if (!address || typeof address === "string") {
9558
+ server.close();
9559
+ throw new Error("Unable to bind the local Fiber credential bridge");
9560
+ }
9561
+ return {
9562
+ url: `http://127.0.0.1:${address.port}`,
9563
+ token: bridgeToken,
9564
+ close: () => new Promise(
9565
+ (resolve11, reject) => server.close((error) => error ? reject(error) : resolve11())
9566
+ )
9567
+ };
9568
+ }
9569
+ async function runFiberThroughBridge(options) {
9570
+ const bridge = await createHarnessCredentialBridge(options);
9571
+ const harnessBin = options.harnessBin ?? createRequire(import.meta.url).resolve("@fabric-harness/cli");
9572
+ const tokenVariable = "FX_FIBER_BRIDGE_TOKEN";
9573
+ const args = [harnessBin, "fiber", "--url", bridge.url, "--token-env", tokenVariable];
9574
+ if (options.plain) args.push("--plain");
9575
+ try {
9576
+ return await new Promise((resolve11, reject) => {
9577
+ const child = (options.spawnProcess ?? spawn)(process.execPath, args, {
9578
+ stdio: "inherit",
9579
+ env: { ...process.env, [tokenVariable]: bridge.token }
9580
+ });
9581
+ child.once("error", reject);
9582
+ child.once("exit", (code, signal) => {
9583
+ if (signal) reject(new Error(`Fiber exited from signal ${signal}`));
9584
+ else resolve11(code ?? 1);
9585
+ });
9586
+ });
9587
+ } finally {
9588
+ await bridge.close();
9589
+ }
9590
+ }
9591
+ async function proxyHarnessRequest(incoming, outgoing, remoteBase, bridgeToken, options) {
9592
+ try {
9593
+ if (incoming.headers.authorization !== `Bearer ${bridgeToken}`) {
9594
+ outgoing.writeHead(401, { "content-type": "application/json" });
9595
+ outgoing.end(JSON.stringify({ error: { message: "Invalid Fiber bridge token" } }));
9596
+ return;
9597
+ }
9598
+ const url = new URL(incoming.url ?? "/", "http://bridge.invalid");
9599
+ if (!isAllowedHarnessPath(incoming.method, url.pathname)) {
9600
+ outgoing.writeHead(404, { "content-type": "application/json" });
9601
+ outgoing.end(JSON.stringify({ error: { message: "Unsupported Harness operator route" } }));
9602
+ return;
9603
+ }
9604
+ const body = await readBody(incoming);
9605
+ const response = await (options.fetchImpl ?? fetch)(
9606
+ `${remoteBase}${url.pathname}${url.search}`,
9607
+ {
9608
+ method: incoming.method,
9609
+ headers: {
9610
+ accept: "application/json",
9611
+ "x-api-key": options.apiKey,
9612
+ ...options.bearerToken ? { authorization: `Bearer ${options.bearerToken}` } : {},
9613
+ ...body.length > 0 ? { "content-type": "application/json" } : {}
9614
+ },
9615
+ body: body.length > 0 ? body.toString("utf8") : void 0
9616
+ }
9617
+ );
9618
+ const responseBody = Buffer.from(await response.arrayBuffer());
9619
+ outgoing.writeHead(response.status, {
9620
+ "content-type": response.headers.get("content-type") ?? "application/json",
9621
+ "cache-control": "no-store"
9622
+ });
9623
+ outgoing.end(responseBody);
9624
+ } catch (error) {
9625
+ outgoing.writeHead(502, { "content-type": "application/json" });
9626
+ outgoing.end(
9627
+ JSON.stringify({
9628
+ error: { message: error instanceof Error ? error.message : "Fiber bridge failed" }
9629
+ })
9630
+ );
9631
+ }
9632
+ }
9633
+ function isAllowedHarnessPath(method, path) {
9634
+ return method === "GET" && path === "/admin/agents" || method === "POST" && /^\/jobs\/[A-Za-z0-9_.-]+$/.test(path);
9635
+ }
9636
+ async function readBody(request) {
9637
+ const chunks = [];
9638
+ let size = 0;
9639
+ for await (const chunk of request) {
9640
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
9641
+ size += value.length;
9642
+ if (size > 64 * 1024) throw new Error("Fiber request body exceeds 64 KiB");
9643
+ chunks.push(value);
9644
+ }
9645
+ return Buffer.concat(chunks);
9646
+ }
9647
+ function parseInput(value) {
9648
+ if (!value) return {};
9649
+ let parsed;
9650
+ try {
9651
+ parsed = JSON.parse(value);
9652
+ } catch {
9653
+ throw new Error("--input must be valid JSON");
9654
+ }
9655
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
9656
+ throw new Error("--input must be a JSON object");
9657
+ }
9658
+ return parsed;
9659
+ }
9321
9660
 
9322
9661
  // src/bin/fx.ts
9323
9662
  var HELP = `fx \u2014 Fabric Experiments CLI
@@ -9343,6 +9682,7 @@ COMMANDS
9343
9682
  logout [profile] Remove a stored hosted profile.
9344
9683
  profile [list|show|use] Inspect or switch hosted profiles.
9345
9684
  doctor Verify API, tenant, gateway, role, and config security.
9685
+ harness <action> List/run operator jobs or open the Fiber terminal console.
9346
9686
  targets list List built-in Databricks target packs.
9347
9687
  targets doctor <pack> Validate target configuration without creating resources.
9348
9688
  targets run <pack> Run a pack and write JSON/JUnit evidence. Requires --live.
@@ -9360,7 +9700,7 @@ GLOBAL FLAGS
9360
9700
  --json plan: emit machine-readable output
9361
9701
  --remote-url <url> publish: post to a manifest-worker
9362
9702
  --admin-token <tok> publish: bearer token for --remote-url
9363
- --static <dir> publish: write signed manifest + tag-loader bundle to <dir>
9703
+ --static <dir> publish: write signed manifest + verification files + tag-loader
9364
9704
  --api-url <url> push/preview/test publish: hosted API base URL
9365
9705
  --api-key <key> push/preview/test publish: hosted API key
9366
9706
  --profile <name> hosted profile (default: active profile)
@@ -9381,6 +9721,8 @@ GLOBAL FLAGS
9381
9721
  --required <ids> targets run: comma-separated required check IDs
9382
9722
  --evidence <file> targets run: evidence JSON output path
9383
9723
  --junit <file> targets run: JUnit XML output path
9724
+ --input <json> harness run: typed operator job input
9725
+ --plain harness fiber: use the line-oriented console
9384
9726
  --key-id <id> publish: keyId to sign with (default: dev-default)
9385
9727
  --out <dir> import-mojito: output directory
9386
9728
  --report <file> import-mojito: compatibility report path
@@ -9388,7 +9730,7 @@ GLOBAL FLAGS
9388
9730
  -h, --help print this help
9389
9731
  -v, --version print version
9390
9732
  `;
9391
- var VERSION2 = "0.11.1";
9733
+ var VERSION2 = package_default.version;
9392
9734
  function parse2(argv) {
9393
9735
  const positional = [];
9394
9736
  const flags = {};
@@ -9459,6 +9801,28 @@ async function main() {
9459
9801
  );
9460
9802
  case "doctor":
9461
9803
  return cmdDoctor({ profileName: args.flags.profile });
9804
+ case "harness": {
9805
+ const action = args.positional[0] ?? "list";
9806
+ const hosted = await resolveHostedContext({
9807
+ profileName: args.flags.profile,
9808
+ databricksProfile: args.flags["databricks-profile"],
9809
+ apiUrl: args.flags["api-url"],
9810
+ apiKey: args.flags["api-key"],
9811
+ tenantId: explicitTenantId
9812
+ });
9813
+ if (!hosted.apiUrl || !hosted.apiKey || !hosted.tenantId) {
9814
+ throw new Error("Run fx login first or provide --api-url, --api-key, and --tenant");
9815
+ }
9816
+ return cmdHarness(action, args.positional[1], {
9817
+ apiUrl: hosted.apiUrl,
9818
+ apiKey: hosted.apiKey,
9819
+ tenantId: hosted.tenantId,
9820
+ bearerToken: hosted.bearerToken,
9821
+ input: args.flags.input,
9822
+ json: args.flags.json === true,
9823
+ plain: args.flags.plain === true
9824
+ });
9825
+ }
9462
9826
  case "targets": {
9463
9827
  const action = args.positional[0] ?? "list";
9464
9828
  if (action === "publish") {