diff --git a/.changeset/35132-gallery-trial-package.md b/.changeset/35132-gallery-trial-package.md new file mode 100644 index 00000000000..43d14976621 --- /dev/null +++ b/.changeset/35132-gallery-trial-package.md @@ -0,0 +1,20 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): the gallery export writes each app as a package a customer can install and try (listing text, business-function facet, sample data), and the gallery check refuses an app with no sample data + +Clause-②: yes +Metadata-protocol: none + +The exporter now adds three things to each app's `source/`. It adds them after the run is scored, so the AI's build is never graded on them, and it never writes them into the run's own project. + +- `objectstack.manifest.json` gets the card's listing text and facet. `displayName` and `description` are the card's English title and one-sentence requirement. The Chinese pair goes under `translations.zh`. `businessFunctions` is the card's own list, primary first. The build's other keys are kept. +- `src/sample-data.json` holds the card's seed rows as stack `data:` datasets: one per object, named with the app's namespace, keyed on the card's row id (`externalId: 'id'`). Lookup values name row ids of the same load. A user-handle field (`run.userHandleFields`) is left out of every row, because its value names a user of the run's own environment, and the app README says which field was left out. +- `objectstack.config.ts` gets one import line and `data: gallerySampleData` as the first property of its default-exported `defineStack({ … })` literal. Every other byte stays as the AI wrote it. The export is refused, with the reason, in four cases: the default export is not such a literal, the literal already declares `data:` or spreads a value, a seeded object is missing from the build, or the build already wrote `src/sample-data.json`. + +Measured on `travel_expense`: the blank scaffold's `objectstack.config.ts`, with the recorded build's objects and the 757 seed rows added this way, passes `objectstack validate`. A dataset naming an object the build lacks is refused there ("Seed data references object … which is not defined in objects"), which shows the validator reads the imported file. + +`export-gallery --check` has a new finding, `app-sample-data`. It reports an app whose `source/` has no `src/sample-data.json`, a file that is not a non-empty list of datasets the spec's `SeedSchema` accepts (each with at least one record), or a `source/objectstack.config.ts` that does not import it. A gallery tree written by an earlier exporter has no sample-data file, so the check reports each of its apps until the next refresh exports them again. The check writes nothing and deletes no app. + +`installModes` and `solutionType` are not written yet: `installModes: ['unmanaged']` makes `defineStack` refuse an app that carries code `plugins` or `capability` items, which an app on the standard scaffold does. `typescript` moves from a dev dependency to a dependency. The exporter loads it, with a dynamic import, only when it edits a config. diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index a61b352155c..1ff8e58214a 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -720,7 +720,14 @@ that version, it prints one `skip: …` line and exits 0, having run nothing. It 1. runs every card the gallery may show (origin `generic`, tier `starter` or `delivery`; `--debut`: the first of them by id) with `run-scenarios --modes scratch --packages published --create-version `, so the apps are built on exactly that release, the turns recorded; -2. exports with screenshots into the checkout (`export-gallery`'s rules: only a run that passed every half); +2. exports with screenshots into the checkout (`export-gallery`'s rules: only a run that passed every half). Each + app's `source/` is written as a package a customer installs to try, after scoring so the build is never graded on + it (`src/export/trial-package.ts`): `objectstack.manifest.json` carries the card's English title and one-sentence + requirement as `displayName` and `description`, the Chinese pair under `translations.zh`, and the card's + `businessFunctions`; `src/sample-data.json` carries the card's seed rows as stack `data:` datasets (namespaced + objects, `externalId: 'id'`, a user-handle field left out), which `objectstack.config.ts` imports into its `data:`. + `installModes` and `solutionType` are not written: `installModes: ['unmanaged']` makes `defineStack` refuse an app + that carries code `plugins` or `capability` items, which an app on the standard scaffold does; 3. creates the branch `export/`, commits `apps/` and `index.json` under the checkout's own git identity, and prints the branch, the commit and a ready PR body. @@ -786,7 +793,9 @@ The check a PR on objectstack-ai/gallery must pass before it is merged (`src/exp layout), so the two cannot drift. It prints one `CODE PATH: MESSAGE` line per finding and exits 1 on any, 0 on a clean tree: `index.json` that does not validate (absent is an empty gallery); an entry without a complete `apps//` (README, run record, scorecard and transcript in JSON and Markdown, `source/objectstack.config.ts`, at least one -screenshot, every listed screenshot on disk and none unlisted); a directory under `apps/` no entry lists; a +screenshot, every listed screenshot on disk and none unlisted); an app whose package arrives with no sample data (no +`source/src/sample-data.json`, one that is not a non-empty list of stack `data:` datasets the spec's `SeedSchema` +accepts, each with a record, or a `source/objectstack.config.ts` that does not import it); a directory under `apps/` no entry lists; a `framework.version` that is not a stable release published for `@objectstack/cli` (read with `npm view … versions`, only when the index lists an app); and anywhere in the tree a `.env*` name, a `node_modules` directory, a symbolic link or a text file naming a local absolute path. diff --git a/packages/qa/scenarios/package.json b/packages/qa/scenarios/package.json index 355e7dcad2e..4867d58b3bd 100644 --- a/packages/qa/scenarios/package.json +++ b/packages/qa/scenarios/package.json @@ -78,11 +78,11 @@ "@objectstack/plugin-sharing": "workspace:*", "@objectstack/spec": "workspace:*", "playwright-core": "1.63.0", + "typescript": "^6.0.3", "zod": "^4.6.6" }, "devDependencies": { "@types/node": "^26.6.5", - "typescript": "^6.0.3", "vitest": "^4.1.11" }, "keywords": [ diff --git a/packages/qa/scenarios/src/export/check.ts b/packages/qa/scenarios/src/export/check.ts index f4048353ff5..0d9fd6d43d4 100644 --- a/packages/qa/scenarios/src/export/check.ts +++ b/packages/qa/scenarios/src/export/check.ts @@ -20,6 +20,12 @@ * the README, the run record, the scorecard and the * transcript (JSON and Markdown each), and a `source/` tree * holding `objectstack.config.ts`. + * app-sample-data an entry's package arrives with no sample data: its + * `source/` holds no {@link SAMPLE_DATA_FILE}, the file is + * not a non-empty list of stack `data:` datasets (each + * valid against the spec's `SeedSchema`, each with at + * least one record), or `source/objectstack.config.ts` + * does not import it ({@link SAMPLE_DATA_SPECIFIER}). * app-screenshots an entry lists no screenshot, a listed screenshot is not * on disk, or `screenshots/` holds a file the entry does * not list. @@ -49,13 +55,16 @@ import { execFileSync } from 'node:child_process'; import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; -import { APP_LAYOUT, FRAMEWORK_PACKAGE, STABLE_VERSION } from './contract.js'; +import { SeedSchema } from '@objectstack/spec/data'; + +import { APP_LAYOUT, FRAMEWORK_PACKAGE, SAMPLE_DATA_FILE, SAMPLE_DATA_SPECIFIER, STABLE_VERSION } from './contract.js'; import { GalleryIndexSchema, type GalleryApp } from './manifest.js'; export const FINDING_CODES = [ 'index-json', 'app-missing', 'app-incomplete', + 'app-sample-data', 'app-screenshots', 'app-unlisted', 'framework-version', @@ -162,6 +171,7 @@ export function checkGallery(dir: string, opts: CheckOptions): GalleryFinding[] if (!isFile(join(root, APP_LAYOUT.source, SOURCE_REQUIRED))) { add('app-incomplete', `${rel}/${APP_LAYOUT.source}`, `a complete app directory holds its metadata source, ${APP_LAYOUT.source}/${SOURCE_REQUIRED} at least, and this one does not`); } + checkSampleData(dir, app, add); checkScreenshots(dir, app, add); } const v = app.framework.version; @@ -181,6 +191,41 @@ export function checkGallery(dir: string, opts: CheckOptions): GalleryFinding[] return findings; } +/** The sample data a trial package arrives with: present, a valid non-empty dataset list, and read by the config. */ +function checkSampleData(dir: string, app: GalleryApp, add: AddFinding): void { + const source = `apps/${app.id}/${APP_LAYOUT.source}`; + const config = join(dir, source, SOURCE_REQUIRED); + if (!isFile(config)) return; // an incomplete source is `app-incomplete` already + const rel = `${source}/${SAMPLE_DATA_FILE}`; + const file = join(dir, rel); + if (!isFile(file)) { + add('app-sample-data', rel, `a gallery app is a package a customer installs to try, and it arrives with the card's seed rows as its sample data in ${APP_LAYOUT.source}/${SAMPLE_DATA_FILE}; this one has none`); + return; + } + let raw: unknown; + try { + raw = JSON.parse(readFileSync(file, 'utf8')); + } catch (e) { + add('app-sample-data', rel, `not JSON: ${e instanceof Error ? e.message : String(e)}`); + return; + } + if (!Array.isArray(raw) || raw.length === 0) { + add('app-sample-data', rel, 'the sample data is a non-empty list of stack `data:` datasets, and this is not one'); + return; + } + raw.forEach((dataset, i) => { + const parsed = SeedSchema.safeParse(dataset); + if (!parsed.success) { + for (const issue of parsed.error.issues) add('app-sample-data', rel, `[${i}]${issue.path.length ? `.${issue.path.join('.')}` : ''}: ${issue.message}`); + } else if (parsed.data.records.length === 0) { + add('app-sample-data', rel, `[${i}] (\`${parsed.data.object}\`) holds no record`); + } + }); + if (!readFileSync(config, 'utf8').includes(`'${SAMPLE_DATA_SPECIFIER}'`)) { + add('app-sample-data', `${source}/${SOURCE_REQUIRED}`, `does not import '${SAMPLE_DATA_SPECIFIER}' into its \`data:\`, so the package installs without its sample data`); + } +} + function checkScreenshots(dir: string, app: GalleryApp, add: AddFinding): void { const rel = `apps/${app.id}/${APP_LAYOUT.screenshots}`; if (app.screenshots.length === 0) add('app-screenshots', rel, `index.json lists no screenshot for \`${app.id}\`: an app is shown with its screenshots`); diff --git a/packages/qa/scenarios/src/export/contract.ts b/packages/qa/scenarios/src/export/contract.ts index e3ed1444dac..511aaf0e91d 100644 --- a/packages/qa/scenarios/src/export/contract.ts +++ b/packages/qa/scenarios/src/export/contract.ts @@ -22,6 +22,17 @@ export const APP_LAYOUT = { screenshots: 'screenshots', } as const; +/** + * The trial package's sample data, relative to `apps//source/`: the card's + * seed rows as stack `data:` datasets (`trial-package.ts`), which the check + * requires (`app-sample-data`). + */ +export const SAMPLE_DATA_FILE = 'src/sample-data.json'; + +/** How `source/objectstack.config.ts` imports {@link SAMPLE_DATA_FILE}: the specifier, and the name it binds. */ +export const SAMPLE_DATA_SPECIFIER = `./${SAMPLE_DATA_FILE}`; +export const SAMPLE_DATA_BINDING = 'gallerySampleData'; + /** The package whose npm `latest` is the framework release the gallery follows. */ export const FRAMEWORK_PACKAGE = '@objectstack/cli'; diff --git a/packages/qa/scenarios/src/export/exporter.ts b/packages/qa/scenarios/src/export/exporter.ts index 043bd0c5755..7b14425e4e1 100644 --- a/packages/qa/scenarios/src/export/exporter.ts +++ b/packages/qa/scenarios/src/export/exporter.ts @@ -12,7 +12,10 @@ * 2. ⛔ the run was on published packages ({@link unpublishedRunRefusal}): a * `--packages workspace` run is never exported or shown; * 3. the record passed every half ({@link judgeRecord}); - * 4. the run's scratch project is still on disk, with its build; + * 4. the run's scratch project is still on disk, with its build, and its + * source can be made the trial package ({@link trialPackageSource}): its + * config default-exports a `defineStack({ … })` literal that declares no + * `data:` of its own, and the build declares every object the card seeds; * 5. its transcript joins with the recording ({@link buildTranscript}); * 6. its screenshots were taken, unless the caller turned them off. * @@ -22,7 +25,9 @@ * * apps//README.md what the app is, the driver that ran it ({@link driverText}), what its authoring cost * ({@link authorCostText}: stated only when every authoring turn reported a cost), its scorecard, the files - * apps//source/… the authored metadata source (`source.ts`) + * apps//source/… the authored metadata source (`source.ts`), as a trial package: the + * card's listing text, facet and sample data added after scoring + * (`trial-package.ts`) * apps//run-record.json the run record, the work directories redacted (`workDirsOf`) * apps//scorecard.json|.md the per-half scorecard * apps//transcript.json|.md the per-persona 问数 transcript @@ -59,6 +64,7 @@ import { judgeRecord, type PassJudgement } from './pass.js'; import { readRunRecords, redactWorkDir, unpublishedRunRefusal, type RecordFile, type ScenarioRunRecord } from './record.js'; import type { CaptureScreenshots, PlannedShot, SkippedShot } from './screenshots.js'; import { projectFrameworkVersion, readAuthoredSource } from './source.js'; +import { SAMPLE_DATA_FILE, trialPackageSource } from './trial-package.js'; import { buildTranscript, mergeRecordings, renderTranscript } from './transcript.js'; /** The files of one exported app, relative to `apps//` (`contract.ts`, which the check reads too). */ @@ -130,7 +136,7 @@ export function driverText(driver: ScenarioRunRecord['env']['driver']): string { return named(driver); } -function appReadme(scenario: LoadedScenario, record: ScenarioRunRecord, entry: GalleryApp, judgement: PassJudgement, scorecard: CardScorecard, shots: PlannedShot[], skipped: SkippedShot[]): string { +function appReadme(scenario: LoadedScenario, record: ScenarioRunRecord, entry: GalleryApp, judgement: PassJudgement, scorecard: CardScorecard, shots: PlannedShot[], skipped: SkippedShot[], omitted: readonly string[]): string { const c = scenario.card; const lines = [ `# ${c.title.en}`, @@ -144,6 +150,7 @@ function appReadme(scenario: LoadedScenario, record: ScenarioRunRecord, entry: G `- Driver: ${driverText(record.env.driver)}`, `- Author cost (as the driver reported it): ${authorCostText(scorecard.authorCost)}`, `- 问数: ${entry.qa.questions} questions, ${entry.qa.turns} persona turns · ${entry.operations} write operations`, + `- Sample data: the card's ${Object.values(c.run.seed).reduce((n, rows) => n + rows.length, 0)} seed rows in ${Object.keys(c.run.seed).length} objects${omitted.length ? `, without ${omitted.map((f) => `\`${f}\``).join(', ')} (a user handle of the run's own environment, left unset)` : ''}`, '', '## The requirement', '', @@ -158,7 +165,7 @@ function appReadme(scenario: LoadedScenario, record: ScenarioRunRecord, entry: G '', '## Files', '', - `- [\`${APP_LAYOUT.source}/\`](./${APP_LAYOUT.source}/) — the app's metadata source, as the AI wrote it (after the change request)`, + `- [\`${APP_LAYOUT.source}/\`](./${APP_LAYOUT.source}/) — the app's metadata source, as the AI wrote it (after the change request), with the package's listing text in \`objectstack.manifest.json\` and the card's seed rows as its sample data (\`${SAMPLE_DATA_FILE}\`, read into \`data:\`), both added after scoring`, `- [\`${APP_LAYOUT.transcriptMd}\`](./${APP_LAYOUT.transcriptMd}) — every data question, each persona's answer and its grade ([JSON](./${APP_LAYOUT.transcriptJson}))`, `- [\`${APP_LAYOUT.scorecardMd}\`](./${APP_LAYOUT.scorecardMd}) — the scorecard ([JSON](./${APP_LAYOUT.scorecardJson}))`, `- [\`${APP_LAYOUT.runRecord}\`](./${APP_LAYOUT.runRecord}) — the full run record`, @@ -294,7 +301,10 @@ async function exportOne( if (!existsSync(projectDir)) throw new Refused([`the run's scratch project is gone: ${projectDir}`]); const artifact = readArtifact(projectDir); if (artifact === undefined) throw new Refused([`${projectDir} holds no dist/objectstack.json`]); - const source = readAuthoredSource(projectDir); + const authored = readAuthoredSource(projectDir); + // The trial package's listing text, facet and sample data: added to the exported copy only, after scoring. + const builtObjects = new Set(((artifact as { objects?: Array<{ name?: unknown }> }).objects ?? []).map((o) => o?.name).filter((n): n is string => typeof n === 'string')); + const source = await trialPackageSource(authored.files, card, builtObjects); const frameworkVersion = projectFrameworkVersion(projectDir); const redact = (v: T): T => redactWorkDir(v, workDirsOf(record.evidenceDir, opts.workDir)); const transcript = redact(buildTranscript(scenario, record, turns)); @@ -332,7 +342,7 @@ async function exportOne( [APP_LAYOUT.scorecardMd, `${renderScorecard(scorecard)}\n`], [APP_LAYOUT.transcriptJson, json(transcript)], [APP_LAYOUT.transcriptMd, renderTranscript(transcript, card.title.en)], - [APP_LAYOUT.readme, redact(appReadme(scenario, record, entry, judgement, scorecard, shots, skipped))], + [APP_LAYOUT.readme, redact(appReadme(scenario, record, entry, judgement, scorecard, shots, skipped, source.omitted))], ]); return { entry, shots, skipped }; } diff --git a/packages/qa/scenarios/src/export/index.ts b/packages/qa/scenarios/src/export/index.ts index fcebb696663..41f5dd8586d 100644 --- a/packages/qa/scenarios/src/export/index.ts +++ b/packages/qa/scenarios/src/export/index.ts @@ -20,3 +20,4 @@ export * from './refresh.js'; export * from './screenshots.js'; export * from './source.js'; export * from './transcript.js'; +export * from './trial-package.js'; diff --git a/packages/qa/scenarios/src/export/trial-package.ts b/packages/qa/scenarios/src/export/trial-package.ts new file mode 100644 index 00000000000..3fac7e6f568 --- /dev/null +++ b/packages/qa/scenarios/src/export/trial-package.ts @@ -0,0 +1,209 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What makes an exported app a package a customer can install and try: the + * listing text and facet it is shown with, and the sample data it arrives + * with. The exporter adds these to the app's `source/` AFTER the run is + * scored, so the AI's build is never graded on them, and it never writes + * them into the run's own project. + * + * - `objectstack.manifest.json` gains the card's listing text and facet + * ({@link listingManifest}): `displayName` and `description` are the + * card's English title and one-sentence requirement (`prompt.short`), the + * Chinese pair goes under `translations.zh`, and `businessFunctions` is the + * card's own list, primary first. `os package publish` reads all four off + * this file. + * - `src/sample-data.json` ({@link SAMPLE_DATA_FILE}) holds the card's seed + * rows as stack `data:` datasets ({@link sampleDataOf}): one per object, + * the object named with the app's namespace, keyed on the card's row id + * (`externalId: 'id'`), each row as the card states it. A lookup value + * names a row id of the same load, which the platform's seed loader + * resolves; it orders the objects itself. This is the shape a package's + * `data[]` has, which both the managed install (`seedSampleData`) and the + * unmanaged install's seed copy read. + * - `objectstack.config.ts` reads that file into its `data:` + * ({@link withSampleData}): one import line and one property, spliced + * into the default-exported `defineStack({ … })` literal, every other byte + * as the AI wrote it. + * + * A user-handle field (`run.userHandleFields`, `account.owner` = `u_sam`) is + * left out of every row: its value stands for a user of the run's own + * environment, which an installer's environment does not have, and a faithful + * build models it as a user lookup that refuses the text. The field stays + * unset on the installed rows. + * + * ⛔ The install modes and the solution type are NOT written here: declaring + * `installModes: ['unmanaged']` makes `defineStack` refuse an app that carries + * code `plugins` or `capability` items, which every app on the standard + * scaffold does today. + */ + +import type { LoadedScenario } from '../loader.js'; +import { scenarioNamespace } from '../schema.js'; +import { SAMPLE_DATA_BINDING, SAMPLE_DATA_FILE, SAMPLE_DATA_SPECIFIER } from './contract.js'; + +export { SAMPLE_DATA_BINDING, SAMPLE_DATA_FILE, SAMPLE_DATA_SPECIFIER }; + +/** One stack `data:` dataset, as `src/sample-data.json` holds it. */ +export interface SampleDataset { + object: string; + externalId: 'id'; + records: Array>; +} + +/** The trial package's additions could not be written: one reason each, printed with the export's refusal. */ +export class TrialPackageRefusal extends Error { + constructor(message: string) { + super(message); + this.name = 'TrialPackageRefusal'; + } +} + +/** + * The card's seed rows as stack `data:` datasets, in the card's object order: + * each object named `_`, keyed on `id`, every row as the + * card states it except its user-handle fields (left out, see the module + * header). `omitted` names each `object.field` left out. + */ +export function sampleDataOf(card: LoadedScenario['card']): { datasets: SampleDataset[]; omitted: string[] } { + const ns = scenarioNamespace(card); + const handles = new Set((card.run.userHandleFields ?? []).map((h) => `${h.object}.${h.field}`)); + const omitted = new Set(); + const datasets: SampleDataset[] = []; + for (const [object, rows] of Object.entries(card.run.seed)) { + if (rows.length === 0) continue; + const records = rows.map((row) => { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) { + if (handles.has(`${object}.${k}`)) omitted.add(`${object}.${k}`); + else out[k] = v; + } + return out; + }); + datasets.push({ object: object.startsWith(`${ns}_`) ? object : `${ns}_${object}`, externalId: 'id', records }); + } + return { datasets, omitted: [...omitted].sort() }; +} + +/** + * The project's `objectstack.manifest.json` (its text, or `undefined` when the + * project has none) with the card's listing text and facet set, as the bytes + * to write. Every other key is kept as it was; the four written keys replace + * whatever the build had there. A text that is not a JSON object is refused. + */ +export function listingManifest(text: string | undefined, card: LoadedScenario['card']): string { + let m: Record = {}; + if (text !== undefined) { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (e) { + throw new TrialPackageRefusal(`objectstack.manifest.json is not JSON, so the listing text cannot be added: ${e instanceof Error ? e.message : String(e)}`); + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new TrialPackageRefusal('objectstack.manifest.json is not a JSON object, so the listing text cannot be added'); + m = parsed as Record; + } + const short = card.prompt.short; + const zh = { displayName: card.title.zh, ...(short.zh ? { description: short.zh } : {}) }; + const translations = m.translations !== null && typeof m.translations === 'object' && !Array.isArray(m.translations) ? (m.translations as Record) : {}; + const out: Record = { + ...m, + displayName: card.title.en, + ...(short.en ? { description: short.en } : {}), + businessFunctions: [...card.businessFunctions], + translations: { ...translations, zh }, + }; + return `${JSON.stringify(out, null, 2)}\n`; +} + +/** The TypeScript compiler API, loaded only when an export edits a config. */ +type Ts = typeof import('typescript'); + +const CONFIG_FILE = 'objectstack.config.ts'; +const LISTING_FILE = 'objectstack.manifest.json'; + +/** + * The authored source (`source.ts`, relative path → bytes) as the trial + * package: the listing manifest written, the sample data file added and read + * into the config. `objects` are the object names the run's build declares + * (its `dist/objectstack.json`): a dataset for an object the build lacks would + * make `defineStack` refuse the source, so it is refused here instead. + * Throws {@link TrialPackageRefusal}. + */ +export async function trialPackageSource( + files: ReadonlyMap, + card: LoadedScenario['card'], + objects: ReadonlySet, +): Promise<{ files: Map; omitted: string[] }> { + const config = files.get(CONFIG_FILE); + if (config === undefined) throw new TrialPackageRefusal(`the source holds no ${CONFIG_FILE}`); + if (files.has(SAMPLE_DATA_FILE)) throw new TrialPackageRefusal(`the build already wrote ${SAMPLE_DATA_FILE}, the file the sample data is written to`); + const { datasets, omitted } = sampleDataOf(card); + if (datasets.length === 0) throw new TrialPackageRefusal('the card has no seed rows, so the package would arrive with no sample data'); + const absent = datasets.map((d) => d.object).filter((o) => !objects.has(o)); + if (absent.length > 0) throw new TrialPackageRefusal(`the build declares no object ${absent.map((o) => `\`${o}\``).join(', ')}, which the sample data loads into`); + const mod = (await import('typescript')) as Ts & { default?: Ts }; + const ts = mod.default ?? mod; + const out = new Map(files); + out.set(CONFIG_FILE, Buffer.from(withSampleData(ts, config.toString('utf8')))); + out.set(LISTING_FILE, Buffer.from(listingManifest(files.get(LISTING_FILE)?.toString('utf8'), card))); + out.set(SAMPLE_DATA_FILE, Buffer.from(`${JSON.stringify(datasets, null, 2)}\n`)); + return { files: new Map([...out].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), omitted }; +} + +/** + * `objectstack.config.ts` with the sample data read into the stack: the import + * line `import BINDING from './src/sample-data.json';` after the file's last + * import, and `data: BINDING,` as the first property of the object literal the + * default export hands `defineStack`. Every other byte is kept. + * + * Refused, each with its reason, when the edit cannot be proved safe: the + * default export is not `defineStack({ … })` with an object literal; that + * literal already declares `data` or spreads another value (which may carry + * one); or the binding name is already used in the file. + */ +export function withSampleData(ts: Ts, source: string): string { + const file = ts.createSourceFile('objectstack.config.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); + const literal = defaultStackLiteral(ts, file); + if (!literal) { + throw new TrialPackageRefusal( + 'objectstack.config.ts does not default-export `defineStack({ … })` with an object literal, so the sample data cannot be added to its `data:`', + ); + } + for (const p of literal.properties) { + if (ts.isSpreadAssignment(p)) throw new TrialPackageRefusal('objectstack.config.ts spreads a value into `defineStack({ … })`, which may declare `data:` already, so the sample data is not added'); + const name = p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : undefined; + if (name === 'data') throw new TrialPackageRefusal('objectstack.config.ts already declares `data:`, so the card\'s seed rows are not added as the sample data'); + } + let used = false; + const visit = (n: import('typescript').Node): void => { + if (ts.isIdentifier(n) && n.text === SAMPLE_DATA_BINDING) used = true; + if (!used) ts.forEachChild(n, visit); + }; + visit(file); + if (used) throw new TrialPackageRefusal(`objectstack.config.ts already uses the name \`${SAMPLE_DATA_BINDING}\`, which the sample-data import takes`); + + const imports = file.statements.filter(ts.isImportDeclaration); + const importLine = `import ${SAMPLE_DATA_BINDING} from '${SAMPLE_DATA_SPECIFIER}';`; + const brace = literal.getStart(file) + 1; + const edits: Array<{ at: number; text: string }> = [ + { at: brace, text: `\n // The card's seed rows, the sample data an install loads (added by the gallery export).\n data: ${SAMPLE_DATA_BINDING},` }, + imports.length > 0 ? { at: imports[imports.length - 1]!.getEnd(), text: `\n${importLine}` } : { at: 0, text: `${importLine}\n` }, + ]; + let out = source; + for (const e of edits.sort((a, b) => b.at - a.at)) out = out.slice(0, e.at) + e.text + out.slice(e.at); + return out; +} + +/** The object literal `export default defineStack({ … })` hands over, or `undefined`. */ +function defaultStackLiteral(ts: Ts, file: import('typescript').SourceFile): import('typescript').ObjectLiteralExpression | undefined { + for (const s of file.statements) { + if (!ts.isExportAssignment(s) || s.isExportEquals) continue; + let e = s.expression; + while (ts.isParenthesizedExpression(e) || ts.isSatisfiesExpression(e) || ts.isAsExpression(e)) e = e.expression; + if (!ts.isCallExpression(e) || !ts.isIdentifier(e.expression) || e.expression.text !== 'defineStack') return undefined; + const arg = e.arguments[0]; + return arg !== undefined && ts.isObjectLiteralExpression(arg) ? arg : undefined; + } + return undefined; +} diff --git a/packages/qa/scenarios/test/export/check.test.ts b/packages/qa/scenarios/test/export/check.test.ts index 7abb3a506ce..feb23bc9a99 100644 --- a/packages/qa/scenarios/test/export/check.test.ts +++ b/packages/qa/scenarios/test/export/check.test.ts @@ -18,7 +18,7 @@ import { runCli } from '../../src/bin.js'; import { checkGallery, FINDING_CODES, LOCAL_PATH, renderFinding, type FindingCode, type GalleryFinding } from '../../src/export/check.js'; import { mainCheck } from '../../src/export/check-cli.js'; import { main as exportCliMain } from '../../src/export/cli.js'; -import { APP_LAYOUT } from '../../src/export/contract.js'; +import { APP_LAYOUT, SAMPLE_DATA_FILE, SAMPLE_DATA_SPECIFIER } from '../../src/export/contract.js'; import { exportGallery } from '../../src/export/exporter.js'; import { parseIndex, serializeIndex, type GalleryApp } from '../../src/export/manifest.js'; import type { CaptureScreenshots } from '../../src/export/screenshots.js'; @@ -154,6 +154,50 @@ describe('checkGallery — complete app directories', () => { }); }); +describe('checkGallery — sample data: a gallery app arrives with it', () => { + const SOURCE = `${APP}/${APP_LAYOUT.source}`; + const DATA = `${SOURCE}/${SAMPLE_DATA_FILE}`; + + it('⛔ an app with no sample-data file — the tree an exporter before the trial package wrote — is one finding', () => { + const dir = tree(); + rmSync(join(dir, DATA)); + expect(check(dir).findings).toEqual([ + { + kind: 'app-sample-data', + path: DATA, + message: `a gallery app is a package a customer installs to try, and it arrives with the card's seed rows as its sample data in ${APP_LAYOUT.source}/${SAMPLE_DATA_FILE}; this one has none`, + }, + ]); + }); + + it('a sample-data file that is not JSON, or not a non-empty list', () => { + for (const [text, why] of [['[{', /^not JSON: /], ['[]', /non-empty list/], ['{"object":"democrm_account"}', /non-empty list/]] as const) { + const dir = tree(); + writeFileSync(join(dir, DATA), text); + const fs = only(check(dir).findings, 'app-sample-data'); + expect(fs.map((f) => f.path), text).toEqual([DATA]); + expect(fs[0]!.message, text).toMatch(why); + } + }); + + it("a dataset the spec's SeedSchema refuses, and one with no record, each located by its index", () => { + const dir = tree(); + const data = JSON.parse(readFileSync(join(dir, DATA), 'utf8')) as Array>; + data[0] = { ...data[0], object: 'Democrm Account' }; + data[1] = { ...data[1], records: [] }; + writeFileSync(join(dir, DATA), JSON.stringify(data)); + const fs = only(check(dir).findings, 'app-sample-data'); + expect(fs.map((f) => f.message.split(':')[0])).toEqual(['[0].object', '[1] (`democrm_contact`) holds no record']); + }); + + it('a config that does not import the sample data into its `data:`', () => { + const dir = tree(); + const config = join(dir, SOURCE, 'objectstack.config.ts'); + writeFileSync(config, readFileSync(config, 'utf8').replace(SAMPLE_DATA_SPECIFIER, './src/other.json')); + expect(only(check(dir).findings, 'app-sample-data').map((f) => f.path)).toEqual([`${SOURCE}/objectstack.config.ts`]); + }); +}); + describe('checkGallery — screenshots', () => { it('⛔ an entry with no screenshot fails, and the file it no longer lists is named too', () => { const dir = tree(); @@ -251,7 +295,7 @@ describe('checkGallery — stray files, anywhere in the tree', () => { describe('every finding code has a case above', () => { it('the codes are the ones the header lists', () => { - expect([...FINDING_CODES]).toEqual(['index-json', 'app-missing', 'app-incomplete', 'app-screenshots', 'app-unlisted', 'framework-version', 'env-file', 'node-modules', 'symbolic-link', 'local-path']); + expect([...FINDING_CODES]).toEqual(['index-json', 'app-missing', 'app-incomplete', 'app-sample-data', 'app-screenshots', 'app-unlisted', 'framework-version', 'env-file', 'node-modules', 'symbolic-link', 'local-path']); }); }); diff --git a/packages/qa/scenarios/test/export/exporter.test.ts b/packages/qa/scenarios/test/export/exporter.test.ts index 636b6ce45bb..b3c057665a5 100644 --- a/packages/qa/scenarios/test/export/exporter.test.ts +++ b/packages/qa/scenarios/test/export/exporter.test.ts @@ -14,7 +14,10 @@ import { join, relative } from 'node:path'; import { describe, expect, it } from 'vitest'; +import ts from 'typescript'; + import { exportGallery, scratchProjectDir, type ExportOptions } from '../../src/export/exporter.js'; +import { listingManifest, SAMPLE_DATA_BINDING, SAMPLE_DATA_FILE, sampleDataOf, trialPackageSource, TrialPackageRefusal, withSampleData } from '../../src/export/trial-package.js'; import { GALLERY_GUARD, type GalleryGuard } from '../../src/export/generic.js'; import { GalleryIndexSchema, parseIndex } from '../../src/export/manifest.js'; import { ASK_MODE_NOT_EXPORTED, judgeRecord } from '../../src/export/pass.js'; @@ -164,6 +167,7 @@ describe('exportGallery — one passing, generic app', () => { 'source/package.json', 'source/src/objects/account.object.ts', 'source/src/objects/contact.object.ts', + 'source/src/sample-data.json', 'source/tsconfig.json', 'transcript.json', 'transcript.md', @@ -468,6 +472,179 @@ describe('exportGallery — ⛔ the default guard: origin `generic`, tier `start }); }); +/** + * The shape every generated app's `objectstack.config.ts` starts from: the + * blank scaffold's config (create-objectstack's `templates/blank`), abridged — + * imports, a module-level helper, comments between the keys, a `manifest` + * literal and barrel lists. Inline, not read from that package, so this suite + * declares no input outside its own package. + */ +const SCAFFOLD_SHAPED_CONFIG = `import { defineStack } from '@objectstack/spec'; +import { ConnectorRestPlugin } from './src/plugins'; +import * as objects from './src/objects'; +import * as views from './src/views'; + +// Every value a barrel exports, as the list a stack key takes. +const exportsOf = (barrel: M): M[keyof M][] => Object.values(barrel); + +// This file is a MODULE, and the whole module is the stack. +export default defineStack({ + manifest: { + id: 'com.example.demotravel', + namespace: 'demotravel', + version: '0.1.0', + type: 'app', + name: 'Travel Expense', + // Protocol compatibility range. + engines: { protocol: '^18' }, + }, + + requires: ['automation', 'triggers'], + + // Generic connector executors, default-present. + plugins: [ + new ConnectorRestPlugin(), + ], + + objects: exportsOf(objects), + views: exportsOf(views), +}); +`; + +/** The `defineStack({ … })` literal's property names, and the module's import specifiers, read back with the compiler. */ +function stackShape(text: string): { keys: string[]; imports: string[]; data?: string } { + const file = ts.createSourceFile('objectstack.config.ts', text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); + const diagnostics = (file as unknown as { parseDiagnostics: unknown[] }).parseDiagnostics; + expect(diagnostics).toEqual([]); + const imports = file.statements.filter(ts.isImportDeclaration).map((d) => (d.moduleSpecifier as ts.StringLiteral).text); + const exported = file.statements.find(ts.isExportAssignment)!; + const literal = (exported.expression as ts.CallExpression).arguments[0] as ts.ObjectLiteralExpression; + const props = literal.properties.filter(ts.isPropertyAssignment); + const data = props.find((p) => (p.name as ts.Identifier).text === 'data'); + return { keys: props.map((p) => (p.name as ts.Identifier).text), imports, ...(data ? { data: data.initializer.getText(file) } : {}) }; +} + +describe('exportGallery — the trial package: listing text, facet and sample data, added after scoring', () => { + it("source/ carries the card's listing text and facet, its seed rows as sample data, and a config that reads them", async () => { + const { out, fx, opts } = await setup(); + const s = await exportGallery(opts()); + expect(s.refused).toEqual([]); + const source = join(out, 'apps', CARD_ID, 'source'); + const card = fx.scenario.card; + + // objectstack.manifest.json: the build's own keys kept, the four listing keys written. + expect(JSON.parse(readFileSync(join(source, 'objectstack.manifest.json'), 'utf8'))).toEqual({ + id: 'com.example.democrm', + displayName: card.title.en, + description: card.prompt.short.en, + businessFunctions: ['sales'], + translations: { zh: { displayName: card.title.zh, description: card.prompt.short.zh } }, + }); + + // src/sample-data.json: one dataset per seeded object, namespaced, keyed on the card's row id; the user handle left out. + const data = JSON.parse(readFileSync(join(source, SAMPLE_DATA_FILE), 'utf8')) as Array<{ object: string; externalId: string; records: Array> }>; + expect(data.map((d) => [d.object, d.externalId, d.records.length])).toEqual([ + ['democrm_account', 'id', card.run.seed.account!.length], + ['democrm_contact', 'id', card.run.seed.contact!.length], + ]); + expect(data[0]!.records[0]).toEqual({ id: 'ac1', name: 'Acme', industry: 'tech', employees: 120 }); + expect(data[1]!.records[0]).toEqual(card.run.seed.contact![0]); + expect(data.flatMap((d) => d.records).some((r) => 'owner' in r)).toBe(false); + + // objectstack.config.ts: the import and the `data:` property, and every other byte as the AI wrote it. + const config = readFileSync(join(source, 'objectstack.config.ts'), 'utf8'); + expect(stackShape(config)).toEqual({ keys: ['data', 'manifest'], imports: ['@objectstack/spec', `./${SAMPLE_DATA_FILE}`], data: SAMPLE_DATA_BINDING }); + const authored = readFileSync(join(scratchProjectDir(fx.work, card), 'objectstack.config.ts'), 'utf8'); + expect(config.replace(`\nimport ${SAMPLE_DATA_BINDING} from './${SAMPLE_DATA_FILE}';`, '').replace(/\n \/\/ The card's seed rows[^\n]*\n data: gallerySampleData,/, '')).toBe(authored); + // ⛔ After scoring, into the export only: the run's own project is as the AI left it. + expect(authored).not.toContain(SAMPLE_DATA_BINDING); + expect(existsSync(join(scratchProjectDir(fx.work, card), SAMPLE_DATA_FILE))).toBe(false); + + const readme = readFileSync(join(out, 'apps', CARD_ID, 'README.md'), 'utf8'); + expect(readme).toContain("- Sample data: the card's 8 seed rows in 2 objects, without `account.owner` (a user handle of the run's own environment, left unset)"); + }); + + it("a scaffold-shaped config gains one import and one `data:` property; the rest of the file is byte for byte", () => { + const scaffold = SCAFFOLD_SHAPED_CONFIG; + const edited = withSampleData(ts, scaffold); + const before = stackShape(scaffold); + const after = stackShape(edited); + expect(after.keys).toEqual(['data', ...before.keys]); + expect(after.imports).toEqual([...before.imports, `./${SAMPLE_DATA_FILE}`]); + expect(after.data).toBe(SAMPLE_DATA_BINDING); + expect(before.keys).not.toContain('data'); + expect(edited.replace(`\nimport ${SAMPLE_DATA_BINDING} from './${SAMPLE_DATA_FILE}';`, '').replace(/\n \/\/ The card's seed rows[^\n]*\n data: gallerySampleData,/, '')).toBe(scaffold); + expect(edited.length - scaffold.length).toBe( + `\nimport ${SAMPLE_DATA_BINDING} from './${SAMPLE_DATA_FILE}';`.length + `\n // The card's seed rows, the sample data an install loads (added by the gallery export).\n data: ${SAMPLE_DATA_BINDING},`.length, + ); + }); + + it('a config with no import line takes the import as its first line', () => { + const edited = withSampleData(ts, "export default defineStack({ manifest: { id: 'com.example.democrm' } });\n"); + expect(edited.startsWith(`import ${SAMPLE_DATA_BINDING} from './${SAMPLE_DATA_FILE}';\n`)).toBe(true); + expect(stackShape(edited).keys).toEqual(['data', 'manifest']); + }); + + it.each([ + ['declares `data:` already', "import { defineStack } from '@objectstack/spec';\nexport default defineStack({ manifest: {}, data: [] });\n", /already declares `data:`/], + ['declares `data` as a shorthand property', "import { defineStack } from '@objectstack/spec';\nconst data = [];\nexport default defineStack({ manifest: {}, data });\n", /already declares `data:`/], + ['spreads a value into the literal', "import { defineStack } from '@objectstack/spec';\nconst base = {};\nexport default defineStack({ ...base, manifest: {} });\n", /spreads a value/], + ['default-exports a binding, not the call', "import { defineStack } from '@objectstack/spec';\nconst stack = defineStack({ manifest: {} });\nexport default stack;\n", /does not default-export `defineStack\(\{ … \}\)`/], + ['hands `defineStack` no object literal', "import { defineStack } from '@objectstack/spec';\nimport base from './base';\nexport default defineStack(base);\n", /does not default-export `defineStack\(\{ … \}\)`/], + ['already uses the import binding name', `import { defineStack } from '@objectstack/spec';\nconst ${SAMPLE_DATA_BINDING} = 1;\nexport default defineStack({ manifest: {} });\n`, /already uses the name/], + ])('⛔ refused, never guessed: a config that %s', (_, text, why) => { + expect(() => withSampleData(ts, text)).toThrow(TrialPackageRefusal); + expect(() => withSampleData(ts, text)).toThrow(why); + }); + + it('⛔ refused: a seeded object the build does not declare, a build that wrote the sample-data file itself, a card with no seed rows', async () => { + const card = loadCrm().card; + const files = new Map([['objectstack.config.ts', Buffer.from("export default defineStack({ manifest: {} });\n")]]); + await expect(trialPackageSource(files, card, new Set(['democrm_account']))).rejects.toThrow('the build declares no object `democrm_contact`, which the sample data loads into'); + const both = new Set(['democrm_account', 'democrm_contact']); + await expect(trialPackageSource(new Map([...files, [SAMPLE_DATA_FILE, Buffer.from('[]')]]), card, both)).rejects.toThrow(`the build already wrote ${SAMPLE_DATA_FILE}`); + await expect(trialPackageSource(files, { ...card, run: { ...card.run, seed: {} } }, both)).rejects.toThrow('the card has no seed rows'); + const ok = await trialPackageSource(files, card, both); + expect([...ok.files.keys()]).toEqual(['objectstack.config.ts', 'objectstack.manifest.json', SAMPLE_DATA_FILE]); + expect(ok.omitted).toEqual(['account.owner']); + }); + + it('an export whose config already declares `data:` is refused with the reason, and no app directory is written', async () => { + const { out, fx, opts } = await setup(); + const config = join(scratchProjectDir(fx.work, fx.scenario.card), 'objectstack.config.ts'); + writeFileSync(config, "import { defineStack } from '@objectstack/spec';\nexport default defineStack({ manifest: { id: 'com.example.democrm', namespace: 'democrm' }, data: [] });\n"); + const s = await exportGallery(opts()); + expect(s.refused).toEqual([{ id: CARD_ID, reasons: ["objectstack.config.ts already declares `data:`, so the card's seed rows are not added as the sample data"] }]); + expect(existsSync(join(out, 'apps', CARD_ID))).toBe(false); + }); + + it('listingManifest: no file is an empty one; a translations map keeps its other locales; a text that is not a JSON object is refused', () => { + const card = loadCrm().card; + expect(JSON.parse(listingManifest(undefined, card)).displayName).toBe(card.title.en); + const kept = JSON.parse(listingManifest(JSON.stringify({ readmePath: 'README.md', displayName: 'Democrm', translations: { ja: { displayName: 'CRM' } } }), card)); + expect(kept).toEqual({ + readmePath: 'README.md', + displayName: card.title.en, + description: card.prompt.short.en, + businessFunctions: ['sales'], + translations: { ja: { displayName: 'CRM' }, zh: { displayName: card.title.zh, description: card.prompt.short.zh } }, + }); + expect(() => listingManifest('{ not json', card)).toThrow(/is not JSON/); + expect(() => listingManifest('[]', card)).toThrow(/is not a JSON object/); + }); + + it("sampleDataOf: every card in the library loads into its own namespace's objects, keyed on id, with each row's fields as the card states them", () => { + for (const { card } of loadAllCards()) { + const { datasets, omitted } = sampleDataOf(card); + const handles = new Set((card.run.userHandleFields ?? []).map((h) => `${h.object}.${h.field}`)); + expect(datasets.map((d) => d.object), card.id).toEqual(Object.keys(card.run.seed).map((o) => `demo${card.code}_${o}`)); + for (const d of datasets) expect(d.externalId).toBe('id'); + expect(datasets.reduce((n, d) => n + d.records.length, 0), card.id).toBe(Object.values(card.run.seed).reduce((n, rows) => n + rows.length, 0)); + expect(omitted, card.id).toEqual([...handles].sort()); + } + }); +}); + describe('exportGallery — what it refuses', () => { it('an asked turn with no recorded reply is refused: a grade is never shown without its answer', async () => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a0dc9c04fb7..fe4613c9eb2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2574,6 +2574,9 @@ importers: playwright-core: specifier: 1.63.0 version: 1.63.0 + typescript: + specifier: ^6.0.3 + version: 6.0.3 zod: specifier: ^4.6.6 version: 4.6.7 @@ -2581,9 +2584,6 @@ importers: '@types/node': specifier: ^26.6.5 version: 26.6.5 - typescript: - specifier: ^6.0.3 - version: 6.0.3 vitest: specifier: ^4.1.11 version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1))