Skip to content

Commit 8d75056

Browse files
committed
build(scenarios): a minimal unpublished tsup build and a narrow ./score entry
@objectstack/scenarios exported .ts sources only, so a consumer that links the framework tree and bundles its own entry with tsup (which leaves the dependency external) could not load ./score under plain Node: ERR_MODULE_NOT_FOUND on the .js specifiers, ESM and CJS alike. - tsup builds dist/ (ESM .js, CJS .cjs, .d.ts/.d.cts) per export subpath; the package stays private and unpublished, and the suites and run-scenarios keep reading src/. - ./score is now the narrow entry (src/score/narrow.ts, re-exports only): graph-shape scorer, naming, operation and run graders. Its import graph reads @objectstack/core and @objectstack/spec, never objectql or plugin-sharing. ./score/full is the previous whole entry (src/score/index.ts, unchanged code). - turbo runs the package's own build before its test, which now includes a tsup-built consumer loaded by plain Node with a resolve recorder. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwgUKpQgCE3UWsA74d
1 parent 0e88208 commit 8d75056

10 files changed

Lines changed: 335 additions & 15 deletions

File tree

‎docs/qa/scenarios/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,6 @@ meet this floor:
165165
## Running the cards
166166

167167
`pnpm --filter @objectstack/scenarios run-scenarios` builds, runs and iterates every card here with a local
168-
Claude Code session, and writes one run record per card. Grading uses `@objectstack/scenarios/score`; no
168+
Claude Code session, and writes one run record per card. Grading uses `@objectstack/scenarios/score/full`; no
169169
API-billed model is used. The runner reads a card's names relative to the card's namespace
170170
(`account` → `democrm_account`), and a build that names any item without the prefix fails its Build half. Flags and modes: [the package README](../../../packages/qa/scenarios/README.md#running-the-cards--objectstackscenariosrunner).

‎packages/qa/scenarios/README.md‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,28 @@ for (const r of refusals) console.error(formatRefusal(r)); // FILE: FIELD.PATH:
1818
seed does not determine.
1919
- `src/loader.ts` — reads a directory of cards, validates shape and cross-references, and
2020
returns typed cards or located refusals.
21-
- `src/score/` — the deterministic scorer, entry `@objectstack/scenarios/score` (below).
21+
- `src/score/` — the deterministic scorer, entries `@objectstack/scenarios/score` and
22+
`@objectstack/scenarios/score/full` (below).
2223

23-
No build step (`exports` points at `src`), and nothing here calls a model or the network.
24+
Not published. `pnpm --filter @objectstack/scenarios build` (tsup) writes `dist/` as ESM, CJS and
25+
`.d.ts`, and every `exports` subpath points there, so a consumer that links the framework tree
26+
and bundles its own entry can load the scorer under plain Node. The suites and `run-scenarios`
27+
read `src/` directly. Nothing here calls a model or the network.
2428

2529
## Scoring a run against a card — `@objectstack/scenarios/score`
2630

27-
Every function takes a card the loader returned, so it judges against the loader's computed
28-
truths and declared outcomes:
31+
`@objectstack/scenarios/score` is the narrow entry (`src/score/narrow.ts`): the graph-shape
32+
scorer (`scoreGraphShape`, `artifactToEvalGraph`), the item-name check and the run and
33+
operation graders. Its import graph reads `@objectstack/core` and `@objectstack/spec` only
34+
(pinned by `test/build/`). `@objectstack/scenarios/score/full` (`src/score/index.ts`) adds the
35+
capability-tag checks, which read `@objectstack/objectql` and `@objectstack/plugin-sharing`, and
36+
the card-level functions below.
37+
38+
Every card-level function takes a card the loader returned, so it judges against the loader's
39+
computed truths and declared outcomes:
2940

3041
```ts
31-
import { gradeCardAnswer, gradeCardOperation, scoreCardArtifact } from '@objectstack/scenarios/score';
42+
import { gradeCardAnswer, gradeCardOperation, scoreCardArtifact } from '@objectstack/scenarios/score/full';
3243

3344
scoreCardArtifact(card, artifact); // a built dist/objectstack.json: expect, tags, agent actions
3445
gradeCardOperation(card, 'remove_chen', observed); // an observed write against its declared outcome

‎packages/qa/scenarios/package.json‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,54 @@
33
"version": "0.1.0",
44
"private": true,
55
"license": "Apache-2.0",
6-
"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, no build step, no model calls: a devx instrument, not a protocol (packages/spec carries no obligation for this format).",
6+
"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).",
77
"type": "module",
8+
"main": "dist/index.js",
9+
"types": "dist/index.d.ts",
810
"exports": {
9-
".": "./src/index.ts",
10-
"./score": "./src/score/index.ts",
11-
"./runner": "./src/runner/index.ts"
11+
".": {
12+
"import": {
13+
"types": "./dist/index.d.ts",
14+
"default": "./dist/index.js"
15+
},
16+
"require": {
17+
"types": "./dist/index.d.cts",
18+
"default": "./dist/index.cjs"
19+
}
20+
},
21+
"./score": {
22+
"import": {
23+
"types": "./dist/score.d.ts",
24+
"default": "./dist/score.js"
25+
},
26+
"require": {
27+
"types": "./dist/score.d.cts",
28+
"default": "./dist/score.cjs"
29+
}
30+
},
31+
"./score/full": {
32+
"import": {
33+
"types": "./dist/score-full.d.ts",
34+
"default": "./dist/score-full.js"
35+
},
36+
"require": {
37+
"types": "./dist/score-full.d.cts",
38+
"default": "./dist/score-full.cjs"
39+
}
40+
},
41+
"./runner": {
42+
"import": {
43+
"types": "./dist/runner.d.ts",
44+
"default": "./dist/runner.js"
45+
},
46+
"require": {
47+
"types": "./dist/runner.d.cts",
48+
"default": "./dist/runner.cjs"
49+
}
50+
}
1251
},
1352
"scripts": {
53+
"build": "tsup && node ../../../scripts/check-dts-emitted.mjs",
1454
"test": "vitest run",
1555
"typecheck": "tsc --noEmit",
1656
"run-scenarios": "tsx src/runner/cli.ts"

‎packages/qa/scenarios/src/score/index.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

33
/**
4-
* `@objectstack/scenarios/score` — score a LOADED card against what a run
5-
* produced: a built artifact (`dist/objectstack.json`), an observed write, or
6-
* an agent's answer. The entry the scenario runner calls; private, like the
7-
* rest of this package.
4+
* `@objectstack/scenarios/score/full` — score a LOADED card against what a
5+
* run produced: a built artifact (`dist/objectstack.json`), an observed write,
6+
* or an agent's answer. The entry the scenario runner calls; private, like the
7+
* rest of this package. The narrow `@objectstack/scenarios/score` is
8+
* `./narrow.ts`: everything here except the capability-tag checks and the
9+
* card-level functions below.
810
*
911
* Every function takes a {@link LoadedScenario} (what `loadScenarios` /
1012
* `loadScenarioFile` return), so the card it judges against has already passed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `@objectstack/scenarios/score` — the NARROW scorer entry (#30915): the
5+
* graph-shape scorer (`scoreGraphShape`, `scoreGraph`, `artifactToEvalGraph`),
6+
* the item-name check, the operation grader and the run graders
7+
* (`gradeRun`, `gradePersonaRun`).
8+
*
9+
* Its import graph reaches `@objectstack/core` and `@objectstack/spec` and no
10+
* other runtime package. The capability-tag checks (`scenario-tags.ts`) read
11+
* `@objectstack/objectql` and `@objectstack/plugin-sharing`, so they and the
12+
* card-level wrappers beside them (`scoreCardArtifact`, `gradeCardOperation`,
13+
* `gradeCardAnswer`) are `@objectstack/scenarios/score/full`
14+
* (`./index.ts`), which re-exports everything here as well.
15+
*
16+
* Re-exports only: the modules stay where they are. Pinned by
17+
* test/build/narrow-score-graph.test.ts.
18+
*/
19+
20+
export * from './scenario-graph.js';
21+
export * from './scenario-naming.js';
22+
export * from './scenario-operation-grade.js';
23+
export * from './scenario-run-grade.js';
24+
export * from './scenario-score.js';
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A BUILT consumer of `@objectstack/scenarios/score` (#30915): a throwaway
5+
* package that depends on this one, bundles its own entry with tsup (which
6+
* leaves a `dependencies` entry external), and is then loaded by plain Node,
7+
* the way a linked framework tree's consumer loads it at boot. Before the
8+
* package had a build step its exports named `.ts` files whose `.js`
9+
* specifiers only a TypeScript resolver follows, so this load failed with
10+
* ERR_MODULE_NOT_FOUND under both module kinds.
11+
*
12+
* The child process records every module it resolves (`module.registerHooks`),
13+
* so the narrow entry's runtime graph is read, not inferred: no
14+
* `@objectstack/objectql` or `@objectstack/plugin-sharing` file loads.
15+
*
16+
* Reads `dist/`: turbo runs this package's own `build` before its `test`.
17+
*/
18+
19+
import { execFileSync } from 'node:child_process';
20+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
21+
import { createRequire } from 'node:module';
22+
import { tmpdir } from 'node:os';
23+
import { dirname, join, resolve } from 'node:path';
24+
import { fileURLToPath, pathToFileURL } from 'node:url';
25+
26+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
27+
28+
const PKG = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
29+
const REPO = resolve(PKG, '../../..');
30+
const BUILT = ['score.js', 'score.cjs', 'score.d.ts', 'score.d.cts'].map((f) => join(PKG, 'dist', f));
31+
32+
const TSUP_PKG = createRequire(join(REPO, 'package.json')).resolve('tsup/package.json');
33+
const TSUP_BIN = join(dirname(TSUP_PKG), (JSON.parse(readFileSync(TSUP_PKG, 'utf8')) as { bin: { tsup: string } }).bin.tsup);
34+
35+
const ENTRY = `
36+
import { scoreGraphShape } from '@objectstack/scenarios/score';
37+
38+
export const shape = () =>
39+
scoreGraphShape({ objects: [{ name: 'loan', fields: [{ name: 'title', type: 'text' }] }] }, { minObjects: 1 });
40+
41+
export const loadScore = () => import('@objectstack/scenarios/score');
42+
`;
43+
44+
// Preloaded into the child: every URL Node resolves, printed as the last line.
45+
const RECORDER = `
46+
const { registerHooks } = require('node:module');
47+
const seen = [];
48+
registerHooks({ resolve(specifier, context, next) { const r = next(specifier, context); seen.push(r.url); return r; } });
49+
process.on('exit', () => process.stdout.write('\\n' + JSON.stringify(seen) + '\\n'));
50+
`;
51+
52+
let fixture = '';
53+
54+
function runNode(code: string, kind: 'module' | 'commonjs'): { out: Record<string, unknown>; resolved: string[] } {
55+
const stdout = execFileSync(process.execPath, ['--require', join(fixture, 'recorder.cjs'), `--input-type=${kind}`, '-e', code], {
56+
cwd: fixture,
57+
encoding: 'utf8',
58+
});
59+
const lines = stdout.trim().split('\n');
60+
return { out: JSON.parse(lines[0]!) as Record<string, unknown>, resolved: JSON.parse(lines.at(-1)!) as string[] };
61+
}
62+
63+
const probe = (mod: string) => `
64+
const m = ${mod};
65+
const s = await m.loadScore();
66+
const r = m.shape();
67+
console.log(JSON.stringify({ shape: typeof s.scoreGraphShape, run: typeof s.gradePersonaRun, tags: typeof s.scoreScenarioArtifact, score: r.score, total: r.total }));
68+
`;
69+
70+
describe('a tsup-built consumer of @objectstack/scenarios/score', () => {
71+
beforeAll(() => {
72+
const missing = BUILT.filter((f) => !existsSync(f));
73+
if (missing.length > 0) throw new Error(`build @objectstack/scenarios first (pnpm --filter @objectstack/scenarios build): missing ${missing.join(', ')}`);
74+
75+
fixture = mkdtempSync(join(tmpdir(), 'scenarios-built-consumer-'));
76+
writeFileSync(
77+
join(fixture, 'package.json'),
78+
JSON.stringify({ name: 'scenarios-built-consumer', private: true, type: 'module', dependencies: { '@objectstack/scenarios': 'workspace:*' } }),
79+
);
80+
mkdirSync(join(fixture, 'src'));
81+
writeFileSync(join(fixture, 'src/index.ts'), ENTRY);
82+
writeFileSync(join(fixture, 'recorder.cjs'), RECORDER);
83+
mkdirSync(join(fixture, 'node_modules/@objectstack'), { recursive: true });
84+
symlinkSync(PKG, join(fixture, 'node_modules/@objectstack/scenarios'), 'dir');
85+
86+
execFileSync(process.execPath, [TSUP_BIN, 'src/index.ts', '--format', 'esm,cjs', '--target', 'es2020', '--silent'], {
87+
cwd: fixture,
88+
stdio: 'pipe',
89+
});
90+
}, 120_000);
91+
92+
afterAll(() => {
93+
if (fixture) rmSync(fixture, { recursive: true, force: true });
94+
});
95+
96+
it('leaves the scorer external: the bundle imports it, it does not carry it', () => {
97+
for (const out of ['dist/index.js', 'dist/index.cjs']) {
98+
const text = readFileSync(join(fixture, out), 'utf8');
99+
expect(text, out).toContain('@objectstack/scenarios/score');
100+
expect(text, out).not.toContain('PLATFORM_OBJECT_PREFIX');
101+
}
102+
});
103+
104+
it.each([
105+
['ESM', 'module', `await import(${JSON.stringify('PLACEHOLDER')})`, 'dist/index.js'],
106+
['CJS', 'commonjs', `require(${JSON.stringify('PLACEHOLDER')})`, 'dist/index.cjs'],
107+
] as const)('loads under plain Node (%s) and reaches neither objectql nor plugin-sharing', (_kind, inputType, load, file) => {
108+
const target = inputType === 'module' ? pathToFileURL(join(fixture, file)).href : join(fixture, file);
109+
const body = probe(load.replace('PLACEHOLDER', target));
110+
const { out, resolved } = runNode(inputType === 'module' ? body : `(async () => { ${body} })()`, inputType);
111+
112+
expect(out).toEqual({ shape: 'function', run: 'function', tags: 'undefined', score: 1, total: 1 });
113+
const scorer = resolved.filter((u) => u.includes('/qa/scenarios/dist/'));
114+
expect(scorer.length, 'the scorer is loaded from its dist').toBeGreaterThan(0);
115+
expect(resolved.filter((u) => u.includes('/qa/scenarios/src/'))).toEqual([]);
116+
expect(resolved.filter((u) => /objectql|plugin-sharing/.test(u))).toEqual([]);
117+
// Control: the recorder sees the scorer's own runtime imports.
118+
expect(resolved.some((u) => u.includes('/packages/core/'))).toBe(true);
119+
});
120+
});
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The narrow scorer entry's SOURCE import graph (#30915): everything
5+
* `src/score/narrow.ts` (`@objectstack/scenarios/score`) reaches through
6+
* relative imports, type-only ones included, names no `@objectstack/objectql`
7+
* or `@objectstack/plugin-sharing` specifier. Read from the checkout, so it
8+
* holds without a build; test/build/built-consumer.test.ts reads the same
9+
* fact off the built entry at runtime.
10+
*
11+
* The control leg walks the full entry (`src/score/index.ts`, `./score/full`)
12+
* with the same walker and must find both packages: a walker that sees no
13+
* import at all would pass the narrow leg too.
14+
*/
15+
16+
import { readFileSync } from 'node:fs';
17+
import { dirname, resolve } from 'node:path';
18+
import { fileURLToPath } from 'node:url';
19+
20+
import { describe, expect, it } from 'vitest';
21+
22+
const SRC = resolve(dirname(fileURLToPath(import.meta.url)), '../../src');
23+
const FORBIDDEN = ['@objectstack/objectql', '@objectstack/plugin-sharing'];
24+
25+
// `import … from 'x'`, `export … from 'x'`, `import 'x'`, `import('x')`.
26+
const SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(?\s*)['"]([^'"]+)['"]/g;
27+
28+
/** Bare specifiers reached from `entry`, each with the first file that imports it. */
29+
function bareImports(entry: string): Map<string, string> {
30+
const bare = new Map<string, string>();
31+
const seen = new Set<string>();
32+
const queue = [resolve(SRC, entry)];
33+
while (queue.length > 0) {
34+
const file = queue.shift()!;
35+
if (seen.has(file)) continue;
36+
seen.add(file);
37+
const text = readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
38+
for (const [, spec] of text.matchAll(SPECIFIER)) {
39+
if (spec.startsWith('.')) queue.push(resolve(dirname(file), spec.replace(/\.js$/, '.ts')));
40+
else if (!bare.has(spec)) bare.set(spec, file.slice(SRC.length + 1));
41+
}
42+
}
43+
return bare;
44+
}
45+
46+
const reaches = (bare: Map<string, string>, pkg: string) =>
47+
[...bare.keys()].filter((s) => s === pkg || s.startsWith(`${pkg}/`));
48+
49+
describe('the ./score entry import graph', () => {
50+
it('reaches neither objectql nor plugin-sharing', () => {
51+
const bare = bareImports('score/narrow.ts');
52+
for (const pkg of FORBIDDEN) expect(reaches(bare, pkg), `${pkg} via ${bare.get(pkg)}`).toEqual([]);
53+
// What it does read: the core stack-collection rule and the spec.
54+
expect([...bare.keys()].filter((s) => s.startsWith('@objectstack/')).sort()).toEqual([
55+
'@objectstack/core',
56+
'@objectstack/spec/api',
57+
'@objectstack/spec/data',
58+
'@objectstack/spec/meta-spelling',
59+
]);
60+
});
61+
62+
it('control: the same walker finds both packages from ./score/full', () => {
63+
const bare = bareImports('score/index.ts');
64+
for (const pkg of FORBIDDEN) expect(reaches(bare, pkg)).toEqual([pkg]);
65+
});
66+
});
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"extends": "../../../tsconfig.base.json",
3+
"compilerOptions": {
4+
"outDir": "./dist",
5+
"rootDir": "./src",
6+
"types": [
7+
"node"
8+
]
9+
},
10+
"include": [
11+
"src/**/*"
12+
],
13+
"exclude": [
14+
"node_modules",
15+
"dist"
16+
]
17+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { defineConfig } from 'tsup';
4+
5+
import { dropSourcesContent } from '../../../scripts/tsup-drop-sources-content.mjs';
6+
7+
/**
8+
* A minimal build for a PRIVATE package (#30915): it is never published, but a
9+
* consumer that links the framework tree and bundles its own entry with tsup
10+
* leaves `@objectstack/scenarios` external, so plain Node must be able to load
11+
* it. The `.ts` sources import with `.js` specifiers, which only a TypeScript
12+
* resolver follows: `dist/` is what Node loads (ESM `.js`, CJS `.cjs`).
13+
*
14+
* One entry per export-map subpath. `score` is the narrow scorer
15+
* (`src/score/narrow.ts`): it reads `@objectstack/core` and `@objectstack/spec`
16+
* only. `score-full` is the whole scorer (`src/score/index.ts`), whose
17+
* capability-tag checks read `@objectstack/objectql` and
18+
* `@objectstack/plugin-sharing`. `splitting: false` keeps each entry one file,
19+
* so an entry's external imports are exactly the ones its own graph reaches.
20+
*
21+
* Dependencies stay external (tsup's default for `dependencies`); the source
22+
* suites and `run-scenarios` keep reading `src/` and never this output.
23+
*/
24+
export default defineConfig({
25+
entry: {
26+
index: 'src/index.ts',
27+
score: 'src/score/narrow.ts',
28+
'score-full': 'src/score/index.ts',
29+
runner: 'src/runner/index.ts',
30+
},
31+
tsconfig: 'tsconfig.build.json',
32+
splitting: false,
33+
sourcemap: true,
34+
clean: true,
35+
dts: !process.env.OS_SKIP_DTS,
36+
format: ['esm', 'cjs'],
37+
target: 'es2020',
38+
shims: true,
39+
esbuildOptions: dropSourcesContent,
40+
});

‎turbo.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -701,7 +701,7 @@
701701
]
702702
},
703703
"@objectstack/scenarios#test": {
704-
"dependsOn": ["^build"],
704+
"dependsOn": ["build"],
705705
"outputs": [],
706706
"env": ["OS_TEST_TIERS"],
707707
"inputs": [

0 commit comments

Comments
 (0)