diff --git a/.github/workflows/kit-ci.yml b/.github/workflows/kit-ci.yml index 1c77a13..ff539e9 100644 --- a/.github/workflows/kit-ci.yml +++ b/.github/workflows/kit-ci.yml @@ -60,6 +60,43 @@ jobs: # catch a syntax error in it before an author ran it against a deck. python3 -c "import ast,sys; ast.parse(open(sys.argv[1]).read(), sys.argv[1])" tools/extract-pptx-assets.py + # `node --check` is syntax-only: it never resolves an import, which is how + # check-tenant-access.mjs shipped importing '../config/workshop-target.mjs' + # as './workshop-target.mjs' and died with ERR_MODULE_NOT_FOUND on every + # run. Importing the modules for real is not an option -- some execute on + # load and would hit a live tenant from CI -- so the edges are resolved + # statically instead. + - name: Every relative import resolves + run: | + node -e " + const fs = require('node:fs'); + const path = require('node:path'); + const roots = ['bin', 'src', 'tools']; + const files = []; + const walk = (dir) => { + for (const e of fs.readdirSync(dir, {withFileTypes: true})) { + const full = path.join(dir, e.name); + if (e.isDirectory()) walk(full); + else if (/\.mjs\$/.test(e.name)) files.push(full); + } + }; + for (const r of roots) if (fs.existsSync(r)) walk(r); + const failures = []; + for (const file of files) { + const src = fs.readFileSync(file, 'utf8'); + for (const m of src.matchAll(/(?:from|import)\s*\(?\s*['\"](\.[^'\"]+)['\"]/g)) { + const target = path.resolve(path.dirname(file), m[1]); + if (!fs.existsSync(target)) failures.push(file + ' -> ' + m[1]); + } + } + if (failures.length) { + console.error('Unresolvable relative imports:'); + for (const f of failures) console.error('- ' + f); + process.exit(1); + } + console.log(files.length + ' module(s) checked; every relative import resolves.'); + " + - name: CLI responds run: | node bin/workshop-kit.mjs --version @@ -128,6 +165,92 @@ jobs: grep -q '{{WORKSHOP_UIPATH_ORG_NAME}}' "$work/downloads/project/AGENTS.md" || { echo 'FAIL: source file was mutated'; exit 1; } echo 'zip pipeline OK' + # Derivation is the only reason two targets can silently share an app name, so + # the uniqueness guard is tested alongside it. `local` and a hosted target + # normally point at the SAME tenant, which is exactly the colliding shape. + - name: Coded App name derives from productSlug and tenant, uniquely + run: | + set -e + work="$(mktemp -d)"; mkdir -p "$work/config" + # $1 = extra top-level JSON, $2 = local's codedApp body, $3 = growth's + write() { + cat > "$work/config/workshop-targets.json" <&1 ); } + + # derives, and normalises underscores + case + write '"productSlug":"ixp",' '"name":"ixp-local",' '' + run growth | grep -q 'Coded App name: ixp-bellevue-july2026-20260727' \ + || { echo 'FAIL: did not derive/normalise'; exit 1; } + + # an explicit name always wins + write '"productSlug":"ixp",' '"name":"ixp-local",' '"name":"hand-written",' + run growth | grep -q 'Coded App name: hand-written' || { echo 'FAIL: explicit name ignored'; exit 1; } + + # no productSlug and no name is still a missing-field error + write '' '"name":"ixp-local",' '' + run growth 2>&1 | grep -q 'missing required fields: codedApp.name' \ + || { echo 'FAIL: absent name not reported'; exit 1; } + + # a derived name over 32 fails, and says it was derived + write '"productSlug":"case-management",' '"name":"cm-local",' '' + out="$(run growth)" && { echo 'FAIL: over-long derived name accepted'; exit 1; } + echo "$out" | grep -q 'derived from productSlug' || { echo 'FAIL: error does not say it was derived'; exit 1; } + + # two targets resolving to one name is refused (same tenant, both derived) + cat > "$work/config/workshop-targets.json" <<'JSON' + {"title":"F","tagline":"t","repo":"o/r","docsLabel":"D","defaultTarget":"growth","productSlug":"ixp", + "targets":{ + "local":{"siteUrl":"http://x","baseUrl":"/","workshop":{"uipathOrgName":"o","uipathTenantName":"Workshops","uipathTenantUrl":"u","orchestratorParentFolder":"Shared"},"codedApp":{"description":"d"}}, + "growth":{"siteUrl":"http://y","baseUrl":"/g/","workshop":{"uipathOrgName":"o","uipathTenantName":"Workshops","uipathTenantUrl":"u","orchestratorParentFolder":"Shared"},"codedApp":{"description":"d"}}}} + JSON + out="$(run growth)" && { echo 'FAIL: colliding app names accepted'; exit 1; } + echo "$out" | grep -q 'both resolve to codedApp.name' || { echo 'FAIL: collision not reported'; exit 1; } + echo 'name derivation OK' + + # The 32-char Coded App name limit is enforced in validateTarget, which every + # command path reaches. It matters because `uip codedapp publish` ACCEPTS an + # over-long name and only `deploy` refuses it, leaving an orphan package in + # Orchestrator -- so the failure has to happen locally, before either runs. + - name: Coded App name length is enforced at the 32-char boundary + run: | + set -e + work="$(mktemp -d)" + mkdir -p "$work/config" + write_target() { + cat > "$work/config/workshop-targets.json" </dev/null 2>&1 ) \ + || { echo 'FAIL: a 32-character name was rejected'; exit 1; } + + write_target "$n33" + out="$( cd "$work" && node "$GITHUB_WORKSPACE/bin/workshop-kit.mjs" codedapp check 2>&1 )" && { + echo 'FAIL: a 33-character name was accepted'; exit 1; } + echo "$out" | grep -q '33 characters' || { echo 'FAIL: error does not report the length'; exit 1; } + + # init must refuse a slug that would blow the budget in any standard pattern. + slugdir="$(mktemp -d)" + ( cd "$slugdir" && node "$GITHUB_WORKSPACE/bin/workshop-kit.mjs" init --product communications-mining >/dev/null 2>&1 ) && { + echo 'FAIL: init accepted a 21-character slug'; exit 1; } + [ -z "$(ls -A "$slugdir")" ] || { echo 'FAIL: init left files behind after rejecting'; exit 1; } + ( cd "$slugdir" && node "$GITHUB_WORKSPACE/bin/workshop-kit.mjs" init --product comms-mining >/dev/null 2>&1 ) \ + || { echo 'FAIL: init rejected a 12-character slug'; exit 1; } + echo 'name length rules OK' + # This prune DELETES files from static/downloads/, so it is covered the same # way. The regression it guards: static/downloads/ is gitignored, so a stale # ZIP is invisible to CI and code review, yet `codedapp pack` packs the local diff --git a/README.md b/README.md index 69ae014..99b0b8c 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ template/ scaffold for `workshop-kit init` (a complete, building workshop-kit prepare zip:downloads + doc-asset + workshop-var checks + agents build workshop-kit agents build regenerate AGENTS.md from base + product workshop-kit agents check fail if AGENTS.md is stale or hand-edited inside the fence -workshop-kit check:tenant-access advisory tenant permission report (never fails a build) +workshop-kit check:tenant-access advisory tenant permission + capacity report (never fails a build) workshop-kit build --target workshop-kit codedapp pack prunes old nupkgs workshop-kit preview --target @@ -45,6 +45,113 @@ workshop-kit repin move a content repo onto a released kit ta workshop-kit init --product ``` +## The tenant check + +`check:tenant-access` answers one question before a workshop is delivered: can +this tenant actually run it? It reports two things. + +**Permissions.** Whether the `-Participants` and `-Facilitators` +groups hold the Document Understanding, Data Fabric, Studio Web and folder roles +the exercises need, and whether the IXP (`reinfer`) service is enabled. For a +missing role it prints the `uip` command that grants it, and never runs it. + +`-Participants` and `-Facilitators` is the UiPath Labs convention, +and it holds for the `uipathlabstraining` tenants that host real deliveries. It does +**not** hold elsewhere: a testing tenant such as `growthuipath/Workshops` uses names +like `Workshop Participants`, `Workshop Trainers` and `Workshops CM-1`, so every +group check there reports "not found" — a naming mismatch that reads as a permission +problem. That is the main reason to gate `requiresTenantAccess` on the tenant a +target actually points at rather than on the target's name. + +**Capacity.** AI Unit and Agent Unit headroom in the account, and every IXP quota +the tenant reports. This is the half that catches "we ran out of units halfway +through" and "nobody can create another dataset" on the morning of delivery +rather than during it. + +Two notes on how the capacity numbers are read, both of which cost time to +establish: + +- Headroom is derived, not read. `Available` is null for consumables in the + licence summary and `Allocated` is what the org handed to tenants, so neither + is the answer. The check subtracts consumption from `TotalUnitsInAccount`. +- The two licence surfaces disagree, so the check reads both and takes the + larger consumption figure. On one org the summary reported 3,675,583 AI Units + consumed against the same 5,000,000 pool that the per-tenant rows summed to + 1,796,083 — a 1.9M gap. Trusting the smaller number would have overstated + headroom 2.4x, in the one check whose job is to stop a workshop running out. + The gap is printed rather than hidden. + +**IXP quotas come from `re`, not `uip`.** They are a Reinfer concept, and `uip` +cannot see them at all — `uip ixp` has no capacity command, and its project list +returns only a count. `re get quotas` returns every kind with a real +`hard_limit` and `current_max_usage`: `sources`, `datasets`, `buckets`, +`comments`, `comments_per_source`, `integrations`, `triggers_per_dataset`, +`extraction_predictions`. So no ceiling has to be declared — only the +per-participant need. + +### Getting `re` credentials to the check + +The check finds the `re` context whose endpoint addresses the same org and tenant +as the target, comparing the first two path segments (the endpoints differ only in +a trailing `reinfer_` against `orchestrator_`). Contexts are read from the table +`re config ls` prints, never from the file `re` stores them in — that file holds +tokens. + +So the operator sets this up once, with `re`'s own supported command: + +```bash +re config add --name --endpoint https://cloud.uipath.com///reinfer_/ --token +``` + +This is deliberately the only route. A token could instead live in +`.env.deploy.` and be materialised into a temporary `--config-file` — +that works, and it was tried — but it puts this check in the business of handling +a raw API key, writing it to disk, and depending on `re`'s config file format +staying put. `re config add` is the supported way to hold Reinfer credentials, so +the setup burden stays with the operator. It is a real burden: it is a manual step +per tenant, and without it IXP quotas skip. + +### Skips are not warnings + +`re` ships separately from `uip` and most people building a workshop site will not +have it. That is a fact about a laptop, not a finding about a tenant, so a missing +`re` — or missing Reinfer credentials — is reported as `SKIP`, counted separately +from warnings, and followed by a short note on how to make it run next time. A +check that warns on every build is a check nobody reads. + +### Turning it on + +A target runs the check at build time when it sets `requiresTenantAccess`, and +gets pass/warn thresholds instead of a bare readout when it declares `capacity`: + +```json +"growth": { + "requiresTenantAccess": true, + "capacity": { + "participants": 25, + "aiUnitsPerParticipant": 2000, + "ixpQuotaPerParticipant": {"datasets": 1, "sources": 2} + } +} +``` + +Every `capacity` field is optional and defaults to 0, which means "report the +number, do not judge it". So a target that declares nothing still gets the full +readout, and only a target that states what it needs can warn — an unconfigured +repo never warns on a healthy tenant, which is how an advisory check earns being +read. `validate-config` rejects unknown keys inside `capacity`, because +`aiUnitsPerParticipants` — plural, one character off — would otherwise fall back +to 0 and silently switch the AI Unit threshold off. The quota kinds inside +`ixpQuotaPerParticipant` are deliberately *not* a closed set, since a new product +quota kind would then fail every build; instead the check warns at run time when a +declared kind is one the tenant does not report, and lists the kinds it does. + +Leave `requiresTenantAccess` off for `local`: an offline build must never depend +on a reachable tenant. With it on, the check runs inside `build --target`, which +means it also runs inside `codedapp pack` and `codedapp all`, since both build +the site first. It cannot fail a deploy — a crash in the check (no `uip` on PATH, +an unreachable tenant) is reported and the build continues. + ## Releasing, and repinning consumers Tag the release and move the major tag: @@ -87,9 +194,12 @@ jobs: ``` It runs `agents check`, `validate-config`, `check:doc-assets`, -`check:workshop-vars`, `typecheck`, a build, and `doctor`. Because the kit repo is -private, it needs a `KIT_READ_TOKEN` secret that can read it, so npm can resolve -the dependency. +`check:workshop-vars`, `typecheck`, a build, and `doctor`. The kit repo is public, +so `npm ci` resolves the `github:` dependency with no credentials and nothing +needs to be passed in. The optional `KIT_READ_TOKEN` secret is a leftover from +when the kit was private: `validate.yml` skips its auth step when the secret is +absent, and no repo defines it, so `secrets: inherit` above passes nothing. It +can be dropped from both once you are sure the kit stays public. `.github/workflows/kit-ci.yml` checks the kit itself, including end-to-end exercises of the two components that fail expensively: the `AGENTS.md` fence @@ -140,6 +250,15 @@ moment you pack a different one, and `publish` is a separate command that runs against the local file, so that would break pack-now-publish-later. Grouping by name also guarantees the file the current run just produced survives. +Coded App names must be unique across the whole **organisation**, not merely +within a folder or a tenant: deployed apps share one org-wide `*.uipath.host` URL +space, and `baseUrl` must equal `//`. Deploying a name another +tenant already holds fails with `This app name is already deployed in this +folder`, which names the wrong scope — the conflict is the URL, not the folder. +A repo with no local `.uipath/` state does not fail early either: `publish` +registers a *second* app of the same name in whichever tenant you happen to be +logged into, and only the later `deploy` refuses. + Local packages are build artifacts, not the deliverable: `publish` uploads to Orchestrator. `.uipath/` and `uipath.json` are gitignored in every content repo and must never be committed. Files in `.uipath/` that are not named diff --git a/agents/base.md b/agents/base.md index 7021ff1..d9aece3 100644 --- a/agents/base.md +++ b/agents/base.md @@ -30,6 +30,29 @@ change the convention here and roll it out everywhere. into the same list. A `## Recap` after it is optional, for a short narrative wrap-up where one genuinely adds something. An up-front `## Requirements` or `## Objectives` section is a different thing and may stay. +- **Coded App names are derived, and must fit 32 characters.** A target that omits + `codedApp.name` gets `-`, normalised to lowercase + hyphens. The name is derived at config load rather than stored, so it cannot drift + between the build and the deploy: Docusaurus compiles `baseUrl` into every asset + path, the app is served at `//`, and a build and deploy that disagree give + you a site where every asset 404s. Set `codedApp.name` explicitly to override -- + that is the escape hatch for a tenant whose name is too long to fit. Nothing is + truncated automatically, because truncating collides: two tenants differing only + by a date suffix truncate to the same name and would overwrite each other's app. + Two targets may never resolve to the same name, which matters because `local` and + a hosted target usually share a tenant -- give at least one of them an explicit + name. +- **Keep the product slug to 15 characters.** + `uip codedapp deploy` rejects a name over 32 characters, and `baseUrl` must + always equal `//`, so the two move together. The standard + patterns spend most of the budget on fixed text: `workshop--local` costs + 15, `growth--workshop` 16, and `staging--workshop` 17. A 15-character + slug therefore fits every pattern; `case-management` is already at exactly 32 for + its staging form. Abbreviate in the slug rather than the prefix -- `comms-mining`, + not `communications-mining` -- because the prefix is what participants recognise + across workshops. `publish` happily accepts an over-long name and only `deploy` + refuses it, which leaves an orphan package behind, so `doctor` fails on this + first. - **Participant placeholders use angle brackets:** ``, and `` where initials specifically are wanted. Never `[participant name]`, `[your-name]`, or `{{your-name}}`. Angle brackets read as replace-me and @@ -141,6 +164,99 @@ npm run build:target -- - If a build prints environment or update-check warnings, treat them as non-fatal only when the build itself succeeds. +### Tenant Checks And Build-Time Validation + +**Gate `requiresTenantAccess` on the tenant a target points at, not on its name.** +A target called `growth` may address a real `uipathlabstraining` delivery tenant in +one repo and the shared `growthuipath/Workshops` testing tenant in another. The +group convention `-Participants` / `-Facilitators` holds only on +the delivery tenants, so switching the check on for a testing target produces +"group not found" on every build for names that were never expected to exist. + +`check:tenant-access` is the advisory pre-delivery check: it reports whether the +participant and facilitator groups hold the roles the exercises need, and whether +the tenant has the AI Units and IXP quota headroom to survive the workshop. It +runs inside `build:target` for any target that sets `requiresTenantAccess`, which +means it also runs inside `codedapp pack` and `codedapp all`. + +The rules below were paid for by `ca-tenant-access-wiring.patch`: a hand-written +patch that wired this same check up and was never applied. Every one of them is a +mistake that patch made, and the check it wired had never executed once. + +- **A step that touches a live tenant is gated on the resolved target, never on + an npm lifecycle hook.** That patch put the check in `prebuild`, which fires on + any `npm run build` — including an offline build with no target argument. There + is no resolved target on that path, so the check falls back to `defaultTarget` + and validates whichever tenant that names, which is not the one being built. + Use `requiresTenantAccess` on the target instead, and leave it off for `local`. +- **One step, one home.** That patch added the check in two places at once + (`prebuild` and the target runner). Two call sites for one decision drift, and + the one you are not looking at is the one that runs. +- **An advisory check must not be able to fail a build.** Setting exit code 0 + inside the script is not enough: that contract only holds while the script runs + at all. A crash before its own handler — an unresolvable import, no `uip` or + `re` on PATH, an unreachable tenant — exits non-zero, and a throwing caller + turns that into a failed deploy. Invoke advisory steps through a runner that + reports and continues. Shipping a workshop site must never depend on a + reachable tenant. +- **Never leave a decision as a `.patch` file in the tree.** That one sat + unapplied long enough for the layout it targeted (flat `scripts/*.mjs`) to stop + existing in every repo, so it could not be applied even if someone wanted to. + Record the decision in `TODO.md` and make the change, or drop it. +- **A check that never runs is worse than no check**, because it reads as + coverage. That one was referenced by the schema, reported on by `doctor`, and + documented — while dying on an unresolved import on every invocation. When + wiring up a validation step, run it and read its output before believing it. +- **Syntax checks do not resolve imports.** `node --check` passes on a module + whose every import is broken, which is exactly how that import shipped. If CI + gates a script it never executes, gate its import edges too. + +### Quota And Licence Surfaces + +- **IXP quotas come from the `re` CLI, not `uip`.** They are a Reinfer concept. + `uip ixp` has no capacity command at all, and its project list returns only a + count. `re get quotas` returns each kind with a real `hard_limit` and + `current_max_usage` — `sources`, `datasets`, `buckets`, `comments`, + `comments_per_source`, `integrations`, `triggers_per_dataset`, + `extraction_predictions` — so no ceiling ever needs to be hand-declared. + Declare only the per-participant need. +- **Discover limits, do not declare them.** A hand-written cap is a guess at a + number the tenant already knows, and it goes stale silently. +- **Match a `re` context, do not pass `--endpoint`.** The API token lives in the + context. Find the context whose endpoint addresses the same org and tenant as + the workshop target; the two URLs differ only in a trailing `reinfer_` against + `orchestrator_`. Read contexts from what `re config ls` prints, never from the + file `re` stores them in — that file holds tokens. +- **Cross-check licence figures before trusting headroom.** `uip platform + licenses summary` and `uip platform licenses consumables get` disagree: on one + org the summary reported 3,675,583 AI Units consumed against the same 5,000,000 + pool that the per-tenant rows summed to 1,796,083. Take the larger consumption + figure and surface the gap. `Available` is null for consumables and `Allocated` + is what the org handed to tenants, so headroom must be derived from + `TotalUnitsInAccount` rather than read from a field. +- **Missing local tooling is a skip, not a warning.** `re` installs separately + from `uip`, so most machines will not have it. Report that as a skipped check + with a note on how to enable it, counted apart from warnings. A check that + warns on every build is a check nobody reads, and it buries the real findings. +- **Let a tool hold its own credentials.** IXP quotas need a `re` context, set up + once per tenant with `re config add`. Do not route an API key through + `.env.deploy.` and a temporary config file to avoid that manual step: + it works, but it makes the check handle a raw key, write it to disk, and depend + on another tool's config format. Read contexts from `re config ls` output, never + from the file `re` stores them in -- that file holds tokens. Accept the setup + burden and skip cleanly when it is not done. +- **Say how short, and what to raise it to.** A capacity warning that only reports + a shortfall leaves the reader to work out the number to put in a quota request. + Recommend current usage plus the full workshop need plus a margin — not the gap, + because existing usage does not go away, and a ceiling raised by only the gap + leaves zero headroom the moment the workshop ends. +- **A threshold that silently defaults to off is a false pass.** Validate the + keys of any capacity or quota configuration. `aiUnitsPerParticipants` — plural, + one character off — otherwise falls back to 0 and turns the check off while + still reporting green. Where the key set cannot be closed (quota kinds are + discovered from the tenant), warn at run time about a declared key the tenant + does not report, and list the ones it does. + ### Visual Design - Reports, dashboards, visual tools, and HTML pages should include a dark-mode option. - Workshop pages should be readable and utilitarian, not marketing-style landing pages. diff --git a/package.json b/package.json index 07be75d..0b316e1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@uipath-lab-tec/workshop-kit", - "version": "1.4.0", + "version": "1.6.0", "description": "Shared Docusaurus infrastructure for UiPath LAB TEC workshop repos.", "license": "UNLICENSED", "type": "module", diff --git a/schemas/workshop-targets.schema.json b/schemas/workshop-targets.schema.json index e64db77..76aa520 100644 --- a/schemas/workshop-targets.schema.json +++ b/schemas/workshop-targets.schema.json @@ -70,6 +70,12 @@ "docsLabel": { "type": "string", "description": "Footer Docs link label. Defaults to 'Workshop Docs'." + }, + "productSlug": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]*$", + "maxLength": 15, + "description": "Product slug used to derive codedApp.name as - for any target that does not set one explicitly. Capped at 15 so the derived name fits the 32-character limit for typical tenant names." } }, "definitions": { @@ -97,6 +103,39 @@ "default": false, "description": "When true, build:target runs the advisory tenant-access check for this target. Left false, local and offline builds never touch a live tenant." }, + "capacity": { + "type": "object", + "additionalProperties": false, + "description": "What this workshop needs from the tenant, used by check:tenant-access to turn raw quota numbers into a pass or a warning. Every field is optional and defaults to 0, which means \"report the number without judging it\" -- so a target that declares nothing still gets the readout, and only a target that states its needs can warn.", + "properties": { + "participants": { + "type": "integer", + "minimum": 0, + "default": 0, + "description": "Expected number of participants. Multiplies every per-participant figure below; leave unset and no threshold is applied." + }, + "aiUnitsPerParticipant": { + "type": "integer", + "minimum": 0, + "default": 0, + "description": "AI Units one participant is expected to burn across the whole workshop. Warns when account headroom is below participants x this." + }, + "agentUnitsPerParticipant": { + "type": "integer", + "minimum": 0, + "default": 0, + "description": "Agent Units one participant is expected to burn. Warns when account headroom is below participants x this." + }, + "ixpQuotaPerParticipant": { + "type": "object", + "description": "Per-participant need for each IXP quota kind, keyed by the kind as `re get quotas` reports it (sources, datasets, buckets, comments, comments_per_source, integrations, triggers_per_dataset, extraction_predictions). The hard limits are discovered from the tenant, so only the need is declared here. A key the tenant does not report is warned about rather than ignored, since it is almost always a typo.", + "additionalProperties": { + "type": "integer", + "minimum": 0 + } + } + } + }, "workshop": { "type": "object", "required": [ @@ -127,14 +166,13 @@ }, "codedApp": { "type": "object", - "required": [ - "name" - ], "additionalProperties": false, "properties": { "name": { "type": "string", - "minLength": 1 + "minLength": 1, + "maxLength": 32, + "description": "Optional when the config sets productSlug: then it defaults to -. An explicit value always wins, which is the escape hatch for tenant names too long to fit. Hard limit: uip codedapp deploy rejects names over 32 characters." }, "description": { "type": "string" diff --git a/src/commands/check-tenant-access.mjs b/src/commands/check-tenant-access.mjs index 99e5d35..f8696f1 100644 --- a/src/commands/check-tenant-access.mjs +++ b/src/commands/check-tenant-access.mjs @@ -1,14 +1,17 @@ #!/usr/bin/env node import {spawnSync} from 'node:child_process'; import process from 'node:process'; -import {getTarget} from './workshop-target.mjs'; +import {getTarget} from '../config/workshop-target.mjs'; const PREFIX = '[tenant-access]'; const DEFAULT_TIMEOUT_MS = 30_000; let passCount = 0; let warningCount = 0; +let skipCount = 0; const checkResults = []; +const capacityResults = []; const remediationCommands = []; +const setupNotes = []; const roleIdCache = new Map(); function pass(message) { @@ -22,6 +25,22 @@ function warn(message) { console.log(`${PREFIX} WARN ${message}`); } +/** + * A check that could not run, as distinct from one that ran and found a problem. + * + * Missing local tooling is not a finding about the tenant. `re` is a separate + * install from `uip` and most people building a workshop site will not have it, + * so counting "you have not installed re" as a warning would put a permanent + * warning on every build for a machine setup issue -- and a check that always + * warns is a check nobody reads. Skips are reported and counted separately, and + * carry a one-line note on how to make the check run next time. + */ +function skip(message, note = '') { + skipCount += 1; + console.log(`${PREFIX} SKIP ${message}`); + if (note) setupNotes.push(note); +} + function reportCheck({group, permission, expected, actual, passed, commands = [], advice = ''}) { checkResults.push({ Group: group, @@ -279,7 +298,7 @@ function checkIxpService(tenant, tenantId) { actual: 'reinfer enabled', passed: true, }); - return; + return true; } reportCheck({ @@ -294,6 +313,7 @@ function checkIxpService(tenant, tenantId) { : `uip admin tenants services add --tenant-id ${shellQuote(tenantId)} --service reinfer`, ], }); + return false; } function checkParticipantsSharedFolderRole(group, groupName, folderPath) { @@ -389,6 +409,495 @@ function buildFolderAdministratorCommand({group, folderPath, roles}) { ]; } +/** + * Capacity defaults, used when a target declares no `capacity` block. + * + * Zero means "report the number, do not judge it": every workshop gets the + * quota readout, and only a target that states what it needs gets a warning + * when the tenant cannot supply it. Guessing a participant count would make + * every unconfigured repo warn on a healthy tenant, which is how an advisory + * check trains people to ignore it. + */ +const CAPACITY_DEFAULTS = { + participants: 0, + aiUnitsPerParticipant: 0, + agentUnitsPerParticipant: 0, + ixpQuotaPerParticipant: {}, +}; + +/** + * The licence summary covers every unit code in one response, so it is fetched + * once and reused rather than re-requested per unit on every build. + */ +let licenceSummaryCache; +function licenceSummary() { + if (licenceSummaryCache === undefined) { + licenceSummaryCache = asArray(runUip('licence summary', ['platform', 'licenses', 'summary'])); + } + return licenceSummaryCache; +} + +function number(input) { + const parsed = Number(input); + return Number.isFinite(parsed) ? parsed : 0; +} + +/** Fixed locale so the output is identical on every machine and in CI logs. */ +function formatUnits(input) { + return Math.round(number(input)).toLocaleString('en-US'); +} + +/** `used` as a percentage of `limit`, for reading how close to the edge this is. */ +function percentUsed(used, limit) { + if (!(number(limit) > 0)) return 'n/a'; + return `${Math.round((number(used) / number(limit)) * 100)}%`; +} + +/** + * What to raise a quota to, given current usage and what the workshop needs. + * + * Current usage plus the full workshop need, not the shortfall: the existing + * usage does not go away, so a ceiling raised by only the gap leaves exactly + * zero headroom the moment the workshop finishes. A 20% margin on top absorbs + * the next delivery and re-runs, and the result is rounded up so the number is + * one a person is willing to paste into a quota request. + */ +function recommendedQuotaLimit({limit, used, need}) { + const required = Math.ceil((number(used) + number(need)) * 1.2); + const target = Math.max(required, number(limit)); + const magnitude = 10 ** Math.max(1, String(Math.floor(target)).length - 2); + return Math.ceil(target / magnitude) * magnitude; +} + +function reportCapacity({resource, metric, need, have, passed, recommend = null, commands = []}) { + capacityResults.push({ + Resource: resource, + Metric: metric, + Needed: need === null ? 'not declared' : formatUnits(need), + Available: formatUnits(have), + Short: passed === false && need !== null ? formatUnits(need - have) : '', + 'Raise to': recommend === null ? '' : formatUnits(recommend), + Result: passed === null ? 'INFO' : passed ? 'PASS' : 'WARN', + }); + + if (passed === null) { + console.log(`${PREFIX} INFO ${resource} ${metric}: ${formatUnits(have)} available.`); + return; + } + if (passed) { + pass(`${resource} ${metric}: ${formatUnits(have)} available, ${formatUnits(need)} needed.`); + return; + } + warn( + `${resource} ${metric}: ${formatUnits(have)} available but ${formatUnits(need)} needed — ` + + `short by ${formatUnits(need - have)}` + + (recommend === null ? '.' : `. Raise the limit to ${formatUnits(recommend)}.`), + ); + if (commands.length > 0) { + remediationCommands.push({group: resource, permission: metric, commands, advice: ''}); + } +} + +/** + * Consumable headroom for one unit code. + * + * Neither licence surface answers "can this workshop run" on its own. + * `Available` is null for consumables in the summary, and `Allocated` is what + * the org has handed to tenants rather than what is left; the consumables + * report has no total-consumed column at all. So headroom is derived: + * TotalUnitsInAccount minus everything consumed. Consumption draws on the + * shared account pool, so a sibling tenant burning units constrains this one -- + * an org-wide figure is the honest one, not a tenant-only slice. + * + * Both surfaces are read because they disagree. Against the same 5,000,000-unit + * AIU pool on the growthuipath org, the summary reported 3,675,583 consumed + * while the per-tenant rows summed to 1,796,083 -- a 1,879,500 gap, most likely + * consumption from tenants no longer in the report. AGU matched to the unit. + * The larger figure wins: this check exists to stop a workshop running out of + * units, and overstating headroom by 2.4x would defeat it. The gap is surfaced + * rather than hidden, because a facilitator seeing one should know the account + * has consumption the per-tenant breakdown cannot explain. + */ +function readConsumable(unitCode, unitLabel, tenantName) { + const rows = asArray( + runUip(`${unitLabel} consumables`, [ + 'platform', + 'licenses', + 'consumables', + 'get', + '--unit', + unitCode, + ]), + ); + + if (rows.length === 0) { + return null; + } + + const total = number(value(rows[0], 'TotalUnitsInAccount', 'totalUnitsInAccount')); + // Repeated identically on every row of the report, so it must be counted once. + const orgOnly = number(value(rows[0], 'ConsumedFromOrgWithoutTenant', 'consumedFromOrgWithoutTenant')); + const perTenantConsumed = + orgOnly + + rows.reduce( + (sum, row) => + sum + + number(value(row, 'ConsumedFromTenantPool', 'consumedFromTenantPool')) + + number(value(row, 'ConsumedFromOrgPool', 'consumedFromOrgPool')), + 0, + ); + + const summaryRow = licenceSummary().find( + (row) => String(value(row, 'Code', 'code') || '').toUpperCase() === unitCode, + ); + const summaryConsumed = summaryRow ? number(value(summaryRow, 'Used', 'used')) : null; + + const consumed = + summaryConsumed === null ? perTenantConsumed : Math.max(summaryConsumed, perTenantConsumed); + + const tenantRow = rows.find( + (row) => + String(value(row, 'TenantName', 'tenantName') || '').toLowerCase() === + String(tenantName).toLowerCase(), + ); + + return { + total, + consumed, + perTenantConsumed, + summaryConsumed, + remaining: total - consumed, + tenantConsumed: tenantRow + ? number(value(tenantRow, 'ConsumedFromTenantPool', 'consumedFromTenantPool')) + + number(value(tenantRow, 'ConsumedFromOrgPool', 'consumedFromOrgPool')) + : null, + endDate: value(rows[0], 'EndDate', 'endDate') || null, + }; +} + +function checkConsumable({unitCode, unitLabel, tenantName, perParticipant, participants}) { + const usage = readConsumable(unitCode, unitLabel, tenantName); + if (!usage) { + reportCheck({ + group: 'Tenant', + permission: `${unitLabel} licensing`, + expected: 'A consumables report', + actual: 'Unable to query', + passed: false, + }); + return; + } + + const need = perParticipant > 0 && participants > 0 ? perParticipant * participants : null; + reportCapacity({ + resource: unitLabel, + metric: 'remaining in account', + need, + have: usage.remaining, + passed: need === null ? null : usage.remaining >= need, + }); + + console.log( + `${PREFIX} INFO ${unitLabel}: ${formatUnits(usage.total)} in the account, ` + + `${formatUnits(usage.consumed)} consumed org-wide` + + (usage.tenantConsumed === null + ? `, no consumption recorded for ${tenantName}` + : `, ${formatUnits(usage.tenantConsumed)} by ${tenantName}`) + + (usage.endDate ? `; bundle ends ${String(usage.endDate).slice(0, 10)}` : '') + + '.', + ); + + // Rounded, not exact: the API returns fractional units, and the two surfaces + // agreeing to the unit still differ in the last float bit (149514.99999999997 + // against 149515), which an exact comparison reports as a divergence. + if ( + usage.summaryConsumed !== null && + Math.round(usage.summaryConsumed) !== Math.round(usage.perTenantConsumed) + ) { + console.log( + `${PREFIX} INFO ${unitLabel}: the licence summary reports ` + + `${formatUnits(usage.summaryConsumed)} consumed but the per-tenant breakdown sums to ` + + `${formatUnits(usage.perTenantConsumed)}. Headroom above uses the larger figure.`, + ); + } + + // A bundle that expires before delivery leaves a healthy-looking balance that + // cannot be spent, so the date is checked rather than merely printed. + if (usage.endDate && new Date(usage.endDate).getTime() < Date.now()) { + warn(`${unitLabel}: the licence bundle ended ${String(usage.endDate).slice(0, 10)}.`); + } +} + +/** + * Whether the `re` CLI exists on PATH at all. + * + * `re` ships separately from `uip` and most people building a workshop site will + * not have it. That is a machine setup fact, not a finding about the tenant, so + * everything downstream of a false here skips rather than warns. + */ +function reIsInstalled() { + const result = spawnSync('re', ['--version'], {encoding: 'utf8', timeout: DEFAULT_TIMEOUT_MS}); + return !result.error && result.status === 0; +} + +/** + * Runs a `re` command and parses its JSONL output. + * + * A separate runner from runUip: `re` is a different CLI with no response + * envelope, and `-o json` emits one object per line rather than an array. + */ +function runRe(label, args) { + const result = spawnSync('re', args, { + cwd: process.cwd(), + encoding: 'utf8', + timeout: DEFAULT_TIMEOUT_MS, + }); + + if (result.error) { + warn(`${label}: could not run the re CLI (${result.error.message}).`); + return null; + } + + if (result.status !== 0) { + // stderr carries the actual API error (a 401 on a stale token, most often), + // and without it the reader is left guessing at an exit code. + const detail = String(result.stderr || '').trim().split(/\r?\n/).filter(Boolean).pop(); + warn(`${label}: re exited with status ${result.status}${detail ? ` — ${detail}` : ''}.`); + return null; + } + + const rows = []; + for (const line of String(result.stdout).split(/\r?\n/)) { + if (!line.trim()) continue; + try { + rows.push(JSON.parse(line)); + } catch { + warn(`${label}: re returned a line that is not JSON.`); + return null; + } + } + return rows; +} + +/** + * The org and tenant a URL addresses, as `//`. + * + * Both the workshop target's Orchestrator URL and a `re` context endpoint carry + * the same two path segments after the origin, differing only in the trailing + * service segment (`orchestrator_` against `reinfer_`), so normalising to the + * first two segments is what lets one be matched to the other. + */ +function orgTenantKey(rawUrl) { + try { + const url = new URL(rawUrl); + const [org, tenant] = url.pathname.split('/').filter(Boolean); + if (!org || !tenant) return null; + return `${url.origin}/${org}/${tenant}`.toLowerCase(); + } catch { + return null; + } +} + +/** + * The `re` context pointing at the same tenant as the workshop target. + * + * The context is matched rather than the endpoint being passed directly, + * because the API token lives in the context: `re --endpoint ` with no + * context has nothing to authenticate with. Contexts are read from the table + * `re config ls` prints, deliberately NOT from the contexts file it stores them + * in -- that file holds the tokens, and this check has no business opening it. + */ +function reContextForTarget(target) { + const result = spawnSync('re', ['config', 'ls'], { + cwd: process.cwd(), + encoding: 'utf8', + timeout: DEFAULT_TIMEOUT_MS, + }); + + if (result.error || result.status !== 0) return null; + + const contexts = []; + for (const line of String(result.stdout).split(/\r?\n/)) { + const columns = line.trim().split(/\s+/); + const endpoint = columns.find((column) => column.startsWith('http')); + if (!endpoint) continue; + // The active context is marked with a leading arrow, so the name is the + // first column that is neither the marker nor the endpoint. + const name = columns.find((column) => column !== '->' && !column.startsWith('http')); + if (name) contexts.push({name, endpoint}); + } + + // The same order `pulse` uses, so the two commands never disagree about which + // context belongs to a target: an explicit RE_CONTEXT override, then the + // established `UiPath__` name. + const explicit = process.env.RE_CONTEXT?.trim(); + if (explicit) { + const match = contexts.find((context) => context.name === explicit); + if (match) return match.name; + warn(`IXP quotas: RE_CONTEXT is set to "${explicit}", but no re context has that name.`); + return null; + } + + const org = target.workshop?.uipathOrgName; + const tenant = target.workshop?.uipathTenantName; + if (org && tenant) { + const inferred = `UiPath_${org}_${tenant}`; + const match = contexts.find((context) => context.name === inferred); + if (match) return match.name; + } + + // Endpoint fallback, for the contexts that predate that convention -- most of + // them, in practice. Matching on org+tenant rather than the exact URL because + // the two differ in their trailing service segment and in stored trailing + // slashes, neither of which changes which tenant is addressed. + const wanted = orgTenantKey(target.workshop?.uipathTenantUrl); + if (!wanted) return null; + return contexts.find((context) => orgTenantKey(context.endpoint) === wanted)?.name || null; +} + +/** + * Reads IXP quotas through the `re` context that points at this tenant. + * + * Deliberately only this route. A token could be read from + * `.env.deploy.` and materialised into a temporary `--config-file`, + * which works -- but it means this check handles a raw API key, writes it to + * disk, and depends on `re`'s config file format staying put. `re config add` + * is the supported way to hold Reinfer credentials, so the setup burden stays + * with the operator and this check stays out of the secret-handling business. + * + * Both failure modes below are skips, not warnings: no `re` and no context are + * facts about the machine this ran on, not findings about the tenant. + */ +function readIxpQuotas(target) { + if (!reIsInstalled()) { + skip( + 'IXP quotas: the re CLI is not installed, so IXP quotas were not checked.', + 'Install the re CLI to check IXP quotas -- they are a Reinfer surface and uip cannot read ' + + 'them. Everything else in this report ran normally.', + ); + return null; + } + + const context = reContextForTarget(target); + if (!context) { + const wanted = orgTenantKey(target.workshop?.uipathTenantUrl); + skip( + `IXP quotas: no re context points at ${wanted || 'this tenant'}, so IXP quotas were not checked.`, + `Add a re context for this tenant: \`re config add --name --endpoint ` + + `${wanted ? `${wanted}/reinfer_/` : '//reinfer_/'} --token \`. ` + + `Get the token from the IXP UI under Manage account > API tokens.`, + ); + return null; + } + + return runRe('IXP quotas', ['-c', context, '-o', 'json', 'get', 'quotas']); +} + +/** + * IXP quota headroom, read from the `re` CLI. + * + * IXP quotas are a Reinfer concept and are managed through `re`, not `uip`: + * `re get quotas` returns each quota kind with its `hard_limit` and + * `current_max_usage`, so sources, datasets, buckets, comments and extraction + * predictions all come back with real discovered ceilings. Nothing here has to + * be declared as a limit, which is the whole point -- an earlier version of this + * check counted `uip ixp projects list` against a hand-written cap, and both + * halves of that were wrong: `uip` cannot see these quotas at all, and the cap + * was a guess at a number the tenant already knows. + */ +function checkIxpQuotas({target, participants, perParticipant, tenantId}) { + const quotas = readIxpQuotas(target); + if (!quotas) return; + + const seen = new Set(); + for (const quota of quotas) { + const kind = String(value(quota, 'quota_kind') || ''); + if (!kind) continue; + seen.add(kind); + + const limit = number(value(quota, 'hard_limit')); + const used = number(value(quota, 'current_max_usage')); + const free = limit - used; + const perHead = number(perParticipant[kind]); + const need = perHead > 0 && participants > 0 ? perHead * participants : null; + const short = need === null ? false : free < need; + + reportCapacity({ + resource: `IXP ${kind}`, + metric: 'free before the hard limit', + need, + have: free, + passed: need === null ? null : !short, + // What to raise the ceiling to, not merely that it is too low. The + // shortfall alone is not the answer a facilitator needs -- they have to + // put a number in a quota request, and it must cover current usage plus + // the whole workshop, not just the gap. + recommend: short ? recommendedQuotaLimit({limit, used, need}) : null, + commands: + short && tenantId + ? [ + `re create quota --quota-kind ${shellQuote(kind)} --limit ` + + `${recommendedQuotaLimit({limit, used, need})} --uipath-tenant-id ${shellQuote(tenantId)}`, + ] + : [], + }); + console.log( + `${PREFIX} INFO IXP ${kind}: ${formatUnits(used)} of ${formatUnits(limit)} used ` + + `(${percentUsed(used, limit)} of the limit).`, + ); + } + + // A declared need for a quota kind the tenant does not report is almost + // always a typo, and it would otherwise pass silently as an unchecked need. + for (const kind of Object.keys(perParticipant)) { + if (number(perParticipant[kind]) > 0 && !seen.has(kind)) { + warn( + `IXP quotas: capacity.ixpQuotaPerParticipant declares "${kind}", but this tenant reports ` + + `no such quota. Known kinds here: ${[...seen].sort().join(', ') || 'none'}.`, + ); + } + } +} + +function checkCapacity({target, tenantName, tenantId, ixpEnabled}) { + const capacity = {...CAPACITY_DEFAULTS, ...(target.capacity || {})}; + const participants = number(capacity.participants); + + console.log( + `\n${PREFIX} Capacity for ${tenantName}` + + (participants > 0 ? ` at ${participants} participants` : ' (no participant count declared)') + + '.', + ); + + checkConsumable({ + unitCode: 'AIU', + unitLabel: 'AI Units', + tenantName, + participants, + perParticipant: number(capacity.aiUnitsPerParticipant), + }); + checkConsumable({ + unitCode: 'AGU', + unitLabel: 'Agent Units', + tenantName, + participants, + perParticipant: number(capacity.agentUnitsPerParticipant), + }); + + // Querying IXP on a tenant without the service returns an error that reads as + // a capacity failure rather than what it is, so this is gated on enablement. + if (ixpEnabled) { + checkIxpQuotas({ + target, + tenantId, + participants, + perParticipant: capacity.ixpQuotaPerParticipant || {}, + }); + } else { + console.log(`${PREFIX} INFO IXP capacity skipped: the reinfer service is not enabled on this tenant.`); + } +} + function main() { const targetArg = process.argv[2]; let targetName; @@ -433,16 +942,16 @@ function main() { } const tenant = runUip('tenant services', ['admin', 'tenants', 'get', tenantId]); - if (tenant) { - checkIxpService(tenant, tenantId); - } + const ixpEnabled = tenant ? checkIxpService(tenant, tenantId) : false; + + const tenantName = value(tenantSummary, 'Name', 'name'); + checkCapacity({target, tenantName, tenantId, ixpEnabled}); const groups = runUip('group lookup', ['admin', 'groups', 'list']); if (!groups) { return; } - const tenantName = value(tenantSummary, 'Name', 'name'); const participants = findExact(groups, `${tenantName}-Participants`); const facilitators = findExact(groups, `${tenantName}-Facilitators`); @@ -489,6 +998,10 @@ try { console.log(`\n${PREFIX} Permission checks`); console.table(checkResults); } + if (capacityResults.length > 0) { + console.log(`\n${PREFIX} Capacity checks`); + console.table(capacityResults); + } if (remediationCommands.length > 0) { console.log(`\n${PREFIX} Suggested fix commands (not executed)`); for (const remediation of remediationCommands) { @@ -501,8 +1014,17 @@ try { } } } + if (setupNotes.length > 0) { + console.log(`\n${PREFIX} To run the skipped checks next time`); + for (const note of setupNotes) { + console.log(`- ${note}`); + } + } console.log( - `${PREFIX} Complete with ${passCount} pass${passCount === 1 ? '' : 'es'} and ${warningCount} warning${warningCount === 1 ? '' : 's'}; this check never blocks the build.`, + `${PREFIX} Complete with ${passCount} pass${passCount === 1 ? '' : 'es'}, ` + + `${warningCount} warning${warningCount === 1 ? '' : 's'}` + + (skipCount > 0 ? ` and ${skipCount} skipped check${skipCount === 1 ? '' : 's'}` : '') + + `; this check never blocks the build.`, ); process.exitCode = 0; } diff --git a/src/commands/docusaurus-target.mjs b/src/commands/docusaurus-target.mjs index 810559b..8d8a2c4 100644 --- a/src/commands/docusaurus-target.mjs +++ b/src/commands/docusaurus-target.mjs @@ -10,23 +10,46 @@ import {spawnSync} from 'node:child_process'; import {getTarget} from '../config/workshop-target.mjs'; export function run(commandName, args, targetName) { + const {status, error} = spawn(commandName, args, targetName); + + if (status !== 0) { + throw new Error( + error + ? `${commandName} failed: ${error.message}` + : `${commandName} exited with status ${status}`, + ); + } +} + +function spawn(commandName, args, targetName) { console.log(`\n> ${[commandName, ...args].join(' ')}`); const needsShim = process.platform === 'win32' && (commandName === 'npm' || commandName === 'npx'); const executable = needsShim ? `${commandName}.cmd` : commandName; - const result = spawnSync(executable, args, { + return spawnSync(executable, args, { stdio: 'inherit', shell: needsShim, env: {...process.env, WORKSHOP_TARGET: targetName}, }); +} - if (result.status !== 0) { - throw new Error( - result.error - ? `${commandName} failed: ${result.error.message}` - : `${commandName} exited with status ${result.status}`, - ); - } +/** + * Runs a step for its report only. The tenant check is advisory by contract -- + * it sets exit code 0 even with warnings -- but that contract holds only while + * the script itself runs. A crash before its own handler is reached (an + * unresolvable import, a missing `uip` binary, a malformed target) exits + * non-zero, and through the throwing `run` above that would fail a build over + * an advisory check. Deploying a workshop site must not depend on the tenant + * being reachable, so the failure is reported and the build continues. + */ +function runAdvisory(commandName, args, targetName) { + const {status, error} = spawn(commandName, args, targetName); + if (status === 0) return; + console.warn( + `\n[tenant-access] The advisory check did not complete ` + + (error ? `(${error.message})` : `(exit status ${status})`) + + '. Continuing the build; verify the tenant by hand before delivery.', + ); } export function docusaurusTarget({command = 'build', targetArg, docusaurusArgs = []}) { @@ -43,7 +66,7 @@ export function docusaurusTarget({command = 'build', targetArg, docusaurusArgs = // build depend on live UiPath connectivity. Gate it on the target instead, so it // runs for real training tenants and never for `local`. if (target.requiresTenantAccess) { - run('npm', ['run', 'check:tenant-access'], targetName); + runAdvisory('npm', ['run', 'check:tenant-access'], targetName); } run('npx', ['docusaurus', command, ...docusaurusArgs], targetName); diff --git a/src/commands/init.mjs b/src/commands/init.mjs index c7ea441..30ae7f8 100644 --- a/src/commands/init.mjs +++ b/src/commands/init.mjs @@ -20,6 +20,10 @@ import {fileURLToPath} from 'node:url'; import process from 'node:process'; const kitRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..'); + +// `staging--workshop` is the tightest standard pattern at 17 characters of +// fixed text, against a 32-character Coded App name limit. +const PRODUCT_SLUG_LIMIT = 15; const templateDir = join(kitRoot, 'template'); const REQUIRED_TEMPLATE_FILES = [ @@ -61,6 +65,21 @@ export function init({product, title, root = process.cwd()} = {}) { console.error(`"${product}" is not a valid slug; use lowercase letters, digits and hyphens.`); return 1; } + // Caught here rather than at deploy time. The slug ends up inside every target's + // codedApp.name, and `uip codedapp deploy` refuses a name over 32 characters -- + // after `publish` has already accepted it and left a package behind. The tightest + // standard pattern is `staging--workshop`, which spends 17 on fixed text. + if (product.length > PRODUCT_SLUG_LIMIT) { + console.error( + `"${product}" is ${product.length} characters; keep the product slug to ${PRODUCT_SLUG_LIMIT}.\n` + + ` Coded App names are capped at 32 and the slug goes inside all of them:\n` + + ` workshop-${product}-local ${`workshop-${product}-local`.length}\n` + + ` growth-${product}-workshop ${`growth-${product}-workshop`.length}\n` + + ` staging-${product}-workshop ${`staging-${product}-workshop`.length}\n` + + ` Abbreviate the slug, not the prefix: "comms-mining", not "communications-mining".`, + ); + return 1; + } const missing = REQUIRED_TEMPLATE_FILES.filter((f) => !existsSync(join(templateDir, f))); if (missing.length > 0) { diff --git a/src/commands/validate-config.mjs b/src/commands/validate-config.mjs index 26a9471..f300b67 100644 --- a/src/commands/validate-config.mjs +++ b/src/commands/validate-config.mjs @@ -8,15 +8,75 @@ * missing a field is otherwise fine until the day someone builds with it. */ import process from 'node:process'; -import {getTarget} from '../config/workshop-target.mjs'; -import {readTargetsConfig, resolveFields} from '../config/workshop-fields.mjs'; +import {getTarget, readMergedTargetsConfig} from '../config/workshop-target.mjs'; +import {resolveFields} from '../config/workshop-fields.mjs'; + +const CAPACITY_INT_KEYS = [ + 'participants', + 'aiUnitsPerParticipant', + 'agentUnitsPerParticipant', +]; +// Quota kinds are discovered from the tenant by `re get quotas`, so the key set +// here cannot be closed without a new product quota kind failing every build. +// The values are still checked, and check:tenant-access warns at run time about +// a kind the tenant does not report -- which is where a typo actually surfaces. +const CAPACITY_MAP_KEYS = ['ixpQuotaPerParticipant']; + +/** + * A misspelled capacity key is the failure mode worth catching here. The check + * reads capacity with a defaults spread, so `aiUnitsPerParticipants` -- plural, + * one character off -- falls back to 0 and silently turns the AI Unit threshold + * off. The result is a green tenant check for a workshop that will run out of + * units, which is the exact outcome the capacity block exists to prevent. + */ +function capacityErrors(targetName, capacity) { + if (capacity === undefined) return []; + + if (typeof capacity !== 'object' || capacity === null || Array.isArray(capacity)) { + return [`target "${targetName}": capacity must be an object.`]; + } + + const known = [...CAPACITY_INT_KEYS, ...CAPACITY_MAP_KEYS]; + const errors = []; + for (const [key, raw] of Object.entries(capacity)) { + if (CAPACITY_MAP_KEYS.includes(key)) { + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) { + errors.push(`target "${targetName}": capacity.${key} must be an object.`); + continue; + } + for (const [kind, need] of Object.entries(raw)) { + if (!Number.isInteger(need) || need < 0) { + errors.push( + `target "${targetName}": capacity.${key}.${kind} must be a non-negative integer, got ${JSON.stringify(need)}.`, + ); + } + } + continue; + } + if (!CAPACITY_INT_KEYS.includes(key)) { + errors.push( + `target "${targetName}": unknown capacity key "${key}". Known keys: ${known.join(', ')}.`, + ); + continue; + } + if (!Number.isInteger(raw) || raw < 0) { + errors.push( + `target "${targetName}": capacity.${key} must be a non-negative integer, got ${JSON.stringify(raw)}.`, + ); + } + } + return errors; +} export function validateConfig({root = process.cwd()} = {}) { const errors = []; let config; try { - config = readTargetsConfig(root); + // The overlay-merging reader, not the plain one: `config/targets/*.json` + // holds the one-off per-delivery tenants, so validating only the main file + // skips exactly the targets most likely to be hand-written and wrong. + config = readMergedTargetsConfig(root); } catch (error) { console.error(`config/workshop-targets.json could not be read: ${error.message}`); return 1; @@ -52,6 +112,7 @@ export function validateConfig({root = process.cwd()} = {}) { } catch (error) { errors.push(`target "${name}": ${error.message}`); } + errors.push(...capacityErrors(name, config.targets[name]?.capacity)); } if (errors.length > 0) { diff --git a/src/config/createWorkshopConfig.d.ts b/src/config/createWorkshopConfig.d.ts index f826a16..f530f1e 100644 --- a/src/config/createWorkshopConfig.d.ts +++ b/src/config/createWorkshopConfig.d.ts @@ -12,6 +12,12 @@ export type WorkshopTarget = { baseUrl: string; /** Run the advisory tenant-access check for this target. Defaults to false. */ requiresTenantAccess?: boolean; + capacity?: { + participants?: number; + aiUnitsPerParticipant?: number; + agentUnitsPerParticipant?: number; + ixpQuotaPerParticipant?: Record; + }; workshop: { uipathOrgName: string; uipathTenantName: string; diff --git a/src/config/workshop-target.mjs b/src/config/workshop-target.mjs index a75ca61..484bd78 100644 --- a/src/config/workshop-target.mjs +++ b/src/config/workshop-target.mjs @@ -4,23 +4,62 @@ import path from 'node:path'; import process from 'node:process'; import {resolveFields} from './workshop-fields.mjs'; +// `uip codedapp deploy` refuses a longer name. `publish` does NOT -- it accepts the +// name, creates the package, and only deploy rejects it, leaving an orphan package +// in Orchestrator. So this is asserted here, in validateTarget, which every command +// path reaches before any of them talks to a tenant. +const CODED_APP_NAME_LIMIT = 32; + +/** + * Normalises a tenant name into a name fragment: lowercase, underscores and any + * other separator collapsed to single hyphens, no leading or trailing hyphen. + * `Bellevue_July2026_20260727` -> `bellevue-july2026-20260727`. + */ +function slugify(value) { + return String(value) + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +/** + * `-`, used when a target omits codedApp.name. + * + * Derived rather than stored so the name cannot drift between the build and the + * deploy. baseUrl is compiled into the static output by Docusaurus, and the app is + * served at //, so a build and a deploy that disagree produce a site whose + * every asset 404s. Both paths call getTarget(), so both see this one value. + * + * A target may still set codedApp.name explicitly, which wins. That is the escape + * hatch for tenants whose names are too long to fit the 32-character limit once + * the product slug is prepended -- deliberately an override rather than automatic + * truncation, because truncating collides: two tenants differing only in a date + * suffix truncate to the same name and would silently overwrite each other's app. + */ +function deriveCodedAppName(config, target) { + const productSlug = config.productSlug; + const tenant = target.workshop?.uipathTenantName; + if (!productSlug || !tenant) return undefined; + return `${slugify(productSlug)}-${slugify(tenant)}`; +} + // The consumer repo, not the kit: this file runs from inside node_modules. const root = process.cwd(); -const configPath = path.join(root, 'config', 'workshop-targets.json'); -const targetOverlayDir = path.join(root, 'config', 'targets'); /** * Reads config/workshop-targets.json, then merges any config/targets/.json * overlay files in as additional targets. Ephemeral one-off training tenants can * live in their own file and be pruned without touching the main config. */ -function readTargetsConfig() { - const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); +export function readMergedTargetsConfig(configRoot = root) { + const mainPath = path.join(configRoot, 'config', 'workshop-targets.json'); + const overlayDir = path.join(configRoot, 'config', 'targets'); + const config = JSON.parse(fs.readFileSync(mainPath, 'utf8')); - if (!fs.existsSync(targetOverlayDir)) return config; + if (!fs.existsSync(overlayDir)) return config; config.targets = config.targets || {}; - for (const entry of fs.readdirSync(targetOverlayDir).sort()) { + for (const entry of fs.readdirSync(overlayDir).sort()) { if (!entry.endsWith('.json')) continue; const name = entry.slice(0, -'.json'.length); if (config.targets[name]) { @@ -28,14 +67,14 @@ function readTargetsConfig() { `Target "${name}" is defined both in config/workshop-targets.json and config/targets/${entry}.`, ); } - config.targets[name] = JSON.parse( - fs.readFileSync(path.join(targetOverlayDir, entry), 'utf8'), - ); + config.targets[name] = JSON.parse(fs.readFileSync(path.join(overlayDir, entry), 'utf8')); } return config; } +const readTargetsConfig = readMergedTargetsConfig; + export function getTargetName(explicitTarget) { const config = readTargetsConfig(); return explicitTarget || process.env.WORKSHOP_TARGET || config.defaultTarget || 'local'; @@ -49,8 +88,51 @@ export function getTarget(explicitTarget) { const known = Object.keys(config.targets || {}).join(', '); throw new Error(`Unknown workshop target "${targetName}". Known targets: ${known}`); } - validateTarget(targetName, target, config); - return {targetName, target}; + const resolved = resolveCodedAppName(config, target); + validateTarget(targetName, resolved, config); + assertUniqueAppNames(config); + return {targetName, target: resolved}; +} + +/** + * No two targets may resolve to the same codedApp.name. + * + * Derivation makes this reachable in a way stored names never were. `local` and + * `growth` legitimately point at the SAME tenant -- the difference between them is + * how the site is served, not which tenant it talks to -- so if both omit + * codedApp.name they derive an identical name and one deploy silently replaces the + * other's app. Per-target validation cannot see that; only a config-wide check can. + */ +function assertUniqueAppNames(config) { + const byName = new Map(); + for (const [name, target] of Object.entries(config.targets || {})) { + const appName = resolveCodedAppName(config, target).codedApp?.name; + if (!appName) continue; + if (!byName.has(appName)) byName.set(appName, []); + byName.get(appName).push(name); + } + + for (const [appName, targets] of byName) { + if (targets.length < 2) continue; + throw new Error( + `Targets ${targets.map((t) => `"${t}"`).join(' and ')} both resolve to codedApp.name ` + + `"${appName}", so deploying one would replace the other's app. Targets that share a ` + + `tenant need an explicit codedApp.name to tell them apart.`, + ); + } +} + +/** + * Returns the target with codedApp.name filled in from productSlug + tenant when + * the target does not set one. Never mutates the parsed config. + */ +function resolveCodedAppName(config, target) { + if (target.codedApp?.name) return target; + + const derived = deriveCodedAppName(config, target); + if (!derived) return target; + + return {...target, codedApp: {...target.codedApp, name: derived}}; } function validateTarget(targetName, target, config) { @@ -78,6 +160,22 @@ function validateTarget(targetName, target, config) { if (!target.baseUrl.startsWith('/') || !target.baseUrl.endsWith('/')) { throw new Error(`Target "${targetName}" baseUrl must start and end with "/".`); } + + const appName = target.codedApp.name; + if (appName.length > CODED_APP_NAME_LIMIT) { + const derived = deriveCodedAppName(config, target) === appName; + throw new Error( + `Target "${targetName}" codedApp.name is ${appName.length} characters; the limit is ` + + `${CODED_APP_NAME_LIMIT}: "${appName}".\n` + + (derived + ? ` This name was derived from productSlug + workshop.uipathTenantName. Set an ` + + `explicit codedApp.name on the "${targetName}" target to override it. It is not ` + + `truncated automatically: two tenants differing only by a date suffix would ` + + `truncate to the same name and overwrite each other's app.` + : ` Shorten the product slug rather than the prefix, which is what participants ` + + `recognise across workshops.`), + ); + } } function printTarget(targetName, target) { diff --git a/src/css/workshop.css b/src/css/workshop.css index 6e02cf7..69ec314 100644 --- a/src/css/workshop.css +++ b/src/css/workshop.css @@ -54,16 +54,6 @@ background: var(--ifm-background-color); } -.workshop-component-visual { - margin: 1.5rem 0; -} - -.workshop-component-visual img { - display: block; - max-width: 100%; - height: auto; -} - .workshop-annotation-media { position: relative; } @@ -72,7 +62,7 @@ width: 100%; } -.workshop-new-chat-crop { +.workshop-image-crop { position: relative; width: min(420px, 100%); height: 170px; @@ -82,7 +72,7 @@ background: var(--ifm-background-color); } -.workshop-new-chat-crop img { +.workshop-image-crop img { width: 760px; max-width: none; border: 0; diff --git a/template/config/workshop-targets.json b/template/config/workshop-targets.json index a48bf27..3f597f3 100644 --- a/template/config/workshop-targets.json +++ b/template/config/workshop-targets.json @@ -3,6 +3,7 @@ "title": "__PRODUCT_TITLE__", "tagline": "Hands-on exercises for __PRODUCT_TITLE__", "repo": "UiPath-LAB-TEC/workshop-__PRODUCT_SLUG__", + "productSlug": "__PRODUCT_SLUG__", "docsLabel": "__PRODUCT_TITLE__ Docs", "defaultTarget": "local", "targets": {