diff --git a/.changeset/31172-publish-scenarios-cli.md b/.changeset/31172-publish-scenarios-cli.md new file mode 100644 index 00000000000..03907977bd3 --- /dev/null +++ b/.changeset/31172-publish-scenarios-cli.md @@ -0,0 +1,16 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): `@objectstack/scenarios` is published, with an `objectstack-scenarios` command line: `npx @objectstack/scenarios run` runs the open scenario cards with no checkout of the platform + +Clause-②: yes +Metadata-protocol: none + +The package was private. It is now released with the `@objectstack/*` packages, at their version, and it carries: + +- **A `bin`, `objectstack-scenarios`.** `objectstack-scenarios run [flags]` is the scenario runner (`run-scenarios` in this repository) with the same flags, defaults and refusals: it drives your own local Claude Code login and refuses to start when `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` is set or the CLI is logged in with an API key. `help` and `version` are the other two commands. The bin runs the built JavaScript in `dist/`. +- **The open card library as package data** (`dist/library/`): the cards of `docs/qa/scenarios/` and the capability areas they are checked against, copied at build time. `run` reads them unless `--cards DIR` names another directory, which is loaded as the overlay. Run records go to `./scenario-runs` unless `--out` says otherwise. +- **The library entries it already had**: the card schema and loader (`@objectstack/scenarios`), the scorer (`./score`, `./score/full`), the runner (`./runner`) and the gallery exporter (`./export`). + +It is not an `objectstack` (`os`) subcommand, and nothing in `@objectstack/cli` changes. diff --git a/.changeset/config.json b/.changeset/config.json index 245b5b985fc..c0d06b28e64 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -83,6 +83,7 @@ "create-objectstack", "@objectstack/connector-openapi", "@objectstack/verify", + "@objectstack/scenarios", "@object-ui/auth", "@object-ui/cli", "@object-ui/collaboration", diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 2aa64fe857c..534bcb232ac 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -1,6 +1,7 @@ # @objectstack/scenarios -Private, unpublished. The schema (zod) and loader for the open scenario library under +Published, with a command line: `npx @objectstack/scenarios run` (below, "Running from npm"). +The schema (zod) and loader for the open scenario library under [`docs/qa/scenarios/`](../../../docs/qa/scenarios/README.md) — that README is the format's reference. @@ -27,10 +28,11 @@ The private overlay's owner migrates its cards to each new card shape (today: `o - `src/score/` — the deterministic scorer, entries `@objectstack/scenarios/score` and `@objectstack/scenarios/score/full` (below). -Not published. `pnpm --filter @objectstack/scenarios build` (tsup) writes `dist/` as ESM, CJS and -`.d.ts`, and every `exports` subpath points there, so a consumer that links the framework tree -and bundles its own entry can load the scorer under plain Node. The suites and `run-scenarios` -read `src/` directly. Nothing here calls a model or the network. +`pnpm --filter @objectstack/scenarios build` (tsup) writes `dist/` as ESM, CJS and `.d.ts`, and +every `exports` subpath points there, so plain Node loads the package with no TypeScript resolver. +The build then copies the open library into `dist/library/` (`scripts/pack-library.mjs`), which +the published command line runs. The suites and `run-scenarios` read `src/` directly. The schema, +loader and scorer call no model and no network; the runner drives a local Claude Code session. ## Scoring a run against a card — `@objectstack/scenarios/score` @@ -138,6 +140,31 @@ pnpm --filter @objectstack/scenarios run-scenarios --packages workspace # o Per card and mode the runner writes `docs/qa/platform-checklist/runs/-scenario-.json` (git-ignored) and prints the scorecard. +### Running from npm + +No checkout needed: the package's `objectstack-scenarios` command is the same runner, with the same flags. + +```bash +npx @objectstack/scenarios run --only service_desk --modes scratch # one card, scratch mode +npx @objectstack/scenarios run # every card, both modes +npx @objectstack/scenarios run --cards ./my-cards # a directory of your own, loaded as the overlay +npx @objectstack/scenarios help # the commands; `version` prints the package version +``` + +- **Prerequisites**: Node 22 or later, and Claude Code installed and logged in with your own subscription + (`claude auth login`). The runner refuses to start when `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` is set, or the + CLI is logged in with an API key. Each card scaffolds a project with `create-objectstack` (`--create-version` picks + its version). +- **The cards**: the package carries the open library of this repository (`docs/qa/scenarios/*.json` and the + capability areas, copied into `dist/library/` at build time) and nothing else. `--cards DIR` runs another directory + as the overlay, where a `generic` card is refused. +- **The records**: one `scenario-runs/-scenario-.json` per card, under the directory you run it from, + unless `--out DIR` says otherwise; the scorecard is printed as in a checkout. `--work DIR` keeps the scaffolded + projects (default: a temp directory). +- **The packages**: always the published ones (`--packages published`, the default). `--packages workspace` builds + and packs a checkout's packages, so the published CLI refuses it; run it from a checkout. +- It is not an `objectstack` (`os`) command: scenario scoring stays out of the customer CLI. + | Mode | Steps | |:---|:---| | `scratch` | `create-objectstack` → the agent builds from the card prompt and the runner's data contract (`prompts.ts`) → `objectstack validate` / `build` / `verify` (proofs chosen from the tags) → score → `objectstack dev --fresh` → seed, one user + permission-set grant + API key per persona → every question as every persona it names and every operation as its persona, over the app's MCP → the iterate change → rebuild, re-score, re-run | diff --git a/packages/qa/scenarios/bin/objectstack-scenarios.js b/packages/qa/scenarios/bin/objectstack-scenarios.js new file mode 100755 index 00000000000..247cc47f9d9 --- /dev/null +++ b/packages/qa/scenarios/bin/objectstack-scenarios.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// `bin.objectstack-scenarios` in package.json: npm packs this file because it +// is the `bin` target. It runs the BUILT CLI (`dist/bin.js`, from +// `src/bin.ts`), never a `.ts` source; a refusal or failure prints its message +// and exits 1, as `run-scenarios` does. +import { runCli } from '../dist/bin.js'; + +runCli(process.argv.slice(2)).then( + (code) => process.exit(code), + (e) => { + console.error(e instanceof Error ? e.message : e); + process.exit(1); + }, +); diff --git a/packages/qa/scenarios/package.json b/packages/qa/scenarios/package.json index 8b1219a88ac..46d73adff4c 100644 --- a/packages/qa/scenarios/package.json +++ b/packages/qa/scenarios/package.json @@ -1,12 +1,14 @@ { "name": "@objectstack/scenarios", "version": "0.1.0", - "private": true, "license": "Apache-2.0", - "description": "Scenario-card schema and loader for the open scenario library under docs/qa/scenarios/. A card states an authoring prompt, the structural expectation a generated app must meet, seed rows, data questions whose truth the loader COMPUTES from a declarative spec over those rows, personas, write operations with their guardrail checks, and one iteration request \u2014 plus the deterministic scorer that judges a built artifact, an observed write or an agent's answer against a loaded card (`@objectstack/scenarios/score`). Not published (a minimal tsup build to `dist/` so a linked consumer's bundled entry can load it under plain Node; `./score` is the narrow scorer, `./score/full` adds the capability-tag checks), no model calls: a devx instrument, not a protocol (packages/spec carries no obligation for this format).", + "description": "Run the open ObjectStack scenario cards end to end from npm: `npx @objectstack/scenarios run` builds an app from each card's prompt with your local Claude Code login, scores it and writes one run record per card. Also the scenario-card schema and loader (computed truths over seed rows) and the deterministic scorer (`@objectstack/scenarios/score`, `./score/full`). Ships the open card library (docs/qa/scenarios) as package data, never a private overlay; refuses an API-billed login. A devx instrument, not a protocol: packages/spec carries no obligation for this format.", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", + "bin": { + "objectstack-scenarios": "./bin/objectstack-scenarios.js" + }, "exports": { ".": { "import": { @@ -60,7 +62,7 @@ } }, "scripts": { - "build": "tsup && node ../../../scripts/check-dts-emitted.mjs", + "build": "tsup && node scripts/pack-library.mjs && node ../../../scripts/check-dts-emitted.mjs", "test": "vitest run", "typecheck": "tsc --noEmit", "run-scenarios": "tsx src/runner/cli.ts", @@ -93,5 +95,16 @@ "directory": "packages/qa/scenarios" }, "homepage": "https://objectstack.ai/docs", - "bugs": "https://github.com/objectstack-ai/objectstack/issues" + "bugs": "https://github.com/objectstack-ai/objectstack/issues", + "publishConfig": { + "access": "public" + }, + "files": [ + "dist", + "README.md", + "CHANGELOG.md" + ], + "engines": { + "node": ">=22.0.0" + } } diff --git a/packages/qa/scenarios/scripts/pack-library.mjs b/packages/qa/scenarios/scripts/pack-library.mjs new file mode 100644 index 00000000000..8c983dff451 --- /dev/null +++ b/packages/qa/scenarios/scripts/pack-library.mjs @@ -0,0 +1,48 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The package build's last step: copy the OPEN card library into +// `dist/library/`, keeping the repository's layout, so the published CLI runs +// the cards with no checkout (`src/runner/library.ts` reads it back): +// +// docs/qa/scenarios/*.json → dist/library/docs/qa/scenarios/ +// docs/qa/platform-checklist/areas/*.json → dist/library/docs/qa/platform-checklist/areas/ +// +// ⛔ Only these two directories of THIS repository, one level deep, regular +// `.json` files only. The private overlay (held-out and customer-derived +// cards, objectstack-ai/cloud#3603) lives outside this repository and has no +// path in here; `test/build/packed-tarball.test.ts` packs the package and +// fails on any card in the tarball that is not byte for byte a card of +// `docs/qa/scenarios/`. +// +// turbo re-runs the build when either directory changes: the package's +// `turbo.json` adds them to the build's inputs. + +import { copyFileSync, lstatSync, mkdirSync, readdirSync, rmSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const PKG = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const REPO = resolve(PKG, '../../..'); +const OUT = join(PKG, 'dist/library'); +const DIRS = ['docs/qa/scenarios', 'docs/qa/platform-checklist/areas']; + +rmSync(OUT, { recursive: true, force: true }); +const counts = []; +for (const dir of DIRS) { + const from = join(REPO, dir); + const to = join(OUT, dir); + mkdirSync(to, { recursive: true }); + let copied = 0; + for (const name of readdirSync(from).sort()) { + if (!name.endsWith('.json') || !lstatSync(join(from, name)).isFile()) continue; + copyFileSync(join(from, name), join(to, name)); + copied++; + } + if (copied === 0) { + console.error(`pack-library: no .json file under ${dir}: the published CLI would have nothing to run`); + process.exit(1); + } + counts.push(`${copied} from ${dir}`); +} +console.log(`pack-library: ${counts.join(', ')} → ${OUT}`); diff --git a/packages/qa/scenarios/src/bin.ts b/packages/qa/scenarios/src/bin.ts new file mode 100644 index 00000000000..8f974564b29 --- /dev/null +++ b/packages/qa/scenarios/src/bin.ts @@ -0,0 +1,66 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `objectstack-scenarios` — the published command line (`npx @objectstack/scenarios run …`). + * + * A thin dispatcher over the runner's own CLI (`runner/cli.ts`): `run` hands + * every argument after it to the same `main` that + * `pnpm --filter @objectstack/scenarios run-scenarios` runs, so the flags, the + * defaults and the refusals are that CLI's (no API-billed login, the published + * packages by default). Not an `os` subcommand, and it carries no scoring of + * a customer's own app: the cards it runs are the open library the package + * ships (`runner/library.ts`), or a `--cards` directory loaded as the overlay. + * + * `bin/objectstack-scenarios.js` imports the BUILT form of this file + * (`dist/bin.js`), so npm runs JavaScript, never a `.ts` source. + * + * The runner is imported only for `run`, and the build keeps it out of this + * file (`tsup.config.ts` turns the import into one of the built `dist/cli.js`): + * its graph (the scorer's objectql and plugin-sharing among it) takes about a + * second warm and several cold, which `help` and `version` must not pay. + */ + +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export const USAGE = `Usage: objectstack-scenarios [flags] + +Commands: + run [flags] run the scenario cards end to end and write one run record per card + (the flags of run-scenarios: --only, --modes, --driver, --cards, --out, …; + see the package README, "Running from npm") + help print this text + version print the package version + +Runs on your own Claude Code login: it refuses to start when an API key is configured.`; + +export interface CliIo { + out: (line: string) => void; + err: (line: string) => void; +} + +const consoleIo: CliIo = { out: (l) => console.log(l), err: (l) => console.error(l) }; + +function packageVersion(): string { + // `src/bin.ts` and `dist/bin.js` both sit one directory below the package root. + const manifest = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'); + return (JSON.parse(readFileSync(manifest, 'utf8')) as { version: string }).version; +} + +/** Run one command line; answers the process exit code. */ +export async function runCli(argv: readonly string[], io: CliIo = consoleIo): Promise { + const [command, ...rest] = argv; + if (command === 'run') return (await import('./runner/cli.js')).main(rest); + if (command === 'help' || command === '--help' || command === '-h') { + io.out(USAGE); + return 0; + } + if (command === 'version' || command === '--version' || command === '-v') { + io.out(packageVersion()); + return 0; + } + io.err(command === undefined ? 'objectstack-scenarios: name a command' : `objectstack-scenarios: unknown command \`${command}\``); + io.err(USAGE); + return 2; +} diff --git a/packages/qa/scenarios/src/runner/cli.ts b/packages/qa/scenarios/src/runner/cli.ts index 032aaf4c41a..52103de1fa3 100644 --- a/packages/qa/scenarios/src/runner/cli.ts +++ b/packages/qa/scenarios/src/runner/cli.ts @@ -4,7 +4,8 @@ * `pnpm --filter @objectstack/scenarios run-scenarios [flags]` — run every card * under `docs/qa/scenarios/` end to end and write one run record per card. * - * --cards DIR the card directory (default: the repo's docs/qa/scenarios); + * --cards DIR the card directory (default: the repo's docs/qa/scenarios, + * or the copy the published package carries, `library.ts`); * any other directory is loaded as the private overlay, * where a `generic` card is refused (`libraryOf`) * --only ID[,ID] run only these cards @@ -24,20 +25,22 @@ * turn (default 12) * --template F a verified build (dist/objectstack.json) for template mode * --no-iterate-run skip the Run half after the iterate (scratch mode) - * --out DIR where records go (default docs/qa/platform-checklist/runs, git-ignored) + * --out DIR where records go (default docs/qa/platform-checklist/runs, git-ignored; + * ./scenario-runs when run from the published package) * --work DIR where projects are scaffolded (default: a temp dir) * --create-version V the create-objectstack version (default latest) * --packages P where the @objectstack/* packages come from (`packages.ts`): * `published` (default) — npm, what a customer gets; * `workspace` — this checkout, built and packed as the - * release would publish it (unreleased; never exported) + * release would publish it (unreleased; never exported; + * refused when run from the published package, which has no checkout) * * ⛔ No API-billed model: the live driver refuses to start when an API key is * configured (the cost ruling on cloud#3600). */ import { execSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -45,6 +48,7 @@ import { fileURLToPath } from 'node:url'; import { formatRefusal, libraryOf, loadScenarios, readCapabilityAreas } from '../loader.js'; import { HttpApp } from './app.js'; import { ClaudeCodeDriver, RecordedDriver, RecordingDriver, type AgentDriver } from './driver.js'; +import { CAPABILITY_AREAS_DIR, locateLibraryRoot } from './library.js'; import { minutesText, runCard, type ProjectOps } from './orchestrate.js'; import { installedSpecVersion, PACKAGES_MODES, prepareWorkspacePackages, settleWorkspaceProject, workspaceScaffolder, type PackageSource, type PackagesMode } from './packages.js'; import { bootDev, os, readArtifact, readNamespace, scaffold } from './project.js'; @@ -160,15 +164,19 @@ export function makeDriver(spec: string, opts: DriverLimits = {}): AgentDriver { export async function main(argv: readonly string[]): Promise { const args = parseArgs(argv); const here = dirname(fileURLToPath(import.meta.url)); - const repo = findUp(here, (d) => existsSync(join(d, 'pnpm-workspace.yaml'))); + // The checkout, or the library root the published package carries (`library.ts`). + const { root: repo, checkout } = locateLibraryRoot(here); + if (args.packages === 'workspace' && !checkout) { + throw new Error('--packages workspace builds and packs the packages of an objectstack checkout; the published CLI has none. Run it from a checkout (`pnpm --filter @objectstack/scenarios run-scenarios --packages workspace`), or use --packages published'); + } const cardsDir = resolve(args.cards ?? join(repo, 'docs/qa/scenarios')); - const outDir = resolve(args.out ?? join(repo, 'docs/qa/platform-checklist/runs')); + const outDir = resolve(args.out ?? (checkout ? join(repo, 'docs/qa/platform-checklist/runs') : 'scenario-runs')); const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'scenario-run-'))); mkdirSync(work, { recursive: true }); mkdirSync(outDir, { recursive: true }); const { cards, refusals } = loadScenarios(cardsDir, { - areas: readCapabilityAreas(join(repo, 'docs/qa/platform-checklist/areas')), + areas: readCapabilityAreas(join(repo, CAPABILITY_AREAS_DIR)), library: libraryOf(cardsDir, repo), }); for (const r of refusals) console.error(formatRefusal(r)); @@ -217,7 +225,8 @@ export async function main(argv: readonly string[]): Promise { const template = args.template ? JSON.parse(readFileSync(args.template, 'utf8')) : undefined; let framework: string | undefined; try { - framework = execSync('git rev-parse --short HEAD', { cwd: repo, encoding: 'utf8' }).trim(); + // Only a checkout has a framework commit: an installed package may sit in someone else's repository. + if (checkout) framework = execSync('git rev-parse --short HEAD', { cwd: repo, encoding: 'utf8' }).trim(); } catch { /* not a checkout */ } diff --git a/packages/qa/scenarios/src/runner/library.ts b/packages/qa/scenarios/src/runner/library.ts new file mode 100644 index 00000000000..06e09c9ed88 --- /dev/null +++ b/packages/qa/scenarios/src/runner/library.ts @@ -0,0 +1,71 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Where the runner reads the open card library from: this repository's + * `docs/qa/scenarios/` when it runs from a checkout, or the copy the published + * package carries when it runs from npm (`npx @objectstack/scenarios run`). + * + * The package build copies the open library, and only it, into + * `dist/library/` with the repository's layout (`scripts/pack-library.mjs`): + * `dist/library/docs/qa/scenarios/*.json` and + * `dist/library/docs/qa/platform-checklist/areas/*.json`. So the root either + * answer names reads the same relative paths, and `libraryOf` judges a + * `--cards` directory against the open library of THAT root: the shipped copy + * is `open`, any other directory the private overlay. + */ + +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +import { OPEN_LIBRARY_DIR } from '../loader.js'; + +/** The capability-area closed set, relative to a library root. */ +export const CAPABILITY_AREAS_DIR = 'docs/qa/platform-checklist/areas'; + +/** The package directory the published copy of the open library lives under. */ +export const PACKED_LIBRARY_DIR = 'dist/library'; + +const PACKAGE_NAME = '@objectstack/scenarios'; +/** Where this package sits in the repository. */ +const PACKAGE_IN_REPO = 'packages/qa/scenarios'; + +export interface LibraryRoot { + /** The directory `docs/qa/scenarios` and `docs/qa/platform-checklist/areas` are read under. */ + root: string; + /** `true` in a repository checkout; `false` when the package was installed from npm. */ + checkout: boolean; +} + +function packageRoot(from: string): string { + for (let dir = resolve(from); ; ) { + const manifest = join(dir, 'package.json'); + if (existsSync(manifest) && (JSON.parse(readFileSync(manifest, 'utf8')) as { name?: unknown }).name === PACKAGE_NAME) return dir; + const up = dirname(dir); + if (up === dir) throw new Error(`no ${PACKAGE_NAME} package.json above ${from}`); + dir = up; + } +} + +/** + * The library root for code running at `from` (a directory inside this + * package). A checkout is recognised by the package sitting at + * `packages/qa/scenarios` of a pnpm workspace that holds the open library, so + * an install of the package inside some other workspace is never read as one. + */ +export function locateLibraryRoot(from: string): LibraryRoot { + const pkg = packageRoot(from); + const repo = resolve(pkg, '../../..'); + if ( + existsSync(join(repo, 'pnpm-workspace.yaml')) && + existsSync(join(repo, OPEN_LIBRARY_DIR)) && + existsSync(join(repo, PACKAGE_IN_REPO)) && + realpathSync(join(repo, PACKAGE_IN_REPO)) === realpathSync(pkg) + ) { + return { root: repo, checkout: true }; + } + const root = join(pkg, PACKED_LIBRARY_DIR); + if (!existsSync(join(root, OPEN_LIBRARY_DIR))) { + throw new Error(`${PACKAGE_NAME} at ${pkg} carries no card library (${PACKED_LIBRARY_DIR}/${OPEN_LIBRARY_DIR}): reinstall the package, or build it in a checkout`); + } + return { root, checkout: false }; +} diff --git a/packages/qa/scenarios/test/build/packed-tarball.test.ts b/packages/qa/scenarios/test/build/packed-tarball.test.ts new file mode 100644 index 00000000000..00ff6cdbf4c --- /dev/null +++ b/packages/qa/scenarios/test/build/packed-tarball.test.ts @@ -0,0 +1,204 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The PUBLISHED package, read as npm would serve it: `pnpm pack` (the tarball + * `pnpm publish` uploads: `files[]` plus the `bin` target, every `workspace:` + * range rewritten to a version), then the tarball installed into a project of + * its own and its `bin` run under plain Node. + * + * Two promises are pinned here: + * + * - **Only the open library ships.** Every `.json` file in the tarball is + * the manifest, a card byte for byte equal to one of `docs/qa/scenarios/`, + * or a capability area byte for byte equal to one of + * `docs/qa/platform-checklist/areas/`; anything else fails, wherever it + * sits. The private overlay (held-out and customer-derived cards, + * objectstack-ai/cloud#3603) is never in this repository, and a card that + * reached the tarball some other way is refused here, not shipped. Every + * shipped card is `generic`. + * - **The `bin` runs as built JavaScript**, no checkout and no TypeScript + * resolver: help, version, the shipped library loaded with no refusal, + * and the runner's own refusal of an API-billed login, before anything is + * scaffolded. + * + * The install links each runtime dependency to the workspace's own build + * (its `dist/`), so no registry is reached; the scenarios package itself is + * the extracted tarball, a real directory with nothing but what was packed. + * + * Reads `dist/`: build the package first (`pnpm --filter @objectstack/scenarios build`). + */ + +import { execFileSync, spawnSync } from 'node:child_process'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { delimiter, dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const PKG = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +const REPO = resolve(PKG, '../../..'); +const CARDS = 'docs/qa/scenarios'; +const AREAS = 'docs/qa/platform-checklist/areas'; +const LIBRARY = 'dist/library'; +const BIN = 'objectstack-scenarios'; + +let work = ''; +let tarball = ''; +/** Paths in the tarball, relative to its `package/` root. */ +let packed: string[] = []; +/** The extracted package, installed at `/node_modules/@objectstack/scenarios`. */ +let installed = ''; +let project = ''; +let manifest: { version: string; private?: boolean; bin?: Record; dependencies: Record }; + +const jsonFiles = (dir: string) => readdirSync(join(REPO, dir)).filter((n) => n.endsWith('.json')).sort(); + +function runBin(args: string[], env: NodeJS.ProcessEnv = {}) { + const r = spawnSync(process.execPath, [join(installed, manifest.bin![BIN]!), ...args], { + cwd: project, + encoding: 'utf8', + env: { ...process.env, ANTHROPIC_API_KEY: '', ANTHROPIC_AUTH_TOKEN: '', ...env }, + }); + return { status: r.status, stdout: r.stdout, stderr: r.stderr }; +} + +beforeAll(() => { + if (!existsSync(join(PKG, 'dist/bin.js')) || !existsSync(join(PKG, LIBRARY, CARDS))) { + throw new Error('build @objectstack/scenarios first (pnpm --filter @objectstack/scenarios build): no dist/bin.js or dist/library'); + } + work = mkdtempSync(join(tmpdir(), 'scenarios-packed-')); + // Run from the package directory, so the repository's pinned pnpm packs it. + const out = execFileSync('pnpm', ['pack', '--pack-destination', work], { cwd: PKG, encoding: 'utf8' }); + tarball = join(work, readdirSync(work).find((n) => n.endsWith('.tgz'))!); + expect(out).toContain(tarball.split('/').pop()); + + packed = execFileSync('tar', ['-tzf', tarball], { encoding: 'utf8' }) + .split('\n') + .filter((l) => l && !l.endsWith('/')) + .map((l) => l.replace(/^package\//, '')) + .sort(); + + project = join(work, 'project'); + mkdirSync(join(project, 'node_modules/@objectstack'), { recursive: true }); + writeFileSync(join(project, 'package.json'), JSON.stringify({ name: 'scenarios-npx-smoke', private: true })); + execFileSync('tar', ['-xzf', tarball, '-C', work]); + installed = join(project, 'node_modules/@objectstack/scenarios'); + renameSync(join(work, 'package'), installed); + manifest = JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8')) as typeof manifest; + for (const dep of Object.keys(manifest.dependencies)) { + const to = join(project, 'node_modules', dep); + mkdirSync(dirname(to), { recursive: true }); + symlinkSync(realpathSync(join(PKG, 'node_modules', dep)), to, 'dir'); + } +}, 120_000); + +afterAll(() => { + if (work) rmSync(work, { recursive: true, force: true }); +}); + +describe('the packed @objectstack/scenarios tarball', () => { + it('is publishable and names its bin', () => { + expect(manifest.private).toBeUndefined(); + expect(manifest.bin).toEqual({ [BIN]: './bin/objectstack-scenarios.js' }); + expect(packed).toContain('bin/objectstack-scenarios.js'); + // Every `workspace:` range became a version the registry can serve. + expect(Object.values(manifest.dependencies).filter((v) => v.startsWith('workspace:'))).toEqual([]); + }); + + it('carries every open card and every capability area, byte for byte', () => { + for (const [dir, names] of [ + [CARDS, jsonFiles(CARDS)], + [AREAS, jsonFiles(AREAS)], + ] as const) { + expect(names.length, dir).toBeGreaterThan(0); + expect(packed.filter((p) => p.startsWith(`${LIBRARY}/${dir}/`)).map((p) => p.slice(`${LIBRARY}/${dir}/`.length))).toEqual(names); + for (const name of names) { + expect(readFileSync(join(installed, LIBRARY, dir, name)).equals(readFileSync(join(REPO, dir, name))), `${dir}/${name}`).toBe(true); + } + } + }); + + it('carries no other JSON: a card from anywhere but docs/qa/scenarios is refused', () => { + const allowed = new Set(['package.json', ...jsonFiles(CARDS).map((n) => `${LIBRARY}/${CARDS}/${n}`), ...jsonFiles(AREAS).map((n) => `${LIBRARY}/${AREAS}/${n}`)]); + expect(packed.filter((p) => p.endsWith('.json') && !allowed.has(p))).toEqual([]); + }); + + it('ships only generic cards, never a held-out or customer-derived one', () => { + const shipped = packed.filter((p) => p.startsWith(`${LIBRARY}/${CARDS}/`)); + expect(shipped.length).toBeGreaterThan(0); + for (const p of shipped) { + expect((JSON.parse(readFileSync(join(installed, p), 'utf8')) as { origin?: unknown }).origin, p).toBe('generic'); + } + }); + + it('keeps the runner out of the bin: help and version load dist/bin.js alone', () => { + // The runner's graph (objectql, plugin-sharing, spec) costs about a second warm and + // several seconds cold; only `run` may pay it, through the built `dist/cli.js`. + const bin = readFileSync(join(installed, 'dist/bin.js'), 'utf8'); + expect(bin.match(/from\s*["'][^"']+["']/g) ?? []).toEqual(['from "fs"', 'from "path"', 'from "url"']); + expect(bin).toContain('import("./cli.js")'); + expect(packed).toContain('dist/cli.js'); + }); + + it('ships JavaScript and declarations, never a TypeScript source', () => { + expect(packed.filter((p) => /\.(c|m)?ts$/.test(p) && !/\.d\.(c|m)?ts$/.test(p))).toEqual([]); + expect(packed.filter((p) => p.startsWith('src/') || p.startsWith('test/') || p.startsWith('scripts/'))).toEqual([]); + }); +}); + +/** + * Each `run` case spawns Node over the runner's whole graph once. Measured: about + * 1.3 s warm in a dev container; 5.7 s and 6.5 s cold on a CI Test Core runner + * (run 42400730182, where vitest's 5 s default timed both out). Budgeted at + * 30 s each, as `built-consumer.test.ts` budgets its own spawn of the same graph. + */ +const RUN_SPAWN_BUDGET_MS = 30_000; + +describe('the packed bin, run under plain Node', () => { + it('prints its usage and its version', () => { + const help = runBin(['--help']); + expect(help.status).toBe(0); + expect(help.stdout).toContain(`Usage: ${BIN} `); + const version = runBin(['version']); + expect(version.status).toBe(0); + expect(version.stdout.trim()).toBe(manifest.version); + const none = runBin([]); + expect(none.status).toBe(2); + expect(none.stderr).toContain('name a command'); + }); + + it('runs the library it ships: every card loads, none matches an unknown id', () => { + const r = runBin(['run', '--only', 'no_such_card']); + expect(r.stderr.trim()).toBe(`no card to run under ${join(realpathSync(installed), LIBRARY, CARDS)} matching no_such_card`); + expect(r.status).toBe(2); + }, RUN_SPAWN_BUDGET_MS); + + it('refuses --packages workspace: an install has no checkout to build', () => { + const scaffolds = join(work, 'workspace-scaffolds'); + const r = runBin(['run', '--packages', 'workspace', '--only', 'service_desk', '--work', scaffolds]); + expect(r.status).toBe(1); + expect(r.stderr).toContain('--packages workspace builds and packs the packages of an objectstack checkout; the published CLI has none'); + // Refused before the run makes anything: no work directory, no build, no pack. + expect(existsSync(scaffolds)).toBe(false); + }, RUN_SPAWN_BUDGET_MS); + + it('refuses an API-billed login before it scaffolds anything', () => { + // A stand-in `claude` on a subscription login: only the key in the environment can refuse it. + const fakeBin = join(work, 'fake-bin'); + mkdirSync(fakeBin, { recursive: true }); + writeFileSync( + join(fakeBin, 'claude'), + '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "9.9.9 (Claude Code)"; else echo \'{"loggedIn":true,"authMethod":"claude.ai"}\'; fi\n', + ); + chmodSync(join(fakeBin, 'claude'), 0o755); + const scaffolds = join(work, 'scaffolds'); + const r = runBin(['run', '--only', 'service_desk', '--modes', 'scratch', '--work', scaffolds], { + PATH: `${fakeBin}${delimiter}${process.env.PATH ?? ''}`, + ANTHROPIC_API_KEY: 'sk-ant-smoke', + }); + expect(r.status).toBe(1); + expect(r.stderr).toContain('`ANTHROPIC_API_KEY` is set'); + expect(readdirSync(scaffolds)).toEqual([]); + }, RUN_SPAWN_BUDGET_MS); +}); diff --git a/packages/qa/scenarios/test/runner/library.test.ts b/packages/qa/scenarios/test/runner/library.test.ts new file mode 100644 index 00000000000..26778d067dc --- /dev/null +++ b/packages/qa/scenarios/test/runner/library.test.ts @@ -0,0 +1,85 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Where the runner reads the open library from (`runner/library.ts`), and the + * published command line's dispatch (`bin.ts`). The packed tarball itself is + * read in `test/build/packed-tarball.test.ts`. + */ + +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { afterAll, describe, expect, it } from 'vitest'; + +import { runCli, USAGE } from '../../src/bin.js'; +// `runCli` imports the runner CLI lazily (only `run` pays for its graph); loading it here +// keeps that transform in the file's import phase, not inside a case's 5 s default. +import '../../src/runner/cli.js'; +import { locateLibraryRoot, PACKED_LIBRARY_DIR } from '../../src/runner/library.js'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const REPO = resolve(HERE, '../../../../..'); +const tmp = mkdtempSync(join(tmpdir(), 'scenarios-library-')); + +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +/** A project with the package installed at `node_modules/@objectstack/scenarios`; `library` adds the packed copy. */ +function installedPackage(project: string, library: boolean): string { + const pkg = join(project, 'node_modules/@objectstack/scenarios'); + mkdirSync(join(pkg, 'dist'), { recursive: true }); + writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name: '@objectstack/scenarios', version: '0.0.0' })); + if (library) mkdirSync(join(pkg, PACKED_LIBRARY_DIR, 'docs/qa/scenarios'), { recursive: true }); + return pkg; +} + +describe('locateLibraryRoot', () => { + it('reads the checkout from the package sources', () => { + expect(locateLibraryRoot(join(REPO, 'packages/qa/scenarios/src/runner'))).toEqual({ root: REPO, checkout: true }); + }); + + it('reads the packed copy from an installed package', () => { + const pkg = installedPackage(join(tmp, 'plain'), true); + expect(locateLibraryRoot(join(pkg, 'dist'))).toEqual({ root: join(pkg, PACKED_LIBRARY_DIR), checkout: false }); + }); + + it('never reads another pnpm workspace holding a docs/qa/scenarios as the checkout', () => { + const project = join(tmp, 'lookalike'); + const pkg = installedPackage(project, true); + writeFileSync(join(project, 'pnpm-workspace.yaml'), 'packages: []\n'); + mkdirSync(join(project, 'docs/qa/scenarios'), { recursive: true }); + // The package's grandparent's grandparent is `project` itself under npm's flat layout. + mkdirSync(join(project, 'packages/qa/scenarios'), { recursive: true }); + expect(locateLibraryRoot(join(pkg, 'dist'))).toEqual({ root: join(pkg, PACKED_LIBRARY_DIR), checkout: false }); + }); + + it('refuses an installed package that carries no library', () => { + const pkg = installedPackage(join(tmp, 'bare'), false); + expect(() => locateLibraryRoot(join(pkg, 'dist'))).toThrow(/carries no card library/); + }); +}); + +describe('the objectstack-scenarios command line', () => { + const capture = () => { + const out: string[] = []; + const err: string[] = []; + return { out, err, io: { out: (l: string) => out.push(l), err: (l: string) => err.push(l) } }; + }; + + it('prints its usage on help, and refuses no command or an unknown one with it', async () => { + const help = capture(); + expect(await runCli(['help'], help.io)).toBe(0); + expect(help.out).toEqual([USAGE]); + for (const argv of [[], ['score']]) { + const c = capture(); + expect(await runCli(argv, c.io)).toBe(2); + expect(c.err[1]).toBe(USAGE); + } + }); + + it('hands every argument after `run` to the runner CLI unchanged', async () => { + await expect(runCli(['run', '--bogus'], capture().io)).rejects.toThrow('unknown flag `--bogus`'); + await expect(runCli(['run', '--modes', 'nightly'], capture().io)).rejects.toThrow('unknown mode `nightly`'); + }); +}); diff --git a/packages/qa/scenarios/tsup.config.ts b/packages/qa/scenarios/tsup.config.ts index f8c9db847a2..837feb3b943 100644 --- a/packages/qa/scenarios/tsup.config.ts +++ b/packages/qa/scenarios/tsup.config.ts @@ -1,15 +1,18 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { defineConfig } from 'tsup'; +import { basename } from 'node:path'; + +import { defineConfig, type Options } from 'tsup'; import { dropSourcesContent } from '../../../scripts/tsup-drop-sources-content.mjs'; /** - * A minimal build for a PRIVATE package (#30915): it is never published, but a - * consumer that links the framework tree and bundles its own entry with tsup - * leaves `@objectstack/scenarios` external, so plain Node must be able to load - * it. The `.ts` sources import with `.js` specifiers, which only a TypeScript - * resolver follows: `dist/` is what Node loads (ESM `.js`, CJS `.cjs`). + * The build of the published package (#30915 first built it for a linked + * consumer; it is published since the standalone CLI). A consumer that bundles + * its own entry with tsup leaves `@objectstack/scenarios` external, so plain + * Node must be able to load it. The `.ts` sources import with `.js` + * specifiers, which only a TypeScript resolver follows: `dist/` is what Node + * loads (ESM `.js`, CJS `.cjs`). * * One entry per export-map subpath. `score` is the narrow scorer * (`src/score/narrow.ts`): it reads `@objectstack/core` and `@objectstack/spec` @@ -17,11 +20,30 @@ import { dropSourcesContent } from '../../../scripts/tsup-drop-sources-content.m * capability-tag checks read `@objectstack/objectql` and * `@objectstack/plugin-sharing`. `splitting: false` keeps each entry one file, * so an entry's external imports are exactly the ones its own graph reaches. + * `bin` is the command line (`src/bin.ts` over `src/runner/cli.ts`), which + * `bin/objectstack-scenarios.js` loads; it is not an `exports` subpath. Its + * one import of the runner CLI is lazy (`run` only) and is kept OUT of the + * bundle: {@link binLoadsBuiltCli} points it at the built `cli` entry, so + * `help` and `version` load `dist/bin.js` alone. The build's next step copies + * the open card library into `dist/library/` (`scripts/pack-library.mjs`). * * Dependencies stay external (tsup's default for `dependencies`; `export`'s * `playwright-core` included, which it loads with a dynamic `import()`); the source * suites and `run-scenarios` keep reading `src/` and never this output. */ +type EsbuildPlugin = NonNullable[number]; + +/** `src/bin.ts`'s `import('./runner/cli.js')` → the built `./cli.js` / `./cli.cjs`, external. */ +const binLoadsBuiltCli: EsbuildPlugin = { + name: 'bin-loads-built-cli', + setup(build) { + const ext = build.initialOptions.format === 'cjs' ? '.cjs' : '.js'; + build.onResolve({ filter: /^\.\/runner\/cli\.js$/ }, (args) => + basename(args.importer) === 'bin.ts' ? { path: `./cli${ext}`, external: true } : undefined, + ); + }, +}; + export default defineConfig({ entry: { index: 'src/index.ts', @@ -29,7 +51,10 @@ export default defineConfig({ 'score-full': 'src/score/index.ts', runner: 'src/runner/index.ts', export: 'src/export/index.ts', + bin: 'src/bin.ts', + cli: 'src/runner/cli.ts', }, + esbuildPlugins: [binLoadsBuiltCli], tsconfig: 'tsconfig.build.json', splitting: false, sourcemap: true, diff --git a/packages/qa/scenarios/turbo.json b/packages/qa/scenarios/turbo.json new file mode 100644 index 00000000000..fdeb17bf244 --- /dev/null +++ b/packages/qa/scenarios/turbo.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://turbo.build/schema.json", + "extends": ["//"], + "tasks": { + "build": { + "inputs": [ + "$TURBO_EXTENDS$", + "$TURBO_ROOT$/docs/qa/scenarios/*.json", + "$TURBO_ROOT$/docs/qa/platform-checklist/areas/*.json" + ] + } + } +} diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index a376e0bfb21..1d4964d525b 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -178,9 +178,9 @@ function registerObject(rawConfig: unknown) { --- -## 7. Package Ecosystem (74 packages) +## 7. Package Ecosystem (75 packages) -The workspace publishes 74 packages under the `@objectstack` scope. The table +The workspace publishes 75 packages under the `@objectstack` scope. The table below is a curated entry-point list, not the full set — drivers, connectors, triggers, plugins and kernel-managed services each form their own family.