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