@diafunc/cli 0.28.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-YK663CPM.js";
3
+ } from "./chunk-WZQ5LS2M.js";
4
4
 
5
5
  // src/index.ts
6
- import chalk40 from "chalk";
6
+ import chalk41 from "chalk";
7
7
 
8
8
  // src/commands/auth/login.ts
9
9
  import chalk4 from "chalk";
@@ -258,13 +258,13 @@ function resolveEndpoint(config, profileOverride) {
258
258
  import chalk from "chalk";
259
259
 
260
260
  // src/client/errors.ts
261
- var LICENCE_REFUSALS = {
262
- licence_required: "A public project needs a licence. Name one with --licence <id>.",
263
- licence_not_selectable: "That licence cannot be chosen: it is not in the catalogue, or it is deprecated or withdrawn.",
264
- licence_share_alike_mismatch: "This project is a fork of a share-alike project, so it has to carry the licence of the project it was forked from.",
265
- licence_forbids_fork: "The licence of this project does not allow adaptations, so it cannot be forked."
261
+ var LICENSE_REFUSALS = {
262
+ licence_required: "A public project needs a license. Name one with --license <id>.",
263
+ licence_not_selectable: "That license cannot be chosen: it is not in the catalog, or it is deprecated or withdrawn.",
264
+ licence_share_alike_mismatch: "This project is a fork of a share-alike project, so it has to carry the license of the project it was forked from.",
265
+ licence_forbids_fork: "The license of this project does not allow adaptations, so it cannot be forked."
266
266
  };
267
- var LICENCE_LIST_REFUSALS = /* @__PURE__ */ new Set(["licence_required", "licence_not_selectable"]);
267
+ var LICENSE_LIST_REFUSALS = /* @__PURE__ */ new Set(["licence_required", "licence_not_selectable"]);
268
268
  var ApiError = class _ApiError extends Error {
269
269
  status;
270
270
  details;
@@ -281,7 +281,7 @@ var ApiError = class _ApiError extends Error {
281
281
  return new _ApiError(status, body.message, body.details, typeof body.error === "string" ? body.error : void 0);
282
282
  }
283
283
  toUserMessage() {
284
- const refusal = this.code && Object.prototype.hasOwnProperty.call(LICENCE_REFUSALS, this.code) ? LICENCE_REFUSALS[this.code] : void 0;
284
+ const refusal = this.code && Object.prototype.hasOwnProperty.call(LICENSE_REFUSALS, this.code) ? LICENSE_REFUSALS[this.code] : void 0;
285
285
  if (refusal) return refusal;
286
286
  const detail2 = this.readableMessage();
287
287
  switch (this.status) {
@@ -748,19 +748,19 @@ function createAdminService(client) {
748
748
  path: `/projects/${encodeURIComponent(projectId)}`
749
749
  });
750
750
  },
751
- // Licences: the catalogue answers anyone, signed in or not.
752
- async listLicences() {
751
+ // Licenses: the catalog answers anyone, signed in or not.
752
+ async listLicenses() {
753
753
  return client.request({
754
754
  method: "GET",
755
755
  service: SERVICE,
756
756
  path: "/licences"
757
757
  });
758
758
  },
759
- async getLicence(licenceId) {
759
+ async getLicense(licenseId) {
760
760
  return client.request({
761
761
  method: "GET",
762
762
  service: SERVICE,
763
- path: `/licences/${encodeURIComponent(licenceId)}`
763
+ path: `/licences/${encodeURIComponent(licenseId)}`
764
764
  });
765
765
  },
766
766
  async createProject(request) {
@@ -1074,7 +1074,7 @@ function createAdminService(client) {
1074
1074
  body: setting
1075
1075
  });
1076
1076
  },
1077
- // Platform settings: the operator-facing catalogue, distinct from the per-user settings above.
1077
+ // Platform settings: the operator-facing catalog, distinct from the per-user settings above.
1078
1078
  // Every entry carries its compiled default, so an unset override reads as null rather than absent.
1079
1079
  async listPlatformSettings() {
1080
1080
  return client.request({
@@ -1240,7 +1240,7 @@ function handleError(error) {
1240
1240
  failure(error.toUserMessage());
1241
1241
  if (error.status === 401 && !(error instanceof SignInRefusedError)) hint(`Run 'diafunc auth login' to sign in.`);
1242
1242
  if (error.status === 404) hint(`Check the id, or list what exists with the matching 'list' command.`);
1243
- if (error.code && LICENCE_LIST_REFUSALS.has(error.code)) hint(`List the licences that can be chosen with 'diafunc licence list'.`);
1243
+ if (error.code && LICENSE_LIST_REFUSALS.has(error.code)) hint(`List the licenses that can be chosen with 'diafunc license list'.`);
1244
1244
  process.exit(error.status === 401 || error.status === 403 ? EXIT_AUTH : EXIT_FAILURE);
1245
1245
  }
1246
1246
  if (error instanceof NetworkError) {
@@ -1289,7 +1289,7 @@ function registerLoginCommand(parent) {
1289
1289
  const client = createHttpClient();
1290
1290
  const admin = createAdminService(client);
1291
1291
  const user = await admin.getMyUser();
1292
- success("Authenticated successfully.");
1292
+ success("Signed in.");
1293
1293
  console.log(` User: ${chalk4.bold(user.name)}`);
1294
1294
  console.log(` Email: ${user.email}`);
1295
1295
  console.log(` Profile: ${config.currentProfile}`);
@@ -1317,7 +1317,7 @@ async function deviceCodeLogin(config, profile) {
1317
1317
  });
1318
1318
  if (!deviceResponse.ok) {
1319
1319
  const text2 = await deviceResponse.text();
1320
- failure(`Failed to start device-code flow: ${text2 || deviceResponse.statusText}`);
1320
+ failure(`The sign-in could not start: ${text2 || deviceResponse.statusText}`);
1321
1321
  process.exit(1);
1322
1322
  }
1323
1323
  const device = await deviceResponse.json();
@@ -1355,7 +1355,7 @@ async function deviceCodeLogin(config, profile) {
1355
1355
  const client = createHttpClient();
1356
1356
  const admin = createAdminService(client);
1357
1357
  const user = await admin.getMyUser();
1358
- success("Logged in successfully.");
1358
+ success("Signed in.");
1359
1359
  console.log(` User: ${chalk4.bold(user.name)}`);
1360
1360
  console.log(` Email: ${user.email}`);
1361
1361
  console.log(` Profile: ${config.currentProfile}`);
@@ -1940,6 +1940,14 @@ function createAnalysisService(client) {
1940
1940
  });
1941
1941
  },
1942
1942
  /** The depth the platform would give the caller's next analysis if its creation named none. */
1943
+ /** The depths an analysis is offered at, shallowest first: the one list every surface shows. */
1944
+ async getDepths() {
1945
+ return client.request({
1946
+ method: "GET",
1947
+ service: SERVICE2,
1948
+ path: "/depths"
1949
+ });
1950
+ },
1943
1951
  async getDepthDefault() {
1944
1952
  return client.request({
1945
1953
  method: "GET",
@@ -2046,6 +2054,69 @@ function createAnalysisService(client) {
2046
2054
  body: request
2047
2055
  });
2048
2056
  },
2057
+ // ----- The owner's notes ("What you know and what matters") ------------------------
2058
+ /** Stores the notes only; reading them into proposals is {@link interpretIntent}. */
2059
+ async patchIntent(analysisId, request) {
2060
+ return client.request({
2061
+ method: "PATCH",
2062
+ service: SERVICE2,
2063
+ path: `/${encodeURIComponent(analysisId)}/intent`,
2064
+ body: request
2065
+ });
2066
+ },
2067
+ /** Reads the notes against the setup in the body; nothing is applied. */
2068
+ async interpretIntent(analysisId, request, options = {}) {
2069
+ const query = {};
2070
+ if (options.force) query.force = "true";
2071
+ if (options.refine) query.refine = "true";
2072
+ return client.request({
2073
+ method: "POST",
2074
+ service: SERVICE2,
2075
+ path: `/${encodeURIComponent(analysisId)}/intent/interpretation`,
2076
+ query,
2077
+ body: request
2078
+ });
2079
+ },
2080
+ async getIntentInterpretation(analysisId) {
2081
+ return client.request({
2082
+ method: "GET",
2083
+ service: SERVICE2,
2084
+ path: `/${encodeURIComponent(analysisId)}/intent/interpretation`
2085
+ });
2086
+ },
2087
+ /** Confirms (applies), declines or re-proposes proposals of the stored interpretation. */
2088
+ async decideIntentItems(analysisId, request) {
2089
+ return client.request({
2090
+ method: "PATCH",
2091
+ service: SERVICE2,
2092
+ path: `/${encodeURIComponent(analysisId)}/intent/interpretation/items`,
2093
+ body: request
2094
+ });
2095
+ },
2096
+ async patchShapeExpectations(analysisId, request) {
2097
+ return client.request({
2098
+ method: "PATCH",
2099
+ service: SERVICE2,
2100
+ path: `/${encodeURIComponent(analysisId)}/shape-expectations`,
2101
+ body: request
2102
+ });
2103
+ },
2104
+ async patchRequestedPairs(analysisId, request) {
2105
+ return client.request({
2106
+ method: "PATCH",
2107
+ service: SERVICE2,
2108
+ path: `/${encodeURIComponent(analysisId)}/requested-pairs`,
2109
+ body: request
2110
+ });
2111
+ },
2112
+ async patchFocusFamilies(analysisId, request) {
2113
+ return client.request({
2114
+ method: "PATCH",
2115
+ service: SERVICE2,
2116
+ path: `/${encodeURIComponent(analysisId)}/focus-families`,
2117
+ body: request
2118
+ });
2119
+ },
2049
2120
  // ----- Data ingest ----------------------------------------------------------------
2050
2121
  async uploadDataMultipart(analysisId, formData) {
2051
2122
  return client.request({
@@ -3380,7 +3451,7 @@ function registerTokenCommands(parent) {
3380
3451
  validityDays: parseInt(options.days, 10)
3381
3452
  });
3382
3453
  if (outputFormat === "human") {
3383
- success("API token created successfully.");
3454
+ success("API token created.");
3384
3455
  console.log();
3385
3456
  console.log(` Token: ${chalk8.bold(result.token)}`);
3386
3457
  console.log(` Token ID: ${result.tokenId}`);
@@ -3574,6 +3645,55 @@ function getNestedValue(obj, path13) {
3574
3645
  // src/commands/project/index.ts
3575
3646
  import chalk13 from "chalk";
3576
3647
 
3648
+ // src/util/hidden-aliases.ts
3649
+ import { Help, Option } from "commander";
3650
+ var hidden = /* @__PURE__ */ new WeakMap();
3651
+ function hiddenAlias(cmd, alias) {
3652
+ cmd.alias(alias);
3653
+ const names = hidden.get(cmd) ?? /* @__PURE__ */ new Set();
3654
+ names.add(alias);
3655
+ hidden.set(cmd, names);
3656
+ return cmd;
3657
+ }
3658
+ function visibleAliases(cmd) {
3659
+ const names = hidden.get(cmd);
3660
+ return cmd.aliases().filter((alias) => !names?.has(alias));
3661
+ }
3662
+ function withVisibleAliasesOnly(cmd, render) {
3663
+ const target = cmd;
3664
+ const all = target._aliases;
3665
+ target._aliases = visibleAliases(cmd);
3666
+ try {
3667
+ return render();
3668
+ } finally {
3669
+ target._aliases = all;
3670
+ }
3671
+ }
3672
+ var HIDDEN_ALIAS_HELP = {
3673
+ subcommandTerm(cmd) {
3674
+ return withVisibleAliasesOnly(cmd, () => Help.prototype.subcommandTerm.call(this, cmd));
3675
+ },
3676
+ commandUsage(cmd) {
3677
+ return withVisibleAliasesOnly(cmd, () => Help.prototype.commandUsage.call(this, cmd));
3678
+ }
3679
+ };
3680
+ var optionTargets = /* @__PURE__ */ new WeakMap();
3681
+ function hiddenOptionAlias(oldFlags, target) {
3682
+ const option = new Option(oldFlags).hideHelp();
3683
+ optionTargets.set(option, target);
3684
+ return option;
3685
+ }
3686
+ function wireHiddenOptionAliases(cmd) {
3687
+ for (const option of cmd.options) {
3688
+ const target = optionTargets.get(option);
3689
+ if (!target) continue;
3690
+ cmd.on(`option:${option.name()}`, (value) => {
3691
+ cmd.setOptionValue(target, value);
3692
+ });
3693
+ }
3694
+ for (const sub of cmd.commands) wireHiddenOptionAliases(sub);
3695
+ }
3696
+
3577
3697
  // src/util/references.ts
3578
3698
  function parseEntityReference(ref, overrides) {
3579
3699
  const config = loadConfig();
@@ -3933,6 +4053,81 @@ async function projectNames(api, projectIds) {
3933
4053
  return names;
3934
4054
  }
3935
4055
 
4056
+ // src/util/entity-attributes.ts
4057
+ function encodeTextAttribute(value) {
4058
+ return Buffer.from(value, "utf-8").toString("base64");
4059
+ }
4060
+ function decodeTextAttribute(value) {
4061
+ if (value === null || value === void 0) return null;
4062
+ return Buffer.from(value, "base64").toString("utf-8");
4063
+ }
4064
+ function encodeLongAttribute(value) {
4065
+ if (!Number.isSafeInteger(value)) {
4066
+ throw new RangeError(`Not an integer attribute value: ${value}`);
4067
+ }
4068
+ const bytes = Buffer.alloc(8);
4069
+ bytes.writeBigInt64BE(BigInt(value));
4070
+ return bytes.toString("base64");
4071
+ }
4072
+
4073
+ // src/util/project-entity.ts
4074
+ function buildProjectRootEntity(args) {
4075
+ const now = Date.now();
4076
+ const attributes = {};
4077
+ const attributeTypes = {};
4078
+ if (args.name) {
4079
+ attributes.name = encodeTextAttribute(args.name);
4080
+ attributeTypes.name = "text";
4081
+ }
4082
+ if (args.description) {
4083
+ attributes.description = encodeTextAttribute(args.description);
4084
+ attributeTypes.description = "text";
4085
+ }
4086
+ return {
4087
+ projectId: args.projectId,
4088
+ projectBranch: "main",
4089
+ entityId: args.projectId,
4090
+ entityBranch: "main",
4091
+ head: true,
4092
+ version: 1,
4093
+ type: "project",
4094
+ attributes,
4095
+ attributeTypes,
4096
+ metaAttributes: {},
4097
+ metaAttributeTypes: {},
4098
+ tags: [],
4099
+ modified: now,
4100
+ created: now,
4101
+ versioned: false,
4102
+ versionTtl: null,
4103
+ retain: false,
4104
+ contentAvailable: false,
4105
+ contentLoaded: false,
4106
+ contentType: null,
4107
+ contentSize: null,
4108
+ content: null
4109
+ };
4110
+ }
4111
+ function withProjectTexts(root, texts) {
4112
+ const attributes = { ...root.attributes ?? {} };
4113
+ const attributeTypes = { ...root.attributeTypes ?? {} };
4114
+ if (texts.name !== void 0) {
4115
+ attributes.name = encodeTextAttribute(texts.name.trim());
4116
+ attributeTypes.name = "text";
4117
+ }
4118
+ if (texts.description !== void 0) {
4119
+ const description = texts.description.trim();
4120
+ if (description) {
4121
+ attributes.description = encodeTextAttribute(description);
4122
+ attributeTypes.description = "text";
4123
+ } else {
4124
+ delete attributes.description;
4125
+ delete attributeTypes.description;
4126
+ }
4127
+ }
4128
+ return { ...root, attributes, attributeTypes, content: null };
4129
+ }
4130
+
3936
4131
  // src/commands/entity/tags.ts
3937
4132
  import chalk12 from "chalk";
3938
4133
 
@@ -4204,11 +4399,13 @@ Showing ${capped.length} of ${projects.length}. Pass --limit 0 to see them all.`
4204
4399
  handleError(error);
4205
4400
  }
4206
4401
  });
4207
- project.command("create").description("Create a new project").option("--visibility <visibility>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--language <language>", "The project's default language for functions (Java, Kotlin, Python, JavaScript, Scala)", DEFAULT_FUNCTION_LANGUAGE).option("--licence <licenceId>", "Licence a public project is published under, an id of the licence catalogue (see 'diafunc licence list')").addHelpText("after", `
4402
+ project.command("create").description("Create a new project").option("--name <name>", "The project's name; without one, a project bundle imported into it names it").option("--description <text>", "The project's description").option("--visibility <visibility>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--language <language>", "The project's default language for functions (Java, Kotlin, Python, JavaScript, Scala)", DEFAULT_FUNCTION_LANGUAGE).option("--license <licenseId>", "License a public project is published under, an id of the license catalog (see 'diafunc license list')").addOption(hiddenOptionAlias("--licence <licenseId>", "license")).addHelpText("after", `
4208
4403
  Examples:
4209
4404
  $ diafunc project create a private project
4210
- $ diafunc project create --visibility PUBLIC --licence CC-BY-4.0 a public one, open for reuse with attribution
4211
- $ diafunc licence list the licences that can be chosen
4405
+ $ diafunc project create --name "Vineyard yield" a private project with a name
4406
+ $ diafunc project import <projectId> guide.dfproj an unnamed one takes the bundle's name
4407
+ $ diafunc project create --visibility PUBLIC --license CC-BY-4.0 a public one, open for reuse with attribution
4408
+ $ diafunc license list the licenses that can be chosen
4212
4409
  `).action(async (options, cmd) => {
4213
4410
  try {
4214
4411
  const outputFormat = getOutputFormat2(cmd);
@@ -4217,19 +4414,25 @@ Examples:
4217
4414
  visibility: options.visibility.toUpperCase(),
4218
4415
  language: options.language,
4219
4416
  active: true,
4220
- ...options.licence ? { licenceId: options.licence } : {}
4417
+ ...options.license ? { licenceId: options.license } : {}
4221
4418
  });
4222
4419
  await api.storage.createProjectBranch({
4223
4420
  projectId: p.projectId,
4224
4421
  sourceProjectBranch: null,
4225
4422
  targetProjectBranch: "main"
4226
4423
  });
4424
+ await api.storage.saveEntities([buildProjectRootEntity({
4425
+ projectId: p.projectId,
4426
+ name: options.name,
4427
+ description: options.description
4428
+ })]);
4227
4429
  if (outputFormat === "human") {
4228
4430
  success("Project created.");
4431
+ if (options.name) console.log(` Name: ${options.name}`);
4229
4432
  console.log(` Project ID: ${chalk13.bold(p.projectId)}`);
4230
4433
  console.log(` Visibility: ${p.visibility}`);
4231
4434
  console.log(` Language: ${p.language}`);
4232
- if (p.licenceId) console.log(` Licence: ${p.licenceId}`);
4435
+ if (p.licenceId) console.log(` License: ${p.licenceId}`);
4233
4436
  } else {
4234
4437
  format(p, { format: outputFormat });
4235
4438
  }
@@ -4237,16 +4440,46 @@ Examples:
4237
4440
  handleError(error);
4238
4441
  }
4239
4442
  });
4240
- project.command("update").description("Update a project").argument("<projectId>", "Project ID").option("--visibility <visibility>", "PRIVATE or PUBLIC").option("--language <language>", "Project language").option("--active <bool>", "Whether the project is active (true/false)").option("--licence <licenceId>", "Licence a public project is published under, an id of the licence catalogue (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").option("--data-source-name <name>", "Who published the data the project analyses; an empty value clears it").option("--data-source-url <url>", "Where the data was obtained, an http(s) address; an empty value clears it").action(async (projectId, options) => {
4241
- try {
4242
- const api = createApiClient();
4443
+ project.command("update").description("Update a project").argument("<projectId>", "Project ID").option("--name <name>", "The project's name, shown on Explore and in the project header").option("--description <text>", "The project's description, shown on Explore; an empty value removes it").option("--visibility <visibility>", "PRIVATE or PUBLIC").option("--language <language>", "Project language").option("--active <bool>", "Whether the project is active (true/false)").option("--license <licenseId>", "License a public project is published under, an id of the license catalog (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").addOption(hiddenOptionAlias("--licence <licenseId>", "license")).option("--data-source-name <name>", "Who published the data the project analyzes; an empty value clears it").option("--data-source-url <url>", "Where the data was obtained, an http(s) address; an empty value clears it").addHelpText("after", `
4444
+ Examples:
4445
+ $ diafunc project update <projectId> --name "Vineyard yield" rename the project
4446
+ $ diafunc project update <projectId> --description "Yield per hectare" set the text Explore shows
4447
+ $ diafunc project update <projectId> --license CC-BY-4.0 publish it under another license
4448
+ `).action(async (projectId, options) => {
4449
+ try {
4450
+ const api = createApiClient();
4451
+ const projectOptions = ["visibility", "language", "active", "license", "dataSourceName", "dataSourceUrl"];
4452
+ const changesProject = projectOptions.some((key) => options[key] !== void 0);
4453
+ const changesTexts = options.name !== void 0 || options.description !== void 0;
4454
+ if (!changesProject && !changesTexts) {
4455
+ throw new Error("Nothing to update: give at least one option (see --help).");
4456
+ }
4457
+ if (options.name !== void 0 && !options.name.trim()) {
4458
+ throw new Error("A project name cannot be empty.");
4459
+ }
4460
+ if (changesTexts) {
4461
+ const root = await api.storage.getEntity({
4462
+ projectId,
4463
+ projectBranch: "main",
4464
+ entityId: projectId,
4465
+ entityBranch: "main"
4466
+ });
4467
+ await api.storage.saveEntities([withProjectTexts(root, {
4468
+ name: options.name,
4469
+ description: options.description
4470
+ })]);
4471
+ }
4472
+ if (!changesProject) {
4473
+ success(`Project "${projectId}" updated.`);
4474
+ return;
4475
+ }
4243
4476
  const current = await api.admin.getProject(projectId);
4244
4477
  const updated = {
4245
4478
  ...current,
4246
4479
  ...options.visibility ? { visibility: options.visibility.toUpperCase() } : {},
4247
4480
  ...options.language ? { language: options.language } : {},
4248
4481
  ...options.active !== void 0 ? { active: options.active === "true" } : {},
4249
- ...options.licence ? { licenceId: options.licence } : {},
4482
+ ...options.license ? { licenceId: options.license } : {},
4250
4483
  ...options.dataSourceName !== void 0 ? { dataSourceName: options.dataSourceName } : {},
4251
4484
  ...options.dataSourceUrl !== void 0 ? { dataSourceUrl: options.dataSourceUrl } : {}
4252
4485
  };
@@ -4363,7 +4596,7 @@ Examples:
4363
4596
  handleError(error);
4364
4597
  }
4365
4598
  });
4366
- project.command("import").description("Import a .dfproj (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project2, file, options, cmd) => {
4599
+ project.command("import").description("Import a .dfproj (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project2, file, options, cmd) => {
4367
4600
  try {
4368
4601
  const outputFormat = getOutputFormat2(cmd);
4369
4602
  const overrides = getOverrides(cmd);
@@ -4560,7 +4793,7 @@ Examples:
4560
4793
  const api = createApiClient();
4561
4794
  const response = await api.admin.cancelTeam(teamId);
4562
4795
  success(
4563
- `Team "${teamId}" cancelled. Access ends ${response.endsAt ?? "at the end of the period"}.`,
4796
+ `Team "${teamId}" canceled. Access ends ${response.endsAt ?? "at the end of the period"}.`,
4564
4797
  { format: getOutputFormat3(cmd) }
4565
4798
  );
4566
4799
  } catch (error) {
@@ -4796,7 +5029,7 @@ function registerOwnershipCommands(team) {
4796
5029
  try {
4797
5030
  const api = createApiClient();
4798
5031
  await api.admin.cancelOwnershipTransfer(teamId);
4799
- success(`Cancelled the ownership transfer for team "${teamId}".`, {
5032
+ success(`Canceled the ownership transfer for team "${teamId}".`, {
4800
5033
  format: getOutputFormat3(cmd)
4801
5034
  });
4802
5035
  } catch (error) {
@@ -5015,7 +5248,7 @@ Examples:
5015
5248
  handleError(error);
5016
5249
  }
5017
5250
  });
5018
- entity.command("import").description("Import a .dfset (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
5251
+ entity.command("import").description("Import a .dfset (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
5019
5252
  try {
5020
5253
  const outputFormat = getOutputFormat4(cmd);
5021
5254
  const overrides = getOverrides2(cmd);
@@ -5164,8 +5397,8 @@ function registerEventCommands(program) {
5164
5397
  });
5165
5398
  event.command("create").description("Create one or more events (body from JSON file or stdin)").argument("[file]", "JSON file containing a BareEvent array; defaults to stdin").action(async (file) => {
5166
5399
  try {
5167
- const fs18 = await import("fs");
5168
- const body = file ? fs18.readFileSync(file, "utf-8") : await new Promise((resolve2, reject) => {
5400
+ const fs19 = await import("fs");
5401
+ const body = file ? fs19.readFileSync(file, "utf-8") : await new Promise((resolve2, reject) => {
5169
5402
  let data = "";
5170
5403
  process.stdin.setEncoding("utf-8");
5171
5404
  process.stdin.on("data", (chunk) => {
@@ -5227,7 +5460,7 @@ function registerBranchCommands(program) {
5227
5460
  Examples:
5228
5461
  $ diafunc branch list <projectId>
5229
5462
  $ diafunc branch create <projectId> experiment
5230
- $ diafunc branch merge --from experiment --to main --entity <id>
5463
+ $ diafunc branch merge --source <projectId>/experiment/<entityId>/main --target <projectId>/main
5231
5464
  `);
5232
5465
  ;
5233
5466
  branch.command("list").description("List branches for a project").argument("[projectId]", "Project ID (uses default if omitted)").action(async (projectId, _options, cmd) => {
@@ -5395,7 +5628,7 @@ async function fetchWindow(fetchPart, window, maxCells = SNAPSHOT_MAX_CELLS) {
5395
5628
  }
5396
5629
  function describeWindow(window, rows, columns) {
5397
5630
  const whole = window.rows.from === 0 && window.rows.to === rows && window.columns.from === 0 && window.columns.to === columns;
5398
- const line = `Rows ${window.rows.from}\u2013${window.rows.to - 1} of ${rows} \xB7 columns ${window.columns.from}\u2013${window.columns.to - 1} of ${columns}`;
5631
+ const line = `Rows ${window.rows.from} to ${window.rows.to - 1} of ${rows} \xB7 columns ${window.columns.from} to ${window.columns.to - 1} of ${columns}`;
5399
5632
  return whole ? line : `${line} \xB7 use --rows/--cols for more`;
5400
5633
  }
5401
5634
  function decodeCellValue(value, type) {
@@ -5415,23 +5648,6 @@ function decodeCellValue(value, type) {
5415
5648
  return bytes.toString("utf-8");
5416
5649
  }
5417
5650
 
5418
- // src/util/entity-attributes.ts
5419
- function encodeTextAttribute(value) {
5420
- return Buffer.from(value, "utf-8").toString("base64");
5421
- }
5422
- function decodeTextAttribute(value) {
5423
- if (value === null || value === void 0) return null;
5424
- return Buffer.from(value, "base64").toString("utf-8");
5425
- }
5426
- function encodeLongAttribute(value) {
5427
- if (!Number.isSafeInteger(value)) {
5428
- throw new RangeError(`Not an integer attribute value: ${value}`);
5429
- }
5430
- const bytes = Buffer.alloc(8);
5431
- bytes.writeBigInt64BE(BigInt(value));
5432
- return bytes.toString("base64");
5433
- }
5434
-
5435
5651
  // src/util/table-entity.ts
5436
5652
  function buildTableEntity(args) {
5437
5653
  const now = Date.now();
@@ -5727,7 +5943,7 @@ Examples:
5727
5943
  const formats = await api.storage.getSupportedExportFormats();
5728
5944
  const format2 = formats.formats.find((f) => f.id.toLowerCase() === fmt.toLowerCase());
5729
5945
  if (!format2) {
5730
- failure(`Unknown format: "${fmt}". Run \`diafunc table export-formats\` to see the catalogue.`);
5946
+ failure(`Unknown format: "${fmt}". Run \`diafunc table export-formats\` to see the catalog.`);
5731
5947
  process.exit(1);
5732
5948
  }
5733
5949
  if (options.compression && !formats.compressionAlgorithms.includes(options.compression)) {
@@ -6011,7 +6227,7 @@ function getOverrides7(cmd) {
6011
6227
  function registerNotebookCommands(program) {
6012
6228
  const notebook = program.command("notebook").description("Export and import notebook bundles").addHelpText("after", `
6013
6229
  Examples:
6014
- $ diafunc notebook export <project> <notebookId> -o notebook.dfnb
6230
+ $ diafunc notebook export <project> <notebookId> --out notebook.dfnb
6015
6231
  $ diafunc notebook import <project> notebook.dfnb --preview
6016
6232
  $ diafunc notebook import <project> notebook.dfnb
6017
6233
  `);
@@ -6037,7 +6253,7 @@ Examples:
6037
6253
  handleError(error);
6038
6254
  }
6039
6255
  });
6040
- notebook.command("import").description("Import a .dfnb bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the .dfnb bundle").option("--on-conflict <policy>", "copy (default), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
6256
+ notebook.command("import").description("Import a .dfnb bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the .dfnb bundle").option("--on-conflict <policy>", "copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
6041
6257
  try {
6042
6258
  const outputFormat = getOutputFormat9(cmd);
6043
6259
  const overrides = getOverrides7(cmd);
@@ -6306,7 +6522,7 @@ Examples:
6306
6522
  } else {
6307
6523
  if (outputFormat === "human") {
6308
6524
  if (result.successful) {
6309
- success("Function completed successfully.");
6525
+ success("Function completed.");
6310
6526
  if (result.result) {
6311
6527
  console.log(` Result: ${resultText(result.result, result.resultEncoding)}`);
6312
6528
  }
@@ -6573,47 +6789,786 @@ function extensionFor(language) {
6573
6789
  return "txt";
6574
6790
  }
6575
6791
 
6576
- // src/commands/trigger/index.ts
6577
- function getOutputFormat11(cmd) {
6578
- const config = loadConfig();
6579
- const globalOpts = cmd.optsWithGlobals();
6580
- return globalOpts.output ?? config.defaults.output ?? "human";
6792
+ // src/commands/analyze/intent.ts
6793
+ import * as fs9 from "fs";
6794
+ import chalk19 from "chalk";
6795
+
6796
+ // src/commands/analyze/columns.ts
6797
+ var MAX_COLUMNS_LISTED = 30;
6798
+ var MAX_NEAR_MATCHES = 3;
6799
+ function parseColumnList(text2) {
6800
+ const names = [];
6801
+ let i = 0;
6802
+ while (i < text2.length) {
6803
+ while (i < text2.length && isSpace(text2[i])) i++;
6804
+ if (i >= text2.length) break;
6805
+ if (text2[i] === '"') {
6806
+ let name = "";
6807
+ let closed = false;
6808
+ i++;
6809
+ while (i < text2.length) {
6810
+ if (text2[i] === '"' && text2[i + 1] === '"') {
6811
+ name += '"';
6812
+ i += 2;
6813
+ } else if (text2[i] === '"') {
6814
+ closed = true;
6815
+ i++;
6816
+ break;
6817
+ } else {
6818
+ name += text2[i++];
6819
+ }
6820
+ }
6821
+ if (!closed) {
6822
+ throw new CliError(`A double quote is opened and never closed in: ${text2}`, {
6823
+ exitCode: EXIT_USAGE,
6824
+ hint: QUOTING_HINT
6825
+ });
6826
+ }
6827
+ while (i < text2.length && isSpace(text2[i])) i++;
6828
+ if (i < text2.length && text2[i] !== ",") {
6829
+ throw new CliError(`Text follows a closing double quote without a comma in: ${text2}`, {
6830
+ exitCode: EXIT_USAGE,
6831
+ hint: QUOTING_HINT
6832
+ });
6833
+ }
6834
+ i++;
6835
+ if (name.length > 0) names.push(name);
6836
+ } else {
6837
+ const end = text2.indexOf(",", i);
6838
+ const name = text2.slice(i, end === -1 ? text2.length : end).trim();
6839
+ i = end === -1 ? text2.length : end + 1;
6840
+ if (name.length > 0) names.push(name);
6841
+ }
6842
+ }
6843
+ return names;
6581
6844
  }
6582
- function getOverrides9(cmd) {
6583
- const opts = cmd.optsWithGlobals();
6584
- return { project: opts.project, branch: opts.branch };
6845
+ var QUOTING_HINT = `Inside a list, put a name that contains a comma in double quotes and write a quote in it twice: '"a, b",c'.`;
6846
+ function isSpace(char) {
6847
+ return char === " " || char === " ";
6585
6848
  }
6586
- function registerTriggerCommands(program) {
6587
- const trigger = program.command("trigger").description("Manage function triggers").addHelpText("after", `
6588
- Examples:
6589
- $ diafunc trigger list <ref>
6590
- $ diafunc trigger create <ref> --expression '0 0 * * *'
6591
- $ diafunc trigger delete <ref> <triggerId>
6592
- `);
6593
- ;
6594
- trigger.command("list").description("List triggers for a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
6595
- try {
6596
- const outputFormat = getOutputFormat11(cmd);
6597
- const overrides = getOverrides9(cmd);
6598
- const resolved = parseEntityReference(ref, overrides);
6599
- const api = createApiClient();
6600
- const triggers = await api.evaluation.getTriggers(
6601
- resolved.projectId,
6602
- resolved.projectBranch,
6603
- resolved.entityId,
6604
- resolved.entityBranch
6849
+ function quoteColumn(name) {
6850
+ return `"${name.replace(/"/g, '""')}"`;
6851
+ }
6852
+ function loose(name) {
6853
+ return name.trim().toLowerCase();
6854
+ }
6855
+ function matchColumn(name, columns) {
6856
+ if (columns.includes(name)) return { kind: "column", column: name };
6857
+ const wanted = loose(name);
6858
+ const candidates = columns.filter((column) => loose(column) === wanted);
6859
+ if (candidates.length === 1) return { kind: "column", column: candidates[0] };
6860
+ return candidates.length > 1 ? { kind: "ambiguous", candidates } : { kind: "unknown" };
6861
+ }
6862
+ function nearMatches(name, columns) {
6863
+ const wanted = loose(name);
6864
+ if (wanted.length === 0) return [];
6865
+ return columns.map((column) => ({ column, distance: distanceTo(wanted, loose(column)) })).filter((scored) => scored.distance !== null).sort((a, b) => a.distance - b.distance).slice(0, MAX_NEAR_MATCHES).map((scored) => scored.column);
6866
+ }
6867
+ function distanceTo(wanted, column) {
6868
+ const edits = editDistance(wanted, column);
6869
+ if (edits <= Math.max(1, Math.floor(Math.min(wanted.length, column.length) / 4))) return edits;
6870
+ if (wanted.length >= 3 && (column.includes(wanted) || wanted.includes(column)) && column.length > 0) {
6871
+ return 100 + Math.abs(column.length - wanted.length);
6872
+ }
6873
+ return null;
6874
+ }
6875
+ function editDistance(a, b) {
6876
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
6877
+ for (let i = 1; i <= a.length; i++) {
6878
+ const current = [i];
6879
+ for (let j = 1; j <= b.length; j++) {
6880
+ current[j] = Math.min(
6881
+ previous[j] + 1,
6882
+ current[j - 1] + 1,
6883
+ previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
6605
6884
  );
6606
- const summary = triggers.map((t) => ({
6607
- triggerId: t.triggerId,
6608
- type: t.type,
6885
+ }
6886
+ previous = current;
6887
+ }
6888
+ return previous[b.length];
6889
+ }
6890
+ function take(name, columns, into, problems) {
6891
+ const match = matchColumn(name, columns);
6892
+ if (match.kind === "column") {
6893
+ if (!into.includes(match.column)) into.push(match.column);
6894
+ return true;
6895
+ }
6896
+ if (match.kind === "ambiguous") problems.ambiguous.push({ name, candidates: match.candidates });
6897
+ else problems.unknown.push(name);
6898
+ return false;
6899
+ }
6900
+ function refuse(problems, columns, analysisId) {
6901
+ const sentences = [];
6902
+ if (problems.unknown.length === 1) {
6903
+ sentences.push(`${quoteColumn(problems.unknown[0])} is not a column of the analysis data.`);
6904
+ } else if (problems.unknown.length > 1) {
6905
+ sentences.push(`These are not columns of the analysis data: ${problems.unknown.map(quoteColumn).join(", ")}.`);
6906
+ }
6907
+ for (const { name, candidates } of problems.ambiguous) {
6908
+ sentences.push(`${quoteColumn(name)} matches more than one column: ${candidates.map(quoteColumn).join(", ")}. Type the one you mean exactly.`);
6909
+ }
6910
+ const hints = [];
6911
+ const near = [...new Set(problems.unknown.flatMap((name) => nearMatches(name, columns)))];
6912
+ if (near.length > 0) hints.push(`Did you mean ${near.map(quoteColumn).join(" or ")}?`);
6913
+ const listed2 = columns.slice(0, MAX_COLUMNS_LISTED).map(quoteColumn).join(", ");
6914
+ const more = columns.length > MAX_COLUMNS_LISTED ? ` and ${columns.length - MAX_COLUMNS_LISTED} more${analysisId ? ` ('diafunc analyze columns ${analysisId}' lists them all)` : ""}` : "";
6915
+ hints.push(`The columns are: ${listed2}${more}.`);
6916
+ if (problems.fromList) {
6917
+ hints.push(`A name that contains a comma is an argument of its own, or goes in double quotes inside a list: '"a, b",c'.`);
6918
+ }
6919
+ throw new CliError(sentences.join(" "), { exitCode: EXIT_USAGE, hint: hints.join("\n ") });
6920
+ }
6921
+ function resolveColumnArguments(given, columns, analysisId) {
6922
+ const resolved = [];
6923
+ if (columns.length === 0) {
6924
+ for (const name of given.flatMap(parseColumnList)) {
6925
+ if (!resolved.includes(name)) resolved.push(name);
6926
+ }
6927
+ return resolved;
6928
+ }
6929
+ const problems = { unknown: [], ambiguous: [], fromList: false };
6930
+ for (const argument of given) {
6931
+ if (argument.trim().length === 0) continue;
6932
+ const whole = matchColumn(argument, columns);
6933
+ if (whole.kind === "column") {
6934
+ if (!resolved.includes(whole.column)) resolved.push(whole.column);
6935
+ continue;
6936
+ }
6937
+ const names = parseColumnList(argument);
6938
+ const single = names.length === 1 && names[0] === argument.trim();
6939
+ for (const name of names) {
6940
+ if (!take(name, columns, resolved, problems) && !single) problems.fromList = true;
6941
+ }
6942
+ }
6943
+ if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
6944
+ return resolved;
6945
+ }
6946
+ function resolveColumnNames(names, columns, analysisId) {
6947
+ if (columns.length === 0) return [...names];
6948
+ const resolved = [];
6949
+ const problems = { unknown: [], ambiguous: [], fromList: false };
6950
+ for (const name of names) take(name, columns, resolved, problems);
6951
+ if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
6952
+ return resolved;
6953
+ }
6954
+ function resolveColumnArgument(given, columns, analysisId) {
6955
+ if (columns.length === 0) return given;
6956
+ return resolveColumnNames([given], columns, analysisId)[0];
6957
+ }
6958
+ function occurrences(value) {
6959
+ if (value === void 0) return void 0;
6960
+ return Array.isArray(value) ? value : [value];
6961
+ }
6962
+ function collectColumns(value, previous = []) {
6963
+ return previous.concat([value]);
6964
+ }
6965
+
6966
+ // src/commands/analyze/intent.ts
6967
+ var MAX_INTENT_LENGTH = 8e3;
6968
+ var MAX_PAIRS = 12;
6969
+ var MAX_FOCUS = 3;
6970
+ var CHART_KINDS = ["scatter", "groups", "counts"];
6971
+ var SHAPE_KINDS = ["increasing", "decreasing", "convex", "concave", "range"];
6972
+ var FOCUS_FAMILIES = [
6973
+ { id: "formula", label: "the formula" },
6974
+ { id: "accuracy", label: "how accurate the model is" },
6975
+ { id: "input_importance", label: "which inputs matter most" },
6976
+ { id: "search", label: "how the search went" },
6977
+ { id: "baselines", label: "the comparison with simple baselines" },
6978
+ { id: "partial_dependence", label: "how each input moves the prediction" },
6979
+ { id: "extrapolation", label: "behavior outside the observed range" },
6980
+ { id: "what_if", label: "what-if scenarios and sensitivity" },
6981
+ { id: "interactions", label: "interactions between inputs" },
6982
+ { id: "term_ablation", label: "what each term of the formula adds" },
6983
+ { id: "residuals", label: "errors and prediction intervals" },
6984
+ { id: "temporal", label: "behavior over time" },
6985
+ { id: "classification", label: "classification performance" },
6986
+ { id: "rating_levels", label: "the rating levels" },
6987
+ { id: "count_distribution", label: "the distribution of counts" },
6988
+ { id: "segments", label: "differences between groups" },
6989
+ { id: "fairness", label: "fairness across groups of people" },
6990
+ { id: "out_of_distribution", label: "inputs unlike the training data" },
6991
+ { id: "causality", label: "whether the relationships are causal" },
6992
+ { id: "deployment", label: "whether the model is ready to use" },
6993
+ { id: "multiple_targets", label: "how the targets relate to each other" },
6994
+ { id: "columns", label: "what each column holds" },
6995
+ { id: "correlations", label: "how the columns move together" },
6996
+ { id: "leakage", label: "columns that give the answer away" },
6997
+ { id: "duplicates", label: "duplicate rows" },
6998
+ { id: "trends", label: "trends over time in the data" },
6999
+ { id: "geography", label: "where the rows are located" }
7000
+ ];
7001
+ function notesFromOptions(options) {
7002
+ if (options.intent !== void 0 && options.intentFile !== void 0) {
7003
+ usageError("Give the notes with --intent or with --intent-file, not both.");
7004
+ }
7005
+ let text2 = options.intent;
7006
+ if (options.intentFile !== void 0) {
7007
+ if (!fs9.existsSync(options.intentFile)) {
7008
+ throw new CliError(`File not found: ${options.intentFile}`, { exitCode: EXIT_USAGE });
7009
+ }
7010
+ text2 = fs9.readFileSync(options.intentFile, "utf8");
7011
+ }
7012
+ if (text2 === void 0) return void 0;
7013
+ checkNotesLength(text2);
7014
+ return text2.trim();
7015
+ }
7016
+ function checkNotesLength(text2) {
7017
+ if (text2.length > MAX_INTENT_LENGTH) {
7018
+ usageError(`The notes are ${text2.length.toLocaleString("en-US")} characters long; at most ${MAX_INTENT_LENGTH.toLocaleString("en-US")} are kept.`, "Shorten them and run it again.");
7019
+ }
7020
+ }
7021
+ function checkedStatement(statement) {
7022
+ const text2 = statement.trim();
7023
+ const refuse2 = (why) => usageError(
7024
+ `'${statement}' is not a shape expectation: ${why}.`,
7025
+ "Write one of increasing(input), decreasing(input, from, to), convex(input), concave(input) or range(lower, upper), with 'check:' (the default) or 'require:' in front."
7026
+ );
7027
+ if (text2.length === 0) refuse2("it is empty");
7028
+ if (/[;\n]/.test(text2)) refuse2("give one expectation per statement");
7029
+ let body = text2;
7030
+ const colon = text2.indexOf(":");
7031
+ const open = text2.indexOf("(");
7032
+ if (colon > 0 && (open < 0 || colon < open)) {
7033
+ const mode = text2.slice(0, colon).trim().toLowerCase();
7034
+ if (mode !== "check" && mode !== "require") refuse2(`the mode '${mode}' is neither check nor require`);
7035
+ body = text2.slice(colon + 1).trim();
7036
+ }
7037
+ const kindEnd = body.indexOf("(");
7038
+ if (kindEnd <= 0 || !body.endsWith(")")) refuse2("it has no kind(arguments) form");
7039
+ const kind = body.slice(0, kindEnd).trim().toLowerCase();
7040
+ if (!SHAPE_KINDS.includes(kind)) refuse2(`'${kind}' is not a kind of expectation`);
7041
+ return text2;
7042
+ }
7043
+ function parseShapeFlag(given) {
7044
+ const equals = given.lastIndexOf("=");
7045
+ if (equals <= 0) {
7046
+ usageError(`'${given}' names no target.`, "Write --shape <target>=<statement>, for example --shape 'price=increasing(size_m2)'.");
7047
+ }
7048
+ const target = given.slice(0, equals).trim();
7049
+ if (target.length === 0) usageError(`'${given}' names no target.`);
7050
+ return { target, statement: checkedStatement(given.slice(equals + 1)) };
7051
+ }
7052
+ function shapesOf(given) {
7053
+ if (given === void 0 || given.length === 0) return null;
7054
+ const byTarget = {};
7055
+ for (const flag of given) {
7056
+ const { target, statement } = parseShapeFlag(flag);
7057
+ byTarget[target] ??= [];
7058
+ if (!byTarget[target].includes(statement)) byTarget[target].push(statement);
7059
+ }
7060
+ return byTarget;
7061
+ }
7062
+ function resolveShapeTargets(byTarget, columns, analysisId) {
7063
+ const resolved = {};
7064
+ for (const [target, statements] of Object.entries(byTarget)) {
7065
+ const column = resolveColumnArgument(target, columns, analysisId);
7066
+ resolved[column] = [...resolved[column] ?? [], ...statements.filter((s) => !(resolved[column] ?? []).includes(s))];
7067
+ }
7068
+ return resolved;
7069
+ }
7070
+ function boundText(text2) {
7071
+ const trimmed = text2.trim();
7072
+ const n = Number(trimmed);
7073
+ return Number.isFinite(n) ? n.toLocaleString("en-US", { maximumFractionDigits: 6 }) : trimmed;
7074
+ }
7075
+ function isOpen(text2) {
7076
+ if (text2 === void 0) return true;
7077
+ const t = text2.trim().toLowerCase();
7078
+ return t === "" || t === "inf" || t === "+inf" || t === "-inf" || t === "infinity" || t === "-infinity";
7079
+ }
7080
+ function expectationText(target, statement) {
7081
+ const read = /^\s*(?:(check|require)\s*:)?\s*([a-z]+)\s*\((.*)\)\s*$/i.exec(statement);
7082
+ if (!read) return `${target}: ${statement}`;
7083
+ const steer = (read[1] ?? "check").toLowerCase() === "require";
7084
+ const kind = read[2].toLowerCase();
7085
+ const args = read[3].split(",").map((a) => a.trim());
7086
+ const mode = steer ? "Steers the model" : "Checked";
7087
+ if (kind === "range") {
7088
+ const [lower, upper] = args;
7089
+ const sentence = !isOpen(lower) && !isOpen(upper) ? `${target} stays between ${boundText(lower)} and ${boundText(upper)}` : !isOpen(lower) ? `${target} is never below ${boundText(lower)}` : !isOpen(upper) ? `${target} is never above ${boundText(upper)}` : `${target} has no bound`;
7090
+ return `${sentence}. ${mode}.`;
7091
+ }
7092
+ const input = args[0];
7093
+ const shape = kind === "increasing" ? `does not fall as ${input} grows` : kind === "decreasing" ? `does not rise as ${input} grows` : kind === "convex" ? `curves upward as ${input} grows` : kind === "concave" ? `levels off as ${input} grows` : null;
7094
+ if (!shape) return `${target}: ${statement}`;
7095
+ const window = args.length === 3 && !(isOpen(args[1]) && isOpen(args[2])) ? ` (${input} ${boundText(args[1])} to ${boundText(args[2])})` : args.length === 1 ? ` (across the observed ${input} values)` : "";
7096
+ return `${target} ${shape}${window}. ${mode}.`;
7097
+ }
7098
+ function expectationLines(byTarget) {
7099
+ if (!byTarget) return [];
7100
+ return Object.entries(byTarget).flatMap(([target, statements]) => statements.map((s) => expectationText(target, s)));
7101
+ }
7102
+ function parsePair(given) {
7103
+ const entries = parseColumnList(given);
7104
+ const usage = `Write <first>,<second> or <first>,<second>,<kind> with kind one of ${CHART_KINDS.join(", ")}; a column whose name holds a comma goes in double quotes: '"a, b",price'.`;
7105
+ if (entries.length < 2 || entries.length > 3) {
7106
+ usageError(`'${given}' is not a chart: it names ${entries.length} ${entries.length === 1 ? "entry" : "entries"}.`, usage);
7107
+ }
7108
+ let kind = null;
7109
+ if (entries.length === 3) {
7110
+ const typed2 = entries[2].trim().toLowerCase();
7111
+ if (!CHART_KINDS.includes(typed2)) {
7112
+ usageError(`'${entries[2]}' is not a chart kind.`, usage);
7113
+ }
7114
+ kind = typed2;
7115
+ }
7116
+ if (entries[0] === entries[1]) usageError(`'${given}' names the same column twice; a chart needs two different columns.`);
7117
+ return { first: entries[0], second: entries[1], kind };
7118
+ }
7119
+ function pairsOf(given) {
7120
+ if (given === void 0) return null;
7121
+ const pairs = [];
7122
+ for (const entry of given) {
7123
+ if (entry.trim().length === 0) continue;
7124
+ const pair = parsePair(entry);
7125
+ if (!pairs.some((p) => p.first === pair.first && p.second === pair.second && p.kind === pair.kind)) pairs.push(pair);
7126
+ }
7127
+ if (pairs.length > MAX_PAIRS) usageError(`${pairs.length} charts are asked for; at most ${MAX_PAIRS} can be.`);
7128
+ return pairs;
7129
+ }
7130
+ function resolvePairs(pairs, columns, analysisId) {
7131
+ return pairs.map((pair) => {
7132
+ const [first, second] = resolveColumnNames([pair.first, pair.second], columns, analysisId);
7133
+ if (second === void 0) {
7134
+ usageError(`${quoteColumn(pair.first)} and ${quoteColumn(pair.second)} are the same column; a chart needs two different columns.`);
7135
+ }
7136
+ return { first, second, kind: pair.kind };
7137
+ });
7138
+ }
7139
+ function pairText(pair) {
7140
+ const how = pair.kind === "scatter" ? " as a scatter plot" : pair.kind === "groups" ? " by group" : pair.kind === "counts" ? " as counts" : "";
7141
+ return `${pair.second} against ${pair.first}${how}`;
7142
+ }
7143
+ function familyId(typed2) {
7144
+ return typed2.trim().toLowerCase().replace(/[- ]/g, "_");
7145
+ }
7146
+ function focusOf(given) {
7147
+ if (given === void 0) return null;
7148
+ const families = [];
7149
+ const unknown = [];
7150
+ for (const typed2 of given.flatMap((g) => g.split(","))) {
7151
+ if (typed2.trim().length === 0) continue;
7152
+ const id = familyId(typed2);
7153
+ if (!FOCUS_FAMILIES.some((f) => f.id === id)) unknown.push(typed2.trim());
7154
+ else if (!families.includes(id)) families.push(id);
7155
+ }
7156
+ if (unknown.length > 0) {
7157
+ usageError(
7158
+ `${unknown.map((u) => `'${u}'`).join(", ")} ${unknown.length === 1 ? "is not a question family" : "are not question families"}.`,
7159
+ `The families are: ${FOCUS_FAMILIES.map((f) => f.id).join(", ")}.`
7160
+ );
7161
+ }
7162
+ if (families.length > MAX_FOCUS) {
7163
+ usageError(`${families.length} families are named; at most ${MAX_FOCUS} can be in focus.`, "Name the ones that matter most.");
7164
+ }
7165
+ return families;
7166
+ }
7167
+ function focusText(id) {
7168
+ return FOCUS_FAMILIES.find((f) => f.id === id)?.label ?? id;
7169
+ }
7170
+ function intentRecipeLines(analysis) {
7171
+ const lines = [];
7172
+ const statements = Object.values(analysis.shapeExpectations ?? {}).flat();
7173
+ if (statements.length > 0) {
7174
+ const steering = statements.filter((s) => /^\s*require\s*:/i.test(s)).length;
7175
+ const checked = statements.length - steering;
7176
+ const parts = [checked > 0 ? `${checked} checked` : null, steering > 0 ? `${steering} ${steering === 1 ? "steers" : "steer"} the model` : null].filter(Boolean);
7177
+ lines.push(`Expectations: ${parts.join(", ")}`);
7178
+ }
7179
+ const pairs = analysis.requestedPairs ?? [];
7180
+ if (pairs.length > 0) lines.push(`Charts: ${pairs.map(pairText).join("; ")}`);
7181
+ const focus = analysis.focusFamilies ?? [];
7182
+ if (focus.length > 0) lines.push(`Focus: ${focus.map(focusText).join(", ")}`);
7183
+ return lines;
7184
+ }
7185
+ function interpretRequestOf(analysis, intent) {
7186
+ return {
7187
+ intent,
7188
+ targets: analysis.targets ?? [],
7189
+ segment: analysis.segment ?? null,
7190
+ inputExclusions: analysis.inputExclusions ?? [],
7191
+ targetKinds: analysis.targetKinds ?? {}
7192
+ };
7193
+ }
7194
+ var PROFILE_ATTEMPTS = 10;
7195
+ var PROFILE_INTERVAL_MS = 2e3;
7196
+ function waitingForProfile(interpretation) {
7197
+ return interpretation.status === "UNAVAILABLE" && (interpretation.findings ?? []).some((f) => /profiled/i.test(f.text ?? ""));
7198
+ }
7199
+ function isProfilePending(error) {
7200
+ return error instanceof ApiError && error.status === 400 && /profiled/i.test(error.message);
7201
+ }
7202
+ var pause2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
7203
+ async function readNotes(api, analysisId, request, options = {}) {
7204
+ let interpretation = await api.analysis.interpretIntent(analysisId, request, options);
7205
+ for (let attempt = 1; attempt < PROFILE_ATTEMPTS && waitingForProfile(interpretation); attempt++) {
7206
+ await pause2(PROFILE_INTERVAL_MS);
7207
+ interpretation = await api.analysis.interpretIntent(analysisId, request, options);
7208
+ }
7209
+ return interpretation;
7210
+ }
7211
+ async function whenProfiled(save) {
7212
+ for (let attempt = 1; ; attempt++) {
7213
+ try {
7214
+ return await save();
7215
+ } catch (error) {
7216
+ if (attempt >= PROFILE_ATTEMPTS || !isProfilePending(error)) throw error;
7217
+ await pause2(PROFILE_INTERVAL_MS);
7218
+ }
7219
+ }
7220
+ }
7221
+ function effectLabel(item) {
7222
+ switch (item.effect) {
7223
+ case "checks":
7224
+ return item.steer ? "Steers the model" : "Checks the model";
7225
+ case "changes":
7226
+ return "Changes what is analyzed";
7227
+ case "presents":
7228
+ return item.kind === "pair" ? "Adds a chart" : item.kind === "question" ? "Adds a question" : item.kind === "focus" ? "Sets the focus" : "Changes what the report shows";
7229
+ case "note":
7230
+ return "A note only";
7231
+ case "unavailable":
7232
+ return "Not possible on this run";
7233
+ default:
7234
+ return item.effect;
7235
+ }
7236
+ }
7237
+ function stateLabel(state) {
7238
+ return state === "CONFIRMED" ? "Used" : state === "DECLINED" ? "Not used" : "Proposed";
7239
+ }
7240
+ function groupOf(item) {
7241
+ if (item.effect === "checks" || item.effect === "changes") return 0;
7242
+ if (item.effect === "presents") return 1;
7243
+ if (item.effect === "note") return 2;
7244
+ return 3;
7245
+ }
7246
+ var GROUP_HEADINGS = [
7247
+ "About the model and the data",
7248
+ "What the report shows",
7249
+ "Notes for the report",
7250
+ "Not possible on this run"
7251
+ ];
7252
+ function orderedItems(items) {
7253
+ return [...items].sort((a, b) => groupOf(a) - groupOf(b));
7254
+ }
7255
+ function printInterpretation(interpretation, analysisId) {
7256
+ const items = orderedItems(interpretation.items ?? []);
7257
+ if (interpretation.status === "EMPTY") {
7258
+ console.log(chalk19.dim("No notes to read."));
7259
+ hint(`Write them with 'diafunc analyze intent ${analysisId} "<text>"'.`);
7260
+ return;
7261
+ }
7262
+ if (interpretation.status === "UNAVAILABLE") {
7263
+ for (const finding of interpretation.findings ?? []) warn(finding.text);
7264
+ if ((interpretation.findings ?? []).length === 0) warn("Your notes could not be read just now. Nothing was changed.");
7265
+ return;
7266
+ }
7267
+ if (items.length === 0) console.log(chalk19.dim("Nothing in the notes could be turned into a proposal."));
7268
+ let group = -1;
7269
+ for (const item of items) {
7270
+ if (groupOf(item) !== group) {
7271
+ group = groupOf(item);
7272
+ heading(GROUP_HEADINGS[group]);
7273
+ }
7274
+ console.log(` ${chalk19.cyan(item.id)} ${stateLabel(item.state)} \xB7 ${effectLabel(item)}`);
7275
+ console.log(` ${item.statement}`);
7276
+ if (item.quote) detail(` from: "${item.quote}"`);
7277
+ }
7278
+ const notUnderstood = interpretation.notUnderstood ?? [];
7279
+ if (notUnderstood.length > 0) {
7280
+ heading("Not understood");
7281
+ for (const note of notUnderstood) console.log(` "${note.quote}"${note.reason ? `: ${note.reason}` : ""}`);
7282
+ }
7283
+ const rejections = interpretation.rejections ?? [];
7284
+ if (rejections.length > 0) {
7285
+ heading("Not used");
7286
+ for (const note of rejections) console.log(` "${note.quote}"${note.reason ? `: ${note.reason}` : ""}`);
7287
+ }
7288
+ const findings = interpretation.findings ?? [];
7289
+ if (findings.length > 0) {
7290
+ heading("Before you launch");
7291
+ for (const finding of findings) console.log(` ${finding.title ? `${finding.title}: ` : ""}${finding.text}`);
7292
+ }
7293
+ if (items.some((item) => item.state === "PROPOSED" && item.effect !== "unavailable")) {
7294
+ console.log();
7295
+ hint("Nothing changes until you confirm a proposal. Expectations are checked; add --steer to let one steer the model.");
7296
+ hint(`Use one with 'diafunc analyze intent confirm ${analysisId} <proposalId...>', or 'decline' it.`);
7297
+ }
7298
+ }
7299
+ async function promptIntentDecisions(prompter, interpretation) {
7300
+ const decisions = [];
7301
+ for (const item of orderedItems(interpretation.items ?? [])) {
7302
+ if (item.state !== "PROPOSED" || item.effect === "unavailable") continue;
7303
+ if (item.quote) detail(`from your notes: "${item.quote}"`);
7304
+ const use = await prompter.confirm({
7305
+ message: `${item.statement} (${effectLabel(item)}) Use it?`,
7306
+ default: item.effect === "presents"
7307
+ });
7308
+ if (!use) {
7309
+ decisions.push({ id: item.id, state: "DECLINED", steer: null });
7310
+ continue;
7311
+ }
7312
+ const steer = item.effect === "checks" ? await prompter.confirm({
7313
+ message: "Also use it to steer the model? Without steering it is checked and reported, and never decides which model is delivered.",
7314
+ default: false
7315
+ }) : null;
7316
+ decisions.push({ id: item.id, state: "CONFIRMED", steer });
7317
+ }
7318
+ return decisions;
7319
+ }
7320
+ function printUnavailable(interpretation) {
7321
+ for (const item of interpretation.items ?? []) {
7322
+ if (item.effect === "unavailable") warn(item.statement);
7323
+ }
7324
+ }
7325
+
7326
+ // src/prompting/resolvers.ts
7327
+ var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
7328
+ var TRIGGER_TYPES = ["CRON", "INTERVAL", "CONTINUOUS", "EVENT"];
7329
+ var ANALYSIS_TRIGGER_KINDS = ["ONCE", "CRON"];
7330
+ var VISIBILITIES = ["PRIVATE", "PUBLIC"];
7331
+ var SHELLS = ["bash", "zsh", "fish"];
7332
+ var CONFIG_KEYS = ["defaults.project", "defaults.branch", "defaults.output"];
7333
+ var ENTITY_TYPE_BY_GROUP = {
7334
+ table: "table",
7335
+ function: "function",
7336
+ trigger: "function",
7337
+ schedule: "function"
7338
+ };
7339
+ var TEXT = { kind: "text" };
7340
+ var TEXT_OR_EMPTY = { kind: "text", allowEmpty: true };
7341
+ var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
7342
+ var INDEX = { kind: "number", min: 0, integer: true };
7343
+ var BY_COMMAND = {
7344
+ "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
7345
+ "analyze targets": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
7346
+ "analyze input-exclusions": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
7347
+ "analyze confirmed-inputs": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
7348
+ "analyze questions": { "<question>": TEXT_OR_EMPTY },
7349
+ "analyze description": { "<text>": TEXT_OR_EMPTY },
7350
+ "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
7351
+ "analyze intent confirm": { "<proposalId>": TEXT },
7352
+ "analyze intent decline": { "<proposalId>": TEXT },
7353
+ "analyze intent reset": { "<proposalId>": TEXT },
7354
+ "analyze charts": { "<pair>": TEXT_OR_EMPTY },
7355
+ "analyze focus": { "<family>": { kind: "choices", choices: FOCUS_FAMILIES.map((f) => f.id) } },
7356
+ // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.
7357
+ "public show": { "<analysisId>": TEXT },
7358
+ "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
7359
+ "branch merge": {
7360
+ "--source": { kind: "entity", form: "ref" },
7361
+ "--target": { kind: "project", withBranch: true }
7362
+ },
7363
+ "branch create": { "<branchName>": TEXT },
7364
+ "branch delete": { "<branchName>": { kind: "projectBranch", projectFrom: "projectId" } },
7365
+ "admin backup restore-project": { "<projectBranch>": { kind: "projectBranch", projectFrom: "projectId" } },
7366
+ "data-sources create": {
7367
+ "--project-id": { kind: "project", withBranch: false },
7368
+ "--project-branch": { kind: "projectBranch", projectFrom: "projectId" },
7369
+ "--target-entity-id": { kind: "entity", form: "id", contentType: "table", projectFrom: "projectId" },
7370
+ "--target-entity-branch": { kind: "text", defaultValue: "main" },
7371
+ "--type": { kind: "connectorType" }
7372
+ },
7373
+ "table-exporters create": {
7374
+ "--function-project": { kind: "project", withBranch: false },
7375
+ "--function-entity": { kind: "entity", form: "id", contentType: "function", projectFrom: "functionProject" },
7376
+ "--format": TEXT
7377
+ },
7378
+ "table exports get": { "--ref": { kind: "entity", form: "ref", contentType: "table" } },
7379
+ "table export": { "<format>": { kind: "exportFormat" } },
7380
+ "entity export": { "<entityIds>": { kind: "entity", form: "id", projectFrom: "project", multiple: true } },
7381
+ "notebook export": {
7382
+ "<notebookIds>": { kind: "entity", form: "id", contentType: "notebook", projectFrom: "project", multiple: true }
7383
+ },
7384
+ "entity tags set": { "<tags>": TEXT_OR_EMPTY },
7385
+ "project tags set": { "<tags>": TEXT_OR_EMPTY },
7386
+ "admin curated-tags create": { "--display-name": TEXT },
7387
+ "link delete": { "<linkId>": { kind: "link" } },
7388
+ "link create": { "<linkId>": TEXT },
7389
+ "config profile use": { "<name>": { kind: "profile" } },
7390
+ "config profile remove": { "<name>": { kind: "profile" } },
7391
+ "config get": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
7392
+ "config set": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
7393
+ "project members invite": { "<userId>": TEXT, "<role>": { kind: "choice", choices: PROJECT_ROLES } },
7394
+ "project members join": { "<userId>": TEXT },
7395
+ "trigger create": { "--type": { kind: "choice", choices: TRIGGER_TYPES } },
7396
+ "analyze triggers create": { "--kind": { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS } },
7397
+ "function outputs": { "<evaluationId>": TEXT },
7398
+ "team create": { "--seats": { kind: "number", min: 1, integer: true } },
7399
+ "team seats preview": { "<count>": { kind: "number", min: 1, integer: true } },
7400
+ "team seats set": { "<count>": { kind: "number", min: 1, integer: true } }
7401
+ };
7402
+ var BY_NAME = {
7403
+ projectId: { kind: "project", withBranch: false },
7404
+ projectRef: { kind: "project", withBranch: true },
7405
+ project: { kind: "project", withBranch: true },
7406
+ teamId: { kind: "team" },
7407
+ invitationId: { kind: "teamInvitation" },
7408
+ analysisId: { kind: "analysis" },
7409
+ licenseId: { kind: "license" },
7410
+ sessionId: { kind: "chatSession" },
7411
+ tokenId: { kind: "apiToken" },
7412
+ resource: { kind: "tokenResource" },
7413
+ scopes: { kind: "choices", choices: VALID_SCOPES },
7414
+ evaluationId: { kind: "evaluation" },
7415
+ eventId: { kind: "event" },
7416
+ occurrenceId: { kind: "occurrence" },
7417
+ exportId: { kind: "tableExport" },
7418
+ invoiceNumber: { kind: "invoice" },
7419
+ fileName: { kind: "invoiceDocument" },
7420
+ shell: { kind: "choice", choices: SHELLS },
7421
+ vis: { kind: "choice", choices: VISIBILITIES },
7422
+ kind: { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS },
7423
+ date: { kind: "date" },
7424
+ file: { kind: "file" },
7425
+ email: { kind: "text", email: true },
7426
+ index: INDEX,
7427
+ row: INDEX,
7428
+ col: INDEX,
7429
+ count: INDEX,
7430
+ version: { kind: "number", min: 1, integer: true },
7431
+ hours: POSITIVE,
7432
+ credits: POSITIVE,
7433
+ seats: { kind: "number", min: 1, integer: true },
7434
+ value: TEXT_OR_EMPTY,
7435
+ // Free text: names, messages and ids the reader is creating rather than choosing.
7436
+ name: TEXT,
7437
+ tag: TEXT,
7438
+ tags: TEXT,
7439
+ newId: TEXT,
7440
+ message: TEXT,
7441
+ query: TEXT,
7442
+ title: TEXT,
7443
+ token: TEXT,
7444
+ subscriptionToken: TEXT,
7445
+ forkProjectId: TEXT,
7446
+ targetBranch: TEXT,
7447
+ bucketName: TEXT,
7448
+ objectName: TEXT,
7449
+ template: TEXT,
7450
+ plan: TEXT,
7451
+ schedule: TEXT,
7452
+ consumerType: TEXT,
7453
+ consumerId: TEXT,
7454
+ format: TEXT,
7455
+ key: TEXT
7456
+ };
7457
+ function tokenOf(input) {
7458
+ return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
7459
+ }
7460
+ function specFor(path13, input) {
7461
+ const exact = BY_COMMAND[path13]?.[tokenOf(input)];
7462
+ if (exact) return exact;
7463
+ const group = path13.split(" ")[0];
7464
+ const sub = path13.split(" ").slice(0, 2).join(" ");
7465
+ switch (input.name) {
7466
+ case "ref":
7467
+ case "sourceRef":
7468
+ case "targetRef":
7469
+ return { kind: "entity", form: "ref", contentType: ENTITY_TYPE_BY_GROUP[group] };
7470
+ case "userId":
7471
+ return group === "team" ? { kind: "teamMember" } : { kind: "projectMember" };
7472
+ case "id":
7473
+ if (sub === "analyze presets") return { kind: "preset" };
7474
+ if (group === "analyze") return { kind: "analysis" };
7475
+ if (group === "data-sources") return { kind: "dataSource" };
7476
+ if (group === "skeleton") return { kind: "skeleton" };
7477
+ if (group === "table-exporters") return { kind: "tableExporter" };
7478
+ if (group === "status") return { kind: "statusComponent" };
7479
+ return null;
7480
+ case "runId":
7481
+ if (group === "analyze") return { kind: "analysisRun" };
7482
+ if (group === "data-sources") return { kind: "dataSourceRun" };
7483
+ return null;
7484
+ case "triggerId":
7485
+ if (group === "analyze") return { kind: "analysisTrigger" };
7486
+ if (group === "trigger") return { kind: "functionTrigger" };
7487
+ return null;
7488
+ case "role":
7489
+ return { kind: "choice", choices: PROJECT_ROLES };
7490
+ case "type":
7491
+ return null;
7492
+ default:
7493
+ return BY_NAME[input.name] ?? null;
7494
+ }
7495
+ }
7496
+ function dependencies(spec) {
7497
+ switch (spec.kind) {
7498
+ case "teamMember":
7499
+ case "teamInvitation":
7500
+ return ["teamId"];
7501
+ case "projectMember":
7502
+ return ["projectId"];
7503
+ case "analysisColumns":
7504
+ return ["id"];
7505
+ case "evaluation":
7506
+ return ["ref", "date"];
7507
+ case "functionTrigger":
7508
+ case "event":
7509
+ case "tableExport":
7510
+ return ["ref"];
7511
+ case "occurrence":
7512
+ return ["ref", "eventId"];
7513
+ case "link":
7514
+ return ["sourceRef"];
7515
+ case "tokenResource":
7516
+ return ["resourceType"];
7517
+ case "dataSourceRun":
7518
+ return ["id"];
7519
+ case "invoiceDocument":
7520
+ return ["invoiceNumber"];
7521
+ case "projectBranch":
7522
+ return [spec.projectFrom];
7523
+ case "entity":
7524
+ return spec.projectFrom ? [spec.projectFrom] : [];
7525
+ default:
7526
+ return [];
7527
+ }
7528
+ }
7529
+
7530
+ // src/commands/trigger/index.ts
7531
+ function getOutputFormat11(cmd) {
7532
+ const config = loadConfig();
7533
+ const globalOpts = cmd.optsWithGlobals();
7534
+ return globalOpts.output ?? config.defaults.output ?? "human";
7535
+ }
7536
+ function getOverrides9(cmd) {
7537
+ const opts = cmd.optsWithGlobals();
7538
+ return { project: opts.project, branch: opts.branch };
7539
+ }
7540
+ function registerTriggerCommands(program) {
7541
+ const trigger = program.command("trigger").description("Manage function triggers").addHelpText("after", `
7542
+ Examples:
7543
+ $ diafunc trigger list <ref>
7544
+ $ diafunc trigger create <ref> --type CRON --expression '0 0 6 * * ?' every day at 06:00 (Quartz cron)
7545
+ $ diafunc trigger create <ref> --type INTERVAL --expression '15min' every 15 minutes
7546
+ $ diafunc trigger delete <ref> <triggerId>
7547
+ `);
7548
+ trigger.command("list").description("List triggers for a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
7549
+ try {
7550
+ const outputFormat = getOutputFormat11(cmd);
7551
+ const overrides = getOverrides9(cmd);
7552
+ const resolved = parseEntityReference(ref, overrides);
7553
+ const api = createApiClient();
7554
+ const triggers = await api.evaluation.getTriggers(
7555
+ resolved.projectId,
7556
+ resolved.projectBranch,
7557
+ resolved.entityId,
7558
+ resolved.entityBranch
7559
+ );
7560
+ const summary = triggers.map((t) => ({
7561
+ triggerId: t.triggerId,
7562
+ type: t.type,
6609
7563
  active: t.active,
6610
7564
  expression: t.expression ?? "\u2014",
6611
7565
  fired: t.fired,
6612
- persistent: t.persistent
7566
+ persistent: t.persistent,
7567
+ createdBy: t.createdBy ? t.createdBy : "paused (save it again to resume)"
6613
7568
  }));
6614
7569
  format(summary, {
6615
7570
  format: outputFormat,
6616
- columns: ["triggerId", "type", "active", "expression", "fired", "persistent"]
7571
+ columns: ["triggerId", "type", "active", "expression", "fired", "persistent", "createdBy"]
6617
7572
  });
6618
7573
  } catch (error) {
6619
7574
  handleError(error);
@@ -6654,10 +7609,18 @@ Examples:
6654
7609
  handleError(error);
6655
7610
  }
6656
7611
  });
6657
- trigger.command("create").description("Create or update a trigger on a function").argument("<ref>", "Function entity reference").requiredOption("--type <type>", "Trigger type (SCHEDULE, EVENT, LINK, MANUAL)").option("--trigger-id <id>", "Trigger ID (auto-generated if omitted)").option("--expression <expr>", "Cron expression (for SCHEDULE) or event pattern").option("--origin <ref>", "Origin entity reference (for LINK/EVENT)").option("--persistent", "Persistent trigger (survives after first fire)").option("--inactive", "Create the trigger inactive").option("--max <n>", "Maximum fire count (0 = unlimited)", "0").option("--args <json>", "Arguments passed on fire (JSON object)").action(async (ref, options, cmd) => {
7612
+ trigger.command("create").description("Create or update a trigger on a function").argument("<ref>", "Function entity reference").requiredOption("--type <type>", `Trigger type (${TRIGGER_TYPES.join(", ")})`).option("--trigger-id <id>", "Trigger ID (auto-generated if omitted)").option("--expression <expr>", "CRON: a Quartz cron expression ('0 0 6 * * ?'); INTERVAL: a duration ('15min', '1h 30min')").option("--origin <ref>", "Origin entity reference (for EVENT)").option("--count <n>", "Runs started each time the trigger fires", "1").option("--persistent", "Persistent trigger (survives after first fire)").option("--inactive", "Create the trigger inactive").option("--max <n>", "Maximum fire count (0 = unlimited)", "0").option("--args <json>", "Arguments passed on fire (JSON object)").action(async (ref, options, cmd) => {
6658
7613
  try {
6659
7614
  const overrides = getOverrides9(cmd);
6660
7615
  const fn = parseEntityReference(ref, overrides);
7616
+ const type = String(options.type).toUpperCase();
7617
+ if (!TRIGGER_TYPES.includes(type)) {
7618
+ throw new Error(`Unknown trigger type "${options.type}": use one of ${TRIGGER_TYPES.join(", ")}.`);
7619
+ }
7620
+ const count = Number(options.count);
7621
+ if (!Number.isInteger(count) || count < 1) {
7622
+ throw new Error(`--count must be a whole number of at least 1, not "${options.count}".`);
7623
+ }
6661
7624
  const api = createApiClient();
6662
7625
  const args = options.args ? JSON.parse(options.args) : null;
6663
7626
  const types = args ? Object.fromEntries(
@@ -6677,14 +7640,14 @@ Examples:
6677
7640
  functionBranch: fn.entityBranch,
6678
7641
  triggerId: options.triggerId ?? null,
6679
7642
  bucketId: null,
6680
- type: options.type.toUpperCase(),
7643
+ type,
6681
7644
  expression: options.expression ?? null,
6682
7645
  conditions: null,
6683
7646
  conditionTypes: null,
6684
7647
  originEntityId,
6685
7648
  originEntityBranch,
6686
7649
  active: !options.inactive,
6687
- quantity: 0,
7650
+ quantity: count,
6688
7651
  fired: 0,
6689
7652
  maximum: options.max ? parseInt(options.max, 10) || null : null,
6690
7653
  evaluationIds: null,
@@ -6797,7 +7760,7 @@ function registerScheduleCommands(program) {
6797
7760
  resolved.entityId,
6798
7761
  resolved.entityBranch
6799
7762
  );
6800
- const scheduled = triggers.filter((t) => t.type === "SCHEDULE");
7763
+ const scheduled = triggers.filter((t) => t.type === "CRON" || t.type === "INTERVAL");
6801
7764
  const rows = scheduled.map((t) => ({
6802
7765
  triggerId: t.triggerId,
6803
7766
  expression: t.expression,
@@ -6817,12 +7780,12 @@ function registerScheduleCommands(program) {
6817
7780
  }
6818
7781
 
6819
7782
  // src/commands/chat/index.ts
6820
- import chalk20 from "chalk";
6821
- import * as fs9 from "fs";
7783
+ import chalk21 from "chalk";
7784
+ import * as fs10 from "fs";
6822
7785
  import * as path7 from "path";
6823
7786
 
6824
7787
  // src/output/markdown.ts
6825
- import chalk19 from "chalk";
7788
+ import chalk20 from "chalk";
6826
7789
  var CODE_OPEN = "\0c";
6827
7790
  var CODE_CLOSE = "\0";
6828
7791
  var MarkdownRenderer = class {
@@ -6858,25 +7821,25 @@ var MarkdownRenderer = class {
6858
7821
  if (fence) {
6859
7822
  const opening = !this.inFence;
6860
7823
  this.inFence = !this.inFence;
6861
- return opening && fence[1] ? [chalk19.dim(` ${fence[1]}`)] : [];
7824
+ return opening && fence[1] ? [chalk20.dim(` ${fence[1]}`)] : [];
6862
7825
  }
6863
7826
  if (this.inFence) {
6864
- return [chalk19.cyan(` ${line}`)];
7827
+ return [chalk20.cyan(` ${line}`)];
6865
7828
  }
6866
7829
  const heading2 = line.match(/^(#{1,6})\s+(.*)$/);
6867
7830
  if (heading2) {
6868
7831
  const text2 = inline(heading2[2]);
6869
- return ["", heading2[1].length <= 2 ? chalk19.bold.underline(text2) : chalk19.bold(text2)];
7832
+ return ["", heading2[1].length <= 2 ? chalk20.bold.underline(text2) : chalk20.bold(text2)];
6870
7833
  }
6871
7834
  if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
6872
- return [chalk19.dim("\u2500".repeat(Math.min(this.width, 60)))];
7835
+ return [chalk20.dim("\u2500".repeat(Math.min(this.width, 60)))];
6873
7836
  }
6874
7837
  const quote2 = line.match(/^\s*>\s?(.*)$/);
6875
- if (quote2) return [chalk19.dim(` \u2502 ${inline(quote2[1])}`)];
7838
+ if (quote2) return [chalk20.dim(` \u2502 ${inline(quote2[1])}`)];
6876
7839
  const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
6877
7840
  if (bullet) {
6878
7841
  return wrapWithIndent(
6879
- `${bullet[1]}${chalk19.cyan("\u2022")} ${inline(bullet[2])}`,
7842
+ `${bullet[1]}${chalk20.cyan("\u2022")} ${inline(bullet[2])}`,
6880
7843
  bullet[1].length + 2,
6881
7844
  this.width
6882
7845
  );
@@ -6884,7 +7847,7 @@ var MarkdownRenderer = class {
6884
7847
  const numbered = line.match(/^(\s*)(\d+)\.\s+(.*)$/);
6885
7848
  if (numbered) {
6886
7849
  return wrapWithIndent(
6887
- `${numbered[1]}${chalk19.cyan(`${numbered[2]}.`)} ${inline(numbered[3])}`,
7850
+ `${numbered[1]}${chalk20.cyan(`${numbered[2]}.`)} ${inline(numbered[3])}`,
6888
7851
  numbered[1].length + numbered[2].length + 2,
6889
7852
  this.width
6890
7853
  );
@@ -6907,10 +7870,10 @@ function inline(text2) {
6907
7870
  codeSpans.push(code);
6908
7871
  return `${CODE_OPEN}${codeSpans.length - 1}${CODE_CLOSE}`;
6909
7872
  });
6910
- working = working.replace(/\*\*([^*]+)\*\*/g, (_m, t) => chalk19.bold(t)).replace(/__([^_]+)__/g, (_m, t) => chalk19.bold(t)).replace(/(^|[^*])\*([^*\n]+)\*/g, (_m, lead, t) => lead + chalk19.italic(t)).replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `${chalk19.underline(label)} ${chalk19.dim(`(${url})`)}`);
7873
+ working = working.replace(/\*\*([^*]+)\*\*/g, (_m, t) => chalk20.bold(t)).replace(/__([^_]+)__/g, (_m, t) => chalk20.bold(t)).replace(/(^|[^*])\*([^*\n]+)\*/g, (_m, lead, t) => lead + chalk20.italic(t)).replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `${chalk20.underline(label)} ${chalk20.dim(`(${url})`)}`);
6911
7874
  return working.replace(
6912
7875
  new RegExp(`${CODE_OPEN}(\\d+)${CODE_CLOSE}`, "g"),
6913
- (_m, i) => chalk19.yellow(codeSpans[Number(i)])
7876
+ (_m, i) => chalk20.yellow(codeSpans[Number(i)])
6914
7877
  );
6915
7878
  }
6916
7879
 
@@ -6923,7 +7886,7 @@ function getOutputFormat13(cmd) {
6923
7886
  async function streamOneTurn(message, sessionId, projectId, branch, signal) {
6924
7887
  const api = createApiClient();
6925
7888
  const status = new Status();
6926
- status.set([` ${chalk20.magenta(SPINNER)} ${chalk20.dim("thinking")}`]);
7889
+ status.set([` ${chalk21.magenta(SPINNER)} ${chalk21.dim("thinking")}`]);
6927
7890
  status.start();
6928
7891
  let response;
6929
7892
  try {
@@ -7000,19 +7963,19 @@ var HELP = [
7000
7963
  ];
7001
7964
  async function runChatRepl(options) {
7002
7965
  const { input: promptInput } = await import("@inquirer/prompts");
7003
- const { getUpdateNotice } = await import("./update-check-JLTGX3S4.js");
7966
+ const { getUpdateNotice } = await import("./update-check-BH7IMKZN.js");
7004
7967
  let sessionId = options.session;
7005
7968
  let lastReportedSession;
7006
- console.log(chalk20.bold("Diafunc chat") + chalk20.dim(" \xB7 /help for commands, /quit to exit"));
7007
- if (options.project) console.log(chalk20.dim(`Project context: ${options.project}`));
7008
- if (sessionId) console.log(chalk20.dim(`Continuing session ${sessionId}`));
7969
+ console.log(chalk21.bold("Diafunc chat") + chalk21.dim(" \xB7 /help for commands, /quit to exit"));
7970
+ if (options.project) console.log(chalk21.dim(`Project context: ${options.project}`));
7971
+ if (sessionId) console.log(chalk21.dim(`Continuing session ${sessionId}`));
7009
7972
  const notice = await getUpdateNotice();
7010
- if (notice) console.log(chalk20.dim(notice));
7973
+ if (notice) console.log(chalk21.dim(notice));
7011
7974
  console.log();
7012
7975
  for (; ; ) {
7013
7976
  let line;
7014
7977
  try {
7015
- line = await promptInput({ message: chalk20.cyan.bold("you >") });
7978
+ line = await promptInput({ message: chalk21.cyan.bold("you >") });
7016
7979
  } catch {
7017
7980
  console.log();
7018
7981
  return;
@@ -7030,27 +7993,27 @@ async function runChatRepl(options) {
7030
7993
  case "new":
7031
7994
  sessionId = void 0;
7032
7995
  lastReportedSession = void 0;
7033
- console.log(chalk20.dim("Started a new session."));
7996
+ console.log(chalk21.dim("Started a new session."));
7034
7997
  continue;
7035
7998
  case "clear":
7036
7999
  console.clear();
7037
8000
  continue;
7038
8001
  case "session":
7039
8002
  if (!arg) {
7040
- console.log(chalk20.dim(`Current session: ${sessionId ?? "(new)"}`));
8003
+ console.log(chalk21.dim(`Current session: ${sessionId ?? "(new)"}`));
7041
8004
  } else {
7042
8005
  sessionId = arg;
7043
8006
  lastReportedSession = void 0;
7044
- console.log(chalk20.dim(`Switched to session ${sessionId}`));
8007
+ console.log(chalk21.dim(`Switched to session ${sessionId}`));
7045
8008
  }
7046
8009
  continue;
7047
8010
  case "help":
7048
8011
  case "h":
7049
8012
  case "?":
7050
- for (const l of HELP) console.log(chalk20.dim(l));
8013
+ for (const l of HELP) console.log(chalk21.dim(l));
7051
8014
  continue;
7052
8015
  default:
7053
- console.log(chalk20.dim(`Unknown command: /${cmd}. Try /help.`));
8016
+ console.log(chalk21.dim(`Unknown command: /${cmd}. Try /help.`));
7054
8017
  continue;
7055
8018
  }
7056
8019
  }
@@ -7063,19 +8026,19 @@ async function runChatRepl(options) {
7063
8026
  sessionId = result.sessionId || sessionId;
7064
8027
  console.log();
7065
8028
  if (controller.signal.aborted) {
7066
- console.log(chalk20.dim(" (cancelled)"));
8029
+ console.log(chalk21.dim(" (canceled)"));
7067
8030
  } else {
7068
8031
  const parts = [`${result.input} in / ${result.output} out`];
7069
8032
  if (sessionId && sessionId !== lastReportedSession) {
7070
8033
  parts.push(`session ${sessionId}`);
7071
8034
  lastReportedSession = sessionId;
7072
8035
  }
7073
- console.log(chalk20.dim(` ${parts.join(" \xB7 ")}`));
8036
+ console.log(chalk21.dim(` ${parts.join(" \xB7 ")}`));
7074
8037
  }
7075
8038
  console.log();
7076
8039
  } catch (error) {
7077
8040
  if (controller.signal.aborted) {
7078
- console.log(chalk20.dim(" (cancelled)"));
8041
+ console.log(chalk21.dim(" (canceled)"));
7079
8042
  console.log();
7080
8043
  } else {
7081
8044
  failure(`Request failed: ${error.message}`);
@@ -7119,7 +8082,7 @@ Examples:
7119
8082
  if (outputFormat === "human") {
7120
8083
  console.log(renderMarkdown(response.content));
7121
8084
  console.log();
7122
- console.log(chalk20.dim(
8085
+ console.log(chalk21.dim(
7123
8086
  ` session ${response.sessionId} \xB7 ${response.inputTokens} in / ${response.outputTokens} out`
7124
8087
  ));
7125
8088
  } else {
@@ -7187,7 +8150,7 @@ Examples:
7187
8150
  sessionId = event.sessionId ?? "";
7188
8151
  console.log();
7189
8152
  console.log();
7190
- console.log(chalk20.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
8153
+ console.log(chalk21.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
7191
8154
  } else if (event.type === "error") {
7192
8155
  failure(`Error: ${event.content}`);
7193
8156
  }
@@ -7203,12 +8166,12 @@ Examples:
7203
8166
  });
7204
8167
  chat.command("upload").description("Upload a file for chat context").argument("<file>", "File to upload").action(async (file) => {
7205
8168
  try {
7206
- if (!fs9.existsSync(file)) {
8169
+ if (!fs10.existsSync(file)) {
7207
8170
  failure(`File not found: ${file}`);
7208
8171
  process.exit(1);
7209
8172
  }
7210
8173
  const api = createApiClient();
7211
- const fileBuffer = fs9.readFileSync(file);
8174
+ const fileBuffer = fs10.readFileSync(file);
7212
8175
  const blob = new Blob([fileBuffer]);
7213
8176
  const formData = new FormData();
7214
8177
  formData.append("file", blob, path7.basename(file));
@@ -7247,11 +8210,11 @@ Examples:
7247
8210
  const api = createApiClient();
7248
8211
  const detail2 = await api.language.getSession(sessionId);
7249
8212
  if (outputFormat === "human") {
7250
- console.log(chalk20.bold(detail2.title) + chalk20.dim(` (${detail2.sessionId})`));
8213
+ console.log(chalk21.bold(detail2.title) + chalk21.dim(` (${detail2.sessionId})`));
7251
8214
  console.log();
7252
8215
  for (const msg of detail2.messages) {
7253
- const role = msg.role === "user" ? chalk20.cyan.bold("You") : chalk20.magenta.bold("Diafunc");
7254
- console.log(`${role} ${chalk20.dim(msg.created)}`);
8216
+ const role = msg.role === "user" ? chalk21.cyan.bold("You") : chalk21.magenta.bold("Diafunc");
8217
+ console.log(`${role} ${chalk21.dim(msg.created)}`);
7255
8218
  console.log(msg.content);
7256
8219
  console.log();
7257
8220
  }
@@ -7284,7 +8247,7 @@ Examples:
7284
8247
  }
7285
8248
 
7286
8249
  // src/commands/search/index.ts
7287
- import chalk21 from "chalk";
8250
+ import chalk22 from "chalk";
7288
8251
  function getOutputFormat14(cmd) {
7289
8252
  const config = loadConfig();
7290
8253
  const globalOpts = cmd.optsWithGlobals();
@@ -7346,7 +8309,7 @@ whose discovered model has the better quality comes first; inside one project th
7346
8309
  });
7347
8310
  }
7348
8311
  if (page.nextCursor && isInteractive()) {
7349
- console.log(chalk21.dim(`More results available. Raise --limit to see them.`));
8312
+ console.log(chalk22.dim(`More results available. Raise --limit to see them.`));
7350
8313
  }
7351
8314
  } catch (error) {
7352
8315
  handleError(error);
@@ -7368,12 +8331,12 @@ function renderResults(items) {
7368
8331
  for (const item of items) {
7369
8332
  const name = item.name || "(unnamed)";
7370
8333
  console.log();
7371
- console.log(`${chalk21.dim(`[${item.contentType}]`)} ${chalk21.bold(name)}${qualityNote(item)}`);
8334
+ console.log(`${chalk22.dim(`[${item.contentType}]`)} ${chalk22.bold(name)}${qualityNote(item)}`);
7372
8335
  const raw = item.snippetField === "name" ? item.description : item.snippet ?? item.description;
7373
8336
  const line = raw ? collapse(raw) : null;
7374
8337
  if (line && stripHighlight(line) !== name) console.log(` ${highlight(line)}`);
7375
8338
  const ref = item.entityId ? `${item.projectId}/${item.projectBranch}/${item.entityId}/${item.entityBranch ?? "main"}` : item.projectId;
7376
- console.log(` ${chalk21.dim(ref)}`);
8339
+ console.log(` ${chalk22.dim(ref)}`);
7377
8340
  }
7378
8341
  console.log();
7379
8342
  }
@@ -7381,16 +8344,16 @@ function qualityNote(item) {
7381
8344
  if (item.contentType !== "project" || typeof item.quality !== "number" || !Number.isFinite(item.quality)) {
7382
8345
  return "";
7383
8346
  }
7384
- return chalk21.dim(` quality ${percent(item.quality).trim()}`);
8347
+ return chalk22.dim(` quality ${percent(item.quality).trim()}`);
7385
8348
  }
7386
8349
  var HIGHLIGHT_OPEN = /<mark>/g;
7387
8350
  var HIGHLIGHT_CLOSE = /<\/mark>/g;
7388
8351
  function highlight(text2) {
7389
8352
  const parts = text2.split(HIGHLIGHT_OPEN);
7390
8353
  return parts.map((part, i) => {
7391
- if (i === 0) return chalk21.dim(part);
8354
+ if (i === 0) return chalk22.dim(part);
7392
8355
  const [marked, ...rest] = part.split(HIGHLIGHT_CLOSE);
7393
- return chalk21.bold.cyan(marked) + chalk21.dim(rest.join(""));
8356
+ return chalk22.bold.cyan(marked) + chalk22.dim(rest.join(""));
7394
8357
  }).join("");
7395
8358
  }
7396
8359
  function stripHighlight(text2) {
@@ -7405,7 +8368,7 @@ function collapse(text2) {
7405
8368
  import { readFile } from "fs/promises";
7406
8369
 
7407
8370
  // src/commands/admin/curated-tags.ts
7408
- import chalk22 from "chalk";
8371
+ import chalk23 from "chalk";
7409
8372
  function getOutputFormat15(cmd) {
7410
8373
  const config = loadConfig();
7411
8374
  const globalOpts = cmd.optsWithGlobals();
@@ -7421,7 +8384,7 @@ var COLUMNS = [
7421
8384
  function curatedTagOf(typed2) {
7422
8385
  const tag = normalizeTag(typed2);
7423
8386
  if (tag === "") usageError(`"${typed2}" is not a usable tag: a tag needs at least one letter or digit.`);
7424
- if (tag !== typed2) console.error(chalk22.dim(`"${typed2}" is written as "${tag}", the form tags are searched by.`));
8387
+ if (tag !== typed2) console.error(chalk23.dim(`"${typed2}" is written as "${tag}", the form tags are searched by.`));
7425
8388
  return tag;
7426
8389
  }
7427
8390
  function parseSortOrder(raw) {
@@ -7687,7 +8650,7 @@ function registerAdminCommands(program) {
7687
8650
  );
7688
8651
  const api = createApiClient();
7689
8652
  await api.storage.restoreFullBackup({ bucketName, objectName });
7690
- success(`Full restore initiated from ${bucketName}/${objectName}.`);
8653
+ success(`Full restore started from ${bucketName}/${objectName}.`);
7691
8654
  } catch (error) {
7692
8655
  handleError(error);
7693
8656
  }
@@ -7698,10 +8661,10 @@ function registerAdminCommands(program) {
7698
8661
  const { project } = cmd.optsWithGlobals();
7699
8662
  if (project) {
7700
8663
  await api.index.rebuildProject(project);
7701
- success(`Index rebuild initiated for project "${project}".`);
8664
+ success(`Index rebuild started for project "${project}".`);
7702
8665
  } else {
7703
8666
  await api.index.rebuildAll();
7704
- success("Index rebuild initiated for all projects.");
8667
+ success("Index rebuild started for all projects.");
7705
8668
  }
7706
8669
  } catch (error) {
7707
8670
  handleError(error);
@@ -7744,7 +8707,7 @@ function registerAdminCommands(program) {
7744
8707
  }
7745
8708
 
7746
8709
  // src/commands/status/summary.ts
7747
- import chalk23 from "chalk";
8710
+ import chalk24 from "chalk";
7748
8711
 
7749
8712
  // src/client/services/status.ts
7750
8713
  function createStatusService() {
@@ -7770,24 +8733,24 @@ function createStatusService() {
7770
8733
 
7771
8734
  // src/commands/status/summary.ts
7772
8735
  var STATE_COLORS = {
7773
- UP: chalk23.green,
7774
- DEGRADED: chalk23.yellow,
7775
- DOWN: chalk23.red,
7776
- UNKNOWN: chalk23.gray
8736
+ UP: chalk24.green,
8737
+ DEGRADED: chalk24.yellow,
8738
+ DOWN: chalk24.red,
8739
+ UNKNOWN: chalk24.gray
7777
8740
  };
7778
8741
  function stateColor(state) {
7779
- return STATE_COLORS[state] ?? chalk23.gray;
8742
+ return STATE_COLORS[state] ?? chalk24.gray;
7780
8743
  }
7781
8744
  function stateSymbol(state) {
7782
8745
  switch (state) {
7783
8746
  case "UP":
7784
- return chalk23.green("\u25CF");
8747
+ return chalk24.green("\u25CF");
7785
8748
  case "DEGRADED":
7786
- return chalk23.yellow("\u25CF");
8749
+ return chalk24.yellow("\u25CF");
7787
8750
  case "DOWN":
7788
- return chalk23.red("\u25CF");
8751
+ return chalk24.red("\u25CF");
7789
8752
  default:
7790
- return chalk23.gray("\u25CB");
8753
+ return chalk24.gray("\u25CB");
7791
8754
  }
7792
8755
  }
7793
8756
  function registerSummaryCommand(parent) {
@@ -7812,20 +8775,20 @@ function registerSummaryCommand(parent) {
7812
8775
  const label = stateColor(domain.state)(domain.state.padEnd(10));
7813
8776
  console.log(` ${stateSymbol(domain.state)} ${label} ${domain.name}`);
7814
8777
  if (domain.componentIds.length > 0) {
7815
- console.log(` ${chalk23.dim(domain.componentIds.join(", "))}`);
8778
+ console.log(` ${chalk24.dim(domain.componentIds.join(", "))}`);
7816
8779
  }
7817
8780
  }
7818
8781
  console.log();
7819
8782
  if (summary.openIncidents > 0) {
7820
- console.log(chalk23.yellow(` ${summary.openIncidents} active incident(s)`));
8783
+ console.log(chalk24.yellow(` ${summary.openIncidents} active incident(s)`));
7821
8784
  } else {
7822
- console.log(chalk23.dim(" No active incidents"));
8785
+ console.log(chalk24.dim(" No active incidents"));
7823
8786
  }
7824
- console.log(chalk23.dim(
8787
+ console.log(chalk24.dim(
7825
8788
  `
7826
8789
  Platform v${version.platformVersion} \xB7 checked ${formatInstant(summary.timestamp)}`
7827
8790
  ));
7828
- console.log(chalk23.dim(` Drill into one with 'diafunc status component <id>'.`));
8791
+ console.log(chalk24.dim(` Drill into one with 'diafunc status component <id>'.`));
7829
8792
  console.log();
7830
8793
  } catch (error) {
7831
8794
  handleError(error);
@@ -7834,17 +8797,17 @@ function registerSummaryCommand(parent) {
7834
8797
  }
7835
8798
 
7836
8799
  // src/commands/status/component.ts
7837
- import chalk24 from "chalk";
8800
+ import chalk25 from "chalk";
7838
8801
  function stateSymbol2(state) {
7839
8802
  switch (state) {
7840
8803
  case "UP":
7841
- return chalk24.green("\u25CF");
8804
+ return chalk25.green("\u25CF");
7842
8805
  case "DEGRADED":
7843
- return chalk24.yellow("\u25CF");
8806
+ return chalk25.yellow("\u25CF");
7844
8807
  case "DOWN":
7845
- return chalk24.red("\u25CF");
8808
+ return chalk25.red("\u25CF");
7846
8809
  default:
7847
- return chalk24.gray("\u25CB");
8810
+ return chalk25.gray("\u25CB");
7848
8811
  }
7849
8812
  }
7850
8813
  function registerComponentCommand(parent) {
@@ -7869,7 +8832,7 @@ function registerComponentCommand(parent) {
7869
8832
  return;
7870
8833
  }
7871
8834
  console.log();
7872
- console.log(` ${stateSymbol2(match.state)} ${chalk24.bold(match.id)} ${match.version ? chalk24.dim("v" + match.version) : ""}`);
8835
+ console.log(` ${stateSymbol2(match.state)} ${chalk25.bold(match.id)} ${match.version ? chalk25.dim("v" + match.version) : ""}`);
7873
8836
  console.log(` State: ${renderState(match.state)}`);
7874
8837
  if (match.lastCheckAt) {
7875
8838
  console.log(` Last check: ${formatInstant(match.lastCheckAt)}`);
@@ -7878,7 +8841,7 @@ function registerComponentCommand(parent) {
7878
8841
  console.log();
7879
8842
  console.log(" Checks:");
7880
8843
  for (const check of match.checks) {
7881
- const cat = check.category ? chalk24.dim(` (${check.category})`) : "";
8844
+ const cat = check.category ? chalk25.dim(` (${check.category})`) : "";
7882
8845
  console.log(` ${stateSymbol2(check.state)} ${check.name}${cat}`);
7883
8846
  }
7884
8847
  }
@@ -7890,12 +8853,12 @@ function registerComponentCommand(parent) {
7890
8853
  }
7891
8854
 
7892
8855
  // src/commands/status/incidents.ts
7893
- import chalk25 from "chalk";
8856
+ import chalk26 from "chalk";
7894
8857
  var SEVERITY_COLORS = {
7895
- ERROR: chalk25.red,
7896
- WARNING: chalk25.yellow,
7897
- INFO: chalk25.blue,
7898
- MAINTENANCE: chalk25.cyan
8858
+ ERROR: chalk26.red,
8859
+ WARNING: chalk26.yellow,
8860
+ INFO: chalk26.blue,
8861
+ MAINTENANCE: chalk26.cyan
7899
8862
  };
7900
8863
  function registerIncidentsCommand(parent) {
7901
8864
  parent.command("incidents").description("List recent incidents").option("-w, --window <window>", "Time window (e.g. 24h, 48h)", "24h").action(async (options, cmd) => {
@@ -7909,22 +8872,22 @@ function registerIncidentsCommand(parent) {
7909
8872
  return;
7910
8873
  }
7911
8874
  if (incidents.length === 0) {
7912
- console.log(chalk25.dim(`
8875
+ console.log(chalk26.dim(`
7913
8876
  No incidents in the last ${options.window}.
7914
8877
  `));
7915
8878
  return;
7916
8879
  }
7917
8880
  console.log();
7918
8881
  for (const incident of incidents) {
7919
- const color = SEVERITY_COLORS[incident.severity] ?? chalk25.gray;
8882
+ const color = SEVERITY_COLORS[incident.severity] ?? chalk26.gray;
7920
8883
  const severity = color(incident.severity.padEnd(8));
7921
8884
  const time = incident.startedAt ? new Date(incident.startedAt).toLocaleString() : "";
7922
- const resolved = incident.resolvedAt ? chalk25.green(" [resolved]") : chalk25.yellow(" [open]");
8885
+ const resolved = incident.resolvedAt ? chalk26.green(" [resolved]") : chalk26.yellow(" [open]");
7923
8886
  console.log(` ${severity} ${incident.summary}${resolved}`);
7924
- console.log(chalk25.dim(` ${time}`));
8887
+ console.log(chalk26.dim(` ${time}`));
7925
8888
  for (const update of incident.updates) {
7926
8889
  const updateTime = new Date(update.at).toLocaleTimeString();
7927
- console.log(chalk25.dim(` ${updateTime} ${update.status} ${update.message}`));
8890
+ console.log(chalk26.dim(` ${updateTime} ${update.status} ${update.message}`));
7928
8891
  }
7929
8892
  console.log();
7930
8893
  }
@@ -7940,7 +8903,7 @@ function registerStatusCommands(program) {
7940
8903
  Examples:
7941
8904
  $ diafunc status summary everything, at a glance
7942
8905
  $ diafunc status component storage one service in detail
7943
- $ diafunc status incidents --days 7
8906
+ $ diafunc status incidents --window 168h
7944
8907
  `);
7945
8908
  ;
7946
8909
  registerSummaryCommand(status);
@@ -7949,12 +8912,12 @@ Examples:
7949
8912
  }
7950
8913
 
7951
8914
  // src/commands/analyze/index.ts
7952
- import * as fs11 from "fs";
8915
+ import * as fs12 from "fs";
7953
8916
  import * as path9 from "path";
7954
8917
  import { spawn as spawn2 } from "child_process";
7955
8918
 
7956
8919
  // src/commands/analyze/watch-view.ts
7957
- import chalk26 from "chalk";
8920
+ import chalk27 from "chalk";
7958
8921
 
7959
8922
  // src/client/types/analysis.ts
7960
8923
  var RUN_PHASE_LABELS = {
@@ -7974,6 +8937,7 @@ function phaseLabel(run) {
7974
8937
  if (run.state === "DISPATCHING") return STARTING;
7975
8938
  if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
7976
8939
  if (run.state === "RUNNING" && !((run.progressTotal ?? 0) > 0)) return RUN_PHASE_LABELS.PREPARING;
8940
+ if (run.state === "CANCELLED") return "Canceled";
7977
8941
  return run.state.charAt(0) + run.state.slice(1).toLowerCase();
7978
8942
  }
7979
8943
  function waitLabel(run) {
@@ -8009,7 +8973,7 @@ function latestRunSentence(state) {
8009
8973
  case "FAILED":
8010
8974
  return "The latest run failed.";
8011
8975
  case "CANCELLED":
8012
- return "The latest run was cancelled.";
8976
+ return "The latest run was canceled.";
8013
8977
  case "QUEUED":
8014
8978
  return "The latest run is waiting for a slot.";
8015
8979
  case "DISPATCHING":
@@ -8021,7 +8985,7 @@ function latestRunSentence(state) {
8021
8985
  function cancelSentence(run) {
8022
8986
  switch (run.state) {
8023
8987
  case "CANCELLED":
8024
- return `Cancelled run ${run.runId}.`;
8988
+ return `Canceled run ${run.runId}.`;
8025
8989
  case "COMPLETED":
8026
8990
  return `Run ${run.runId} had already completed.`;
8027
8991
  case "FAILED":
@@ -8039,7 +9003,7 @@ function terminalSentence(state, duration, credits = null) {
8039
9003
  case "COMPLETED":
8040
9004
  return `Analysis completed in ${duration}${cost}.`;
8041
9005
  case "CANCELLED":
8042
- return `Analysis cancelled after ${duration}${cost}.`;
9006
+ return `Analysis canceled after ${duration}${cost}.`;
8043
9007
  default:
8044
9008
  return `Analysis failed after ${duration}${cost}.`;
8045
9009
  }
@@ -8050,7 +9014,30 @@ function isImporting(dataImport) {
8050
9014
  function importingLabel(dataImport) {
8051
9015
  const progress = dataImport.progress;
8052
9016
  if (progress === null || progress === void 0 || !Number.isFinite(progress)) return "Importing data";
8053
- return `Importing data, ${Math.floor(Math.max(0, Math.min(progress, 1)) * 100)} %`;
9017
+ return `Importing data, ${Math.floor(Math.max(0, Math.min(progress, 1)) * 100)}%`;
9018
+ }
9019
+ function verdictLabel(run) {
9020
+ switch (run.validity) {
9021
+ case "valid":
9022
+ if (!run.validityByStatement) return "Valid";
9023
+ return run.validityReviewedAt != null ? "Valid by the owner's statement, reviewed" : "Valid by the owner's statement";
9024
+ case "needs_review":
9025
+ return "Needs review";
9026
+ case "not_valid":
9027
+ return "Not valid";
9028
+ default:
9029
+ return null;
9030
+ }
9031
+ }
9032
+ function verdictSentence(validity) {
9033
+ switch (validity) {
9034
+ case "needs_review":
9035
+ return "The result needs review: the report's Validity chapter says why and what settles it.";
9036
+ case "not_valid":
9037
+ return "The result is not valid: the report's Validity chapter says why.";
9038
+ default:
9039
+ return null;
9040
+ }
8054
9041
  }
8055
9042
 
8056
9043
  // src/commands/analyze/watch-view.ts
@@ -8072,238 +9059,77 @@ function phaseDetail(run) {
8072
9059
  if (run.fitGeneration !== null && run.fitGeneration !== void 0) {
8073
9060
  parts.push(`generation ${formatNumber(run.fitGeneration)}`);
8074
9061
  }
8075
- if (run.fitQuality !== null && run.fitQuality !== void 0) {
8076
- parts.push(`quality ${qualityPercent(run.fitQuality)}`);
8077
- }
8078
- if (run.fitBudgetFraction !== null && run.fitBudgetFraction !== void 0) {
8079
- parts.push(`${Math.round(run.fitBudgetFraction * 100)}% of budget used`);
8080
- }
8081
- }
8082
- if (parts.length === 0 && run.progressTotal && run.progressTotal > 0) {
8083
- parts.push(`${formatNumber(run.progressDone ?? 0)} of ${formatNumber(run.progressTotal)} tasks`);
8084
- } else if (parts.length === 0 && run.phaseFraction !== null && run.phaseFraction !== void 0) {
8085
- parts.push(`${Math.round(run.phaseFraction * 100)}% of this step`);
8086
- }
8087
- return parts.length > 0 ? parts.join(" \xB7 ") : null;
8088
- }
8089
- function renderWatchBlock(input) {
8090
- const { run, elapsedMs, caption, budgetHours } = input;
8091
- const lines = [];
8092
- const step = stepCounter(run);
8093
- const headline = [
8094
- chalk26.cyan(SPINNER),
8095
- chalk26.bold(phaseLabel(run)),
8096
- step ? chalk26.dim(step) : null
8097
- ].filter(Boolean).join(" ");
8098
- lines.push(` ${headline}`);
8099
- const fraction = overallProgress(run);
8100
- const elapsed = chalk26.dim(formatDurationPrecise(elapsedMs));
8101
- if (fraction === null) {
8102
- lines.push(` ${chalk26.dim("working")} ${elapsed}`);
8103
- } else {
8104
- const ceiling = remainingCeiling(run, budgetHours);
8105
- lines.push(
8106
- ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (ceiling !== null ? chalk26.dim(` \xB7 at most ${formatDurationPrecise(ceiling)} remaining`) : "")
8107
- );
8108
- }
8109
- const detail2 = caption ?? phaseDetail(run);
8110
- if (detail2) lines.push(` ${chalk26.dim(detail2)}`);
8111
- if (run.retryAttempts && run.retryAttempts > 0) {
8112
- lines.push(` ${chalk26.yellow("!")} ${chalk26.dim(
8113
- `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`
8114
- )}`);
8115
- }
8116
- return lines;
8117
- }
8118
-
8119
- // src/commands/analyze/wizard.ts
8120
- import chalk27 from "chalk";
8121
-
8122
- // src/commands/analyze/columns.ts
8123
- var MAX_COLUMNS_LISTED = 30;
8124
- var MAX_NEAR_MATCHES = 3;
8125
- function parseColumnList(text2) {
8126
- const names = [];
8127
- let i = 0;
8128
- while (i < text2.length) {
8129
- while (i < text2.length && isSpace(text2[i])) i++;
8130
- if (i >= text2.length) break;
8131
- if (text2[i] === '"') {
8132
- let name = "";
8133
- let closed = false;
8134
- i++;
8135
- while (i < text2.length) {
8136
- if (text2[i] === '"' && text2[i + 1] === '"') {
8137
- name += '"';
8138
- i += 2;
8139
- } else if (text2[i] === '"') {
8140
- closed = true;
8141
- i++;
8142
- break;
8143
- } else {
8144
- name += text2[i++];
8145
- }
8146
- }
8147
- if (!closed) {
8148
- throw new CliError(`A double quote is opened and never closed in: ${text2}`, {
8149
- exitCode: EXIT_USAGE,
8150
- hint: QUOTING_HINT
8151
- });
8152
- }
8153
- while (i < text2.length && isSpace(text2[i])) i++;
8154
- if (i < text2.length && text2[i] !== ",") {
8155
- throw new CliError(`Text follows a closing double quote without a comma in: ${text2}`, {
8156
- exitCode: EXIT_USAGE,
8157
- hint: QUOTING_HINT
8158
- });
8159
- }
8160
- i++;
8161
- if (name.length > 0) names.push(name);
8162
- } else {
8163
- const end = text2.indexOf(",", i);
8164
- const name = text2.slice(i, end === -1 ? text2.length : end).trim();
8165
- i = end === -1 ? text2.length : end + 1;
8166
- if (name.length > 0) names.push(name);
8167
- }
8168
- }
8169
- return names;
8170
- }
8171
- var QUOTING_HINT = `Inside a list, put a name that contains a comma in double quotes and write a quote in it twice: '"a, b",c'.`;
8172
- function isSpace(char) {
8173
- return char === " " || char === " ";
8174
- }
8175
- function quoteColumn(name) {
8176
- return `"${name.replace(/"/g, '""')}"`;
8177
- }
8178
- function loose(name) {
8179
- return name.trim().toLowerCase();
8180
- }
8181
- function matchColumn(name, columns) {
8182
- if (columns.includes(name)) return { kind: "column", column: name };
8183
- const wanted = loose(name);
8184
- const candidates = columns.filter((column) => loose(column) === wanted);
8185
- if (candidates.length === 1) return { kind: "column", column: candidates[0] };
8186
- return candidates.length > 1 ? { kind: "ambiguous", candidates } : { kind: "unknown" };
8187
- }
8188
- function nearMatches(name, columns) {
8189
- const wanted = loose(name);
8190
- if (wanted.length === 0) return [];
8191
- return columns.map((column) => ({ column, distance: distanceTo(wanted, loose(column)) })).filter((scored) => scored.distance !== null).sort((a, b) => a.distance - b.distance).slice(0, MAX_NEAR_MATCHES).map((scored) => scored.column);
8192
- }
8193
- function distanceTo(wanted, column) {
8194
- const edits = editDistance(wanted, column);
8195
- if (edits <= Math.max(1, Math.floor(Math.min(wanted.length, column.length) / 4))) return edits;
8196
- if (wanted.length >= 3 && (column.includes(wanted) || wanted.includes(column)) && column.length > 0) {
8197
- return 100 + Math.abs(column.length - wanted.length);
8198
- }
8199
- return null;
8200
- }
8201
- function editDistance(a, b) {
8202
- let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
8203
- for (let i = 1; i <= a.length; i++) {
8204
- const current = [i];
8205
- for (let j = 1; j <= b.length; j++) {
8206
- current[j] = Math.min(
8207
- previous[j] + 1,
8208
- current[j - 1] + 1,
8209
- previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
8210
- );
8211
- }
8212
- previous = current;
8213
- }
8214
- return previous[b.length];
8215
- }
8216
- function take(name, columns, into, problems) {
8217
- const match = matchColumn(name, columns);
8218
- if (match.kind === "column") {
8219
- if (!into.includes(match.column)) into.push(match.column);
8220
- return true;
8221
- }
8222
- if (match.kind === "ambiguous") problems.ambiguous.push({ name, candidates: match.candidates });
8223
- else problems.unknown.push(name);
8224
- return false;
8225
- }
8226
- function refuse(problems, columns, analysisId) {
8227
- const sentences = [];
8228
- if (problems.unknown.length === 1) {
8229
- sentences.push(`${quoteColumn(problems.unknown[0])} is not a column of the analysis data.`);
8230
- } else if (problems.unknown.length > 1) {
8231
- sentences.push(`These are not columns of the analysis data: ${problems.unknown.map(quoteColumn).join(", ")}.`);
8232
- }
8233
- for (const { name, candidates } of problems.ambiguous) {
8234
- sentences.push(`${quoteColumn(name)} matches more than one column: ${candidates.map(quoteColumn).join(", ")}. Type the one you mean exactly.`);
8235
- }
8236
- const hints = [];
8237
- const near = [...new Set(problems.unknown.flatMap((name) => nearMatches(name, columns)))];
8238
- if (near.length > 0) hints.push(`Did you mean ${near.map(quoteColumn).join(" or ")}?`);
8239
- const listed2 = columns.slice(0, MAX_COLUMNS_LISTED).map(quoteColumn).join(", ");
8240
- const more = columns.length > MAX_COLUMNS_LISTED ? ` and ${columns.length - MAX_COLUMNS_LISTED} more${analysisId ? ` ('diafunc analyze columns ${analysisId}' lists them all)` : ""}` : "";
8241
- hints.push(`The columns are: ${listed2}${more}.`);
8242
- if (problems.fromList) {
8243
- hints.push(`A name that contains a comma is an argument of its own, or goes in double quotes inside a list: '"a, b",c'.`);
8244
- }
8245
- throw new CliError(sentences.join(" "), { exitCode: EXIT_USAGE, hint: hints.join("\n ") });
8246
- }
8247
- function resolveColumnArguments(given, columns, analysisId) {
8248
- const resolved = [];
8249
- if (columns.length === 0) {
8250
- for (const name of given.flatMap(parseColumnList)) {
8251
- if (!resolved.includes(name)) resolved.push(name);
8252
- }
8253
- return resolved;
8254
- }
8255
- const problems = { unknown: [], ambiguous: [], fromList: false };
8256
- for (const argument of given) {
8257
- if (argument.trim().length === 0) continue;
8258
- const whole = matchColumn(argument, columns);
8259
- if (whole.kind === "column") {
8260
- if (!resolved.includes(whole.column)) resolved.push(whole.column);
8261
- continue;
8262
- }
8263
- const names = parseColumnList(argument);
8264
- const single = names.length === 1 && names[0] === argument.trim();
8265
- for (const name of names) {
8266
- if (!take(name, columns, resolved, problems) && !single) problems.fromList = true;
8267
- }
8268
- }
8269
- if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
8270
- return resolved;
8271
- }
8272
- function resolveColumnNames(names, columns, analysisId) {
8273
- if (columns.length === 0) return [...names];
8274
- const resolved = [];
8275
- const problems = { unknown: [], ambiguous: [], fromList: false };
8276
- for (const name of names) take(name, columns, resolved, problems);
8277
- if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
8278
- return resolved;
8279
- }
8280
- function resolveColumnArgument(given, columns, analysisId) {
8281
- if (columns.length === 0) return given;
8282
- return resolveColumnNames([given], columns, analysisId)[0];
8283
- }
8284
- function occurrences(value) {
8285
- if (value === void 0) return void 0;
8286
- return Array.isArray(value) ? value : [value];
9062
+ if (run.fitQuality !== null && run.fitQuality !== void 0) {
9063
+ parts.push(`quality ${qualityPercent(run.fitQuality)}`);
9064
+ }
9065
+ if (run.fitBudgetFraction !== null && run.fitBudgetFraction !== void 0) {
9066
+ parts.push(`${Math.round(run.fitBudgetFraction * 100)}% of budget used`);
9067
+ }
9068
+ }
9069
+ if (parts.length === 0 && run.progressTotal && run.progressTotal > 0) {
9070
+ parts.push(`${formatNumber(run.progressDone ?? 0)} of ${formatNumber(run.progressTotal)} tasks`);
9071
+ } else if (parts.length === 0 && run.phaseFraction !== null && run.phaseFraction !== void 0) {
9072
+ parts.push(`${Math.round(run.phaseFraction * 100)}% of this step`);
9073
+ }
9074
+ return parts.length > 0 ? parts.join(" \xB7 ") : null;
8287
9075
  }
8288
- function collectColumns(value, previous = []) {
8289
- return previous.concat([value]);
9076
+ function renderWatchBlock(input) {
9077
+ const { run, elapsedMs, caption, budgetHours } = input;
9078
+ const lines = [];
9079
+ const step = stepCounter(run);
9080
+ const headline = [
9081
+ chalk27.cyan(SPINNER),
9082
+ chalk27.bold(phaseLabel(run)),
9083
+ step ? chalk27.dim(step) : null
9084
+ ].filter(Boolean).join(" ");
9085
+ lines.push(` ${headline}`);
9086
+ const fraction = overallProgress(run);
9087
+ const elapsed = chalk27.dim(formatDurationPrecise(elapsedMs));
9088
+ if (fraction === null) {
9089
+ lines.push(` ${chalk27.dim("working")} ${elapsed}`);
9090
+ } else {
9091
+ const ceiling = remainingCeiling(run, budgetHours);
9092
+ lines.push(
9093
+ ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (ceiling !== null ? chalk27.dim(` \xB7 at most ${formatDurationPrecise(ceiling)} remaining`) : "")
9094
+ );
9095
+ }
9096
+ const detail2 = caption ?? phaseDetail(run);
9097
+ if (detail2) lines.push(` ${chalk27.dim(detail2)}`);
9098
+ if (run.retryAttempts && run.retryAttempts > 0) {
9099
+ lines.push(` ${chalk27.yellow("!")} ${chalk27.dim(
9100
+ `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`
9101
+ )}`);
9102
+ }
9103
+ return lines;
8290
9104
  }
8291
9105
 
8292
9106
  // src/commands/analyze/wizard.ts
8293
- var DEPTH_PRESETS = [
8294
- { name: "Express", hours: "1", budget: "500" },
8295
- { name: "Quick", hours: "2", budget: "2000" },
8296
- { name: "Standard", hours: "4", budget: "10000" },
8297
- { name: "Thorough", hours: "8", budget: "40000" },
8298
- { name: "Deep", hours: "24", budget: "150000" }
8299
- ];
8300
- var STARTING_DEPTH_RULE = "Defaults to the account's starting depth: Express (1 hour, 500 credits) until the account has a finished analysis, Standard (4 hours, 10,000 credits) afterwards.";
9107
+ import chalk28 from "chalk";
9108
+ var STARTING_DEPTH_RULE = "Defaults to the account's starting depth: Express (1 hour, 500 credits) until the account has a finished analysis, Standard (4 hours, 4,000 credits) afterwards.";
9109
+ function creditsLabel(budget) {
9110
+ const n = Number(budget);
9111
+ return `${Number.isFinite(n) ? n.toLocaleString("en-US") : budget} credits`;
9112
+ }
9113
+ function timeLabel(hours) {
9114
+ const h = Number(hours);
9115
+ if (!Number.isFinite(h) || h <= 0) return `${hours} hours`;
9116
+ const trim = (v) => Number.isInteger(v) ? v.toString() : (Math.round(v * 10) / 10).toString();
9117
+ if (h < 24) return h === 1 ? "1 hour" : `${trim(h)} hours`;
9118
+ const days = h / 24;
9119
+ if (days < 14) return days === 1 ? "1 day" : `${trim(Math.round(days * 10) / 10)} days`;
9120
+ return `${Math.round(days / 7)} weeks`;
9121
+ }
9122
+ function findDepth(depths, nameOrCredits) {
9123
+ const wanted = nameOrCredits.trim();
9124
+ const credits = wanted.replace(/[,_]/g, "");
9125
+ return depths.find((step) => step.name.toLowerCase() === wanted.toLowerCase() || step.budget === credits);
9126
+ }
8301
9127
  function depthOf(hours, budget) {
8302
9128
  const h = hours?.trim();
8303
9129
  const b = budget?.trim();
8304
9130
  return h && b ? { hours: h, budget: b } : null;
8305
9131
  }
8306
- async function promptCreationFields(prompter, supplied, fallbackName, licences) {
9132
+ async function promptCreationFields(prompter, supplied, fallbackName, licenses) {
8307
9133
  const name = supplied.name ?? await prompter.input({
8308
9134
  message: "Analysis name",
8309
9135
  default: fallbackName,
@@ -8321,34 +9147,34 @@ async function promptCreationFields(prompter, supplied, fallbackName, licences)
8321
9147
  ]
8322
9148
  });
8323
9149
  const answers = { name: name.trim(), description: description.trim() || null, visibility };
8324
- const licenceId = supplied.licenceId ?? (visibility === "PUBLIC" && licences ? await promptLicence(prompter, await licences()) : void 0);
8325
- if (licenceId) answers.licenceId = licenceId;
9150
+ const licenseId = supplied.licenceId ?? (visibility === "PUBLIC" && licenses ? await promptLicense(prompter, await licenses()) : void 0);
9151
+ if (licenseId) answers.licenceId = licenseId;
8326
9152
  return answers;
8327
9153
  }
8328
- var ALL_LICENCES = ":all";
8329
- async function promptLicence(prompter, catalogue) {
8330
- const selectable = catalogue.filter((l) => l.state === "ACTIVE");
9154
+ var ALL_LICENSES = ":all";
9155
+ async function promptLicense(prompter, catalog) {
9156
+ const selectable = catalog.filter((l) => l.state === "ACTIVE");
8331
9157
  if (selectable.length === 0) return void 0;
8332
9158
  const choice = (l) => ({ name: `${l.name} (${l.licenceId})`, value: l.licenceId, description: l.summary ?? void 0 });
8333
9159
  const recommended = selectable.filter((l) => l.recommended);
8334
9160
  const others = selectable.filter((l) => !l.recommended);
8335
9161
  if (recommended.length === 0 || others.length === 0) {
8336
- return prompter.select({ message: "Licence", default: selectable[0].licenceId, choices: selectable.map(choice) });
9162
+ return prompter.select({ message: "License", default: selectable[0].licenceId, choices: selectable.map(choice) });
8337
9163
  }
8338
9164
  const picked = await prompter.select({
8339
- message: "Licence",
9165
+ message: "License",
8340
9166
  default: recommended[0].licenceId,
8341
9167
  choices: [
8342
9168
  ...recommended.map(choice),
8343
- { name: "Another licence\u2026", value: ALL_LICENCES, description: `${others.length} more in the catalogue.` }
9169
+ { name: "Another license\u2026", value: ALL_LICENSES, description: `${others.length} more in the catalog.` }
8344
9170
  ]
8345
9171
  });
8346
- if (picked !== ALL_LICENCES) return picked;
8347
- return prompter.select({ message: "Licence (all)", default: others[0].licenceId, choices: selectable.map(choice) });
9172
+ if (picked !== ALL_LICENSES) return picked;
9173
+ return prompter.select({ message: "License (all)", default: others[0].licenceId, choices: selectable.map(choice) });
8348
9174
  }
8349
- function matchDepthPreset(hours, budget) {
9175
+ function matchDepthPreset(depths, hours, budget) {
8350
9176
  if (!hours || !budget) return null;
8351
- return DEPTH_PRESETS.find((p) => p.hours === hours && p.budget === budget) ?? null;
9177
+ return depths.find((p) => p.hours === hours && p.budget === budget) ?? null;
8352
9178
  }
8353
9179
  function defaultTargets(columns) {
8354
9180
  const named = columns.filter((c) => c.name && c.name.length > 0);
@@ -8363,6 +9189,7 @@ function positiveNumber(label) {
8363
9189
  }
8364
9190
  async function promptRunFields(prompter, options) {
8365
9191
  const { columns, depthDefault } = options;
9192
+ const depths = options.depths ?? [];
8366
9193
  const named = columns.filter((c) => c.name && c.name.length > 0);
8367
9194
  let supplied = { ...options.supplied };
8368
9195
  const nothingSupplied = supplied.targets === void 0 && supplied.segment === void 0 && supplied.questions === void 0 && supplied.hours === void 0 && supplied.budget === void 0;
@@ -8384,6 +9211,7 @@ async function promptRunFields(prompter, options) {
8384
9211
  targets: preset.targets.length > 0 ? preset.targets : void 0,
8385
9212
  questions: preset.questions.length > 0 ? preset.questions : void 0,
8386
9213
  segment: preset.segmentKey ?? void 0,
9214
+ intent: supplied.intent,
8387
9215
  hours: preset.time || void 0,
8388
9216
  budget: preset.budget || void 0
8389
9217
  };
@@ -8396,7 +9224,7 @@ async function promptRunFields(prompter, options) {
8396
9224
  targets = await prompter.checkbox({
8397
9225
  message: "Target columns: what should the analysis predict?",
8398
9226
  choices: named.map((c) => ({
8399
- name: c.valueType ? `${c.name} ${chalk27.dim(`(${c.valueType})`)}` : c.name,
9227
+ name: c.valueType ? `${c.name} ${chalk28.dim(`(${c.valueType})`)}` : c.name,
8400
9228
  value: c.name,
8401
9229
  checked: preselected.has(c.name)
8402
9230
  })),
@@ -8425,7 +9253,7 @@ async function promptRunFields(prompter, options) {
8425
9253
  choices: [
8426
9254
  { name: "No segmentation", value: null },
8427
9255
  ...remaining.map((c) => ({
8428
- name: c.valueType ? `${c.name} ${chalk27.dim(`(${c.valueType})`)}` : c.name,
9256
+ name: c.valueType ? `${c.name} ${chalk28.dim(`(${c.valueType})`)}` : c.name,
8429
9257
  value: c.name
8430
9258
  }))
8431
9259
  ]
@@ -8450,19 +9278,27 @@ async function promptRunFields(prompter, options) {
8450
9278
  questions = collected.length > 0 ? collected : null;
8451
9279
  }
8452
9280
  }
9281
+ let intent = supplied.intent ?? null;
9282
+ if (supplied.intent === void 0) {
9283
+ const typed2 = await prompter.input({
9284
+ message: "What you know and what matters (optional, private to you; blank to skip)",
9285
+ validate: (value) => value.length <= MAX_INTENT_LENGTH || `At most ${MAX_INTENT_LENGTH.toLocaleString("en-US")} characters; --intent-file takes longer notes.`
9286
+ });
9287
+ intent = typed2.trim() || null;
9288
+ }
8453
9289
  let hours = supplied.hours;
8454
9290
  let budget = supplied.budget;
8455
- if (hours === void 0 && budget === void 0) {
9291
+ if (hours === void 0 && budget === void 0 && depths.length > 0) {
8456
9292
  const chosen = await prompter.select({
8457
- message: "Depth: how long may the search run, and what may it spend?",
8458
- default: matchDepthPreset(depthDefault?.hours, depthDefault?.budget) ?? void 0,
9293
+ message: "Depth: what may the analysis spend, and how long may it take?",
9294
+ default: matchDepthPreset(depths, depthDefault?.hours, depthDefault?.budget) ?? void 0,
8459
9295
  choices: [
8460
- ...DEPTH_PRESETS.map((p) => ({
8461
- name: p.name,
9296
+ ...depths.map((p) => ({
9297
+ name: `${p.name}: ${creditsLabel(p.budget)}, up to ${timeLabel(p.hours)}`,
8462
9298
  value: p,
8463
- description: `${p.hours}h \xB7 ${p.budget} credits`
9299
+ description: p.longRun ? "A long analysis: it runs for days and shares the server. If the platform restarts, its search starts again; the interrupted attempt is not charged." : void 0
8464
9300
  })),
8465
- { name: "Set your own", value: null }
9301
+ { name: "Set your own time and credits", value: null }
8466
9302
  ]
8467
9303
  });
8468
9304
  if (chosen) {
@@ -8488,6 +9324,7 @@ async function promptRunFields(prompter, options) {
8488
9324
  targets: targets ?? [],
8489
9325
  segment,
8490
9326
  questions,
9327
+ intent,
8491
9328
  hours: hours.trim(),
8492
9329
  budget: budget.trim()
8493
9330
  };
@@ -8500,24 +9337,25 @@ function describePreset(preset) {
8500
9337
  if (preset.segmentKey) parts.push(`segmented by ${preset.segmentKey}`);
8501
9338
  return parts.join(" \xB7 ");
8502
9339
  }
8503
- function summaryLines(creation, run) {
9340
+ function summaryLines(creation, run, depths = []) {
8504
9341
  const lines = [
8505
9342
  `Name: ${creation.name}`,
8506
9343
  `Visibility: ${creation.visibility === "PUBLIC" ? "Public" : "Private"}`
8507
9344
  ];
8508
- if (creation.licenceId) lines.push(`Licence: ${creation.licenceId}`);
9345
+ if (creation.licenceId) lines.push(`License: ${creation.licenceId}`);
8509
9346
  lines.push(`Targets: ${run.targets.join(", ")}`);
8510
9347
  if (run.segment) lines.push(`Segment: ${run.segment}`);
8511
9348
  if (run.questions && run.questions.length > 0) {
8512
9349
  lines.push(`Questions: ${run.questions.length}`);
8513
9350
  }
8514
- lines.push(`Depth: ${depthLabel(run)}`);
9351
+ if (run.intent) lines.push("Notes: written (private to you)");
9352
+ lines.push(`Depth: ${depthLabel(run, depths)}`);
8515
9353
  return lines;
8516
9354
  }
8517
- function depthLabel(depth) {
8518
- const preset = matchDepthPreset(depth.hours, depth.budget);
9355
+ function depthLabel(depth, depths = []) {
9356
+ const preset = matchDepthPreset(depths, depth.hours, depth.budget);
8519
9357
  const named = preset ? `${preset.name}, ` : "";
8520
- return `${named}${depth.hours}h \xB7 ${depth.budget} credits`;
9358
+ return `${named}${creditsLabel(depth.budget)}, up to ${timeLabel(depth.hours)}`;
8521
9359
  }
8522
9360
  function missingRunFields(recipe) {
8523
9361
  const missing = [];
@@ -8532,7 +9370,8 @@ function suppliedFromAnalysis(analysis) {
8532
9370
  hours: analysis.hours?.trim() ? analysis.hours : void 0,
8533
9371
  budget: analysis.budget?.trim() ? analysis.budget : void 0,
8534
9372
  segment: analysis.segment ?? null,
8535
- questions: analysis.questions ?? null
9373
+ questions: analysis.questions ?? null,
9374
+ intent: analysis.intent ?? null
8536
9375
  };
8537
9376
  }
8538
9377
  var FIELD_COMMANDS = {
@@ -8554,10 +9393,10 @@ function joinList(items) {
8554
9393
  }
8555
9394
 
8556
9395
  // src/prompting/prompter.ts
8557
- var PromptCancelled = class extends Error {
9396
+ var PromptCanceled = class extends Error {
8558
9397
  constructor() {
8559
- super("Cancelled.");
8560
- this.name = "PromptCancelled";
9398
+ super("Canceled.");
9399
+ this.name = "PromptCanceled";
8561
9400
  }
8562
9401
  };
8563
9402
  function createInquirerPrompter() {
@@ -8566,7 +9405,7 @@ function createInquirerPrompter() {
8566
9405
  try {
8567
9406
  return await work();
8568
9407
  } catch (error) {
8569
- if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCancelled();
9408
+ if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCanceled();
8570
9409
  throw error;
8571
9410
  }
8572
9411
  };
@@ -8609,16 +9448,16 @@ function whyNoPrompt(outputFormat, noInteractive) {
8609
9448
  }
8610
9449
 
8611
9450
  // src/commands/analyze/data-import.ts
8612
- import chalk28 from "chalk";
9451
+ import chalk29 from "chalk";
8613
9452
 
8614
9453
  // src/commands/analyze/details.ts
8615
- function analysisDetails(analysis, endpoint) {
9454
+ function analysisDetails(analysis, endpoint, verdict = null) {
8616
9455
  const data = {
8617
9456
  analysisId: analysis.analysisId,
8618
9457
  name: analysis.name,
8619
9458
  description: analysis.description,
8620
9459
  visibility: sentenceCase(analysis.visibility),
8621
- licence: licenceText(analysis),
9460
+ license: licenseText(analysis),
8622
9461
  introduction: analysis.introduction,
8623
9462
  data: dataShape(analysis.rowCount, analysis.columnCount),
8624
9463
  dataImport: analysis.dataImport?.message ?? null,
@@ -8628,6 +9467,11 @@ function analysisDetails(analysis, endpoint) {
8628
9467
  confirmedInputs: analysis.confirmedInputs,
8629
9468
  questions: analysis.questions,
8630
9469
  segment: analysis.segment,
9470
+ // The platform sends the notes to their owner only; for anyone else they are null and the line is empty.
9471
+ intent: analysis.intent ?? null,
9472
+ expectations: joinedLines(expectationLines(analysis.shapeExpectations)),
9473
+ charts: joinedLines((analysis.requestedPairs ?? []).map(pairText)),
9474
+ focus: joinedLines((analysis.focusFamilies ?? []).map(focusText)),
8631
9475
  hours: hoursText(analysis.hours),
8632
9476
  budget: creditsText(analysis.budget),
8633
9477
  constraints: constraintsText(analysis),
@@ -8635,7 +9479,8 @@ function analysisDetails(analysis, endpoint) {
8635
9479
  // While the data is still arriving no run can start, so the import is what the analysis is doing.
8636
9480
  latestRunState: isImporting(analysis.dataImport) ? importingLabel(analysis.dataImport) : analysis.latestRunState ? sentenceCase(analysis.latestRunState) : null,
8637
9481
  latestRunId: analysis.latestRunId,
8638
- quality: qualityText(analysis),
9482
+ quality: qualityText(analysis, verdict),
9483
+ validity: verdict ? verdictLabel(verdict) : null,
8639
9484
  targetResults: targetResultsText(analysis),
8640
9485
  resultRunId: analysis.resultRunId,
8641
9486
  creditsUsed: creditsText(analysis.creditsUsed),
@@ -8650,16 +9495,20 @@ function analysisDetails(analysis, endpoint) {
8650
9495
  { key: "name", header: "Name" },
8651
9496
  { key: "description", header: "Description" },
8652
9497
  { key: "visibility", header: "Visibility" },
8653
- { key: "licence", header: "Licence" },
9498
+ { key: "license", header: "License" },
8654
9499
  { key: "introduction", header: "Introduction" },
8655
9500
  { key: "data", header: "Data" },
8656
9501
  { key: "dataImport", header: "Data import" },
8657
9502
  { key: "targets", header: "Targets" },
8658
9503
  { key: "targetKinds", header: "Target kinds" },
8659
- { key: "inputExclusions", header: "Columns left out of the fit" },
9504
+ { key: "inputExclusions", header: "Columns left out as inputs" },
8660
9505
  { key: "confirmedInputs", header: "Known before the target" },
8661
9506
  { key: "questions", header: "Questions" },
8662
9507
  { key: "segment", header: "Segment" },
9508
+ { key: "intent", header: "Your notes" },
9509
+ { key: "expectations", header: "Expectations" },
9510
+ { key: "charts", header: "Charts you asked for" },
9511
+ { key: "focus", header: "Focus" },
8663
9512
  { key: "hours", header: "Time limit" },
8664
9513
  { key: "budget", header: "Credit budget" },
8665
9514
  { key: "constraints", header: "Constraints" },
@@ -8667,6 +9516,7 @@ function analysisDetails(analysis, endpoint) {
8667
9516
  { key: "latestRunState", header: "Latest run", kind: "state" },
8668
9517
  { key: "latestRunId", header: "Latest run ID", kind: "id" },
8669
9518
  { key: "quality", header: "Quality" },
9519
+ { key: "validity", header: "Validity" },
8670
9520
  { key: "targetResults", header: "Target results" },
8671
9521
  { key: "resultRunId", header: "Result from run", kind: "id" },
8672
9522
  { key: "creditsUsed", header: "Credits used" },
@@ -8678,7 +9528,10 @@ function analysisDetails(analysis, endpoint) {
8678
9528
  ];
8679
9529
  return { data, columns };
8680
9530
  }
8681
- function licenceText(analysis) {
9531
+ function joinedLines(lines) {
9532
+ return lines.length > 0 ? lines.join("\n") : null;
9533
+ }
9534
+ function licenseText(analysis) {
8682
9535
  if (analysis.licenceId) return analysis.licenceId;
8683
9536
  return analysis.visibility === "PUBLIC" ? "none chosen" : null;
8684
9537
  }
@@ -8705,10 +9558,11 @@ function dataShape(rows, columns) {
8705
9558
  if (columns != null) parts.push(`${formatNumber(columns)} ${columns === 1 ? "column" : "columns"}`);
8706
9559
  return parts.join(" \xD7 ");
8707
9560
  }
8708
- function qualityText(analysis) {
8709
- if (analysis.heldOutQuality != null) return qualityPercent(analysis.heldOutQuality);
8710
- if (analysis.resultRunQuality != null) return `${qualityPercent(analysis.resultRunQuality)} on the training rows`;
8711
- return null;
9561
+ function qualityText(analysis, verdict) {
9562
+ if (verdict?.validity === "not_valid") return "not shown: the result is not valid";
9563
+ const figure = analysis.heldOutQuality != null ? qualityPercent(analysis.heldOutQuality) : analysis.resultRunQuality != null ? `${qualityPercent(analysis.resultRunQuality)} on the training rows` : null;
9564
+ if (figure == null) return null;
9565
+ return verdict?.validity === "needs_review" ? `${figure}, needs review` : figure;
8712
9566
  }
8713
9567
  function targetResultsText(analysis) {
8714
9568
  const results = analysis.targetResults ?? [];
@@ -8739,12 +9593,12 @@ function constraintsText(analysis) {
8739
9593
  var IMPORT_POLL_INTERVAL_MS = 2e3;
8740
9594
  function renderImportBlock(dataImport, elapsedMs) {
8741
9595
  const title = dataImport.state === "STOPPING" ? "Stopping the data import" : "Importing data";
8742
- const lines = [` ${chalk28.cyan(SPINNER)} ${chalk28.bold(title)}`];
8743
- const elapsed = chalk28.dim(formatDurationPrecise(elapsedMs));
9596
+ const lines = [` ${chalk29.cyan(SPINNER)} ${chalk29.bold(title)}`];
9597
+ const elapsed = chalk29.dim(formatDurationPrecise(elapsedMs));
8744
9598
  if (dataImport.state === "IMPORTING" && dataImport.progress !== null && dataImport.progress !== void 0) {
8745
9599
  lines.push(` ${bar(dataImport.progress)} ${percent(dataImport.progress)} ${elapsed}`);
8746
9600
  } else {
8747
- lines.push(` ${chalk28.dim(dataImport.message)} ${elapsed}`);
9601
+ lines.push(` ${chalk29.dim(dataImport.message)} ${elapsed}`);
8748
9602
  }
8749
9603
  return lines;
8750
9604
  }
@@ -8776,10 +9630,10 @@ async function followImport(ctx, first) {
8776
9630
  try {
8777
9631
  for (; ; ) {
8778
9632
  if (ctx.live) status.set(renderImportBlock(current, Date.now() - since));
8779
- const pause2 = sleep3(IMPORT_POLL_INTERVAL_MS);
8780
- const woke = await Promise.race([pause2.done, interrupted]);
9633
+ const pause3 = sleep3(IMPORT_POLL_INTERVAL_MS);
9634
+ const woke = await Promise.race([pause3.done, interrupted]);
8781
9635
  if (woke === "interrupted") {
8782
- pause2.cancel();
9636
+ pause3.cancel();
8783
9637
  status.stop();
8784
9638
  warn("Stopped waiting. The import keeps running on the platform.");
8785
9639
  hint(`See how far it is with 'diafunc analyze get ${analysisId}'.`);
@@ -8912,7 +9766,7 @@ async function queueRun(api, analysisId) {
8912
9766
  }
8913
9767
 
8914
9768
  // src/commands/analyze/sources.ts
8915
- import * as fs10 from "fs";
9769
+ import * as fs11 from "fs";
8916
9770
  import * as path8 from "path";
8917
9771
  var CAUTIONS = /* @__PURE__ */ new Set([
8918
9772
  "UNEVEN_COLUMNS",
@@ -9007,12 +9861,12 @@ function planLines(plan) {
9007
9861
  }
9008
9862
  function multipart(file) {
9009
9863
  const formData = new FormData();
9010
- formData.append("content", new Blob([fs10.readFileSync(file)]), path8.basename(file));
9864
+ formData.append("content", new Blob([fs11.readFileSync(file)]), path8.basename(file));
9011
9865
  return formData;
9012
9866
  }
9013
9867
  async function uploadSeveral(api, analysisId, files, choices, human) {
9014
9868
  for (const file of files) {
9015
- if (!fs10.existsSync(file)) {
9869
+ if (!fs11.existsSync(file)) {
9016
9870
  throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
9017
9871
  }
9018
9872
  }
@@ -9132,19 +9986,75 @@ function budgetHoursOf(hours) {
9132
9986
  return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
9133
9987
  }
9134
9988
  function multipartFromFile(file) {
9135
- const buffer = fs11.readFileSync(file);
9989
+ const buffer = fs12.readFileSync(file);
9136
9990
  const blob = new Blob([buffer]);
9137
9991
  const formData = new FormData();
9138
9992
  formData.append("content", blob, path9.basename(file));
9139
9993
  return formData;
9140
9994
  }
9141
9995
  function reportCommandError(error) {
9142
- if (error instanceof PromptCancelled) throw error;
9996
+ if (error instanceof PromptCanceled) throw error;
9143
9997
  handleError(error);
9144
9998
  }
9999
+ var DEPTH_HELP = "A step of the depth ladder, by name or credits (for example standard, deep or 32000); not together with --hours and --budget";
10000
+ function launchIntentOf(options) {
10001
+ return {
10002
+ notes: notesFromOptions(options),
10003
+ shapes: shapesOf(options.shape),
10004
+ pairs: pairsOf(options.pair),
10005
+ focus: focusOf(options.focus)
10006
+ };
10007
+ }
10008
+ function creationIntent(launch) {
10009
+ const fields = {};
10010
+ if (launch.notes) fields.intent = launch.notes;
10011
+ if (launch.focus && launch.focus.length > 0) fields.focusFamilies = launch.focus;
10012
+ return fields;
10013
+ }
10014
+ async function saveLaunchFields(api, analysisId, columns, launch) {
10015
+ const names = columns.map((c) => c.name).filter((name) => name && name.length > 0);
10016
+ const pickUp = (what, command) => (error) => {
10017
+ const message = error instanceof ApiError ? error.toUserMessage() : error instanceof Error ? error.message : String(error);
10018
+ throw new CliError(message, {
10019
+ exitCode: error instanceof CliError ? error.exitCode : EXIT_FAILURE,
10020
+ hint: [
10021
+ error instanceof CliError ? error.hint : void 0,
10022
+ `Analysis ${analysisId} is created and holds the data. Set the ${what} with '${command}' and start it with 'diafunc analyze rerun ${analysisId}'.`
10023
+ ].filter(Boolean).join("\n ")
10024
+ });
10025
+ };
10026
+ if (launch.shapes) {
10027
+ try {
10028
+ const byTarget = resolveShapeTargets(launch.shapes, names, analysisId);
10029
+ await withStatus("Saving the expectations", () => whenProfiled(
10030
+ () => api.analysis.patchShapeExpectations(analysisId, { byTarget })
10031
+ ));
10032
+ } catch (error) {
10033
+ pickUp("expectations", `diafunc analyze expectations ${analysisId} --target <target> <statement...>`)(error);
10034
+ }
10035
+ }
10036
+ if (launch.pairs && launch.pairs.length > 0) {
10037
+ try {
10038
+ const pairs = resolvePairs(launch.pairs, names, analysisId);
10039
+ await withStatus("Saving the charts", () => api.analysis.patchRequestedPairs(analysisId, { pairs }));
10040
+ } catch (error) {
10041
+ pickUp("charts", `diafunc analyze charts ${analysisId} <first>,<second>[,<kind>]...`)(error);
10042
+ }
10043
+ }
10044
+ }
10045
+ async function readNotesUnattended(api, analysis, notes, outputFormat) {
10046
+ const reading = () => readNotes(api, analysis.analysisId, interpretRequestOf(analysis, notes));
10047
+ const interpretation = outputFormat === "human" ? await withStatus("Reading your notes", reading) : await reading();
10048
+ if (outputFormat !== "human") {
10049
+ process.stdout.write(JSON.stringify({ type: "intent", ...interpretation }) + "\n");
10050
+ return;
10051
+ }
10052
+ printInterpretation(interpretation, analysis.analysisId);
10053
+ console.log();
10054
+ }
9145
10055
  async function runAnalysis(files, options, cmd) {
9146
10056
  for (const candidate of files) {
9147
- if (!fs11.existsSync(candidate)) {
10057
+ if (!fs12.existsSync(candidate)) {
9148
10058
  failure(`File not found: ${candidate}`);
9149
10059
  process.exit(EXIT_FAILURE);
9150
10060
  }
@@ -9153,7 +10063,9 @@ async function runAnalysis(files, options, cmd) {
9153
10063
  const outputFormat = getOutputFormat17(cmd);
9154
10064
  const noInteractive = noInteractiveFlag(cmd);
9155
10065
  const interactive = canPrompt(outputFormat, noInteractive);
10066
+ const launch = launchIntentOf(options);
9156
10067
  const api = createApiClient();
10068
+ applyDepthOption(options, options.depth === void 0 ? [] : await readDepths(api));
9157
10069
  let presetTargets;
9158
10070
  if (options.preset) {
9159
10071
  const opt = await api.analysis.getPreset(options.preset);
@@ -9183,12 +10095,12 @@ async function runAnalysis(files, options, cmd) {
9183
10095
  name: options.name,
9184
10096
  description: options.description,
9185
10097
  visibility: options.visibility === void 0 ? void 0 : parseVisibility(options.visibility),
9186
- licenceId: options.licence
9187
- }, fallbackName, () => api.admin.listLicences()) : {
10098
+ licenceId: options.license
10099
+ }, fallbackName, () => api.admin.listLicenses()) : {
9188
10100
  name: options.name ?? fallbackName,
9189
10101
  description: options.description?.trim() || null,
9190
10102
  visibility: options.visibility === void 0 ? "PRIVATE" : parseVisibility(options.visibility),
9191
- licenceId: options.licence
10103
+ licenceId: options.license
9192
10104
  };
9193
10105
  const request = {
9194
10106
  name: creation.name,
@@ -9204,6 +10116,7 @@ async function runAnalysis(files, options, cmd) {
9204
10116
  };
9205
10117
  const created = await withStatus(`Creating analysis "${creation.name}"`, () => api.analysis.create({
9206
10118
  ...request,
10119
+ ...creationIntent(launch),
9207
10120
  ...creation.licenceId ? { licenceId: creation.licenceId } : {}
9208
10121
  }));
9209
10122
  if (isDryRun()) {
@@ -9223,7 +10136,7 @@ async function runAnalysis(files, options, cmd) {
9223
10136
  }
9224
10137
  );
9225
10138
  }
9226
- detail(`depth: ${depthLabel(stored)}${created.depthPreselection ? " (the account's starting depth)" : ""}`);
10139
+ detail(`depth: ${depthLabel(stored, await readDepths(api))}${created.depthPreselection ? " (the account's starting depth)" : ""}`);
9227
10140
  }
9228
10141
  await sendData(importContext(api, created.analysisId, cmd, "stream"), () => files.length > 1 ? uploadSeveral(api, created.analysisId, files, stackChoices(options, files), outputFormat === "human") : uploadOne(api, created.analysisId, file, asUploadedOf(options.asUploaded, files), outputFormat === "human"));
9229
10142
  const columns = await readColumns(api, created.analysisId);
@@ -9239,17 +10152,23 @@ async function runAnalysis(files, options, cmd) {
9239
10152
  targets: named.targets,
9240
10153
  segment: named.segment,
9241
10154
  questions: options.question === void 0 ? void 0 : questionsOf(options.question),
10155
+ intent: launch.notes === void 0 ? void 0 : launch.notes || null,
9242
10156
  hours: options.hours,
9243
10157
  budget: options.budget
9244
- }, columns, creation.licenceId);
10158
+ }, columns, creation.licenceId, { launch, storedNotes: launch.notes || null });
9245
10159
  if (configuredHours === null) return;
9246
10160
  runHours = configuredHours;
9247
10161
  } else {
9248
- await withStatus("Saving the analysis settings", () => api.analysis.update(created.analysisId, {
10162
+ const saved = await withStatus("Saving the analysis settings", () => api.analysis.update(created.analysisId, {
9249
10163
  ...recipe,
9250
10164
  targets: named.targets ?? null,
9251
10165
  segment: named.segment ?? null
9252
10166
  }));
10167
+ await saveLaunchFields(api, created.analysisId, columns, launch);
10168
+ if (launch.notes) {
10169
+ await readNotesUnattended(api, { ...created, ...saved, analysisId: created.analysisId }, launch.notes, outputFormat);
10170
+ if (outputFormat === "human") hint(`Confirmed proposals take part from the next run: 'diafunc analyze rerun ${created.analysisId}'.`);
10171
+ }
9253
10172
  }
9254
10173
  const run = await withStatus("Queuing analysis run", () => queueRun(api, created.analysisId));
9255
10174
  detail(`runId: ${run.runId}`);
@@ -9280,13 +10199,14 @@ function namedColumns(analysisId, columns, interactive, given) {
9280
10199
  const segment = given.segment === void 0 || given.segment === "" ? void 0 : read(() => resolveColumnArgument(given.segment, names, analysisId));
9281
10200
  return { targets, segment };
9282
10201
  }
9283
- async function configureInteractively(api, prompter, analysisId, recipe, supplied, knownColumns, licenceId) {
10202
+ async function configureInteractively(api, prompter, analysisId, recipe, supplied, knownColumns, licenceId, fromCommandLine) {
9284
10203
  const columns = knownColumns ?? await readColumns(api, analysisId);
9285
10204
  const presets = await readPresets(api);
9286
10205
  const depthAsked = supplied.hours === void 0 || supplied.budget === void 0;
9287
10206
  const depthDefault = depthAsked ? await readDepthDefault(api, recipe) : null;
10207
+ const depths = await readDepths(api);
9288
10208
  console.log();
9289
- const answers = await promptRunFields(prompter, { columns, presets, supplied, depthDefault });
10209
+ const answers = await promptRunFields(prompter, { columns, presets, supplied, depthDefault, depths });
9290
10210
  console.log();
9291
10211
  const saved = await withStatus("Saving the analysis settings", () => api.analysis.update(analysisId, {
9292
10212
  ...recipe,
@@ -9296,6 +10216,16 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
9296
10216
  hours: answers.hours,
9297
10217
  budget: answers.budget
9298
10218
  }));
10219
+ const recipeNow = await settleNotes(
10220
+ api,
10221
+ prompter,
10222
+ analysisId,
10223
+ saved,
10224
+ columns,
10225
+ answers.intent,
10226
+ fromCommandLine ?? { launch: null, storedNotes: supplied.intent ?? null },
10227
+ { targets: answers.targets, segment: answers.segment }
10228
+ );
9299
10229
  console.log();
9300
10230
  heading("Ready to run");
9301
10231
  const identity = {
@@ -9305,7 +10235,8 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
9305
10235
  ...licenceId ? { licenceId } : {}
9306
10236
  };
9307
10237
  const depth = depthOf(saved?.hours, saved?.budget) ?? { hours: answers.hours, budget: answers.budget };
9308
- for (const line of summaryLines(identity, { ...answers, ...depth })) detail(line);
10238
+ for (const line of summaryLines(identity, { ...answers, ...depth }, depths)) detail(line);
10239
+ for (const line of intentRecipeLines(recipeNow ?? {})) detail(line);
9309
10240
  console.log();
9310
10241
  if (!await prompter.confirm({ message: "Start the analysis?", default: true })) {
9311
10242
  warn("Not started. The analysis and these settings are saved.");
@@ -9314,6 +10245,65 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
9314
10245
  }
9315
10246
  return depth.hours;
9316
10247
  }
10248
+ async function settleNotes(api, prompter, analysisId, saved, columns, notes, given, setup) {
10249
+ let touched = false;
10250
+ if (given.launch && (given.launch.shapes || (given.launch.pairs?.length ?? 0) > 0)) {
10251
+ await saveLaunchFields(api, analysisId, columns, given.launch);
10252
+ touched = true;
10253
+ }
10254
+ if (notes && notes !== given.storedNotes) {
10255
+ await withStatus("Saving your notes", () => api.analysis.patchIntent(analysisId, { intent: notes }));
10256
+ }
10257
+ if (notes && !isDryRun()) {
10258
+ const base = { ...saved, analysisId, targets: saved?.targets ?? setup.targets, segment: saved?.segment ?? setup.segment };
10259
+ const interpretation = await withStatus("Reading your notes", () => readNotes(api, analysisId, interpretRequestOf(base, notes)));
10260
+ if (interpretation.status !== "READY") {
10261
+ printInterpretation(interpretation, analysisId);
10262
+ } else {
10263
+ printUnavailable(interpretation);
10264
+ for (const note of [...interpretation.notUnderstood ?? [], ...interpretation.rejections ?? []]) {
10265
+ warn(`Not used: "${note.quote}"${note.reason ? `: ${note.reason}` : ""}`);
10266
+ }
10267
+ const decisions = await promptIntentDecisions(prompter, interpretation);
10268
+ if (decisions.length > 0) {
10269
+ await withStatus("Saving your decisions", () => api.analysis.decideIntentItems(analysisId, { decisions }));
10270
+ touched = true;
10271
+ }
10272
+ }
10273
+ }
10274
+ if (!touched || isDryRun()) return saved;
10275
+ try {
10276
+ return (await api.analysis.get(analysisId)).analysis ?? saved;
10277
+ } catch (error) {
10278
+ if (isAuthenticationFailure(error)) throw error;
10279
+ return saved;
10280
+ }
10281
+ }
10282
+ async function readDepths(api) {
10283
+ try {
10284
+ return await api.analysis.getDepths() ?? [];
10285
+ } catch {
10286
+ return [];
10287
+ }
10288
+ }
10289
+ function applyDepthOption(options, depths) {
10290
+ if (options.depth === void 0) return;
10291
+ if (options.hours !== void 0 || options.budget !== void 0) {
10292
+ usageError("Name a depth with --depth, or a time limit and a credit budget with --hours and --budget, not both.");
10293
+ }
10294
+ if (depths.length === 0) {
10295
+ usageError("The depths could not be read from the platform.", "Pass --hours and --budget instead.");
10296
+ }
10297
+ const step = findDepth(depths, options.depth);
10298
+ if (!step) {
10299
+ usageError(
10300
+ `There is no depth '${options.depth}'.`,
10301
+ `Name one of ${depths.map((d) => d.name).join(", ")}, or its credits (for example --depth 4000).`
10302
+ );
10303
+ }
10304
+ options.hours = step.hours;
10305
+ options.budget = step.budget;
10306
+ }
9317
10307
  async function readDepthDefault(api, stored) {
9318
10308
  try {
9319
10309
  const answer = await api.analysis.getDepthDefault();
@@ -9439,6 +10429,7 @@ async function reportTerminalRun(api, config, run, analysisId, runId, outputForm
9439
10429
  analysisId,
9440
10430
  durationMs,
9441
10431
  credits,
10432
+ validity: run.validity ?? null,
9442
10433
  error: run.errorMessage
9443
10434
  }, { format: outputFormat });
9444
10435
  if (run.state !== "COMPLETED") process.exit(EXIT_FAILURE);
@@ -9448,6 +10439,8 @@ async function reportTerminalRun(api, config, run, analysisId, runId, outputForm
9448
10439
  const sentence = terminalSentence(run.state, formatDurationPrecise(durationMs), credits);
9449
10440
  if (run.state === "COMPLETED") {
9450
10441
  success(sentence);
10442
+ const verdict = verdictSentence(run.validity);
10443
+ if (verdict) warn(verdict);
9451
10444
  await printNotebookLink(api, config, analysisId);
9452
10445
  return;
9453
10446
  }
@@ -9510,15 +10503,33 @@ async function getAnalysisDetails(analysisId, options, cmd) {
9510
10503
  format(result.analysis, { format: outputFormat });
9511
10504
  return;
9512
10505
  }
9513
- const analysis = options.full ? result.analysis : { ...result.analysis, introduction: abbreviate(result.analysis.introduction) };
10506
+ const analysis = options.full ? result.analysis : {
10507
+ ...result.analysis,
10508
+ introduction: abbreviate(result.analysis.introduction),
10509
+ intent: abbreviate(result.analysis.intent ?? null)
10510
+ };
9514
10511
  const config = loadConfig();
9515
10512
  const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
9516
- const details = analysisDetails(analysis, endpoint);
10513
+ const details = analysisDetails(analysis, endpoint, await resultVerdict(api, result.analysis));
9517
10514
  format(details.data, { format: outputFormat, columns: details.columns });
9518
10515
  if (!options.full && isLong(result.analysis.introduction)) {
9519
10516
  hint("Introduction abbreviated. Pass --full to print it whole.");
9520
10517
  }
10518
+ if (!options.full && isLong(result.analysis.intent ?? null)) {
10519
+ hint("Your notes abbreviated. Pass --full, or run 'diafunc analyze intent " + result.analysis.analysisId + "', to print them whole.");
10520
+ }
10521
+ }
10522
+ async function resultVerdict(api, analysis) {
10523
+ if (!analysis.resultRunId) return null;
10524
+ try {
10525
+ const runs = await api.analysis.getRunsForAnalysis(analysis.analysisId, RESULT_RUN_LOOKBACK);
10526
+ return runs.find((r) => r.runId === analysis.resultRunId) ?? null;
10527
+ } catch (error) {
10528
+ if (isAuthenticationFailure(error)) throw error;
10529
+ return null;
10530
+ }
9521
10531
  }
10532
+ var RESULT_RUN_LOOKBACK = 20;
9522
10533
  var INTRODUCTION_PREVIEW_LINES = 3;
9523
10534
  function isLong(text2) {
9524
10535
  return Boolean(text2 && text2.split("\n").length > INTRODUCTION_PREVIEW_LINES);
@@ -9547,6 +10558,8 @@ async function watchAnalysis(analysisId, cmd) {
9547
10558
  const sentence = latestRunSentence(latest.state);
9548
10559
  if (latest.state === "COMPLETED") {
9549
10560
  success(sentence);
10561
+ const verdict = verdictSentence(latest.validity);
10562
+ if (verdict) warn(verdict);
9550
10563
  } else {
9551
10564
  warn(sentence);
9552
10565
  if (latest.errorMessage) hint(latest.errorMessage);
@@ -9623,13 +10636,29 @@ async function openAnalysis(analysisId) {
9623
10636
  hint("The notebook is not available yet. Run the analysis first.");
9624
10637
  }
9625
10638
  }
10639
+ function windowedShapes(shapes) {
10640
+ if (!shapes) return null;
10641
+ for (const statement of Object.values(shapes).flat()) {
10642
+ const args = /\((.*)\)\s*$/.exec(statement)?.[1].split(",") ?? [];
10643
+ if (!/range\s*\(/i.test(statement) && args.length !== 3) {
10644
+ usageError(
10645
+ `'${statement}' has no window, and an analysis without data has no observed range to bind it to.`,
10646
+ "Give the window, for example increasing(size_m2, 20, 200), or set the expectation after the upload with 'diafunc analyze expectations <id> --target <target> <statement...>'."
10647
+ );
10648
+ }
10649
+ }
10650
+ return shapes;
10651
+ }
9626
10652
  function typedColumns(given) {
9627
10653
  const entries = occurrences(given);
9628
10654
  return entries === void 0 ? null : resolveColumnArguments(entries, []);
9629
10655
  }
9630
10656
  async function createAnalysis(options, cmd) {
9631
10657
  const outputFormat = getOutputFormat17(cmd);
10658
+ const launch = launchIntentOf(options);
10659
+ const shapes = windowedShapes(launch.shapes);
9632
10660
  const api = createApiClient();
10661
+ applyDepthOption(options, options.depth === void 0 ? [] : await readDepths(api));
9633
10662
  const visibility = parseVisibility(options.visibility);
9634
10663
  const request = {
9635
10664
  name: options.name ?? "CLI Analysis",
@@ -9643,13 +10672,19 @@ async function createAnalysis(options, cmd) {
9643
10672
  };
9644
10673
  const created = await api.analysis.create({
9645
10674
  ...request,
9646
- ...options.licence ? { licenceId: options.licence } : {}
10675
+ ...creationIntent(launch),
10676
+ ...shapes ? { shapeExpectations: shapes } : {},
10677
+ ...launch.pairs && launch.pairs.length > 0 ? { requestedPairs: launch.pairs } : {},
10678
+ ...options.license ? { licenceId: options.license } : {}
9647
10679
  });
9648
10680
  if (isDryRun()) {
9649
10681
  hint("Dry run: nothing was created.");
9650
10682
  return;
9651
10683
  }
9652
10684
  format(created, { format: outputFormat });
10685
+ if (launch.notes && outputFormat === "human") {
10686
+ hint(`Your notes are stored. Read them into proposals once the data is uploaded: 'diafunc analyze intent read ${created.analysisId}'.`);
10687
+ }
9653
10688
  }
9654
10689
  async function deleteAnalysis(analysisId) {
9655
10690
  const api = createApiClient();
@@ -9682,6 +10717,223 @@ async function patchColumns(analysisId, given, send, successLabel, cmd) {
9682
10717
  const columns = resolveColumnArguments(occurrences(given) ?? [], await columnNames(api, analysisId), analysisId);
9683
10718
  await patchAndPrint(analysisId, "", () => send(api, columns), successLabel, cmd);
9684
10719
  }
10720
+ async function ownAnalysis(api, analysisId) {
10721
+ const found = await api.analysis.get(analysisId);
10722
+ if (!found.analysis) {
10723
+ failure(`Analysis not found: ${analysisId}`);
10724
+ process.exit(EXIT_FAILURE);
10725
+ }
10726
+ return found.analysis;
10727
+ }
10728
+ async function notesCommand(analysisId, text2, options, cmd) {
10729
+ const outputFormat = getOutputFormat17(cmd);
10730
+ const api = createApiClient();
10731
+ const given = [text2 !== void 0, options.file !== void 0, options.clear === true].filter(Boolean).length;
10732
+ if (given > 1) usageError("Give the notes as text, with --file, or clear them with --clear: one of the three.");
10733
+ if (given === 0) {
10734
+ const analysis = await ownAnalysis(api, analysisId);
10735
+ if (outputFormat !== "human") {
10736
+ format({ analysisId, intent: analysis.intent ?? null }, { format: outputFormat });
10737
+ return;
10738
+ }
10739
+ if (!analysis.intent) {
10740
+ empty("notes");
10741
+ hint(`Write them with 'diafunc analyze intent ${analysisId} "<text>"'. Only you can read them.`);
10742
+ return;
10743
+ }
10744
+ console.log(analysis.intent);
10745
+ hint(`Only you can read these notes. Read them into proposals with 'diafunc analyze intent read ${analysisId}'.`);
10746
+ return;
10747
+ }
10748
+ let notes;
10749
+ if (options.clear) {
10750
+ notes = null;
10751
+ } else if (options.file !== void 0) {
10752
+ notes = notesFromOptions({ intentFile: options.file }) || null;
10753
+ } else {
10754
+ checkNotesLength(text2);
10755
+ notes = text2.trim() || null;
10756
+ }
10757
+ const updated = await api.analysis.patchIntent(analysisId, { intent: notes });
10758
+ if (isDryRun()) {
10759
+ hint("Dry run: nothing was changed.");
10760
+ return;
10761
+ }
10762
+ if (outputFormat !== "human") {
10763
+ format(updated, { format: outputFormat });
10764
+ return;
10765
+ }
10766
+ if (notes === null) {
10767
+ success(`Notes cleared for analysis ${analysisId}.`);
10768
+ hint("Proposals you confirmed earlier stay in place until you decline them.");
10769
+ return;
10770
+ }
10771
+ success(`Notes saved for analysis ${analysisId}. Only you can read them.`);
10772
+ hint(`Read them into proposals with 'diafunc analyze intent read ${analysisId}'. Nothing changes until you confirm one.`);
10773
+ }
10774
+ async function readNotesCommand(analysisId, options, cmd) {
10775
+ const outputFormat = getOutputFormat17(cmd);
10776
+ const api = createApiClient();
10777
+ const analysis = await ownAnalysis(api, analysisId);
10778
+ if (!analysis.intent) {
10779
+ if (outputFormat !== "human") {
10780
+ format(
10781
+ { status: "EMPTY", hash: null, derivedAt: null, items: [], notUnderstood: [], rejections: [], findings: [] },
10782
+ { format: outputFormat }
10783
+ );
10784
+ return;
10785
+ }
10786
+ empty("notes");
10787
+ hint(`Write them first with 'diafunc analyze intent ${analysisId} "<text>"'.`);
10788
+ return;
10789
+ }
10790
+ const reading = () => readNotes(
10791
+ api,
10792
+ analysisId,
10793
+ interpretRequestOf(analysis, analysis.intent),
10794
+ { force: options.force, refine: options.refine }
10795
+ );
10796
+ const interpretation = outputFormat === "human" ? await withStatus("Reading your notes", reading) : await reading();
10797
+ if (isDryRun()) {
10798
+ hint("Dry run: the notes were not read.");
10799
+ return;
10800
+ }
10801
+ if (outputFormat !== "human") {
10802
+ format(interpretation, { format: outputFormat });
10803
+ return;
10804
+ }
10805
+ printInterpretation(interpretation, analysisId);
10806
+ }
10807
+ async function decideCommand(state, analysisId, ids, options, cmd) {
10808
+ const outputFormat = getOutputFormat17(cmd);
10809
+ const wanted = [...new Set(ids.flatMap((id) => id.split(",")).map((id) => id.trim()).filter((id) => id.length > 0))];
10810
+ if (wanted.length === 0) usageError("Name at least one proposal.", `The ids are in 'diafunc analyze intent read ${analysisId}'.`);
10811
+ if (options.steer !== void 0 && state !== "CONFIRMED") {
10812
+ usageError("--steer and --no-steer go with confirm only.");
10813
+ }
10814
+ const api = createApiClient();
10815
+ const stored = await api.analysis.getIntentInterpretation(analysisId);
10816
+ const known = new Map((stored.items ?? []).map((item) => [item.id, item]));
10817
+ const unknown = wanted.filter((id) => !known.has(id));
10818
+ if (unknown.length > 0) {
10819
+ usageError(
10820
+ `${unknown.map((id) => `'${id}'`).join(", ")} ${unknown.length === 1 ? "is not a proposal" : "are not proposals"} of analysis ${analysisId}.`,
10821
+ `List the proposals with 'diafunc analyze intent read ${analysisId}'.`
10822
+ );
10823
+ }
10824
+ if (options.steer !== void 0) {
10825
+ const notExpectations = wanted.filter((id) => known.get(id)?.effect !== "checks");
10826
+ if (notExpectations.length > 0) {
10827
+ usageError(`Only an expectation can steer the model; ${notExpectations.map((id) => `'${id}'`).join(", ")} ${notExpectations.length === 1 ? "is" : "are"} not one.`);
10828
+ }
10829
+ }
10830
+ const decisions = wanted.map((id) => ({ id, state, steer: options.steer ?? null }));
10831
+ const decided = await api.analysis.decideIntentItems(analysisId, { decisions });
10832
+ if (isDryRun()) {
10833
+ hint("Dry run: nothing was changed.");
10834
+ return;
10835
+ }
10836
+ if (outputFormat !== "human") {
10837
+ format(decided, { format: outputFormat });
10838
+ return;
10839
+ }
10840
+ const verb = state === "CONFIRMED" ? "Using" : state === "DECLINED" ? "Not using" : "Open again:";
10841
+ for (const item of (decided.items ?? []).filter((i) => wanted.includes(i.id))) {
10842
+ success(`${verb} ${item.id}: ${item.statement}`);
10843
+ }
10844
+ if (state === "CONFIRMED") hint(`It takes part from the next run: 'diafunc analyze rerun ${analysisId}'.`);
10845
+ }
10846
+ async function expectationsCommand(analysisId, given, options, cmd) {
10847
+ const outputFormat = getOutputFormat17(cmd);
10848
+ const api = createApiClient();
10849
+ const analysis = await ownAnalysis(api, analysisId);
10850
+ const current = analysis.shapeExpectations ?? {};
10851
+ const statements = given.filter((g) => g.trim().length > 0);
10852
+ if (options.clear && statements.length > 0) usageError("Give statements or --clear, not both.");
10853
+ if (!options.clear && statements.length === 0) {
10854
+ const shown = options.target === void 0 ? current : Object.fromEntries(Object.entries(current).filter(([target]) => target === options.target));
10855
+ if (outputFormat !== "human") {
10856
+ format({ analysisId, shapeExpectations: shown }, { format: outputFormat });
10857
+ return;
10858
+ }
10859
+ const lines = expectationLines(shown);
10860
+ if (lines.length === 0) {
10861
+ empty("expectations");
10862
+ hint(`Set one with 'diafunc analyze expectations ${analysisId} --target <target> "increasing(<input>)"'.`);
10863
+ return;
10864
+ }
10865
+ for (const line of lines) console.log(line);
10866
+ hint("An expectation is checked and reported; one written with require: also steers the model.");
10867
+ return;
10868
+ }
10869
+ const columns = await columnNames(api, analysisId);
10870
+ const targetOf = (typed2) => resolveColumnArgument(typed2, columns, analysisId);
10871
+ const byTarget = Object.fromEntries(Object.entries(current).map(([t, s]) => [t, [...s]]));
10872
+ if (options.clear) {
10873
+ if (options.target === void 0) {
10874
+ for (const target of Object.keys(byTarget)) delete byTarget[target];
10875
+ } else {
10876
+ delete byTarget[targetOf(options.target)];
10877
+ }
10878
+ } else {
10879
+ const named = {};
10880
+ for (const entry of statements) {
10881
+ let target;
10882
+ let statement;
10883
+ if (options.target !== void 0) {
10884
+ target = targetOf(options.target);
10885
+ statement = checkedStatement(entry);
10886
+ } else if (entry.includes("=")) {
10887
+ const read = parseShapeFlag(entry);
10888
+ target = targetOf(read.target);
10889
+ statement = read.statement;
10890
+ } else if ((analysis.targets ?? []).length === 1) {
10891
+ target = analysis.targets[0];
10892
+ statement = checkedStatement(entry);
10893
+ } else {
10894
+ usageError(
10895
+ `'${entry}' names no target, and the analysis has ${(analysis.targets ?? []).length === 0 ? "none yet" : "several"}.`,
10896
+ `Pass --target <target>, or write <target>=<statement>.`
10897
+ );
10898
+ }
10899
+ named[target] ??= [];
10900
+ if (!named[target].includes(statement)) named[target].push(statement);
10901
+ }
10902
+ Object.assign(byTarget, named);
10903
+ }
10904
+ const updated = await api.analysis.patchShapeExpectations(analysisId, { byTarget });
10905
+ if (isDryRun()) {
10906
+ hint("Dry run: nothing was changed.");
10907
+ return;
10908
+ }
10909
+ if (outputFormat !== "human") {
10910
+ format(updated, { format: outputFormat });
10911
+ return;
10912
+ }
10913
+ success(`Expectations updated for analysis ${analysisId}.`);
10914
+ for (const line of expectationLines(updated?.shapeExpectations)) detail(line);
10915
+ }
10916
+ async function chartsCommand(analysisId, given, cmd) {
10917
+ const api = createApiClient();
10918
+ const pairs = resolvePairs(pairsOf(given) ?? [], await columnNames(api, analysisId), analysisId);
10919
+ await patchAndPrint(
10920
+ analysisId,
10921
+ pairs.map(pairText).join("; "),
10922
+ () => api.analysis.patchRequestedPairs(analysisId, { pairs }),
10923
+ "Charts",
10924
+ cmd
10925
+ );
10926
+ }
10927
+ async function focusCommand(analysisId, given, cmd) {
10928
+ const families = focusOf(given) ?? [];
10929
+ await patchAndPrint(
10930
+ analysisId,
10931
+ families.map(focusText).join(", "),
10932
+ (api, aid) => api.analysis.patchFocusFamilies(aid, { families }),
10933
+ "Focus",
10934
+ cmd
10935
+ );
10936
+ }
9685
10937
  function collectAsUploaded(value, previous) {
9686
10938
  return [...Array.isArray(previous) ? previous : [], value];
9687
10939
  }
@@ -9745,7 +10997,7 @@ async function uploadData(analysisId, files, options, cmd) {
9745
10997
  `For example: diafunc analyze upload ${analysisId} data.csv`
9746
10998
  );
9747
10999
  }
9748
- if (!fs11.existsSync(file)) {
11000
+ if (!fs12.existsSync(file)) {
9749
11001
  throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
9750
11002
  }
9751
11003
  }
@@ -9804,6 +11056,7 @@ async function listRuns(analysisId, count, cmd) {
9804
11056
  runId: r.runId,
9805
11057
  state: r.state,
9806
11058
  phase: runPhaseCell(r),
11059
+ validity: verdictLabel(r),
9807
11060
  submittedAt: r.submittedAt,
9808
11061
  startedAt: r.startedAt,
9809
11062
  endedAt: r.endedAt,
@@ -9814,6 +11067,7 @@ async function listRuns(analysisId, count, cmd) {
9814
11067
  { key: "runId", kind: "id" },
9815
11068
  { key: "state", kind: "state" },
9816
11069
  { key: "phase" },
11070
+ { key: "validity" },
9817
11071
  { key: "submittedAt", header: "submitted", kind: "date" },
9818
11072
  { key: "endedAt", header: "ended", kind: "date" }
9819
11073
  ]
@@ -9968,11 +11222,21 @@ async function updateTriggerCmd(triggerId, options, cmd) {
9968
11222
  format(trigger, { format: outputFormat });
9969
11223
  }
9970
11224
  var COLUMN_LIST_HELP = "one argument each or comma-separated; a name that contains a comma is an argument of its own, or goes in double quotes inside a list";
9971
- var LICENCE_HELP = "With PUBLIC: the licence the analysis's project is published under, an id of the licence catalogue (see 'diafunc licence list')";
11225
+ var LICENSE_HELP = "With PUBLIC: the license the analysis's project is published under, an id of the license catalog (see 'diafunc license list')";
9972
11226
  var TARGETS_HELP = `Target column names: repeat the flag or separate them with commas; a name that contains a comma is one flag of its own, or goes in double quotes inside a list`;
11227
+ var INTENT_HELP = "What you know about the data and what matters to you, in your own words. Private to you. It is read into proposals; nothing changes until you confirm one";
11228
+ var SHAPE_HELP = "An expectation about a target's shape, <target>=<statement>, for example price=increasing(size_m2); checked and reported, or with require: in front also steering the model; repeat the flag for several";
11229
+ var PAIR_QUOTING_HELP = `A column whose name holds a comma goes in double quotes: '"a, b",price'`;
11230
+ var PAIR_HELP = `A chart to add to the report: the second column against the first, with kind scatter, groups or counts, or none; at most ${MAX_PAIRS}; repeat the flag for several. ${PAIR_QUOTING_HELP}`;
11231
+ var FOCUS_HELP = `A question family that matters most to you, for example extrapolation or input_importance; at most ${MAX_FOCUS}, most important first; repeat the flag for several`;
11232
+ var FOCUS_FAMILY_LINES = FOCUS_FAMILIES.map((f) => ` ${f.id.padEnd(20)}${f.label}`).join("\n");
11233
+ var FOCUS_FAMILIES_HELP = `
11234
+ Question families:
11235
+ ${FOCUS_FAMILY_LINES}
11236
+ `;
9973
11237
  function registerAnalyzeCommand(program) {
9974
11238
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
9975
- analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[files...]", "Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--licence <licenceId>", LICENCE_HELP).option("--hours <hours>", `Time limit (hours). ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", `${TARGETS_HELP} (required when not interactive)`, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").option("--no-file-column", "With several files: do not add the column that records the file each row came from").option("--keep-duplicates", "With several files: keep rows that occur in more than one file").option("--rows-of <file>", "With several files that can be read two ways: the file in which one row is one observation").option("--as-uploaded [file]", AS_UPLOADED_HELP, collectAsUploaded).action(async (files, options, cmd) => {
11239
+ analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[files...]", "Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--license <licenseId>", LICENSE_HELP).addOption(hiddenOptionAlias("--licence <licenseId>", "license")).option("--depth <name or credits>", DEPTH_HELP).option("--hours <hours>", `Time limit (hours) for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", `${TARGETS_HELP} (required when not interactive)`, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").option("--no-file-column", "With several files: do not add the column that records the file each row came from").option("--keep-duplicates", "With several files: keep rows that occur in more than one file").option("--rows-of <file>", "With several files that can be read two ways: the file in which one row is one observation").option("--as-uploaded [file]", AS_UPLOADED_HELP, collectAsUploaded).option("--intent <text>", INTENT_HELP).option("--intent-file <path>", "Read the notes from a file instead (for notes longer than a line)").option("--shape <target=statement>", SHAPE_HELP, collectQuestion).option("--pair <first,second[,kind]>", PAIR_HELP, collectQuestion).option("--focus <family>", FOCUS_HELP, collectQuestion).action(async (files, options, cmd) => {
9976
11240
  try {
9977
11241
  if (files.length === 0) {
9978
11242
  analyze.help();
@@ -9990,7 +11254,7 @@ function registerAnalyzeCommand(program) {
9990
11254
  handleError(error);
9991
11255
  }
9992
11256
  });
9993
- analyze.command("get").description("Show details of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").option("--full", "Print the introduction in full instead of abbreviating it").addHelpText("after", REPORT_TERMS_HELP).action(async (id, options, cmd) => {
11257
+ analyze.command("get").description("Show details of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").option("--full", "Print the introduction and your notes in full instead of abbreviating them").addHelpText("after", REPORT_TERMS_HELP).action(async (id, options, cmd) => {
9994
11258
  try {
9995
11259
  await getAnalysisDetails(id, options, cmd);
9996
11260
  } catch (error) {
@@ -10018,14 +11282,14 @@ function registerAnalyzeCommand(program) {
10018
11282
  reportCommandError(error);
10019
11283
  }
10020
11284
  });
10021
- analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--licence <licenceId>", LICENCE_HELP).option("--hours <hours>", `Time limit (hours). ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", TARGETS_HELP, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").action(async (options, cmd) => {
11285
+ analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--license <licenseId>", LICENSE_HELP).addOption(hiddenOptionAlias("--licence <licenseId>", "license")).option("--depth <name or credits>", DEPTH_HELP).option("--hours <hours>", `Time limit (hours) for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", TARGETS_HELP, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--intent <text>", INTENT_HELP).option("--intent-file <path>", "Read the notes from a file instead (for notes longer than a line)").option("--shape <target=statement>", SHAPE_HELP, collectQuestion).option("--pair <first,second[,kind]>", PAIR_HELP, collectQuestion).option("--focus <family>", FOCUS_HELP, collectQuestion).action(async (options, cmd) => {
10022
11286
  try {
10023
11287
  await createAnalysis(options, cmd);
10024
11288
  } catch (error) {
10025
11289
  handleError(error);
10026
11290
  }
10027
11291
  });
10028
- analyze.command("delete").description("Delete an analysis, cancelling any run still in flight").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
11292
+ analyze.command("delete").description("Delete an analysis, canceling any run still in flight").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
10029
11293
  try {
10030
11294
  await confirmDestructive(`This will permanently delete analysis "${id}".`, { yes: options.yes, resourceId: id });
10031
11295
  await deleteAnalysis(id);
@@ -10059,10 +11323,10 @@ function registerAnalyzeCommand(program) {
10059
11323
  handleError(error);
10060
11324
  }
10061
11325
  });
10062
- analyze.command("visibility").description("Set analysis visibility (PRIVATE or PUBLIC)").argument("<id>", "Analysis ID").argument("<vis>", "PRIVATE or PUBLIC").option("--licence <licenceId>", LICENCE_HELP).addHelpText("after", `
11326
+ analyze.command("visibility").description("Set analysis visibility (PRIVATE or PUBLIC)").argument("<id>", "Analysis ID").argument("<vis>", "PRIVATE or PUBLIC").option("--license <licenseId>", LICENSE_HELP).addOption(hiddenOptionAlias("--licence <licenseId>", "license")).addHelpText("after", `
10063
11327
  Examples:
10064
- $ diafunc analyze visibility <id> PUBLIC --licence CC-BY-4.0 publish under a licence
10065
- $ diafunc analyze visibility <id> PRIVATE withdraw it; the licence is kept for later
11328
+ $ diafunc analyze visibility <id> PUBLIC --license CC-BY-4.0 publish under a license
11329
+ $ diafunc analyze visibility <id> PRIVATE withdraw it; the license is kept for later
10066
11330
  `).action(async (id, vis, options, cmd) => {
10067
11331
  try {
10068
11332
  const visibility = parseVisibility(vis);
@@ -10071,7 +11335,7 @@ Examples:
10071
11335
  visibility,
10072
11336
  (api, aid, v) => api.analysis.patchVisibility(aid, {
10073
11337
  visibility: v,
10074
- ...options.licence ? { licenceId: options.licence } : {}
11338
+ ...options.license ? { licenceId: options.license } : {}
10075
11339
  }),
10076
11340
  "Visibility",
10077
11341
  cmd
@@ -10132,13 +11396,13 @@ Examples:
10132
11396
  handleError(error);
10133
11397
  }
10134
11398
  });
10135
- analyze.command("input-exclusions").description("Set the columns every fit leaves out as an input (a single empty string leaves nothing out)").argument("<id>", "Analysis ID").argument("<column...>", `Column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
11399
+ analyze.command("input-exclusions").description("Set the columns the analysis leaves out as inputs (a single empty string leaves nothing out)").argument("<id>", "Analysis ID").argument("<column...>", `Column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
10136
11400
  try {
10137
11401
  await patchColumns(
10138
11402
  id,
10139
11403
  given,
10140
11404
  (api, columns) => api.analysis.patchInputExclusions(id, { columns }),
10141
- "Columns left out of the fit",
11405
+ "Columns left out as inputs",
10142
11406
  cmd
10143
11407
  );
10144
11408
  } catch (error) {
@@ -10158,31 +11422,85 @@ Examples:
10158
11422
  handleError(error);
10159
11423
  }
10160
11424
  });
10161
- analyze.command("questions").description("Set the questions the analysis answers, one argument per question").argument("<id>", "Analysis ID").argument("<question...>", "The questions, each quoted as one argument (a single empty string clears them)").action(async (id, given, _options, cmd) => {
11425
+ analyze.command("questions").description("Set the questions the analysis answers, one argument per question").argument("<id>", "Analysis ID").argument("<question...>", "The questions, each quoted as one argument (a single empty string clears them)").action(async (id, given, _options, cmd) => {
11426
+ try {
11427
+ const questions = questionsOf(Array.isArray(given) ? given : [given]) ?? [];
11428
+ await patchAndPrint(
11429
+ id,
11430
+ questions.join(" | "),
11431
+ (api, aid) => api.analysis.patchQuestions(aid, { questions }),
11432
+ "Questions",
11433
+ cmd
11434
+ );
11435
+ } catch (error) {
11436
+ handleError(error);
11437
+ }
11438
+ });
11439
+ analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name, matched against the columns of the analysis data (empty string to clear)").action(async (id, name, _options, cmd) => {
11440
+ try {
11441
+ const api = createApiClient();
11442
+ const segment = name === "" ? null : resolveColumnArgument(name, await columnNames(api, id), id);
11443
+ await patchAndPrint(
11444
+ id,
11445
+ name,
11446
+ () => api.analysis.patchSegment(id, { segment }),
11447
+ "Segment",
11448
+ cmd
11449
+ );
11450
+ } catch (error) {
11451
+ handleError(error);
11452
+ }
11453
+ });
11454
+ const intent = analyze.command("intent").description('Your private notes ("What you know and what matters"), read into proposals that apply only when you confirm them');
11455
+ intent.command("notes", { isDefault: true }).description("Show your notes, or set them (an empty text or --clear clears them). Only you can read them; storing them does not read them").argument("<id>", "Analysis ID").argument("[text]", `The notes, in your own words (at most ${MAX_INTENT_LENGTH.toLocaleString("en-US")} characters)`).option("--file <path>", "Read the notes from a file").option("--clear", "Clear the notes").action(async (id, text2, options, cmd) => {
11456
+ try {
11457
+ await notesCommand(id, text2, options, cmd);
11458
+ } catch (error) {
11459
+ handleError(error);
11460
+ }
11461
+ });
11462
+ intent.command("read").description("Read your notes into proposals and print them. Nothing changes until you confirm one").argument("<id>", "Analysis ID").option("--force", "Read them again even when nothing changed since the last reading").option("--refine", "Read them for a refinement of the analysis, where a row focus can be applied").action(async (id, options, cmd) => {
11463
+ try {
11464
+ await readNotesCommand(id, options, cmd);
11465
+ } catch (error) {
11466
+ handleError(error);
11467
+ }
11468
+ });
11469
+ const decisions = [
11470
+ { name: "confirm", state: "CONFIRMED", description: "Use proposals: each is applied to the analysis from the next run. An expectation is checked; --steer lets it steer the model too" },
11471
+ { name: "decline", state: "DECLINED", description: "Do not use proposals; one that was applied is taken back out" },
11472
+ { name: "reset", state: "PROPOSED", description: "Open proposals again, undoing the decision; one that was applied is taken back out" }
11473
+ ];
11474
+ for (const decision of decisions) {
11475
+ const command = intent.command(decision.name).description(decision.description).argument("<id>", "Analysis ID").argument("<proposalId...>", "Proposal ids, as 'analyze intent read' prints them");
11476
+ if (decision.state === "CONFIRMED") {
11477
+ command.option("--steer", "Also let the expectations steer which model is delivered").option("--no-steer", "Check and report the expectations only (the default for a new one)");
11478
+ }
11479
+ command.action(async (id, ids, options, cmd) => {
11480
+ try {
11481
+ await decideCommand(decision.state, id, ids, options, cmd);
11482
+ } catch (error) {
11483
+ handleError(error);
11484
+ }
11485
+ });
11486
+ }
11487
+ analyze.command("expectations").description("Show or set expectations about a target's shape. Each is checked and reported; one written with require: also steers the model").argument("<id>", "Analysis ID").argument("[statements...]", "Statements such as increasing(size_m2), decreasing(price, 1, 20), convex(x), concave(x) or range(0, inf), each with check: (the default) or require: in front; without --target written <target>=<statement>. A window left open is the input's observed range").option("--target <target>", "The target the statements are about; with --clear, the target to clear").option("--clear", "Clear the expectations of the target named, or all of them").action(async (id, statements, options, cmd) => {
11488
+ try {
11489
+ await expectationsCommand(id, statements, options, cmd);
11490
+ } catch (error) {
11491
+ handleError(error);
11492
+ }
11493
+ });
11494
+ analyze.command("charts").description(`Set the charts to add to the report, at most ${MAX_PAIRS} (a single empty string clears them)`).argument("<id>", "Analysis ID").argument("<pair...>", `Each <first>,<second>[,<kind>]: the second column against the first; kind is scatter, groups or counts, or left out for the chart rules to choose. ${PAIR_QUOTING_HELP}`).action(async (id, given, _options, cmd) => {
10162
11495
  try {
10163
- const questions = questionsOf(Array.isArray(given) ? given : [given]) ?? [];
10164
- await patchAndPrint(
10165
- id,
10166
- questions.join(" | "),
10167
- (api, aid) => api.analysis.patchQuestions(aid, { questions }),
10168
- "Questions",
10169
- cmd
10170
- );
11496
+ await chartsCommand(id, given, cmd);
10171
11497
  } catch (error) {
10172
11498
  handleError(error);
10173
11499
  }
10174
11500
  });
10175
- analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name, matched against the columns of the analysis data (empty string to clear)").action(async (id, name, _options, cmd) => {
11501
+ analyze.command("focus").description(`Set what matters most to you, as question families, most important first, at most ${MAX_FOCUS} (a single empty string clears them). The report answers these first`).argument("<id>", "Analysis ID").argument("<family...>", "Question families, for example extrapolation or input_importance").addHelpText("after", FOCUS_FAMILIES_HELP).action(async (id, given, _options, cmd) => {
10176
11502
  try {
10177
- const api = createApiClient();
10178
- const segment = name === "" ? null : resolveColumnArgument(name, await columnNames(api, id), id);
10179
- await patchAndPrint(
10180
- id,
10181
- name,
10182
- () => api.analysis.patchSegment(id, { segment }),
10183
- "Segment",
10184
- cmd
10185
- );
11503
+ await focusCommand(id, given, cmd);
10186
11504
  } catch (error) {
10187
11505
  handleError(error);
10188
11506
  }
@@ -10363,7 +11681,7 @@ async function listPublicAnalyses(options, cmd) {
10363
11681
  { key: "projectId", kind: "id" },
10364
11682
  { key: "publishedAt", header: "published", kind: "date" },
10365
11683
  { key: "changedAt", header: "changed", kind: "date" },
10366
- { key: "licenceId", header: "licence" }
11684
+ { key: "licenceId", header: "license" }
10367
11685
  ]
10368
11686
  });
10369
11687
  }
@@ -10450,44 +11768,44 @@ Examples:
10450
11768
  });
10451
11769
  }
10452
11770
 
10453
- // src/commands/licence/index.ts
10454
- import chalk29 from "chalk";
11771
+ // src/commands/license/index.ts
11772
+ import chalk30 from "chalk";
10455
11773
  function getOutputFormat19(cmd) {
10456
11774
  const config = loadConfig();
10457
11775
  const globalOpts = cmd.optsWithGlobals();
10458
11776
  return globalOpts.output ?? config.defaults.output ?? "human";
10459
11777
  }
10460
- var LICENCE_MARKS = [
11778
+ var LICENSE_MARKS = [
10461
11779
  { mark: "C", flag: "commercialUse", meaning: "commercial use" },
10462
11780
  { mark: "D", flag: "derivatives", meaning: "adaptations and forks" },
10463
11781
  { mark: "R", flag: "redistribution", meaning: "redistribution" },
10464
11782
  { mark: "BY", flag: "attributionRequired", meaning: "attribution required" },
10465
11783
  { mark: "SA", flag: "shareAlike", meaning: "share-alike" }
10466
11784
  ];
10467
- function licenceMarks(licence) {
10468
- const marks = LICENCE_MARKS.filter(({ flag }) => licence[flag] === true).map(({ mark }) => mark);
11785
+ function licenseMarks(license) {
11786
+ const marks = LICENSE_MARKS.filter(({ flag }) => license[flag] === true).map(({ mark }) => mark);
10469
11787
  return marks.length > 0 ? marks.join(" ") : null;
10470
11788
  }
10471
11789
  function stateWord(state) {
10472
11790
  return state.toLowerCase();
10473
11791
  }
10474
- async function listLicences(cmd) {
11792
+ async function listLicenses(cmd) {
10475
11793
  const outputFormat = getOutputFormat19(cmd);
10476
11794
  const api = createApiClient();
10477
- const licences = await api.admin.listLicences();
11795
+ const licenses = await api.admin.listLicenses();
10478
11796
  if (outputFormat === "json") {
10479
- format(licences, { format: outputFormat });
11797
+ format(licenses, { format: outputFormat });
10480
11798
  return;
10481
11799
  }
10482
- if (licences.length === 0 && outputFormat === "human") {
10483
- empty("licences");
11800
+ if (licenses.length === 0 && outputFormat === "human") {
11801
+ empty("licenses");
10484
11802
  return;
10485
11803
  }
10486
- format(licences.map((l) => ({
11804
+ format(licenses.map((l) => ({
10487
11805
  licenceId: l.licenceId,
10488
11806
  name: l.name,
10489
11807
  state: stateWord(l.state),
10490
- flags: licenceMarks(l),
11808
+ flags: licenseMarks(l),
10491
11809
  recommended: l.recommended
10492
11810
  })), {
10493
11811
  format: outputFormat,
@@ -10500,42 +11818,42 @@ async function listLicences(cmd) {
10500
11818
  ]
10501
11819
  });
10502
11820
  if (outputFormat === "human") {
10503
- console.error(chalk29.dim(
11821
+ console.error(chalk30.dim(
10504
11822
  `
10505
- Flags: ${LICENCE_MARKS.map(({ mark, meaning }) => `${mark} ${meaning}`).join(", ")}. A deprecated licence stays on the projects that carry it and cannot be chosen.`
11823
+ Flags: ${LICENSE_MARKS.map(({ mark, meaning }) => `${mark} ${meaning}`).join(", ")}. A deprecated license stays on the projects that carry it and cannot be chosen.`
10506
11824
  ));
10507
11825
  }
10508
11826
  }
10509
- async function showLicence(licenceId, cmd) {
11827
+ async function showLicense(licenseId, cmd) {
10510
11828
  const outputFormat = getOutputFormat19(cmd);
10511
11829
  const api = createApiClient();
10512
- let licence;
11830
+ let license;
10513
11831
  try {
10514
- licence = await api.admin.getLicence(licenceId);
11832
+ license = await api.admin.getLicense(licenseId);
10515
11833
  } catch (error) {
10516
11834
  if (error instanceof ApiError && error.status === 404) {
10517
- throw new CliError(`No licence "${licenceId}" in the catalogue.`, {
10518
- hint: `List the licences with 'diafunc licence list'.`
11835
+ throw new CliError(`No license "${licenseId}" in the catalog.`, {
11836
+ hint: `List the licenses with 'diafunc license list'.`
10519
11837
  });
10520
11838
  }
10521
11839
  throw error;
10522
11840
  }
10523
11841
  if (outputFormat !== "human") {
10524
- format(licence, { format: outputFormat });
11842
+ format(license, { format: outputFormat });
10525
11843
  return;
10526
11844
  }
10527
11845
  format({
10528
- licenceId: licence.licenceId,
10529
- name: licence.name,
10530
- state: stateWord(licence.state),
10531
- summary: licence.summary,
10532
- url: licence.url,
10533
- commercialUse: licence.commercialUse,
10534
- derivatives: licence.derivatives,
10535
- redistribution: licence.redistribution,
10536
- attributionRequired: licence.attributionRequired,
10537
- shareAlike: licence.shareAlike,
10538
- recommended: licence.recommended
11846
+ licenceId: license.licenceId,
11847
+ name: license.name,
11848
+ state: stateWord(license.state),
11849
+ summary: license.summary,
11850
+ url: license.url,
11851
+ commercialUse: license.commercialUse,
11852
+ derivatives: license.derivatives,
11853
+ redistribution: license.redistribution,
11854
+ attributionRequired: license.attributionRequired,
11855
+ shareAlike: license.shareAlike,
11856
+ recommended: license.recommended
10539
11857
  }, {
10540
11858
  format: outputFormat,
10541
11859
  columns: [
@@ -10543,7 +11861,7 @@ async function showLicence(licenceId, cmd) {
10543
11861
  { key: "name", header: "Name" },
10544
11862
  { key: "state", header: "State", kind: "state" },
10545
11863
  { key: "summary", header: "Summary" },
10546
- { key: "url", header: "Licence text" },
11864
+ { key: "url", header: "License text" },
10547
11865
  { key: "commercialUse", header: "Commercial use", kind: "boolean" },
10548
11866
  { key: "derivatives", header: "Adaptations and forks", kind: "boolean" },
10549
11867
  { key: "redistribution", header: "Redistribution", kind: "boolean" },
@@ -10553,24 +11871,24 @@ async function showLicence(licenceId, cmd) {
10553
11871
  ]
10554
11872
  });
10555
11873
  }
10556
- function registerLicenceCommands(program) {
10557
- const licence = program.command("licence").description("The licences a public project can be published under (no sign-in needed)").addHelpText("after", `
11874
+ function registerLicenseCommands(program) {
11875
+ const license = hiddenAlias(program.command("license"), "licence").description("The licenses a public project can be published under (no sign-in needed)").addHelpText("after", `
10558
11876
  Examples:
10559
- $ diafunc licence list the licences that can be chosen
10560
- $ diafunc licence show CC-BY-4.0 one licence and what it allows
10561
- $ diafunc project create --visibility PUBLIC --licence CC-BY-4.0
10562
- $ diafunc analyze visibility <id> PUBLIC --licence CC0-1.0
11877
+ $ diafunc license list the licenses that can be chosen
11878
+ $ diafunc license show CC-BY-4.0 one license and what it allows
11879
+ $ diafunc project create --visibility PUBLIC --license CC-BY-4.0
11880
+ $ diafunc analyze visibility <id> PUBLIC --license CC0-1.0
10563
11881
  `);
10564
- licence.command("list").description("List the licence catalogue: the active and the deprecated licences, in catalogue order").action(async (_options, cmd) => {
11882
+ license.command("list").description("List the license catalog: the active and the deprecated licenses, in catalog order").action(async (_options, cmd) => {
10565
11883
  try {
10566
- await listLicences(cmd);
11884
+ await listLicenses(cmd);
10567
11885
  } catch (error) {
10568
11886
  handleError(error);
10569
11887
  }
10570
11888
  });
10571
- licence.command("show").description("Show one licence, in any state, and what it allows").argument("<licenceId>", "Licence ID (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").action(async (licenceId, _options, cmd) => {
11889
+ license.command("show").description("Show one license, in any state, and what it allows").argument("<licenseId>", "License ID (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").action(async (licenseId, _options, cmd) => {
10572
11890
  try {
10573
- await showLicence(licenceId, cmd);
11891
+ await showLicense(licenseId, cmd);
10574
11892
  } catch (error) {
10575
11893
  handleError(error);
10576
11894
  }
@@ -10578,7 +11896,7 @@ Examples:
10578
11896
  }
10579
11897
 
10580
11898
  // src/commands/data-sources/index.ts
10581
- import chalk30 from "chalk";
11899
+ import chalk31 from "chalk";
10582
11900
  function getOutputFormat20(cmd) {
10583
11901
  const config = loadConfig();
10584
11902
  const globalOpts = cmd.optsWithGlobals();
@@ -10714,7 +12032,7 @@ async function showDashboard(projectId, cmd) {
10714
12032
  return;
10715
12033
  }
10716
12034
  const r = dashboard.rollup;
10717
- let line = chalk30.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
12035
+ let line = chalk31.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
10718
12036
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
10719
12037
  console.log(line);
10720
12038
  if (dashboard.sources.length === 0) {
@@ -10775,9 +12093,9 @@ async function createForAnalysis(api, options, human) {
10775
12093
  if (human) {
10776
12094
  success(`Added ${source.fileName} to analysis ${analysisId} from data source ${source.dataSourceId ?? ""}`.trimEnd());
10777
12095
  for (const line of planLines(build.plan)) {
10778
- console.log(line.caution ? chalk30.yellow(` ${line.text}`) : chalk30.dim(` ${line.text}`));
12096
+ console.log(line.caution ? chalk31.yellow(` ${line.text}`) : chalk31.dim(` ${line.text}`));
10779
12097
  }
10780
- console.log(chalk30.dim(options.scheduleCron ? ` Refreshes ${humanizeCron(options.scheduleCron)}; each refresh replaces the file and builds the data again.` : " No schedule of its own: refresh it with `data-sources refresh`, or let a trigger fetch it before a run (`analyze triggers create --refresh-first`)."));
12098
+ console.log(chalk31.dim(options.scheduleCron ? ` Refreshes ${humanizeCron(options.scheduleCron)}; each refresh replaces the file and builds the data again.` : " No schedule of its own: refresh it with `data-sources refresh`, or let a trigger fetch it before a run (`analyze triggers create --refresh-first`)."));
10781
12099
  }
10782
12100
  return { source, build };
10783
12101
  }
@@ -10805,8 +12123,8 @@ async function createDataSource(options, cmd) {
10805
12123
  const ds = await api.storage.createDataSource(request);
10806
12124
  if (outputFormat === "human") {
10807
12125
  success(`Created data source ${ds.id}`);
10808
- console.log(chalk30.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
10809
- if (ds.lastRunError) console.log(chalk30.dim(` Error: ${ds.lastRunError}`));
12126
+ console.log(chalk31.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
12127
+ if (ds.lastRunError) console.log(chalk31.dim(` Error: ${ds.lastRunError}`));
10810
12128
  } else {
10811
12129
  format(ds, { format: outputFormat });
10812
12130
  }
@@ -10852,7 +12170,7 @@ async function refreshDataSource(id, cmd) {
10852
12170
  const run = await api.storage.refreshDataSource(id);
10853
12171
  if (outputFormat === "human") {
10854
12172
  success(`Refresh queued: run ${run.runId}, status ${run.status}.`);
10855
- if (run.errorMessage) console.log(chalk30.red(` Error: ${run.errorMessage}`));
12173
+ if (run.errorMessage) console.log(chalk31.red(` Error: ${run.errorMessage}`));
10856
12174
  } else {
10857
12175
  format(run, { format: outputFormat });
10858
12176
  }
@@ -10979,7 +12297,7 @@ Examples:
10979
12297
  }
10980
12298
 
10981
12299
  // src/commands/table-exporters/index.ts
10982
- import chalk31 from "chalk";
12300
+ import chalk32 from "chalk";
10983
12301
  function getOutputFormat21(cmd) {
10984
12302
  const config = loadConfig();
10985
12303
  const globalOpts = cmd.optsWithGlobals();
@@ -11010,7 +12328,7 @@ function registerTableExportersCommands(program) {
11010
12328
  format: outputFormat,
11011
12329
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
11012
12330
  });
11013
- console.log(chalk31.dim(`${list.length} exporter(s)`));
12331
+ console.log(chalk32.dim(`${list.length} exporter(s)`));
11014
12332
  } catch (error) {
11015
12333
  handleError(error);
11016
12334
  }
@@ -11068,8 +12386,8 @@ function registerTableExportersCommands(program) {
11068
12386
  }
11069
12387
 
11070
12388
  // src/commands/skeleton/index.ts
11071
- import chalk32 from "chalk";
11072
- import * as fs12 from "fs";
12389
+ import chalk33 from "chalk";
12390
+ import * as fs13 from "fs";
11073
12391
  function getOutputFormat22(cmd) {
11074
12392
  const config = loadConfig();
11075
12393
  const globalOpts = cmd.optsWithGlobals();
@@ -11081,7 +12399,7 @@ function resolveProjectId2(cmd) {
11081
12399
  const config = loadConfig();
11082
12400
  if (config.defaults.project) return config.defaults.project;
11083
12401
  throw new Error(
11084
- "No project specified. Pass --project <id>, set the global --project flag, or run `diafunc config defaults project <id>`."
12402
+ "No project specified. Pass --project <id>, set the global --project flag, or run `diafunc config set defaults.project <id>`."
11085
12403
  );
11086
12404
  }
11087
12405
  function resolveTemplate(raw) {
@@ -11093,10 +12411,10 @@ function resolveTemplate(raw) {
11093
12411
  if (!file) {
11094
12412
  throw new Error("--template @ requires a filename after the @, e.g. --template @template.txt");
11095
12413
  }
11096
- if (!fs12.existsSync(file)) {
12414
+ if (!fs13.existsSync(file)) {
11097
12415
  throw new Error(`Template file not found: ${file}`);
11098
12416
  }
11099
- return fs12.readFileSync(file, "utf-8").trim();
12417
+ return fs13.readFileSync(file, "utf-8").trim();
11100
12418
  }
11101
12419
  return raw;
11102
12420
  }
@@ -11135,10 +12453,10 @@ async function createSkeleton(options, cmd) {
11135
12453
  const skeleton = await api.storage.createSkeleton(request);
11136
12454
  if (outputFormat === "human") {
11137
12455
  success(`Created skeleton ${skeleton.id}`);
11138
- console.log(chalk32.dim(` name: ${skeleton.name}`));
11139
- console.log(chalk32.dim(` template: ${skeleton.template}`));
11140
- console.log(chalk32.dim(` paramCount: ${skeleton.paramCount}`));
11141
- console.log(chalk32.dim(` weight: ${skeleton.weight}`));
12456
+ console.log(chalk33.dim(` name: ${skeleton.name}`));
12457
+ console.log(chalk33.dim(` template: ${skeleton.template}`));
12458
+ console.log(chalk33.dim(` paramCount: ${skeleton.paramCount}`));
12459
+ console.log(chalk33.dim(` weight: ${skeleton.weight}`));
11142
12460
  } else {
11143
12461
  format(skeleton, { format: outputFormat });
11144
12462
  }
@@ -11177,10 +12495,10 @@ async function updateSkeleton(id, options, cmd) {
11177
12495
  const skeleton = await api.storage.updateSkeleton(id, request);
11178
12496
  if (outputFormat === "human") {
11179
12497
  success(`Updated skeleton ${skeleton.id}`);
11180
- console.log(chalk32.dim(` name: ${skeleton.name}`));
11181
- console.log(chalk32.dim(` template: ${skeleton.template}`));
11182
- console.log(chalk32.dim(` paramCount: ${skeleton.paramCount}`));
11183
- console.log(chalk32.dim(` weight: ${skeleton.weight}`));
12498
+ console.log(chalk33.dim(` name: ${skeleton.name}`));
12499
+ console.log(chalk33.dim(` template: ${skeleton.template}`));
12500
+ console.log(chalk33.dim(` paramCount: ${skeleton.paramCount}`));
12501
+ console.log(chalk33.dim(` weight: ${skeleton.weight}`));
11184
12502
  } else {
11185
12503
  format(skeleton, { format: outputFormat });
11186
12504
  }
@@ -11197,7 +12515,7 @@ Examples:
11197
12515
  $ diafunc skeleton create --project <id> --name linear --template 'a*x+b'
11198
12516
  `);
11199
12517
  ;
11200
- skeleton.command("create").description("Create a skeleton. Parse errors from the engine are surfaced as stderr.").requiredOption("--name <name>", "Display name").requiredOption(
12518
+ skeleton.command("create").description("Create a skeleton. A template the platform cannot parse is reported on stderr.").requiredOption("--name <name>", "Display name").requiredOption(
11201
12519
  "--template <expr>",
11202
12520
  'Skeleton template expression (e.g. "?*x+?"). Use "@file.txt" to read from a file; "@@\u2026" escapes a literal leading @.'
11203
12521
  ).option("--weight <number>", "Sampling weight (positive; server default applies if omitted)").action(async (options, cmd) => {
@@ -11505,7 +12823,7 @@ function registerCompletionCommand(program) {
11505
12823
  }
11506
12824
 
11507
12825
  // src/commands/whoami/index.ts
11508
- import chalk33 from "chalk";
12826
+ import chalk34 from "chalk";
11509
12827
  function registerWhoamiCommand(program) {
11510
12828
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
11511
12829
  try {
@@ -11515,8 +12833,8 @@ function registerWhoamiCommand(program) {
11515
12833
  const api = createApiClient();
11516
12834
  const user = await api.admin.getMyUser();
11517
12835
  if (outputFormat === "human") {
11518
- console.log(chalk33.bold(user.name) + chalk33.dim(` <${user.email}>`));
11519
- console.log(chalk33.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
12836
+ console.log(chalk34.bold(user.name) + chalk34.dim(` <${user.email}>`));
12837
+ console.log(chalk34.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
11520
12838
  } else {
11521
12839
  format(user, { format: outputFormat });
11522
12840
  }
@@ -11527,7 +12845,7 @@ function registerWhoamiCommand(program) {
11527
12845
  }
11528
12846
 
11529
12847
  // src/commands/utilization/index.ts
11530
- import chalk34 from "chalk";
12848
+ import chalk35 from "chalk";
11531
12849
  function getOutputFormat23(cmd) {
11532
12850
  const config = loadConfig();
11533
12851
  const globalOpts = cmd.optsWithGlobals();
@@ -11544,19 +12862,19 @@ function windowLabel(u) {
11544
12862
  }
11545
12863
  function printUtilizationHuman(u, label) {
11546
12864
  const when2 = windowLabel(u);
11547
- console.log(label ? chalk34.bold(label) + " " + chalk34.dim(when2) : chalk34.bold(when2));
12865
+ console.log(label ? chalk35.bold(label) + " " + chalk35.dim(when2) : chalk35.bold(when2));
11548
12866
  if (u.types.length === 0) {
11549
- console.log(chalk34.dim(" (no usage)"));
12867
+ console.log(chalk35.dim(" (no usage)"));
11550
12868
  return;
11551
12869
  }
11552
12870
  const types = [...u.types].sort((a, b) => b.credits - a.credits);
11553
12871
  const width = Math.max(...types.map((t) => t.type.length));
11554
12872
  for (const t of types) {
11555
- const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk34.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
11556
- console.log(t.credits === 0 ? chalk34.dim(line) : line);
12873
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk35.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
12874
+ console.log(t.credits === 0 ? chalk35.dim(line) : line);
11557
12875
  }
11558
12876
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
11559
- console.log(chalk34.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk34.dim("credits")} ${total.toFixed(2).padStart(10)}`));
12877
+ console.log(chalk35.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk35.dim("credits")} ${total.toFixed(2).padStart(10)}`));
11560
12878
  }
11561
12879
  function formatDailyHistory(history) {
11562
12880
  const spentOn = (u) => u.dailyCredits ?? u.types.reduce((sum, t) => sum + (t.dailyCredits ?? 0), 0);
@@ -11573,14 +12891,14 @@ function formatDailyHistory(history) {
11573
12891
  for (const u of history) {
11574
12892
  const spent = spentOn(u);
11575
12893
  total += spent;
11576
- const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk34.dim("credits")}`;
11577
- lines.push(spent > 0 ? chalk34.bold(line) : chalk34.dim(line));
12894
+ const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk35.dim("credits")}`;
12895
+ lines.push(spent > 0 ? chalk35.bold(line) : chalk35.dim(line));
11578
12896
  for (const t of costly(u)) {
11579
12897
  lines.push(` ${t.type.padEnd(width - 2)} ${amount(t.dailyCredits ?? 0)}`);
11580
12898
  }
11581
12899
  }
11582
12900
  lines.push("");
11583
- lines.push(chalk34.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk34.dim("credits")}`));
12901
+ lines.push(chalk35.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk35.dim("credits")}`));
11584
12902
  return lines;
11585
12903
  }
11586
12904
  function registerUtilizationCommand(program) {
@@ -11736,7 +13054,7 @@ Examples:
11736
13054
  }
11737
13055
 
11738
13056
  // src/commands/invoice/index.ts
11739
- import * as fs13 from "fs";
13057
+ import * as fs14 from "fs";
11740
13058
  function getOutputFormat26(cmd) {
11741
13059
  const config = loadConfig();
11742
13060
  const globalOpts = cmd.optsWithGlobals();
@@ -11774,7 +13092,7 @@ Examples:
11774
13092
  const response = await api.admin.downloadInvoice(invoiceNumber, fileName);
11775
13093
  const buffer = Buffer.from(await response.arrayBuffer());
11776
13094
  const outPath = options.out ?? fileName;
11777
- fs13.writeFileSync(outPath, buffer);
13095
+ fs14.writeFileSync(outPath, buffer);
11778
13096
  success(`Invoice saved to ${outPath}`);
11779
13097
  } catch (error) {
11780
13098
  handleError(error);
@@ -11783,8 +13101,8 @@ Examples:
11783
13101
  }
11784
13102
 
11785
13103
  // src/commands/shell/index.ts
11786
- import chalk35 from "chalk";
11787
- import * as fs14 from "fs";
13104
+ import chalk36 from "chalk";
13105
+ import * as fs15 from "fs";
11788
13106
  import * as os4 from "os";
11789
13107
  import * as path10 from "path";
11790
13108
  import { spawn as spawn3 } from "child_process";
@@ -11800,15 +13118,15 @@ function extensionFor2(language) {
11800
13118
  }
11801
13119
  async function openInEditor(initial, ext) {
11802
13120
  const tmpFile = path10.join(os4.tmpdir(), `diafunc-shell-${randomUUID4()}.${ext}`);
11803
- fs14.writeFileSync(tmpFile, initial);
13121
+ fs15.writeFileSync(tmpFile, initial);
11804
13122
  const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
11805
13123
  await new Promise((resolve2, reject) => {
11806
13124
  const child = spawn3(editor, [tmpFile], { stdio: "inherit" });
11807
13125
  child.on("exit", (code) => code === 0 ? resolve2() : reject(new Error(`Editor exited with ${code}`)));
11808
13126
  child.on("error", reject);
11809
13127
  });
11810
- const content = fs14.readFileSync(tmpFile, "utf-8");
11811
- fs14.unlinkSync(tmpFile);
13128
+ const content = fs15.readFileSync(tmpFile, "utf-8");
13129
+ fs15.unlinkSync(tmpFile);
11812
13130
  return content;
11813
13131
  }
11814
13132
  function utcNowParts() {
@@ -11849,21 +13167,21 @@ async function evaluate(api, fnRef, language, sourceCode) {
11849
13167
  }, false);
11850
13168
  if (result.outputs?.length) {
11851
13169
  for (const out of result.outputs) {
11852
- console.log(chalk35.dim(` [${out.type}]`) + " " + out.output);
13170
+ console.log(chalk36.dim(` [${out.type}]`) + " " + out.output);
11853
13171
  }
11854
13172
  }
11855
13173
  if (result.successful) {
11856
13174
  if (result.result) {
11857
- console.log(chalk35.green("=>") + " " + resultText(result.result, result.resultEncoding));
13175
+ console.log(chalk36.green("=>") + " " + resultText(result.result, result.resultEncoding));
11858
13176
  } else {
11859
- console.log(chalk35.dim("=> (no value)"));
13177
+ console.log(chalk36.dim("=> (no value)"));
11860
13178
  }
11861
13179
  const duration = result.completed - result.started;
11862
- console.log(chalk35.dim(` [${duration}ms \xB7 ${evaluationId}]`));
13180
+ console.log(chalk36.dim(` [${duration}ms \xB7 ${evaluationId}]`));
11863
13181
  } else {
11864
- console.log(chalk35.red("error: ") + result.error);
13182
+ console.log(chalk36.red("error: ") + result.error);
11865
13183
  if (result.lineNumber > 0) {
11866
- console.log(chalk35.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
13184
+ console.log(chalk36.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
11867
13185
  }
11868
13186
  }
11869
13187
  }
@@ -11884,19 +13202,19 @@ function registerShellCommand(program) {
11884
13202
  });
11885
13203
  const api = createApiClient();
11886
13204
  const { input: promptInput } = await import("@inquirer/prompts");
11887
- const { getUpdateNotice } = await import("./update-check-JLTGX3S4.js");
13205
+ const { getUpdateNotice } = await import("./update-check-BH7IMKZN.js");
11888
13206
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
11889
- console.log(chalk35.bold("Diafunc shell") + chalk35.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
11890
- console.log(chalk35.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
11891
- console.log(chalk35.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
13207
+ console.log(chalk36.bold("Diafunc shell") + chalk36.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
13208
+ console.log(chalk36.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
13209
+ console.log(chalk36.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
11892
13210
  const notice = await getUpdateNotice();
11893
- if (notice) console.log(chalk35.dim(notice));
13211
+ if (notice) console.log(chalk36.dim(notice));
11894
13212
  console.log();
11895
13213
  let language = resolvedLanguage;
11896
13214
  for (; ; ) {
11897
13215
  let line;
11898
13216
  try {
11899
- line = await promptInput({ message: chalk35.cyan.bold(`${language} >`) });
13217
+ line = await promptInput({ message: chalk36.cyan.bold(`${language} >`) });
11900
13218
  } catch {
11901
13219
  console.log();
11902
13220
  return;
@@ -11914,54 +13232,54 @@ function registerShellCommand(program) {
11914
13232
  case "help":
11915
13233
  case "h":
11916
13234
  case "?":
11917
- console.log(chalk35.dim(" /edit open $EDITOR for multi-line code"));
11918
- console.log(chalk35.dim(" /file <path> evaluate the contents of a file"));
11919
- console.log(chalk35.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
11920
- console.log(chalk35.dim(" /quit exit the shell"));
13235
+ console.log(chalk36.dim(" /edit open $EDITOR for multi-line code"));
13236
+ console.log(chalk36.dim(" /file <path> evaluate the contents of a file"));
13237
+ console.log(chalk36.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
13238
+ console.log(chalk36.dim(" /quit exit the shell"));
11921
13239
  continue;
11922
13240
  case "lang":
11923
13241
  if (arg) language = arg;
11924
- console.log(chalk35.dim(`Language: ${language}`));
13242
+ console.log(chalk36.dim(`Language: ${language}`));
11925
13243
  continue;
11926
13244
  case "edit": {
11927
13245
  const sourceCode = await openInEditor("", extensionFor2(language));
11928
13246
  if (!sourceCode.trim()) {
11929
- console.log(chalk35.dim("(empty; not evaluated)"));
13247
+ console.log(chalk36.dim("(empty; not evaluated)"));
11930
13248
  continue;
11931
13249
  }
11932
13250
  try {
11933
13251
  await evaluate(api, fnRef, language, sourceCode);
11934
13252
  } catch (e) {
11935
- console.error(chalk35.red(e.message));
13253
+ console.error(chalk36.red(e.message));
11936
13254
  }
11937
13255
  continue;
11938
13256
  }
11939
13257
  case "file": {
11940
13258
  if (!arg) {
11941
- console.log(chalk35.dim("usage: /file <path>"));
13259
+ console.log(chalk36.dim("usage: /file <path>"));
11942
13260
  continue;
11943
13261
  }
11944
- if (!fs14.existsSync(arg)) {
11945
- console.log(chalk35.red(`file not found: ${arg}`));
13262
+ if (!fs15.existsSync(arg)) {
13263
+ console.log(chalk36.red(`file not found: ${arg}`));
11946
13264
  continue;
11947
13265
  }
11948
- const sourceCode = fs14.readFileSync(arg, "utf-8");
13266
+ const sourceCode = fs15.readFileSync(arg, "utf-8");
11949
13267
  try {
11950
13268
  await evaluate(api, fnRef, language, sourceCode);
11951
13269
  } catch (e) {
11952
- console.error(chalk35.red(e.message));
13270
+ console.error(chalk36.red(e.message));
11953
13271
  }
11954
13272
  continue;
11955
13273
  }
11956
13274
  default:
11957
- console.log(chalk35.dim(`Unknown command: /${cmd2}. Try /help.`));
13275
+ console.log(chalk36.dim(`Unknown command: /${cmd2}. Try /help.`));
11958
13276
  continue;
11959
13277
  }
11960
13278
  }
11961
13279
  try {
11962
13280
  await evaluate(api, fnRef, language, trimmed);
11963
13281
  } catch (e) {
11964
- console.error(chalk35.red(e.message));
13282
+ console.error(chalk36.red(e.message));
11965
13283
  }
11966
13284
  }
11967
13285
  } catch (error) {
@@ -11971,19 +13289,19 @@ function registerShellCommand(program) {
11971
13289
  }
11972
13290
 
11973
13291
  // src/commands/update/index.ts
11974
- import chalk36 from "chalk";
13292
+ import chalk37 from "chalk";
11975
13293
  import * as path11 from "path";
11976
13294
  import { spawn as spawn4 } from "child_process";
11977
13295
 
11978
13296
  // src/util/install-method.ts
11979
- import * as fs15 from "fs";
13297
+ import * as fs16 from "fs";
11980
13298
  function detectInstall() {
11981
13299
  const exec = process.execPath;
11982
13300
  const exe = exec.replace(/\\/g, "/").toLowerCase();
11983
13301
  const isNode = exe.endsWith("/node") || exe.endsWith("/node.exe");
11984
13302
  return {
11985
13303
  method: isNode ? "npm" : "binary",
11986
- binaryPath: isNode ? exec : fs15.realpathSync(exec)
13304
+ binaryPath: isNode ? exec : fs16.realpathSync(exec)
11987
13305
  };
11988
13306
  }
11989
13307
 
@@ -12017,14 +13335,14 @@ function registerUpdateCommand(program) {
12017
13335
  const install = detectInstall();
12018
13336
  const latest = await fetchLatestVersion();
12019
13337
  if (latest === package_default.version) {
12020
- console.log(chalk36.dim(`diafunc is already at the latest version (${package_default.version}).`));
13338
+ console.log(chalk37.dim(`diafunc is already at the latest version (${package_default.version}).`));
12021
13339
  return;
12022
13340
  }
12023
- console.log(chalk36.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
13341
+ console.log(chalk37.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
12024
13342
  if (install.method === "npm") {
12025
13343
  console.log();
12026
13344
  console.log("Installed via npm. Upgrade with:");
12027
- console.log(chalk36.bold(` npm install -g @diafunc/cli@${latest}`));
13345
+ console.log(chalk37.bold(` npm install -g @diafunc/cli@${latest}`));
12028
13346
  return;
12029
13347
  }
12030
13348
  const installDir = path11.dirname(install.binaryPath);
@@ -12038,9 +13356,9 @@ function registerUpdateCommand(program) {
12038
13356
  }
12039
13357
 
12040
13358
  // src/commands/uninstall/index.ts
12041
- import chalk37 from "chalk";
13359
+ import chalk38 from "chalk";
12042
13360
  import { spawn as spawn5 } from "child_process";
12043
- import * as fs16 from "fs";
13361
+ import * as fs17 from "fs";
12044
13362
  import * as os5 from "os";
12045
13363
  import * as path12 from "path";
12046
13364
  function registerUninstallCommand(program) {
@@ -12050,11 +13368,11 @@ function registerUninstallCommand(program) {
12050
13368
  const configDir = path12.join(os5.homedir(), ".diafunc");
12051
13369
  if (install.method === "npm") {
12052
13370
  console.log("Installed via npm. Remove with:");
12053
- console.log(chalk37.bold(" npm uninstall -g @diafunc/cli"));
12054
- if (fs16.existsSync(configDir)) {
13371
+ console.log(chalk38.bold(" npm uninstall -g @diafunc/cli"));
13372
+ if (fs17.existsSync(configDir)) {
12055
13373
  console.log();
12056
13374
  console.log(`Config and credentials live at ${configDir}. Remove them manually with:`);
12057
- console.log(chalk37.bold(` rm -rf ${configDir}`));
13375
+ console.log(chalk38.bold(` rm -rf ${configDir}`));
12058
13376
  }
12059
13377
  return;
12060
13378
  }
@@ -12064,19 +13382,19 @@ function registerUninstallCommand(program) {
12064
13382
  default: false
12065
13383
  });
12066
13384
  if (!removeBinary) {
12067
- console.log(chalk37.dim("Aborted."));
13385
+ console.log(chalk38.dim("Aborted."));
12068
13386
  return;
12069
13387
  }
12070
13388
  let removeConfig = options.purge ?? false;
12071
- if (!options.purge && !options.yes && fs16.existsSync(configDir)) {
13389
+ if (!options.purge && !options.yes && fs17.existsSync(configDir)) {
12072
13390
  removeConfig = await confirm({
12073
13391
  message: `Also remove ${configDir} (config + credentials)?`,
12074
13392
  default: false
12075
13393
  });
12076
13394
  }
12077
- if (removeConfig && fs16.existsSync(configDir)) {
12078
- fs16.rmSync(configDir, { recursive: true, force: true });
12079
- console.log(chalk37.dim(`Removed ${configDir}`));
13395
+ if (removeConfig && fs17.existsSync(configDir)) {
13396
+ fs17.rmSync(configDir, { recursive: true, force: true });
13397
+ console.log(chalk38.dim(`Removed ${configDir}`));
12080
13398
  }
12081
13399
  if (process.platform === "win32") {
12082
13400
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -12086,13 +13404,13 @@ function registerUninstallCommand(program) {
12086
13404
  windowsHide: true
12087
13405
  });
12088
13406
  child.unref();
12089
- console.log(chalk37.dim(`Removing ${install.binaryPath} on exit...`));
13407
+ console.log(chalk38.dim(`Removing ${install.binaryPath} on exit...`));
12090
13408
  console.log();
12091
13409
  console.log("diafunc uninstalled.");
12092
13410
  return;
12093
13411
  }
12094
- fs16.rmSync(install.binaryPath, { force: true });
12095
- console.log(chalk37.dim(`Removed ${install.binaryPath}`));
13412
+ fs17.rmSync(install.binaryPath, { force: true });
13413
+ console.log(chalk38.dim(`Removed ${install.binaryPath}`));
12096
13414
  console.log();
12097
13415
  console.log("diafunc uninstalled.");
12098
13416
  } catch (error) {
@@ -12102,9 +13420,9 @@ function registerUninstallCommand(program) {
12102
13420
  }
12103
13421
 
12104
13422
  // src/prompting/command.ts
12105
- import { Command } from "commander";
12106
- var commanderOriginal = Command.prototype;
12107
- var DiafuncCommand = class _DiafuncCommand extends Command {
13423
+ import { Command as Command2 } from "commander";
13424
+ var commanderOriginal = Command2.prototype;
13425
+ var DiafuncCommand = class _DiafuncCommand extends Command2 {
12108
13426
  /** Gaps recorded during the current parse, in the order commander found them. */
12109
13427
  pendingInputs = [];
12110
13428
  /** Set on the program only; every command reads it from there. */
@@ -12156,210 +13474,11 @@ var DiafuncCommand = class _DiafuncCommand extends Command {
12156
13474
  };
12157
13475
 
12158
13476
  // src/prompting/fill.ts
12159
- import chalk39 from "chalk";
12160
-
12161
- // src/prompting/resolvers.ts
12162
- var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
12163
- var TRIGGER_TYPES = ["SCHEDULE", "EVENT", "LINK", "MANUAL"];
12164
- var ANALYSIS_TRIGGER_KINDS = ["ONCE", "CRON"];
12165
- var VISIBILITIES = ["PRIVATE", "PUBLIC"];
12166
- var SHELLS = ["bash", "zsh", "fish"];
12167
- var CONFIG_KEYS = ["defaults.project", "defaults.branch", "defaults.output"];
12168
- var ENTITY_TYPE_BY_GROUP = {
12169
- table: "table",
12170
- function: "function",
12171
- trigger: "function",
12172
- schedule: "function"
12173
- };
12174
- var TEXT = { kind: "text" };
12175
- var TEXT_OR_EMPTY = { kind: "text", allowEmpty: true };
12176
- var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
12177
- var INDEX = { kind: "number", min: 0, integer: true };
12178
- var BY_COMMAND = {
12179
- "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
12180
- "analyze targets": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
12181
- "analyze input-exclusions": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
12182
- "analyze confirmed-inputs": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
12183
- "analyze questions": { "<question>": TEXT_OR_EMPTY },
12184
- "analyze description": { "<text>": TEXT_OR_EMPTY },
12185
- "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
12186
- // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.
12187
- "public show": { "<analysisId>": TEXT },
12188
- "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
12189
- "branch merge": {
12190
- "--source": { kind: "entity", form: "ref" },
12191
- "--target": { kind: "project", withBranch: true }
12192
- },
12193
- "branch create": { "<branchName>": TEXT },
12194
- "branch delete": { "<branchName>": { kind: "projectBranch", projectFrom: "projectId" } },
12195
- "admin backup restore-project": { "<projectBranch>": { kind: "projectBranch", projectFrom: "projectId" } },
12196
- "data-sources create": {
12197
- "--project-id": { kind: "project", withBranch: false },
12198
- "--project-branch": { kind: "projectBranch", projectFrom: "projectId" },
12199
- "--target-entity-id": { kind: "entity", form: "id", contentType: "table", projectFrom: "projectId" },
12200
- "--target-entity-branch": { kind: "text", defaultValue: "main" },
12201
- "--type": { kind: "connectorType" }
12202
- },
12203
- "table-exporters create": {
12204
- "--function-project": { kind: "project", withBranch: false },
12205
- "--function-entity": { kind: "entity", form: "id", contentType: "function", projectFrom: "functionProject" },
12206
- "--format": TEXT
12207
- },
12208
- "table exports get": { "--ref": { kind: "entity", form: "ref", contentType: "table" } },
12209
- "table export": { "<format>": { kind: "exportFormat" } },
12210
- "entity export": { "<entityIds>": { kind: "entity", form: "id", projectFrom: "project", multiple: true } },
12211
- "notebook export": {
12212
- "<notebookIds>": { kind: "entity", form: "id", contentType: "notebook", projectFrom: "project", multiple: true }
12213
- },
12214
- "entity tags set": { "<tags>": TEXT_OR_EMPTY },
12215
- "project tags set": { "<tags>": TEXT_OR_EMPTY },
12216
- "admin curated-tags create": { "--display-name": TEXT },
12217
- "link delete": { "<linkId>": { kind: "link" } },
12218
- "link create": { "<linkId>": TEXT },
12219
- "config profile use": { "<name>": { kind: "profile" } },
12220
- "config profile remove": { "<name>": { kind: "profile" } },
12221
- "config get": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
12222
- "config set": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
12223
- "project members invite": { "<userId>": TEXT, "<role>": { kind: "choice", choices: PROJECT_ROLES } },
12224
- "project members join": { "<userId>": TEXT },
12225
- "trigger create": { "--type": { kind: "choice", choices: TRIGGER_TYPES } },
12226
- "analyze triggers create": { "--kind": { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS } },
12227
- "function outputs": { "<evaluationId>": TEXT },
12228
- "team create": { "--seats": { kind: "number", min: 1, integer: true } },
12229
- "team seats preview": { "<count>": { kind: "number", min: 1, integer: true } },
12230
- "team seats set": { "<count>": { kind: "number", min: 1, integer: true } }
12231
- };
12232
- var BY_NAME = {
12233
- projectId: { kind: "project", withBranch: false },
12234
- projectRef: { kind: "project", withBranch: true },
12235
- project: { kind: "project", withBranch: true },
12236
- teamId: { kind: "team" },
12237
- invitationId: { kind: "teamInvitation" },
12238
- analysisId: { kind: "analysis" },
12239
- licenceId: { kind: "licence" },
12240
- sessionId: { kind: "chatSession" },
12241
- tokenId: { kind: "apiToken" },
12242
- resource: { kind: "tokenResource" },
12243
- scopes: { kind: "choices", choices: VALID_SCOPES },
12244
- evaluationId: { kind: "evaluation" },
12245
- eventId: { kind: "event" },
12246
- occurrenceId: { kind: "occurrence" },
12247
- exportId: { kind: "tableExport" },
12248
- invoiceNumber: { kind: "invoice" },
12249
- fileName: { kind: "invoiceDocument" },
12250
- shell: { kind: "choice", choices: SHELLS },
12251
- vis: { kind: "choice", choices: VISIBILITIES },
12252
- kind: { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS },
12253
- date: { kind: "date" },
12254
- file: { kind: "file" },
12255
- email: { kind: "text", email: true },
12256
- index: INDEX,
12257
- row: INDEX,
12258
- col: INDEX,
12259
- count: INDEX,
12260
- version: { kind: "number", min: 1, integer: true },
12261
- hours: POSITIVE,
12262
- credits: POSITIVE,
12263
- seats: { kind: "number", min: 1, integer: true },
12264
- value: TEXT_OR_EMPTY,
12265
- // Free text: names, messages and ids the reader is creating rather than choosing.
12266
- name: TEXT,
12267
- tag: TEXT,
12268
- tags: TEXT,
12269
- newId: TEXT,
12270
- message: TEXT,
12271
- query: TEXT,
12272
- title: TEXT,
12273
- token: TEXT,
12274
- subscriptionToken: TEXT,
12275
- forkProjectId: TEXT,
12276
- targetBranch: TEXT,
12277
- bucketName: TEXT,
12278
- objectName: TEXT,
12279
- template: TEXT,
12280
- plan: TEXT,
12281
- schedule: TEXT,
12282
- consumerType: TEXT,
12283
- consumerId: TEXT,
12284
- format: TEXT,
12285
- key: TEXT
12286
- };
12287
- function tokenOf(input) {
12288
- return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
12289
- }
12290
- function specFor(path13, input) {
12291
- const exact = BY_COMMAND[path13]?.[tokenOf(input)];
12292
- if (exact) return exact;
12293
- const group = path13.split(" ")[0];
12294
- const sub = path13.split(" ").slice(0, 2).join(" ");
12295
- switch (input.name) {
12296
- case "ref":
12297
- case "sourceRef":
12298
- case "targetRef":
12299
- return { kind: "entity", form: "ref", contentType: ENTITY_TYPE_BY_GROUP[group] };
12300
- case "userId":
12301
- return group === "team" ? { kind: "teamMember" } : { kind: "projectMember" };
12302
- case "id":
12303
- if (sub === "analyze presets") return { kind: "preset" };
12304
- if (group === "analyze") return { kind: "analysis" };
12305
- if (group === "data-sources") return { kind: "dataSource" };
12306
- if (group === "skeleton") return { kind: "skeleton" };
12307
- if (group === "table-exporters") return { kind: "tableExporter" };
12308
- if (group === "status") return { kind: "statusComponent" };
12309
- return null;
12310
- case "runId":
12311
- if (group === "analyze") return { kind: "analysisRun" };
12312
- if (group === "data-sources") return { kind: "dataSourceRun" };
12313
- return null;
12314
- case "triggerId":
12315
- if (group === "analyze") return { kind: "analysisTrigger" };
12316
- if (group === "trigger") return { kind: "functionTrigger" };
12317
- return null;
12318
- case "role":
12319
- return { kind: "choice", choices: PROJECT_ROLES };
12320
- case "type":
12321
- return null;
12322
- default:
12323
- return BY_NAME[input.name] ?? null;
12324
- }
12325
- }
12326
- function dependencies(spec) {
12327
- switch (spec.kind) {
12328
- case "teamMember":
12329
- case "teamInvitation":
12330
- return ["teamId"];
12331
- case "projectMember":
12332
- return ["projectId"];
12333
- case "analysisColumns":
12334
- return ["id"];
12335
- case "evaluation":
12336
- return ["ref", "date"];
12337
- case "functionTrigger":
12338
- case "event":
12339
- case "tableExport":
12340
- return ["ref"];
12341
- case "occurrence":
12342
- return ["ref", "eventId"];
12343
- case "link":
12344
- return ["sourceRef"];
12345
- case "tokenResource":
12346
- return ["resourceType"];
12347
- case "dataSourceRun":
12348
- return ["id"];
12349
- case "invoiceDocument":
12350
- return ["invoiceNumber"];
12351
- case "projectBranch":
12352
- return [spec.projectFrom];
12353
- case "entity":
12354
- return spec.projectFrom ? [spec.projectFrom] : [];
12355
- default:
12356
- return [];
12357
- }
12358
- }
13477
+ import chalk40 from "chalk";
12359
13478
 
12360
13479
  // src/prompting/pickers.ts
12361
- import * as fs17 from "fs";
12362
- import chalk38 from "chalk";
13480
+ import * as fs18 from "fs";
13481
+ import chalk39 from "chalk";
12363
13482
  var SEARCH_THRESHOLD = 10;
12364
13483
  var TYPE_IT = "\0type-it";
12365
13484
  async function askFor(spec, input, ctx) {
@@ -12447,7 +13566,7 @@ async function askFor(spec, input, ctx) {
12447
13566
  const invoices = await ctx.api().admin.getInvoices();
12448
13567
  for (const i of invoices) ctx.prefill.set(`invoiceKind:${i.invoiceNumber}`, i.kind ?? "INVOICE");
12449
13568
  return invoices.map((i) => ({
12450
- label: `#${i.invoiceNumber} ${i.periodFrom ?? ""}\u2013${i.periodTo ?? ""}`,
13569
+ label: `#${i.invoiceNumber} ${i.periodFrom ?? ""} to ${i.periodTo ?? ""}`,
12451
13570
  value: String(i.invoiceNumber),
12452
13571
  hint: `${i.status ?? ""} \xB7 ${i.total ?? ""} ${i.currency ?? ""}`.trim()
12453
13572
  }));
@@ -12481,8 +13600,8 @@ async function askFor(spec, input, ctx) {
12481
13600
  return listed(ctx, "profiles", messageFor(input, "Profile"), async () => Object.keys(loadConfig().profiles).map((p) => ({ label: p, value: p })));
12482
13601
  case "statusComponent":
12483
13602
  return listed(ctx, "components", messageFor(input, "Component"), async () => (await createStatusService().getComponents()).map((c) => ({ label: c.id, value: c.id, hint: `${c.state} \xB7 ${c.domainId}` })));
12484
- case "licence":
12485
- return listed(ctx, "licences", messageFor(input, "Licence"), async () => (await ctx.api().admin.listLicences()).map((l) => ({ label: l.name, value: l.licenceId, hint: `${l.state.toLowerCase()} \xB7 ${l.licenceId}` })));
13603
+ case "license":
13604
+ return listed(ctx, "licenses", messageFor(input, "License"), async () => (await ctx.api().admin.listLicenses()).map((l) => ({ label: l.name, value: l.licenceId, hint: `${l.state.toLowerCase()} \xB7 ${l.licenceId}` })));
12486
13605
  case "choice":
12487
13606
  return choose(ctx, question(input), spec.choices.map((c) => ({ label: c, value: c })));
12488
13607
  case "choices": {
@@ -12495,7 +13614,7 @@ async function askFor(spec, input, ctx) {
12495
13614
  }
12496
13615
  case "file":
12497
13616
  return typed(ctx, question(input), {
12498
- validate: (value) => fs17.existsSync(value.trim()) || `No file at ${value.trim()}.`
13617
+ validate: (value) => fs18.existsSync(value.trim()) || `No file at ${value.trim()}.`
12499
13618
  });
12500
13619
  case "number":
12501
13620
  return typed(ctx, question(input), { validate: numberRule(spec) });
@@ -12709,7 +13828,7 @@ function typedValue(ctx, message) {
12709
13828
  return typed(ctx, message);
12710
13829
  }
12711
13830
  function typeItChoice() {
12712
- return { name: chalk38.dim("Type it instead"), value: TYPE_IT };
13831
+ return { name: chalk39.dim("Type it instead"), value: TYPE_IT };
12713
13832
  }
12714
13833
  function text(ctx, name) {
12715
13834
  const value = ctx.known.get(name);
@@ -12739,7 +13858,7 @@ function capitalize(value) {
12739
13858
  return value.charAt(0).toUpperCase() + value.slice(1);
12740
13859
  }
12741
13860
  function labelled(label, hint2) {
12742
- return hint2 && hint2 !== label ? `${label} ${chalk38.dim(hint2)}` : label;
13861
+ return hint2 && hint2 !== label ? `${label} ${chalk39.dim(hint2)}` : label;
12743
13862
  }
12744
13863
  function numberRule(spec) {
12745
13864
  return (raw) => {
@@ -12785,7 +13904,7 @@ async function fillPendingInputs(actionCommand) {
12785
13904
  known: knownValues(actionCommand),
12786
13905
  globals: actionCommand.optsWithGlobals(),
12787
13906
  prefill: /* @__PURE__ */ new Map(),
12788
- note: (line) => process.stderr.write(chalk39.dim(` ${line}
13907
+ note: (line) => process.stderr.write(chalk40.dim(` ${line}
12789
13908
  `))
12790
13909
  };
12791
13910
  for (const item of orderByDependencies(pending)) {
@@ -12794,7 +13913,7 @@ async function fillPendingInputs(actionCommand) {
12794
13913
  ctx.known.set(item.input.name, value);
12795
13914
  }
12796
13915
  const log = env.log ?? ((line) => console.log(line));
12797
- log(chalk39.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
13916
+ log(chalk40.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
12798
13917
  }
12799
13918
  function commandChain(cmd) {
12800
13919
  const chain = [];
@@ -12891,7 +14010,7 @@ Docs: https://diafunc.com/documentation
12891
14010
  function createProgram(environment = {}) {
12892
14011
  const program = new DiafuncCommand();
12893
14012
  program.promptEnvironment = environment;
12894
- program.name("diafunc").description("Diafunc CLI: the command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
14013
+ program.name("diafunc").description("Diafunc CLI: the command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable colored output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true, ...HIDDEN_ALIAS_HELP }).configureOutput({
12895
14014
  // Commander writes usage errors to stdout by default, which puts a complaint in the middle
12896
14015
  // of whatever a caller was capturing.
12897
14016
  writeErr: (str) => process.stderr.write(str)
@@ -12899,7 +14018,7 @@ function createProgram(environment = {}) {
12899
14018
  const opts = thisCommand.optsWithGlobals();
12900
14019
  if (opts.dryRun) setDryRun(true);
12901
14020
  if (opts.verbose) setVerbose(true);
12902
- if (opts.color === false) chalk40.level = 0;
14021
+ if (opts.color === false) chalk41.level = 0;
12903
14022
  }).hook("preAction", (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));
12904
14023
  program.addHelpText("after", HELP_EPILOGUE);
12905
14024
  registerAuthCommands(program);
@@ -12921,7 +14040,7 @@ function createProgram(environment = {}) {
12921
14040
  registerStatusCommands(program);
12922
14041
  registerAnalyzeCommand(program);
12923
14042
  registerPublicCommands(program);
12924
- registerLicenceCommands(program);
14043
+ registerLicenseCommands(program);
12925
14044
  registerDataSourcesCommands(program);
12926
14045
  registerTableExportersCommands(program);
12927
14046
  registerSkeletonCommands(program);
@@ -12934,13 +14053,14 @@ function createProgram(environment = {}) {
12934
14053
  registerShellCommand(program);
12935
14054
  registerUpdateCommand(program);
12936
14055
  registerUninstallCommand(program);
14056
+ wireHiddenOptionAliases(program);
12937
14057
  return program;
12938
14058
  }
12939
14059
 
12940
14060
  export {
12941
14061
  EXIT_CANCELLED,
12942
14062
  handleError,
12943
- PromptCancelled,
14063
+ PromptCanceled,
12944
14064
  createProgram
12945
14065
  };
12946
- //# sourceMappingURL=chunk-ZBC2S7R6.js.map
14066
+ //# sourceMappingURL=chunk-6QBACH4J.js.map