diff --git a/.changeset/37257-scenarios-allowed-rollups.md b/.changeset/37257-scenarios-allowed-rollups.md new file mode 100644 index 00000000000..95d107fd809 --- /dev/null +++ b/.changeset/37257-scenarios-allowed-rollups.md @@ -0,0 +1,10 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): a scenario card may name the roll-ups a persona is meant to read over rows it withholds + +Clause-②: no +Metadata-protocol: none + +A persona on a scenario card may now carry `allowedRollups` (`[{ "object": "invoice", "field": "amount_paid" }]`, in the card's bare names). The runner's Build charge for `security-rollup-source-unreadable` does not charge a finding the build acknowledged (`rollupSourceUnreadableReason` on the persona's set) on one of those roll-ups; an unacknowledged finding on it, and every other roll-up over withheld data, is still charged. The schema refuses an allowed roll-up the persona's own `hidden` names. The `order_to_cash` card uses it: a sales rep sees their invoices' amount paid, balance and status, never the payment rows. diff --git a/docs/qa/scenarios/order_to_cash.json b/docs/qa/scenarios/order_to_cash.json index 2d8d2d4db2d..d14f8a4605f 100644 --- a/docs/qa/scenarios/order_to_cash.json +++ b/docs/qa/scenarios/order_to_cash.json @@ -12,8 +12,8 @@ "en": "Build an order-to-cash app: accounts, follow-up activities, sales orders with lines, invoices, payments and receivables aging." }, "detailed": { - "zh": "订单到收款应用。每个客户有一名负责的销售代表和付款条件(net_30 或 net_45);对客户的每次跟进(会议、电话、邮件、催收电话)都作为一条独立的活动记录挂在客户下,形成时间线,而不是在客户记录里直接填写。产品有标价和成本。销售代表为自己的客户录入销售订单,订单下有多条明细(产品、数量、单价、折扣百分比、金额),单价默认取产品标价,金额 = 数量 × 单价 × (1 − 折扣),订单合计自动汇总明细金额。订单明细是订单的从属记录(主从关系),在订单表单上直接内联编辑。任何一条明细折扣超过 10% 的订单要提交给该销售代表的销售经理审批,经理批准后订单才确认(审批人和批准日期记在订单本身上,批准就是更新订单);销售代表不能审批自己的订单,折扣不得超过 30%。订单履约后开具一张发票,金额等于订单合计,到期日 = 开票日 + 付款条件天数。收款记录挂在发票下:发票的已收金额汇总其收款,余额 = 金额 − 已收,状态随之变为部分收款或已收清;单笔收款不得超过发票当前余额。账龄分段按今天与到期日的差计算(未到期、逾期 1–30 天、31–60 天、61–90 天、90 天以上)。发票逾期 15 天仍未收清时,自动为应收专员创建一条催收电话活动。核销坏账只能由财务操作,且不可撤销。销售代表只能看到自己客户的订单、发票和活动,看不到收款记录和产品成本;销售经理能看到本团队的全部,但看不到收款的银行流水号;应收专员能看到全部客户、订单、发票、收款和活动,但看不到产品成本。需要一张按账龄分段和客户统计未收余额的应收账龄报表。尽量用声明式配置(公式字段、汇总字段、校验规则、按时间触发的流程)而不是代码钩子,以便应用能以非托管方式安装。", - "en": "An order-to-cash app. Each account has one owning sales rep and payment terms (net_30 or net_45); every follow-up with an account (meeting, call, email, collection call) is its own activity record on the account's timeline, never typed into the account record itself. A product has a list price and a cost. A rep enters sales orders for their own accounts; an order has several lines (product, quantity, unit price, discount percent, amount), the unit price defaults to the product's list price, the amount is quantity x unit price x (1 - discount), and the order total sums its line amounts. The lines are details of the order (master-detail), edited inline on the order's form. An order with any line discounted above 10% goes to the rep's sales manager for approval and is confirmed only once the manager approves (the order itself records its approver and approval date, and approving updates the order); a rep cannot approve their own order, and no discount may exceed 30%. A fulfilled order is invoiced once, for the order total, due the invoice date plus the account's terms. Payments are recorded against an invoice: the invoice's amount paid sums its payments, the balance is the amount less the amount paid, and the status follows (partially paid, paid); a payment may not exceed the invoice's open balance. The aging bucket comes from today against the due date (current, 1-30, 31-60, 61-90 and over 90 days overdue). When an invoice is 15 days past due and not fully paid, a collection call activity is created for the AR clerk automatically. Only Finance may write off a balance as bad debt, and a write-off cannot be undone. A rep sees only their own accounts' orders, invoices and activities, and neither payment records nor product costs; a sales manager sees their whole team's, except the bank reference of a payment; the AR clerk sees every account, order, invoice, payment and activity but no product cost. Add a receivables aging report of the open balance by aging bucket and account. Prefer declarative configuration (formula and roll-up fields, validation rules, a time-triggered flow) over code hooks, so the app can be installed unmanaged." + "zh": "订单到收款应用。每个客户有一名负责的销售代表和付款条件(net_30 或 net_45);对客户的每次跟进(会议、电话、邮件、催收电话)都作为一条独立的活动记录挂在客户下,形成时间线,而不是在客户记录里直接填写。产品有标价和成本。销售代表为自己的客户录入销售订单,订单下有多条明细(产品、数量、单价、折扣百分比、金额),单价默认取产品标价,金额 = 数量 × 单价 × (1 − 折扣),订单合计自动汇总明细金额。订单明细是订单的从属记录(主从关系),在订单表单上直接内联编辑。任何一条明细折扣超过 10% 的订单要提交给该销售代表的销售经理审批,经理批准后订单才确认(审批人和批准日期记在订单本身上,批准就是更新订单);销售代表不能审批自己的订单,折扣不得超过 30%。订单履约后开具一张发票,金额等于订单合计,到期日 = 开票日 + 付款条件天数。收款记录挂在发票下:发票的已收金额汇总其收款,余额 = 金额 − 已收,状态随之变为部分收款或已收清;单笔收款不得超过发票当前余额。账龄分段按今天与到期日的差计算(未到期、逾期 1–30 天、31–60 天、61–90 天、90 天以上)。发票逾期 15 天仍未收清时,自动为应收专员创建一条催收电话活动。核销坏账只能由财务操作,且不可撤销。销售代表只能看到自己客户的订单、发票和活动,能看到自己发票的已收金额、余额和状态,但看不到一笔笔的收款记录,也看不到产品成本;销售经理能看到本团队的全部,但看不到收款的银行流水号;应收专员能看到全部客户、订单、发票、收款和活动,但看不到产品成本。需要一张按账龄分段和客户统计未收余额的应收账龄报表。尽量用声明式配置(公式字段、汇总字段、校验规则、按时间触发的流程)而不是代码钩子,以便应用能以非托管方式安装。", + "en": "An order-to-cash app. Each account has one owning sales rep and payment terms (net_30 or net_45); every follow-up with an account (meeting, call, email, collection call) is its own activity record on the account's timeline, never typed into the account record itself. A product has a list price and a cost. A rep enters sales orders for their own accounts; an order has several lines (product, quantity, unit price, discount percent, amount), the unit price defaults to the product's list price, the amount is quantity x unit price x (1 - discount), and the order total sums its line amounts. The lines are details of the order (master-detail), edited inline on the order's form. An order with any line discounted above 10% goes to the rep's sales manager for approval and is confirmed only once the manager approves (the order itself records its approver and approval date, and approving updates the order); a rep cannot approve their own order, and no discount may exceed 30%. A fulfilled order is invoiced once, for the order total, due the invoice date plus the account's terms. Payments are recorded against an invoice: the invoice's amount paid sums its payments, the balance is the amount less the amount paid, and the status follows (partially paid, paid); a payment may not exceed the invoice's open balance. The aging bucket comes from today against the due date (current, 1-30, 31-60, 61-90 and over 90 days overdue). When an invoice is 15 days past due and not fully paid, a collection call activity is created for the AR clerk automatically. Only Finance may write off a balance as bad debt, and a write-off cannot be undone. A rep sees only their own accounts' orders, invoices and activities, including each of their invoices' amount paid, balance and status, but not the individual payment records, nor product costs; a sales manager sees their whole team's, except the bank reference of a payment; the AR clerk sees every account, order, invoice, payment and activity but no product cost. Add a receivables aging report of the open balance by aging bucket and account. Prefer declarative configuration (formula and roll-up fields, validation rules, a time-triggered flow) over code hooks, so the app can be installed unmanaged." } }, "expect": { @@ -878,6 +878,7 @@ "role": "Sales rep, team east, owner of Cedar Logistics and Bluebird Outfitters — e03", "record": {"object": "employee", "id": "e03"}, "hidden": {"objects": ["payment"], "fields": [{"object": "product", "field": "unit_cost"}]}, + "allowedRollups": [{"object": "invoice", "field": "amount_paid"}], "scope": [ {"object": "account", "field": "owner", "value": "e03"}, {"object": "sales_order", "field": "owner", "value": "e03"}, diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 6346dfcd873..059fc93012e 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -742,7 +742,9 @@ npx @objectstack/scenarios help # the comma lets the persona read, or the rule's `info` row-scope arm is not charged. A finding the build acknowledged (`rollupSourceUnreadableReason` on the set's entry for the roll-up, which turns the rule's finding to `info` and suffixes its message with the reason) is still charged, in the same check: a written reason does not change what - the persona sees, and a total the card withholds is masked, never explained. The remedy is the rule's own: mask the + the persona sees, and a total the card withholds is masked, never explained. The one exception is a roll-up the card + names in the persona's `allowedRollups` (`[{ "object": "invoice", "field": "amount_paid" }]`, bare card names): an + acknowledged finding on it is not charged, an unacknowledged one is. The remedy is the rule's own: mask the parent summary on the set (`fields["."]: { readable: false }`). Ask mode authors nothing and is never charged. - **Persona contract**: the build is asked for one permission set per persona, named `_`. The runner diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 9ec68fba277..9f7c6d1acc4 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -853,11 +853,19 @@ export function readRollupSourceFinding(f: Pick [permissionSetName(card, p.id), p] as const)); + // The card's names are namespace-relative; the finding's are the build's (`demoorder_invoice.amount_paid`). + const ns = scenarioNamespace(card); + const named = (object: string) => (object.startsWith(`${ns}_`) ? object : `${ns}_${object}`); + const allowed = new Map(card.run.personas.map((p) => [p.id, new Set((p.allowedRollups ?? []).map((r) => `${named(r.object)}.${r.field}`))] as const)); const stack = { objects: resolveStackCollection(artifact, 'objects'), objectExtensions: resolveStackCollection(artifact, 'objectExtensions'), @@ -869,8 +877,9 @@ export function rollupSourceCharges(scenario: LoadedScenario, artifact: unknown) const r = readRollupSourceFinding(f); const persona = personas.get(r.permissionSet); if (!persona) continue; - const named = 'object' in r.unreadable ? r.childFields : [r.unreadable.field]; - const hiddenField = (persona.hidden.fields ?? []).find((h) => h.object === r.child && named.includes(h.field)); + if (f.severity === 'info' && allowed.get(persona.id)!.has(r.rollup)) continue; + const childNamed = 'object' in r.unreadable ? r.childFields : [r.unreadable.field]; + const hiddenField = (persona.hidden.fields ?? []).find((h) => h.object === r.child && childNamed.includes(h.field)); const withheld = (persona.hidden.objects ?? []).includes(r.child) ? { object: r.child } : hiddenField ? { field: `${hiddenField.object}.${hiddenField.field}` } : undefined; if (!withheld) continue; out.push({ persona: persona.id, permissionSet: r.permissionSet, rollup: r.rollup, child: r.child, withheld, finding: { rule: f.rule, where: f.where, path: f.path, message: f.message } }); diff --git a/packages/qa/scenarios/src/schema.ts b/packages/qa/scenarios/src/schema.ts index f79c4d08d68..297a56ab22c 100644 --- a/packages/qa/scenarios/src/schema.ts +++ b/packages/qa/scenarios/src/schema.ts @@ -412,6 +412,16 @@ export const PersonaSchema = z objects: z.array(MachineNameSchema).optional(), fields: z.array(FieldRefSchema).optional(), }), + /** + * The roll-ups (summary fields, `invoice.amount_paid`) the persona is meant + * to read although `hidden` withholds their source rows: a rep sees what an + * invoice has been paid, never the payments. The runner does not charge a + * `security-rollup-source-unreadable` finding on one of these the build + * ACKNOWLEDGED on the persona's set (`rollupSourceUnreadableReason`); an + * unacknowledged finding on it, and every roll-up not named here, is still + * charged (`rollupSourceCharges`). Absent: every such roll-up is charged. + */ + allowedRollups: z.array(FieldRefSchema).min(1).optional(), /** * ROW scope: of each named object the persona sees only the rows whose * `field` (a field or relation path) equals `value` — a rep sees their own @@ -437,6 +447,12 @@ export const PersonaSchema = z .refine((p) => (p.hidden.objects?.length ?? 0) + (p.hidden.fields?.length ?? 0) > 0, { path: ['hidden'], message: 'a persona names at least one object or field it must NOT see', + }) + .superRefine((p, ctx) => { + (p.allowedRollups ?? []).forEach((r, i) => { + const hidden = (p.hidden.objects ?? []).includes(r.object) || (p.hidden.fields ?? []).some((h) => h.object === r.object && h.field === r.field); + if (hidden) ctx.addIssue({ code: 'custom', path: ['allowedRollups', i], message: `\`${r.object}.${r.field}\` is in the persona's hidden: an allowed roll-up is one the persona reads` }); + }); }); // ── Layer 5: run.operations + run.guardrails ──────────────────────────────── diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index d66f1298cf9..dd8561f2e9f 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -35,7 +35,7 @@ import { askModeRefusal, buildPassed, doorHarnessGap, confirmationAmbiguous, con import { derivedFields, RESTORE_UNCOMPARED, rowDrift } from '../../src/runner/seed.js'; import { askCostText, askSpend, askTimeText, buildDenialFindings, cardScorecard, cardStampOf, confirmationTally, datasetTally, confirmedWriteTally, elapsedText, guardrailTally, kindCell, kindTally, modelTally, opsTally, renderScorecard, repeatTally, runRecord, type AskSpend } from '../../src/runner/scorecard.js'; import { askKindCounts } from '../../src/ask-kinds.js'; -import { ASK_KINDS } from '../../src/schema.js'; +import { ASK_KINDS, PersonaSchema } from '../../src/schema.js'; import type { PackageSource } from '../../src/runner/packages.js'; import { buildPrompt, CONFIRMATION_WORDS, doorBuildPrompt, confirmPrompt, iteratePrompt, MissingLanguageError, promptLanguageGaps, promptLanguageRefusal, questionPrompt } from '../../src/runner/prompts.js'; import type { ParsedTurn } from '../../src/runner/transcript.js'; @@ -1570,6 +1570,75 @@ describe('rollupSourceCharges — an acknowledged roll-up over a child the card }); }); +describe('rollupSourceCharges — a roll-up the card allows a persona is not charged once acknowledged (ruling B on #37257)', () => { + const scenario = namespacedScenario(load(resolve(HERE, '../../../../../docs/qa/scenarios/order_to_cash.json'))); + const p = (name: string) => `demoorder_${name}`; + const REASON = 'a rep follows what their invoices have been paid'; + + /** + * order_to_cash: the card withholds `payment` from the sales rep and allows + * the rep `invoice.amount_paid` (a sum over payment.amount). The rep's set + * reads invoice and not payment, so the rule finds each invoice roll-up; + * `ack` names the roll-up columns the set acknowledges. + */ + const artifact = (ack: string[]) => ({ + manifest: { id: 'com.example.demoorder', namespace: 'demoorder' }, + objects: [ + { + name: p('invoice'), + fields: { + amount: { type: 'currency' }, + amount_paid: { type: 'summary', summaryOperations: { object: p('payment'), function: 'sum', field: 'amount' } }, + payment_count: { type: 'summary', summaryOperations: { object: p('payment'), function: 'count' } }, + }, + }, + { name: p('payment'), fields: { amount: { type: 'currency' }, invoice: { type: 'lookup', reference: p('invoice') } } }, + ], + permissions: [ + { + name: p('sales_rep'), + objects: { [p('invoice')]: { allowRead: true } }, + fields: Object.fromEntries(ack.map((c) => [`${p('invoice')}.${c}`, { rollupSourceUnreadableReason: REASON }])), + }, + ], + }); + const charged = (s: LoadedScenario, built: unknown) => rollupSourceCharges(s, built).map((c) => [c.persona, c.rollup, c.withheld]); + const withoutKey: LoadedScenario = { + ...scenario, + card: { ...scenario.card, run: { ...scenario.card.run, personas: scenario.card.run.personas.map(({ allowedRollups: _, ...rest }) => rest) } }, + }; + + it('the card allows the sales rep invoice.amount_paid, in its own bare names', () => { + expect(scenario.card.run.personas.find((x) => x.id === 'sales_rep')!.allowedRollups).toEqual([{ object: 'invoice', field: 'amount_paid' }]); + }); + + it('an acknowledged finding on the allowed roll-up is not charged; an acknowledged one on another roll-up is', () => { + expect(charged(scenario, artifact(['amount_paid', 'payment_count']))).toEqual([['sales_rep', p('invoice.payment_count'), { object: p('payment') }]]); + }); + + it('the same build is charged for both once the card names no allowed roll-up', () => { + expect(charged(withoutKey, artifact(['amount_paid', 'payment_count']))).toEqual([ + ['sales_rep', p('invoice.amount_paid'), { object: p('payment') }], + ['sales_rep', p('invoice.payment_count'), { object: p('payment') }], + ]); + }); + + it('an UNacknowledged finding on the allowed roll-up is charged', () => { + expect(charged(scenario, artifact([]))).toEqual([ + ['sales_rep', p('invoice.amount_paid'), { object: p('payment') }], + ['sales_rep', p('invoice.payment_count'), { object: p('payment') }], + ]); + }); + + it('the schema refuses an allowed roll-up the persona\'s hidden withholds', () => { + const base = { id: 'rep', role: 'Rep', hidden: { objects: ['payment'], fields: [{ object: 'product', field: 'unit_cost' }] } }; + expect(PersonaSchema.safeParse({ ...base, allowedRollups: [{ object: 'invoice', field: 'amount_paid' }] }).success).toBe(true); + const refused = PersonaSchema.safeParse({ ...base, allowedRollups: [{ object: 'product', field: 'unit_cost' }] }); + expect(refused.success).toBe(false); + expect(refused.error!.issues.map((i) => i.path)).toEqual([['allowedRollups', 0]]); + }); +}); + // ── The model each turn was served ────────────────────────────────────────── /**