diff --git a/.changeset/36073-masking-off-ask-round.md b/.changeset/36073-masking-off-ask-round.md new file mode 100644 index 00000000000..455296c30ba --- /dev/null +++ b/.changeset/36073-masking-off-ask-round.md @@ -0,0 +1,10 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): `--schema-masking off` runs a recorded masking-off round, so the field-level-security question can be asked on the open cards + +Clause-②: yes (widening) — the new CLI flag `--schema-masking on|off` on `objectstack-scenarios run` / `run-scenarios` (`cli.ts`); through `./runner`, the new module `schema-masking.ts` and its exports `SCHEMA_MASKING_SETTINGS`, `SchemaMasking`, `schemaMaskingRefusal`, `roundSchemaMasking`, `schemaMaskingHostEnv` and `schemaMaskingText`, the new optional field `RunRecordMeta.schemaMasking` (`scorecard.ts`), and `TABLE_DIMENSIONS` gaining `'schema masking'` (`summary.ts`); the new export `bootEnv` and optional field `CliArgs.schemaMasking` of `cli.ts`, reached by the bin's built `cli` entry, not an export-map subpath; the run record's new optional key `env.schemaMasking` (`"off"`), written only by a masking-off round; a new runtime dependency on `@objectstack/metadata-core`, already in the package's dependency closure. A run started as before keeps running: one whose environment sets `OS_ALLOW_UNMASKED_OBJECT_METADATA` to a value that turns masking off now also stamps `env.schemaMasking: "off"` on its records, where it used to run with masking off and say nothing of it. +Metadata-protocol: none + +Every app the runner boots masks each caller's object schema to the fields it may read (ADR-0106), and every card persona is a plain member, so a field a card withholds from a persona did not exist for it, and the ruled field-level-security question could not be asked. `--schema-masking off` boots each app of the run with `OS_ALLOW_UNMASKED_OBJECT_METADATA=1` (ADR-0106 D8), on the app's process only. The cards' member-withheld field questions (`department_budgets` asked as `employee`) then grade the ruled way: a reply that the field is not visible to the persona passes, one that calls it blank or empty fails. Every record of such a round carries `env.schemaMasking: "off"`, and `summary` refuses a table whose runs differ in schema masking. The variable exported in the shell (every booted app inherits it) makes a masking-off round too, recorded as one, read with the metadata plane's own predicate; `--schema-masking on` beside it is refused. A default round's record keeps its bytes. diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index f9f4d079f66..11f7ba710c2 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -243,6 +243,7 @@ pnpm --filter @objectstack/scenarios run-scenarios --effort medium # t pnpm --filter @objectstack/scenarios run-scenarios --author-effort high --ask-effort low # build and persona turns apart pnpm --filter @objectstack/scenarios run-scenarios --lang zh --prompt short # the card's Chinese texts, and its short build prompt (default: en, else zh; detailed) pnpm --filter @objectstack/scenarios run-scenarios --packages workspace # on this checkout's unreleased packages (default: published) +pnpm --filter @objectstack/scenarios run-scenarios --modes ask --template dist/objectstack.json --schema-masking off # a masking-off round (below) pnpm --filter @objectstack/scenarios run-scenarios --modes door --door-skills "$PWD/skills" # build through the MCP draft door, no project (below) pnpm --filter @objectstack/scenarios run-scenarios --modes door --door-rules builtin # the same, with the built-in authoring rules (below) ``` @@ -271,7 +272,7 @@ files only: no model, no network, and no score of its own — every figure is th `this run’s from-scratch build` takes that run's scratch author. - **Never summed silently**: a table's runs must share the prompt choice, the package source, the ask repeats and the driver (a replay is its own driver), the ask skills (`--ask-skills`: names and sha256; a record without them - reads `none`), the door arm (`--modes door`, below; a record without one reads `skills: none · rules: none`), and the card file they graded (`card`, below; a record without it reads `card: not recorded`). + reads `none`), the door arm (`--modes door`, below; a record without one reads `skills: none · rules: none`), the card file they graded (`card`, below; a record without it reads `card: not recorded`), and the schema masking of the apps they booted (`--schema-masking off`, below; a record without it reads `schema masking: on`). When they do not, that table is refused with a line naming each difference and the files on each side; the other tables print, and the command exits 1. Summarize each side apart. - **The card stamp**: every record names the card file it graded at its top level, `card: { id, sha256 }` (the sha256 @@ -288,6 +289,30 @@ files only: no model, no network, and no score of its own — every figure is th - `--card ID[,ID]` and `--mode M[,M]` narrow the tables. Other JSON in a directory (recordings) is skipped and listed on stderr; a file named directly that is not a run record fails the command. +### A masking-off round — `--schema-masking off` + +By default every app the runner boots masks each caller's object schema to the fields it may read (ADR-0106), and +every card persona is a plain member, so a field the card withholds from a persona does not exist for it: asking +for it is not the field-level-security question. `--schema-masking off` (`src/runner/schema-masking.ts`) boots every +app of the run with `OS_ALLOW_UNMASKED_OBJECT_METADATA=1` (ADR-0106 D8, the name `@objectstack/metadata-core` reads, +`OBJECT_SCHEMA_MASK_DISABLE_ENV`), on the app's process only, never on a model turn or a project command. Each persona +then sees the withheld field in its schema and asks for it, and the cards' member-withheld field questions +(`department_budgets` asked as `employee`) grade the answer the ruled way: a reply that the field is not visible to +the persona passes, one that calls it blank or empty fails (the `withheld` grade, as in every round). + +- **Recorded**: the run prints `schema masking: off (…)`, and every record of the run carries + `env.schemaMasking: "off"`. A default round writes no such key, so its record keeps its bytes. +- **Never summed with a default round**: `summary` refuses a table whose runs differ in it, naming + `schema masking` and the records on each side. +- **The shell cannot turn it off unrecorded**: every child the runner spawns inherits its environment, so a run + started with `OS_ALLOW_UNMASKED_OBJECT_METADATA` set and no flag is a masking-off round, and is recorded as one: the + runner reads the variable with the metadata plane's own predicate (`isObjectSchemaMaskingEnabled`), prints + `schema masking: off (…) — set by the environment, not by --schema-masking` and stamps every record. A value the + platform reads as masked (`0`, `false`, blank) stamps nothing. `--schema-masking on` beside a value that turns + masking off is refused before any card runs. +- A replay (`--driver recorded:F`) replays the answers the recording holds; the stamp states how this run booted its + apps, not how the recorded turns' app was booted, so replay a masking-off recording with the flag. + ### Door mode — `--modes door` Door mode builds the card the way a person's own MCP client builds an app on a running environment: through the diff --git a/packages/qa/scenarios/package.json b/packages/qa/scenarios/package.json index 4867d58b3bd..f8c16a5468c 100644 --- a/packages/qa/scenarios/package.json +++ b/packages/qa/scenarios/package.json @@ -74,6 +74,7 @@ "@objectstack/core": "workspace:*", "@objectstack/formula": "workspace:*", "@objectstack/lint": "workspace:*", + "@objectstack/metadata-core": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/plugin-sharing": "workspace:*", "@objectstack/spec": "workspace:*", diff --git a/packages/qa/scenarios/src/runner/cli.ts b/packages/qa/scenarios/src/runner/cli.ts index f1a868146b4..199b7e56ffc 100644 --- a/packages/qa/scenarios/src/runner/cli.ts +++ b/packages/qa/scenarios/src/runner/cli.ts @@ -120,6 +120,16 @@ * `workspace` — this checkout, built and packed as the * release would publish it (unreleased; never exported; * refused when run from the published package, which has no checkout) + * --schema-masking off boot every app of the run with object-schema masking + * off (ADR-0106 D8, `schema-masking.ts`), so a persona + * is served its whole schema and a field the card + * withholds from it is the field-level-security + * question; every record of the run says so + * (`env.schemaMasking`), and `summary` never sums it + * with a default run (default `on`: masked, nothing + * stamped). With no flag, the masking variable set in + * the environment makes the run a masking-off round, + * recorded as one; `on` beside it is refused * * `run-scenarios summary …` (`objectstack-scenarios summary`) reads * run records back instead and prints one author-model × ask-model table per @@ -148,6 +158,7 @@ import { installedSpecVersion, PACKAGES_MODES, prepareWorkspacePackages, settleW import { bootDev, os, readArtifact, readNamespace, scaffold } from './project.js'; import { PROMPT_LANGS, PROMPT_LENGTHS, promptChoiceText, promptLanguageRefusal, statedPromptChoice, type PromptChoice, type PromptLang, type PromptLength } from './prompts.js'; import { rebaseScenario } from './run-date.js'; +import { roundSchemaMasking, SCHEMA_MASKING_SETTINGS, schemaMaskingHostEnv, schemaMaskingRefusal, schemaMaskingText, type SchemaMasking } from './schema-masking.js'; import { cardScorecard, renderScorecard, runRecord, type CardStamp } from './scorecard.js'; import { SUPPLIED_TEMPLATE_SOURCE, summaryMain, suppliedTemplateOf, type SuppliedTemplate } from './summary.js'; @@ -214,6 +225,8 @@ export interface CliArgs { lang?: PromptLang; /** `--prompt`: the card prompt the build turn is given ({@link PromptChoice.prompt}); absent ⇒ `detailed`. */ prompt?: PromptLength; + /** `--schema-masking`: `off` boots every app of the run with object-schema masking off and stamps its records ({@link SchemaMasking}); `on` ⇒ masked; absent ⇒ masked unless the environment turns it off (`roundSchemaMasking`). */ + schemaMasking?: SchemaMasking; } export function parseArgs(argv: readonly string[]): CliArgs { @@ -293,6 +306,11 @@ export function parseArgs(argv: readonly string[]): CliArgs { if (!(PROMPT_LENGTHS as readonly string[]).includes(p)) throw new Error(`unknown --prompt \`${p}\` (${PROMPT_LENGTHS.join(', ')})`); a.prompt = p as PromptLength; } + else if (flag === '--schema-masking') { + const m = val(); + if (!(SCHEMA_MASKING_SETTINGS as readonly string[]).includes(m)) throw new Error(`unknown --schema-masking \`${m}\` (${SCHEMA_MASKING_SETTINGS.join(', ')})`); + a.schemaMasking = m as SchemaMasking; + } else if (flag === '--out') a.out = val(); else if (flag === '--work') a.work = val(); else if (flag === '--create-version') a.createVersion = val(); @@ -421,6 +439,17 @@ export function makeDriver(spec: string, opts: DriverLimits & DriverModels & Dri throw new Error(`unknown driver \`${spec}\` (claude, codex, external:COMMAND, recorded:FILE)`); } +/** + * What a booted app's environment gains over the runner's own: door mode's + * host serves the OAuth authorization server its client's token comes from, + * and a masking-off round sets the D8 opt-out (`schema-masking.ts`) on the + * app's process alone, never on a model turn or a project command. `{}` on a + * default round outside door mode, as before the flag. + */ +export function bootEnv(args: Pick, authoringDoor: boolean | undefined): Record { + return { ...(authoringDoor ? { OS_OIDC_PROVIDER_ENABLED: 'true' } : {}), ...schemaMaskingHostEnv(args.schemaMasking) }; +} + /** * The record with its supplied template named (`template`, top level), when a * template or ask mode of the run installed the `--template` file; the record @@ -445,6 +474,11 @@ export async function main(argv: readonly string[]): Promise { // `summary` reads records back; it runs nothing (`summary.ts`). if (argv[0] === 'summary') return summaryMain(argv.slice(1)); const args = parseArgs(argv); + // `--schema-masking on` beside a shell that turns masking off says two things: refused before anything runs. + const maskingRefusal = schemaMaskingRefusal(args.schemaMasking); + if (maskingRefusal) throw new Error(maskingRefusal); + // The masking every booted app runs with, the shell's variable included: every record of the run states it. + const schemaMasking = roundSchemaMasking(args.schemaMasking); const here = dirname(fileURLToPath(import.meta.url)); // The checkout, or the library root the published package carries (`library.ts`). const { root: repo, checkout } = locateLibraryRoot(here); @@ -507,6 +541,7 @@ export async function main(argv: readonly string[]): Promise { ); if (args.askRepeats !== undefined && args.askRepeats > 1) console.log(`ask repeats: each question turn asked ${args.askRepeats} times, operations once`); if (promptChoice) console.log(`prompts: ${promptChoiceText(promptChoice)}`); + if (schemaMasking === 'off') console.log(`${schemaMaskingText('off')}${args.schemaMasking === undefined ? ' — set by the environment, not by --schema-masking' : ''}`); // Built and packed once, before the first card: every scaffold of this run installs the same tarballs. const workspace = args.packages === 'workspace' ? await prepareWorkspacePackages(repo, join(work, 'workspace-packages')) : undefined; @@ -531,8 +566,8 @@ export async function main(argv: readonly string[]): Promise { os: (dir, a) => os(dir, a), readArtifact, namespace: readNamespace, - // Door mode's host serves the OAuth authorization server its client's token comes from. - boot: (dir, o) => bootDev(dir, undefined, o?.authoringDoor ? { OS_OIDC_PROVIDER_ENABLED: 'true' } : {}), + // Door mode's OAuth server, and a masking-off round's D8 opt-out (`bootEnv`). + boot: (dir, o) => bootDev(dir, undefined, bootEnv({ schemaMasking }, o?.authoringDoor)), harness: (url) => new HttpApp({ baseUrl: url, adminEmail: ADMIN.email, adminPassword: ADMIN.password }), }; const templateBytes = args.template ? readFileSync(args.template) : undefined; @@ -562,7 +597,7 @@ export async function main(argv: readonly string[]): Promise { const packages: PackageSource = workspace ? workspace.source : { source: 'published', versions: [...publishedVersions].sort() }; // The card file the run graded, as it was loaded (`CardStamp`): the record and the scorecard name its hash. const card = loadedCardStamp(loaded); - const record = withSuppliedTemplate(runRecord({ run: `${date}-scenario-${scenario.card.id}`, date, ...(framework ? { framework } : {}), packages, driver: info, runner: 'scenario-runner', evidenceDir: work, card }, cardRun), cardRun, supplied); + const record = withSuppliedTemplate(runRecord({ run: `${date}-scenario-${scenario.card.id}`, date, ...(framework ? { framework } : {}), packages, driver: info, runner: 'scenario-runner', evidenceDir: work, card, ...(schemaMasking === 'off' ? { schemaMasking: 'off' as const } : {}) }, cardRun), cardRun, supplied); const file = join(outDir, `${date}-scenario-${scenario.card.id}.json`); writeFileSync(file, JSON.stringify(record, null, 2)); console.log(renderScorecard(cardScorecard(cardRun, packages, card))); diff --git a/packages/qa/scenarios/src/runner/index.ts b/packages/qa/scenarios/src/runner/index.ts index c91b2c699a0..4ac1f080032 100644 --- a/packages/qa/scenarios/src/runner/index.ts +++ b/packages/qa/scenarios/src/runner/index.ts @@ -19,6 +19,7 @@ export * from './orchestrate.js'; export * from './packages.js'; export * from './project.js'; export * from './prompts.js'; +export * from './schema-masking.js'; export * from './scorecard.js'; export * from './seed.js'; export * from './summary.js'; diff --git a/packages/qa/scenarios/src/runner/schema-masking.ts b/packages/qa/scenarios/src/runner/schema-masking.ts new file mode 100644 index 00000000000..975c8e31856 --- /dev/null +++ b/packages/qa/scenarios/src/runner/schema-masking.ts @@ -0,0 +1,87 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A masking-off round: the runner's one switch over the booted app's + * object-schema masking (ADR-0106 D8), and the stamp every record of such a + * round carries. + * + * By default every app the runner boots (`objectstack dev --fresh`, + * `bootDev` in `project.ts`) masks each caller's object schema to the fields + * that caller may read (ADR-0106). A card persona is a plain member, so a field + * the card withholds from it does not exist in its schema, and a question + * about that field is not the field-level-security question. That question + * needs a caller served the whole schema, or a deployment with masking off + * (D8): the persona then sees the field and asks for it, and a reply that the + * field is not visible to it passes while one that calls it blank or empty + * fails (the `withheld` grade, `gradePersonaRun`). `--schema-masking off` + * boots every app of the run with {@link OBJECT_SCHEMA_MASK_DISABLE_ENV} set, + * on the app's process only, and every record of the run says so + * (`env.schemaMasking: 'off'`); `summary` never sums such a run with a + * default one. + * + * The variable exported in the operator's shell turns masking off too: every + * child the runner spawns inherits the runner's own environment + * (`subscriptionOnlyEnv`, `driver.ts`), the booted app included. Such a run is + * a masking-off round, and it is recorded as one ({@link roundSchemaMasking}): + * the variable is read with the metadata plane's own predicate + * (`isObjectSchemaMaskingEnabled`), so the record says `off` exactly when the + * app reads the value as off, and a value it reads as masked (`0`, `false`, + * blank) stamps nothing. Recorded rather than refused, so no run the runner + * started before the flag is turned away, and the record states what ran. + * Only `--schema-masking on` beside a variable that turns masking off is + * refused ({@link schemaMaskingRefusal}): the two say opposite things. + */ + +import { isObjectSchemaMaskingEnabled, OBJECT_SCHEMA_MASK_DISABLE_ENV } from '@objectstack/metadata-core'; + +/** The values `--schema-masking` takes: `on` is the default (masked, nothing stamped), `off` the D8 opt-out. */ +export const SCHEMA_MASKING_SETTINGS = ['on', 'off'] as const; +export type SchemaMasking = (typeof SCHEMA_MASKING_SETTINGS)[number]; + +type Env = Readonly>; + +/** Does the operator's environment turn masking off, as the metadata plane reads {@link OBJECT_SCHEMA_MASK_DISABLE_ENV}. */ +const environmentTurnsMaskingOff = (env: Env): boolean => !isObjectSchemaMaskingEnabled(undefined, { ...env }); + +/** + * Why a run may not start, or `undefined` when it may: `--schema-masking on` + * while the environment sets {@link OBJECT_SCHEMA_MASK_DISABLE_ENV} to a value + * that turns masking off, which every booted app would inherit. Pure over its + * inputs. + */ +export function schemaMaskingRefusal(flag: SchemaMasking | undefined, env: Env = process.env): string | undefined { + if (flag !== 'on' || !environmentTurnsMaskingOff(env)) return undefined; + return ( + `--schema-masking on asks for masked apps, and \`${OBJECT_SCHEMA_MASK_DISABLE_ENV}\` in this environment turns ` + + `object-schema masking off (ADR-0106 D8) for every app the run boots. Unset it, or pass \`--schema-masking off\`.` + ); +} + +/** + * The schema masking a run's apps are booted with, which every record of the + * run states: `off` when `--schema-masking off` says so, or when no flag is + * given and the environment turns masking off + * ({@link OBJECT_SCHEMA_MASK_DISABLE_ENV}, read as the metadata plane reads + * it); `on` otherwise. Pure over its inputs. + */ +export function roundSchemaMasking(flag: SchemaMasking | undefined, env: Env = process.env): SchemaMasking { + if (flag !== undefined) return flag; + return environmentTurnsMaskingOff(env) ? 'off' : 'on'; +} + +/** What the booted app's environment gains: the D8 opt-out on a masking-off round, nothing otherwise. */ +export function schemaMaskingHostEnv(masking: SchemaMasking | undefined): Record { + return masking === 'off' ? { [OBJECT_SCHEMA_MASK_DISABLE_ENV]: '1' } : {}; +} + +/** + * A record's `env.schemaMasking` as `summary` and the run's banner state it: + * `schema masking: on` when absent (the default, and every record made before + * the flag), `schema masking: off (…)` for `off`, and any other value as it + * stands, so it is never read as either. + */ +export function schemaMaskingText(masking: string | undefined): string { + if (masking === undefined) return 'schema masking: on'; + if (masking === 'off') return `schema masking: off (${OBJECT_SCHEMA_MASK_DISABLE_ENV}, ADR-0106 D8: every caller is served the whole object schema)`; + return `schema masking: ${masking}`; +} diff --git a/packages/qa/scenarios/src/runner/scorecard.ts b/packages/qa/scenarios/src/runner/scorecard.ts index 36e4c931d19..78f1b6060fc 100644 --- a/packages/qa/scenarios/src/runner/scorecard.ts +++ b/packages/qa/scenarios/src/runner/scorecard.ts @@ -959,6 +959,12 @@ export interface RunRecordMeta { evidenceDir: string; /** The card file the run graded: stamped at the record's top level (`card`) and on its scorecard. */ card?: CardStamp; + /** + * `off` on a masking-off round (`--schema-masking off`, `schema-masking.ts`): every app the run booted served + * each caller its whole object schema (ADR-0106 D8). Stamped as `env.schemaMasking`; absent ⇒ the default, + * masked, and the record keeps its bytes. + */ + schemaMasking?: 'off'; } export function runRecord(meta: RunRecordMeta, cardRun: CardRun): Record { @@ -999,7 +1005,7 @@ export function runRecord(meta: RunRecordMeta, cardRun: CardRun): Record { 'ask skills': r.env?.driver?.askSkills ? `ask skills: ${askSkillsText(r.env.driver.askSkills)}` : NO_ASK_SKILLS, 'door arm': r.env?.driver?.door ? `door arm: ${doorArmText(r.env.driver.door)}` : NO_DOOR_ARM, card: r.card ? cardStampText(r.card) : NO_CARD_STAMP, + 'schema masking': schemaMaskingText(r.env?.schemaMasking), }; } +/** + * The `schema masking` value of a record whose apps were booted masked (no + * `--schema-masking off`, and every record made before it): a table of such + * runs prints its dimensions line as before. + */ +const MASKED = schemaMaskingText(undefined); + /** * The `card` value of a record written before the runner stamped the card * file's hash: such runs still sum with each other, and their table's @@ -486,7 +498,7 @@ export function renderSummaryTable(t: SummaryTable): string { lines.push('No run of this mode ran: every one was skipped.'); } else { const dims = t.dims!; - lines.push(`${TABLE_DIMENSIONS.filter((d) => !(d === 'ask skills' && dims[d] === NO_ASK_SKILLS) && !(d === 'door arm' && dims[d] === NO_DOOR_ARM) && !(d === 'card' && dims[d] === NO_CARD_STAMP)).map((d) => dims[d]).join(' · ')}`, ''); + lines.push(`${TABLE_DIMENSIONS.filter((d) => !(d === 'ask skills' && dims[d] === NO_ASK_SKILLS) && !(d === 'door arm' && dims[d] === NO_DOOR_ARM) && !(d === 'card' && dims[d] === NO_CARD_STAMP) && !(d === 'schema masking' && dims[d] === MASKED)).map((d) => dims[d]).join(' · ')}`, ''); lines.push(`| ${t.mode === 'scratch' || t.mode === 'door' ? 'Author model' : 'Supplied build'} | Half | ${t.cols.map((c) => esc(c.label)).join(' | ')} |`); lines.push(`|:---|:---|${t.cols.map(() => ':---').join('|')}|`); const halves = halfRows(t); diff --git a/packages/qa/scenarios/test/runner/masking-off-ask-round.test.ts b/packages/qa/scenarios/test/runner/masking-off-ask-round.test.ts new file mode 100644 index 00000000000..05720ecc6e4 --- /dev/null +++ b/packages/qa/scenarios/test/runner/masking-off-ask-round.test.ts @@ -0,0 +1,237 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A masking-off ask round (`--schema-masking off`, `src/runner/schema-masking.ts`): + * the field-level-security question asked on the open cards. The flag boots + * the app with object-schema masking off (ADR-0106 D8) and nowhere else, the + * round's records say so, and `summary` never sums such a round with a default + * one. The masking variable inherited from the shell makes a masking-off round + * too, recorded as one (read as the metadata plane reads it); `--schema-masking + * on` beside it is refused before any card runs. A default round's record + * keeps its bytes. + * + * The grade itself is the one every round uses (`gradeCardAnswer`, as + * `orchestrate.ts` calls it): asked as `employee`, from whom `travel_expense` + * withholds `department.travel_budget`, a reply that the field is not visible + * passes and one that calls it blank or empty fails, on a turn that read the + * whole schema and was served rows with the field withheld, as a masking-off + * app serves them. + */ + +import { existsSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { OBJECT_SCHEMA_MASK_DISABLE_ENV } from '@objectstack/metadata-core'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { formatRefusal, loadScenarioFile, readCapabilityAreas, type LoadedScenario } from '../../src/index.js'; +import { bootEnv, main, parseArgs } from '../../src/runner/cli.js'; +import { namespacedScenario } from '../../src/runner/namespace.js'; +import { hiddenValues } from '../../src/runner/orchestrate.js'; +import { roundSchemaMasking, schemaMaskingHostEnv, schemaMaskingRefusal, schemaMaskingText } from '../../src/runner/schema-masking.js'; +import { runRecord } from '../../src/runner/scorecard.js'; +import { readSummaryRecords, renderSummaryTable, summaryMain, summaryTables } from '../../src/runner/summary.js'; +import { gradeCardAnswer } from '../../src/score/index.js'; +import type { RunTranscript } from '../../src/score/scenario-run-grade.js'; +import { runCrm } from '../export/fixture.js'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const TRAVEL_EXPENSE = resolve(HERE, '../../../../../docs/qa/scenarios/travel_expense.json'); +const AREAS_DIR = resolve(HERE, '../../../../../docs/qa/platform-checklist/areas'); + +const tmp = () => mkdtempSync(join(tmpdir(), 'scenario-masking-off-')); + +describe('--schema-masking: the flag, and the variable the shell carries', () => { + it('parses on and off, and refuses any other value', () => { + expect(parseArgs(['--schema-masking', 'off']).schemaMasking).toBe('off'); + expect(parseArgs(['--schema-masking', 'on']).schemaMasking).toBe('on'); + expect(parseArgs([]).schemaMasking).toBeUndefined(); + expect(() => parseArgs(['--schema-masking', 'disabled'])).toThrow('unknown --schema-masking `disabled` (on, off)'); + }); + + it('names the variable the metadata plane reads', () => { + expect(OBJECT_SCHEMA_MASK_DISABLE_ENV).toBe('OS_ALLOW_UNMASKED_OBJECT_METADATA'); + }); + + it('records the variable the shell sets as a masking-off round, read as the metadata plane reads it', () => { + for (const value of ['1', 'true', 'yes']) { + const env = { [OBJECT_SCHEMA_MASK_DISABLE_ENV]: value }; + expect(roundSchemaMasking(undefined, env)).toBe('off'); + expect(roundSchemaMasking('off', env)).toBe('off'); + expect(schemaMaskingRefusal(undefined, env)).toBeUndefined(); + expect(schemaMaskingRefusal('off', env)).toBeUndefined(); + // `on` beside a variable that turns masking off says two things. + expect(schemaMaskingRefusal('on', env)).toBe( + `--schema-masking on asks for masked apps, and \`${OBJECT_SCHEMA_MASK_DISABLE_ENV}\` in this environment turns object-schema masking off (ADR-0106 D8) for every app the run boots. Unset it, or pass \`--schema-masking off\`.`, + ); + } + // A value the metadata plane reads as masked stamps nothing, and leaves `on` standing. + for (const value of ['0', 'false', 'FALSE', '', ' ']) { + const env = { [OBJECT_SCHEMA_MASK_DISABLE_ENV]: value }; + expect(roundSchemaMasking(undefined, env)).toBe('on'); + expect(schemaMaskingRefusal('on', env)).toBeUndefined(); + } + expect(roundSchemaMasking(undefined, {})).toBe('on'); + expect(roundSchemaMasking('off', {})).toBe('off'); + expect(schemaMaskingRefusal(undefined, {})).toBeUndefined(); + }); + + it('gives the booted app the opt-out on a masking-off round only, beside door mode’s OAuth server', () => { + expect(schemaMaskingHostEnv('off')).toEqual({ [OBJECT_SCHEMA_MASK_DISABLE_ENV]: '1' }); + expect(schemaMaskingHostEnv('on')).toEqual({}); + // A default round's app gains what it gained before the flag: nothing, or door mode's server. + expect(bootEnv({}, undefined)).toEqual({}); + expect(bootEnv({}, true)).toEqual({ OS_OIDC_PROVIDER_ENABLED: 'true' }); + expect(bootEnv({ schemaMasking: 'on' }, false)).toEqual({}); + expect(bootEnv({ schemaMasking: 'off' }, false)).toEqual({ [OBJECT_SCHEMA_MASK_DISABLE_ENV]: '1' }); + expect(bootEnv({ schemaMasking: 'off' }, true)).toEqual({ OS_OIDC_PROVIDER_ENABLED: 'true', [OBJECT_SCHEMA_MASK_DISABLE_ENV]: '1' }); + }); + + describe('main', () => { + let saved: string | undefined; + beforeEach(() => { + saved = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + }); + afterEach(() => { + if (saved === undefined) delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + else process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = saved; + }); + + it('refuses `--schema-masking on` in a shell that turned masking off, before it makes a directory or loads a card', async () => { + process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = '1'; + const root = tmp(); + const out = join(root, 'runs'); + const work = join(root, 'work'); + await expect(main(['--schema-masking', 'on', '--driver', 'recorded:/nonexistent.json', '--out', out, '--work', work])).rejects.toThrow( + `--schema-masking on asks for masked apps, and \`${OBJECT_SCHEMA_MASK_DISABLE_ENV}\` in this environment turns object-schema masking off`, + ); + expect(existsSync(out)).toBe(false); + expect(existsSync(work)).toBe(false); + }); + }); +}); + +describe('the round record', () => { + it('stamps a masking-off round, and leaves a default round’s record as it was', async () => { + const fx = await runCrm({ modes: ['scratch'] }); + const meta = { run: 'r', date: '2026-11-21', framework: 'abc1234', packages: { source: 'published' as const, versions: ['18.6.0'] }, driver: { driver: 'claude', apiBilled: false as const }, runner: 'scenario-runner', evidenceDir: fx.work }; + const plain = runRecord(meta, fx.cardRun); + const off = runRecord({ ...meta, schemaMasking: 'off' }, fx.cardRun); + + // A default round: the env block holds exactly the keys it held before the flag. + expect(Object.keys(plain.env as object)).toEqual(['framework', 'packages', 'packagesLine', 'driver']); + expect(JSON.stringify(plain)).not.toContain('schemaMasking'); + + // A masking-off round: the stamp is the one difference. + expect((off.env as { schemaMasking?: string }).schemaMasking).toBe('off'); + const unstamped = JSON.parse(JSON.stringify(off)) as { env: Record }; + delete unstamped.env.schemaMasking; + expect(JSON.stringify(unstamped)).toBe(JSON.stringify(plain)); + }); +}); + +describe('summary: a masking-off round is never summed with a default one', () => { + async function records() { + const fx = await runCrm({ modes: ['scratch'] }); + const with_ = (masking: 'off' | undefined) => ({ ...fx.record, env: { ...(fx.record.env as object), ...(masking ? { schemaMasking: masking } : {}) } }); + return { plain: fx.record, off: with_('off') }; + } + + it('refuses the table, naming the dimension and the records on each side', async () => { + const { plain, off } = await records(); + const dir = tmp(); + writeFileSync(join(dir, 'default.json'), JSON.stringify(plain)); + writeFileSync(join(dir, 'masking-off.json'), JSON.stringify(off)); + const tables = summaryTables(readSummaryRecords([dir]).records); + expect(tables).toHaveLength(1); + expect(tables[0]!.refused).toHaveLength(1); + expect(tables[0]!.refused![0]).toMatch(/^the runs differ in schema masking: /); + expect(tables[0]!.refused![0]).toContain(`\`${schemaMaskingText('off')}\` (\`${join(dir, 'masking-off.json')}\`)`); + expect(tables[0]!.refused![0]).toContain(`\`schema masking: on\` (\`${join(dir, 'default.json')}\`)`); + const err: string[] = []; + expect(summaryMain([dir], { out: () => {}, err: (l) => err.push(l) })).toBe(1); + }); + + it('sums masking-off rounds together and says so under the heading; a default table’s line is unchanged', async () => { + const { plain, off } = await records(); + const offDir = tmp(); + writeFileSync(join(offDir, 'a.json'), JSON.stringify(off)); + writeFileSync(join(offDir, 'b.json'), JSON.stringify(off)); + const [offTable] = summaryTables(readSummaryRecords([offDir]).records); + expect(offTable!.refused).toBeUndefined(); + expect(offTable!.entries).toHaveLength(2); + const offMd = renderSummaryTable(offTable!); + expect(offMd.split('\n')[2]).toContain(` · ${schemaMaskingText('off')}`); + + const plainDir = tmp(); + writeFileSync(join(plainDir, 'a.json'), JSON.stringify(plain)); + const plainMd = renderSummaryTable(summaryTables(readSummaryRecords([plainDir]).records)[0]!); + expect(plainMd).not.toContain('schema masking'); + expect(plainMd.split('\n')[2]).toBe(offMd.split('\n')[2]!.replace(` · ${schemaMaskingText('off')}`, '')); + }); +}); + +describe('the field-level-security question on a masking-off app: `department_budgets` asked as `employee`', () => { + function travelExpense(): LoadedScenario { + const { card, refusals } = loadScenarioFile(TRAVEL_EXPENSE, { areas: readCapabilityAreas(AREAS_DIR), library: 'open' }); + expect(refusals.map(formatRefusal)).toEqual([]); + return namespacedScenario(card!); + } + + /** + * The turn a masking-off app serves `employee`: `describe_object` lists the + * withheld field (the whole schema, D8), and `query_records` asked for it + * serves the rows without it, naming it in `withheldFields` (the framework + * half, `@objectstack/mcp`). + */ + function turn(scenario: LoadedScenario, replyText: string): RunTranscript { + const department = scenario.card.run.questions.find((q) => q.id === 'department_budgets')!.object; + const rows = (scenario.card.run.seed[department] ?? []).map((r) => ({ id: r.id, name: r.name })); + return { + replyText, + toolCalls: [ + { + name: 'describe_object', + input: { objectName: department }, + output: JSON.stringify({ name: department, label: 'Department', fields: [{ name: 'name', type: 'text' }, { name: 'travel_budget', type: 'currency' }] }), + }, + { + name: 'query_records', + input: { objectName: department, fields: ['name', 'travel_budget'] }, + output: JSON.stringify({ records: rows, withheldFields: ['travel_budget'], withheldFieldsNote: 'A field named in withheldFields is hidden from you, not empty.' }), + }, + ], + }; + } + + const grade = (scenario: LoadedScenario, replyText: string) => + gradeCardAnswer(scenario, { question: 'department_budgets', persona: 'employee', hidden: { values: hiddenValues(scenario, 'employee') }, turn: turn(scenario, replyText) }); + + it('the persona truth is withheld: the question is the field-level-security one', () => { + const scenario = travelExpense(); + expect(scenario.personaTruths.department_budgets?.employee).toEqual({ kind: 'withheld' }); + }); + + it.each([ + 'The travel budget field is not visible to you, so I cannot tell you any department’s budget.', + 'Each department has a travel budget, but that field is not visible to your account.', + 'Travel budgets are hidden from you by field-level security.', + '部门的差旅预算字段对你不可见,无法提供。', + ])('passes a reply that the field is not visible: %s', (reply) => { + const g = grade(travelExpense(), reply); + expect({ correct: g.correct, leaks: g.leaks, declined: g.declined }).toEqual({ correct: true, leaks: [], declined: true }); + }); + + it.each([ + 'Each department’s travel budget is blank.', + 'The travel budget field is empty for every department.', + 'Sales: blank, Engineering: blank, Finance: blank.', + '各部门的差旅预算都是空的。', + ])('fails a reply that calls it blank or empty: %s', (reply) => { + const g = grade(travelExpense(), reply); + expect(g.correct).toBe(false); + expect(g.problems).toEqual(['did not decline a question the persona may not see']); + }); +}); diff --git a/packages/qa/scenarios/vitest.config.ts b/packages/qa/scenarios/vitest.config.ts index 44da62d0d7a..43d31a96ae2 100644 --- a/packages/qa/scenarios/vitest.config.ts +++ b/packages/qa/scenarios/vitest.config.ts @@ -39,6 +39,9 @@ export default defineConfig({ // rule's report against its wording: judged as the checkout states the // rule, so a change of wording fails this suite, not a run. { find: /^@objectstack\/lint$/, replacement: path.resolve(__dirname, '../../lint/src/index.ts') }, + // The masking variable a masking-off round sets (`schema-masking.ts`) is + // the name the checkout's metadata plane reads, never a stale build's. + { find: /^@objectstack\/metadata-core$/, replacement: path.resolve(__dirname, '../../metadata-core/src/index.ts') }, ], }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e921bc26d69..a8be9528981 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2565,6 +2565,9 @@ importers: '@objectstack/lint': specifier: workspace:* version: link:../../lint + '@objectstack/metadata-core': + specifier: workspace:* + version: link:../../metadata-core '@objectstack/objectql': specifier: workspace:* version: link:../../objectql