diff --git a/.changeset/36558-scenario-scorer-gallery-refresh.md b/.changeset/36558-scenario-scorer-gallery-refresh.md new file mode 100644 index 00000000000..3f643995fbe --- /dev/null +++ b/.changeset/36558-scenario-scorer-gallery-refresh.md @@ -0,0 +1,14 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): scorer and card defects from the 18.6.0 gallery refresh + +Clause-②: no +Metadata-protocol: none + +- On a `withheld` question, a sentence about what a dataset or report covers ("The Approved Leave dataset can't group by medical note") is no longer read as a decline, unless it binds to the asker. +- The agent-action check also fails an action the build gates (`ai.requiresConfirmation: true`) where the card has the agent act at once (`confirm: false`): `action:OBJECT.NAME->not-confirm-gated`. The build prompt says an unmarked action runs with no confirmation gate. +- `persona-grant:*:delete` reads the platform's owner-only delete floor: `allowDelete` without Modify All (or a write depth of `org`) no longer passes a delete of a seed row the persona does not own; a delete only a row-dependent rule, a `controlled_by_parent` master gate or a declared route action could admit is not measured. +- A declared `VALIDATION_FAILED` is met by a hook's own refusal with no declared code (`HOOK_ABORTED`) at a client-error status. +- Card wording: service_desk `log_ticket` states it assigns the signed-in agent and opens the ticket; leave_balances `sick_by_medical_note` asks by what the medical note says; requisition_to_receipt and travel_expense ask for a record-triggered flow. diff --git a/docs/qa/scenarios/README.md b/docs/qa/scenarios/README.md index 5c7b8dc37da..d783b3e7111 100644 --- a/docs/qa/scenarios/README.md +++ b/docs/qa/scenarios/README.md @@ -454,7 +454,9 @@ for not guessing a name. it answers, the kind of each write it applies or confirms, and a refusal of each write the card refuses it with `PERMISSION_DENIED` (no grant, or a field it may not edit). A write the card has wait on confirmation may instead go through the card's confirm-gated agent action: when - the set withholds the verb and the build declares that action, the check is not measured. The prompt names + the set withholds the verb and the build declares that action, the check is not measured. A delete + is also read against the platform's owner-only delete floor: a granted delete of a seed row the + persona does not own needs Modify All (or a write depth of `org`) on it as well. The prompt names the set and the persona's role; the questions and operations stay out of it, so the role the card's prose gives a persona must already imply its reads and writes. A grant it does not imply is a card fix, never a sentence added to the prompt. diff --git a/docs/qa/scenarios/leave_balances.json b/docs/qa/scenarios/leave_balances.json index dbb4c22a4ae..657d707667a 100644 --- a/docs/qa/scenarios/leave_balances.json +++ b/docs/qa/scenarios/leave_balances.json @@ -795,7 +795,7 @@ }, { "id": "sick_by_medical_note", - "ask": {"zh": "病假单按就诊说明分别有多少张?", "en": "How many sick-leave requests are there for each medical note?"}, + "ask": {"zh": "病假单按就诊说明里写的内容分别有多少张?(按说明本身,不是按是否附有医疗证明)", "en": "How many sick-leave requests are there for each medical note, counted by what the note itself says (not by whether a medical certificate is attached)?"}, "object": "leave_request", "truth": { "kind": "count", diff --git a/docs/qa/scenarios/requisition_to_receipt.json b/docs/qa/scenarios/requisition_to_receipt.json index d62dc75d545..51a4e193663 100644 --- a/docs/qa/scenarios/requisition_to_receipt.json +++ b/docs/qa/scenarios/requisition_to_receipt.json @@ -12,8 +12,8 @@ "en": "Build a requisition-to-receipt app: purchase requisitions, an amount-threshold multi-level approval, purchase orders with lines, goods receipts and suppliers." }, "detailed": { - "zh": "采购应用,覆盖从采购申请到收货的全过程。员工提交采购申请(类别、用途说明、金额)。申请按金额分级审批:5000 元及以下只需部门经理审批;超过 5000 元、不超过 30000 元的还要财务主管审批;超过 30000 元的再加总经理审批。审批级数由金额自动算出,逐级流转,任一级驳回即结束。每一级都是一条独立的审批步骤记录(申请、级别、审批人、审批结果和日期),批准或驳回一级就是更新这条记录。申请全部批准后,采购员向供应商下采购单,采购单下有多条明细(物品、数量、单价、金额),明细金额等于数量乘单价,采购单合计自动汇总明细,明细是采购单的从属记录(主从关系),在采购单表单上直接内联编辑;采购单发给供应商后,申请状态变为已下单。到货后由申请人按明细登记收货,收货数量不能超过订购数量,否则不能保存;全部收齐后采购单和申请都变为已收货。取消已发给供应商的采购单不可撤销,必须先确认。员工只能看到自己的申请及其审批、采购单和收货;部门经理能看到本部门的;采购员能看到全部申请和采购单。部门采购预算只有本部门经理和财务可见,采购员和普通员工看不到;供应商银行账号只有采购员和财务可见。需要一个按部门和类别统计采购支出的报表。尽量用声明式配置(公式字段、汇总字段、校验规则)而不是代码钩子,以便应用能以非托管方式安装。", - "en": "A procurement app covering the way from a purchase requisition to the goods receipt. An employee files a requisition (category, description, amount). It is approved in levels set by its amount: up to 5,000 the department manager alone; above 5,000 and up to 30,000 the finance controller as well; above 30,000 the general manager too. The number of levels is computed from the amount, the levels run in order, and a rejection at any level ends it. Each level is its own approval step record (the requisition, the level, the approver, the decision and its date), and approving or rejecting a level updates that record. Once every level has approved, the buyer raises a purchase order to a supplier with several lines (item, quantity, unit price, amount); a line's amount is quantity times unit price, and the order total sums its lines. The lines are details of the order (master-detail), edited inline on the order's form. When the order is sent to the supplier the requisition becomes ordered. When the goods arrive the requester records a receipt per line, and a receipt above the ordered quantity cannot be saved; once everything has arrived, the order and the requisition become received. Cancelling an order already sent to the supplier cannot be undone and is confirmed first. An employee sees only their own requisitions with their approvals, orders and receipts, a department manager sees their department's, and the buyer sees every requisition and order. A department's purchasing budget is visible to that department's manager and to Finance only, not to the buyer or an employee; a supplier's bank account to the buyer and Finance only. Add a report of purchasing spend by department and category. Prefer declarative configuration (formula and roll-up fields, validation rules) over code hooks, so the app can be installed unmanaged." + "zh": "采购应用,覆盖从采购申请到收货的全过程。员工提交采购申请(类别、用途说明、金额)。申请按金额分级审批:5000 元及以下只需部门经理审批;超过 5000 元、不超过 30000 元的还要财务主管审批;超过 30000 元的再加总经理审批。审批级数由金额自动算出,逐级流转,任一级驳回即结束。每一级都是一条独立的审批步骤记录(申请、级别、审批人、审批结果和日期),批准或驳回一级就是更新这条记录。申请全部批准后,采购员向供应商下采购单,采购单下有多条明细(物品、数量、单价、金额),明细金额等于数量乘单价,采购单合计自动汇总明细,明细是采购单的从属记录(主从关系),在采购单表单上直接内联编辑;采购单发给供应商后,申请状态变为已下单,由采购单上的记录触发流程在其状态变为已发送时更新。到货后由申请人按明细登记收货,收货数量不能超过订购数量,否则不能保存;全部收齐后采购单和申请都变为已收货。取消已发给供应商的采购单不可撤销,必须先确认。员工只能看到自己的申请及其审批、采购单和收货;部门经理能看到本部门的;采购员能看到全部申请和采购单。部门采购预算只有本部门经理和财务可见,采购员和普通员工看不到;供应商银行账号只有采购员和财务可见。需要一个按部门和类别统计采购支出的报表。尽量用声明式配置(公式字段、汇总字段、校验规则、记录触发流程)而不是代码钩子,以便应用能以非托管方式安装。", + "en": "A procurement app covering the way from a purchase requisition to the goods receipt. An employee files a requisition (category, description, amount). It is approved in levels set by its amount: up to 5,000 the department manager alone; above 5,000 and up to 30,000 the finance controller as well; above 30,000 the general manager too. The number of levels is computed from the amount, the levels run in order, and a rejection at any level ends it. Each level is its own approval step record (the requisition, the level, the approver, the decision and its date), and approving or rejecting a level updates that record. Once every level has approved, the buyer raises a purchase order to a supplier with several lines (item, quantity, unit price, amount); a line's amount is quantity times unit price, and the order total sums its lines. The lines are details of the order (master-detail), edited inline on the order's form. When the order is sent to the supplier the requisition becomes ordered, set by a record-triggered flow on the purchase order when its status changes to sent. When the goods arrive the requester records a receipt per line, and a receipt above the ordered quantity cannot be saved; once everything has arrived, the order and the requisition become received. Cancelling an order already sent to the supplier cannot be undone and is confirmed first. An employee sees only their own requisitions with their approvals, orders and receipts, a department manager sees their department's, and the buyer sees every requisition and order. A department's purchasing budget is visible to that department's manager and to Finance only, not to the buyer or an employee; a supplier's bank account to the buyer and Finance only. Add a report of purchasing spend by department and category. Prefer declarative configuration (formula and roll-up fields, validation rules, record-triggered flows) over code hooks, so the app can be installed unmanaged." } }, "expect": { diff --git a/docs/qa/scenarios/service_desk.json b/docs/qa/scenarios/service_desk.json index 2a35745a8ab..e298a4d82ab 100644 --- a/docs/qa/scenarios/service_desk.json +++ b/docs/qa/scenarios/service_desk.json @@ -889,7 +889,7 @@ { "name": "log_ticket", "object": "ticket", - "summary": "Log a ticket for a customer, with its first comment, in the right group's queue.", + "summary": "Log a ticket for a customer, with its first comment, in the right group's queue; it assigns the ticket to the signed-in agent who logs it and opens it (status open), so the agent can go on to work it.", "confirm": false }, { diff --git a/docs/qa/scenarios/travel_expense.json b/docs/qa/scenarios/travel_expense.json index b3c02f638e7..fb77a9f7f1e 100644 --- a/docs/qa/scenarios/travel_expense.json +++ b/docs/qa/scenarios/travel_expense.json @@ -12,8 +12,8 @@ "en": "Build a travel expense app: trip requests, expense claims with lines, grade-based travel standards and a two-step approval." }, "detailed": { - "zh": "差旅报销应用。员工先提交出差申请(目的地、起止日期、事由),批准后出行;回来后填写报销单,报销单下有多条明细(住宿、餐补、机票),每条有数量、单价和金额,报销单合计自动汇总明细金额。报销明细是报销单的从属记录(主从关系),在报销单表单上直接内联编辑。差旅标准按职级(g1/g2/g3)和费用类型规定上限;超出标准的明细自动标记为超标,且必须填写超标原因,否则不能保存。报销单走两级审批:先由部门经理审批(经理本人的报销单由财务经理审批),再由一名财务专员(财务经理以外的财务人员)审批;每一步都是一条独立的审批步骤记录(报销单、步骤、审批人、审批结果和日期),批准或驳回一步就是更新这条记录。财务审批通过后由财务付款,付款不可撤销。员工只能看到自己的出差申请和报销单,部门经理能看到本部门的,财务能看到全部报销单但不看出差申请;部门差旅预算只有经理和财务可见,员工银行账号只有本人和财务可见。需要一个按部门和费用类型统计明细金额的报表,数据取自 claim_lines 数据集。尽量用声明式配置(公式字段、汇总字段、校验规则)而不是代码钩子,以便应用能以非托管方式安装。", - "en": "A travel expense app. An employee first files a trip request (destination, start and end dates, purpose); once it is approved they travel. Afterwards they file an expense claim with several lines (hotel, meals, airfare), each with a quantity, a unit amount and an amount, and the claim total sums its line amounts. The lines are details of the claim (master-detail), edited inline on the claim's form. A travel standard caps each expense type per grade (g1/g2/g3); a line above the cap is flagged over-standard automatically and cannot be saved without a reason. A claim goes through a two-step approval: the department manager first (a manager's own claim goes to the finance manager), then a Finance officer (Finance staff other than the finance manager); each step is its own approval step record (the claim, the step, the approver, the decision and its date), and approving or rejecting a step updates that record; once Finance approves, Finance pays it, and a payment cannot be undone. An employee sees only their own trip requests and claims, a department manager sees their department's, and Finance sees every claim but no trip request; a department's travel budget is visible to managers and Finance only, and an employee's bank account to that employee and Finance only. Add a report of claim line amounts by department and expense type, built on the claim_lines dataset. Prefer declarative configuration (formula and roll-up fields, validation rules) over code hooks, so the app can be installed unmanaged." + "zh": "差旅报销应用。员工先提交出差申请(目的地、起止日期、事由),批准后出行;回来后填写报销单,报销单下有多条明细(住宿、餐补、机票),每条有数量、单价和金额,报销单合计自动汇总明细金额。报销明细是报销单的从属记录(主从关系),在报销单表单上直接内联编辑。差旅标准按职级(g1/g2/g3)和费用类型规定上限;超出标准的明细自动标记为超标,且必须填写超标原因,否则不能保存。报销单走两级审批:先由部门经理审批(经理本人的报销单由财务经理审批),再由一名财务专员(财务经理以外的财务人员)审批;每一步都是一条独立的审批步骤记录(报销单、步骤、审批人、审批结果和日期),批准或驳回一步就是更新这条记录,再由审批步骤上的记录触发流程推进报销单(部门经理批准后,报销单变为经理已批准,并生成财务审批步骤)。财务审批通过后由财务付款,付款不可撤销。员工只能看到自己的出差申请和报销单,部门经理能看到本部门的,财务能看到全部报销单但不看出差申请;部门差旅预算只有经理和财务可见,员工银行账号只有本人和财务可见。需要一个按部门和费用类型统计明细金额的报表,数据取自 claim_lines 数据集。尽量用声明式配置(公式字段、汇总字段、校验规则、记录触发流程)而不是代码钩子,以便应用能以非托管方式安装。", + "en": "A travel expense app. An employee first files a trip request (destination, start and end dates, purpose); once it is approved they travel. Afterwards they file an expense claim with several lines (hotel, meals, airfare), each with a quantity, a unit amount and an amount, and the claim total sums its line amounts. The lines are details of the claim (master-detail), edited inline on the claim's form. A travel standard caps each expense type per grade (g1/g2/g3); a line above the cap is flagged over-standard automatically and cannot be saved without a reason. A claim goes through a two-step approval: the department manager first (a manager's own claim goes to the finance manager), then a Finance officer (Finance staff other than the finance manager); each step is its own approval step record (the claim, the step, the approver, the decision and its date), and approving or rejecting a step updates that record; a record-triggered flow on the approval step then moves the claim on (once the manager approves, the claim becomes manager-approved and its Finance step opens); once Finance approves, Finance pays it, and a payment cannot be undone. An employee sees only their own trip requests and claims, a department manager sees their department's, and Finance sees every claim but no trip request; a department's travel budget is visible to managers and Finance only, and an employee's bank account to that employee and Finance only. Add a report of claim line amounts by department and expense type, built on the claim_lines dataset. Prefer declarative configuration (formula and roll-up fields, validation rules, record-triggered flows) over code hooks, so the app can be installed unmanaged." } }, "expect": { diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 87c318e11d8..cfb4b699459 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -58,8 +58,9 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a the artifact into the graph both score. - `scenario-tags.ts` — the capability-tag checks and the agent-action exposure check (each declared action exists on its object, carries `ai.exposed: true`, and carries - `ai.requiresConfirmation: true` where the card says `confirm`; a missing action fails, never - skipped), and the persona grant checks (`gradePersonaGrants`): one Build check per persona × + `ai.requiresConfirmation: true` where the card says `confirm`, and not where it says the agent + acts at once, `->not-confirm-gated`, since an over-gated action meets the door's confirmation + the card never gives; a missing action fails, never skipped), and the persona grant checks (`gradePersonaGrants`): one Build check per persona × object × verb the card implies, `persona-grant:::`, against that persona's own set (`_`). A question asked as the persona needs `read` on its object (not when the persona hides that object: it declines), and an `applied` or @@ -77,6 +78,13 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a card designs for a write that asks first, and its body writes as the platform, so whether the write goes through it is the run's to observe (ruling A on #31999 item 9, carried to the Build side). An `applied` write stays measured against the grant, whatever actions the build adds. + A `delete` the set grants is also read against the platform's owner-only delete floor + (`owner_only_deletes`, `created_by == current_user.id`, which the runner's admin-loaded seed + rows never meet): it passes on each deleted seed row the persona owns (`rowOwner`) or holds + Modify All or a write depth of `org` on, where the object's org-wide default is not public and + it has an `owner_id`; it is not measured where only an authored delete policy, a + `controlled_by_parent` master's gate or a declared route action could admit the row, and fails + otherwise (`deleteFloorReading`). - `scenario-operation-grade.ts` — an observed write against `applied` / `refused` / `pending_confirmation`; a fact the observation does not carry fails. An `applied` state entry may be an aggregate over every row its `where` matches: `sum` (`state:LABEL.sum(amount)`, @@ -89,12 +97,12 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a asks for a correction) and the platform half, `platform:` checks (the runner's own write of the declared values, the probe, was refused with that code and stored nothing); so is every other `refused` create or update, permission oversteps included (`isProbedOperation`). A - declared `VALIDATION_FAILED` is met by the app's own refusal at any 4xx status, or by the - app's flow refusal (`refusalMeets`). A hook's declared refusal reaches the MCP data tools + declared `VALIDATION_FAILED` is met by the app's own refusal at any 4xx status, a hook's + undeclared one (`HOOK_ABORTED`) included, or by the app's flow refusal (`refusalMeets`). A hook's declared refusal reaches the MCP data tools with `code` set to the status's catalogue code (`RESOURCE_CONFLICT` at 409) and the hook's own code beside it as `declaredCode` (`ASSET_NOT_IN_STOCK`); the runner keeps both, and a declared code meets its `declaredCode` exactly. A platform catalogue code other than the - declared one, with no `declaredCode`, never meets it. The platform half is not measured, out of passed and total with the reason in the + declared one and `HOOK_ABORTED`, with no `declaredCode`, never meets it. The platform half is not measured, out of passed and total with the reason in the scorecard's findings, when the probe met the build's own lock: refused 403 `PERMISSION_DENIED`, nothing written, and the build locks a field the probe writes for the persona and declares an action on the object (`buildLockOf`; ruling A on #31999 item 9). @@ -173,6 +181,9 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a and `USD3,000` still are. A figure a `query_dataset` answer served over its object is cited by a source line naming that answer's dataset, or by the answer's `sourceLine` carried verbatim — the source the door tells the client to cite, which names the dataset rather than the object. + On a `withheld` truth a sentence about what a dataset or report covers ("The Approved Leave + dataset can't group by medical note") is no decline unless it binds to the asker + (`datasetCoverage`). ### The closed capability-tag table @@ -199,7 +210,7 @@ discrimination test; ⛔ never match by area prefix. | `automation.record-triggered-flow` | carries a record-triggered flow, each bound to an object it serves, one bound to an object the card names | | `dashboards.widget-measures` | carries a dashboard widget with a measure, and every widget measure resolves on the dataset it binds | | `dashboards.report` | carries a report whose dataset binds an object the card names, every report selecting only measures and dimensions its datasets declare | -| `ai.agent-actions` | carries every action in `run.agentActions` on its object, AI-exposed and confirm-gated where the card says `confirm` (the agent-action checks) | +| `ai.agent-actions` | carries every action in `run.agentActions` on its object, AI-exposed and confirm-gated where the card says `confirm`, and only there (the agent-action checks) | ## Running the cards in a Claude Code cloud session diff --git a/packages/qa/scenarios/src/row-owner.ts b/packages/qa/scenarios/src/row-owner.ts new file mode 100644 index 00000000000..b7e275a3d9e --- /dev/null +++ b/packages/qa/scenarios/src/row-owner.ts @@ -0,0 +1,57 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Who owns a seed row (`owner_id`): the runner loads each row as owned by the + * persona it names, and the scorer judges a persona's writes against the same + * owner (`score/scenario-tags.ts`, the platform's owner-only delete floor). One + * reading, in a module both reach without the scorer importing the runner. + */ + +import type { ScenarioCard } from './schema.js'; + +/** The parts of a card the owner of a seed row is read from. */ +export type RowOwnerCard = Pick & { run: Pick }; + +/** The declared lookups (`expect.lookups`) that point at a person object, the object of some persona's `record` (`ticket.assignee` → `agent`). */ +export function personLookups(card: RowOwnerCard): Array<{ object: string; field: string; to: string }> { + const people = new Set(card.run.personas.flatMap((p) => (p.record ? [p.record.object] : []))); + return (card.expect.lookups ?? []).filter((l) => people.has(l.to)).map(({ object, field, to }) => ({ object, field, to })); +} + +/** + * The persona a seed row is loaded as owned by (`owner_id`), or undefined + * when it names no person and the inserter (the admin) keeps it. A row names a + * persona when it IS that persona's record, when a declared direct lookup on + * it holds that record's id (`ticket.assignee` = `a02`), or when a declared + * user-handle field on it holds that persona's handle (`account.owner` = + * `u_sam`). The first persona in `run.personas` order the row names owns it. + * An option value (`ticket_comment.visibility` = `public`), a row id scope + * (`department.id` = `dep_sales`) and a lookup to a row no persona is (a + * department, a group) name nobody. + */ +export function rowOwner(card: RowOwnerCard, object: string, row: Readonly>): string | undefined { + const lookups = personLookups(card).filter((l) => l.object === object); + const handles = userHandleFields(card); + for (const p of card.run.personas) { + const rec = p.record; + if (rec !== undefined) { + if (rec.object === object && row.id === rec.id) return p.id; + if (lookups.some((l) => l.to === rec.object && row[l.field] === rec.id)) return p.id; + } + for (const sc of p.scope ?? []) { + if (sc.object === object && !sc.field.includes('.') && handles.has(`${object}.${sc.field}`) && row[sc.field] === sc.value) return p.id; + } + } + return undefined; +} + +/** + * The seed fields whose values are user handles, `object.field`: the card's + * declared `run.userHandleFields`, read and never inferred. In the crm card + * that is `account.owner` (`u_sam`, `u_tia`). Every other field holds a row id + * or an option value (`asset.custodian` = `e06`, an employee row; + * `ticket_comment.visibility` = `public`), which the seed loads verbatim. + */ +export function userHandleFields(card: Pick): Set { + return new Set((card.run.userHandleFields ?? []).map((h) => `${h.object}.${h.field}`)); +} diff --git a/packages/qa/scenarios/src/runner/prompts.ts b/packages/qa/scenarios/src/runner/prompts.ts index 044021f6cf5..0530e6e1daf 100644 --- a/packages/qa/scenarios/src/runner/prompts.ts +++ b/packages/qa/scenarios/src/runner/prompts.ts @@ -43,10 +43,14 @@ import type { LoadedScenario } from '../loader.js'; import { PERSON_USER_FIELD, scenarioNamespace, type LocalizedText, type ScenarioCard, type ScenarioExpect } from '../schema.js'; +import { personLookups, rowOwner, userHandleFields } from '../row-owner.js'; import { permissionSetName } from './namespace.js'; import { cycleText, referenceCycles } from './seed.js'; type Card = ScenarioCard; + +// The seed rows' owners, read by the scorer too: kept where both reach them, re-exported here for the runner. +export { rowOwner, userHandleFields }; type Persona = Card['run']['personas'][number]; const code = (name: string): string => `\`${name}\``; @@ -282,50 +286,6 @@ export function personaRecords(card: Card): Map { return out; } -/** The declared lookups (`expect.lookups`) that point at a person object, the object of some persona's `record` (`ticket.assignee` → `agent`). */ -function personLookups(card: Card): Array<{ object: string; field: string; to: string }> { - const people = new Set(card.run.personas.flatMap((p) => (p.record ? [p.record.object] : []))); - return (card.expect.lookups ?? []).filter((l) => people.has(l.to)).map(({ object, field, to }) => ({ object, field, to })); -} - -/** - * The persona a seed row is loaded as owned by (`owner_id`), or undefined - * when it names no person and the inserter (the admin) keeps it. A row names a - * persona when it IS that persona's record, when a declared direct lookup on - * it holds that record's id (`ticket.assignee` = `a02`), or when a declared - * user-handle field on it holds that persona's handle (`account.owner` = - * `u_sam`). The first persona in `run.personas` order the row names owns it. - * An option value (`ticket_comment.visibility` = `public`), a row id scope - * (`department.id` = `dep_sales`) and a lookup to a row no persona is (a - * department, a group) name nobody. - */ -export function rowOwner(card: Card, object: string, row: Readonly>): string | undefined { - const lookups = personLookups(card).filter((l) => l.object === object); - const handles = userHandleFields(card); - for (const p of card.run.personas) { - const rec = p.record; - if (rec !== undefined) { - if (rec.object === object && row.id === rec.id) return p.id; - if (lookups.some((l) => l.to === rec.object && row[l.field] === rec.id)) return p.id; - } - for (const sc of p.scope ?? []) { - if (sc.object === object && !sc.field.includes('.') && handles.has(`${object}.${sc.field}`) && row[sc.field] === sc.value) return p.id; - } - } - return undefined; -} - -/** - * The seed fields whose values are user handles, `object.field`: the card's - * declared `run.userHandleFields`, read and never inferred. In the crm card - * that is `account.owner` (`u_sam`, `u_tia`). Every other field holds a row id - * or an option value (`asset.custodian` = `e06`, an employee row; - * `ticket_comment.visibility` = `public`), which the seed loads verbatim. - */ -export function userHandleFields(card: Card): Set { - return new Set((card.run.userHandleFields ?? []).map((h) => `${h.object}.${h.field}`)); -} - /** The handles a seed row names in a {@link userHandleFields} field that no persona signs in as (`u_tia`): the seed loads each as the admin user. */ export function unheldHandles(card: Card): string[] { const held = personaHandles(card); @@ -504,7 +464,7 @@ export function dataContract(card: Card): string { } if (card.run.agentActions?.length) { lines.push(''); - lines.push('Business actions an AI agent may call (expose each to AI; ask before acting where marked):'); + lines.push('Business actions an AI agent may call (expose each to AI; ask before acting where marked, and only there: an unmarked action runs at once, with no confirmation gate):'); for (const a of card.run.agentActions) lines.push(`- \`${a.name}\` on \`${a.object}\`: ${a.summary}${a.confirm ? ` (${CONFIRM_FIRST_LOCK})` : ''}`); } return lines.join('\n'); diff --git a/packages/qa/scenarios/src/score/scenario-operation-grade.ts b/packages/qa/scenarios/src/score/scenario-operation-grade.ts index 4d7192c3d5a..0750c9635d4 100644 --- a/packages/qa/scenarios/src/score/scenario-operation-grade.ts +++ b/packages/qa/scenarios/src/score/scenario-operation-grade.ts @@ -414,6 +414,18 @@ function isValidationCode(code: string): boolean { return code === ('VALIDATION_FAILED' satisfies ErrorCode); } +/** + * The code a write door answers when a hook body refused the write in its own + * words and declared no code (`UNDECLARED_HOOK_REFUSAL_CODE`, the ledger's + * `HOOK_ABORTED`): the app's own rule, answered at the status the body chose, + * else 400. A sandbox FAULT (a crash, a budget) is answered 5xx instead, so a + * 4xx `HOOK_ABORTED` is a refusal and never an error. A comparison, as + * {@link isValidationCode} is. + */ +function isUndeclaredHookRefusal(code: string): boolean { + return code === ('HOOK_ABORTED' satisfies ErrorCode); +} + /** * The refusal met the declared code. Exactly that code, as the door's `code` * or as its `declaredCode`, or — for a declared `VALIDATION_FAILED` — the @@ -429,11 +441,17 @@ function isValidationCode(code: string): boolean { * unregistered code, #31407), whatever the catalogue `code`; * - a `code` that is none of the platform's (it fails the spec's `ErrorCode` * catalogue, ADR-0112) at any 4xx status; + * - `HOOK_ABORTED` at any 4xx status ({@link isUndeclaredHookRefusal}): a + * hook that refused in its own words and declared no code. A card whose + * data contract steers a rule off a declarative check (order_to_cash + * `overpay_invoice`: the seed posture forbids a validation rule comparing + * a loaded payment with its invoice's stored balance) leaves a hook as the + * build's route, and its refusal is still the app's own; * - the flow's declared refusal ({@link flowRefused}): the build routed the * write through an action whose flow refused it. * * Platform codes stay strict: a catalogue code with no `declaredCode`, other - * than the declared one, never meets it at any status (a denial at 403, a + * than the declared one and `HOOK_ABORTED`, never meets it at any status (a denial at 403, a * missing row at 404, a conflict at 409, an error at 500). Nor does an app * code or a `declaredCode` with no status or a 5xx one, nor the runner's other * parenthesized labels. @@ -445,7 +463,7 @@ export function refusalMeets(declared: string, answer: ObservedAnswer): boolean if (answer.code === flowRefused) return true; if (answer.status === undefined || answer.code.startsWith('(')) return false; const clientError = answer.status >= 400 && answer.status < 500; - if (answer.declaredCode !== undefined) return clientError; + if (answer.declaredCode !== undefined || isUndeclaredHookRefusal(answer.code)) return clientError; if (ErrorCode.safeParse(answer.code).success) return false; return clientError; } @@ -454,6 +472,7 @@ const refusalText = (declared: string, a: ObservedAnswer): string => { if (!refusalMeets(declared, a) || a.kind !== 'refused' || a.code === declared) return answerText(a); if (a.code === flowRefused) return `${answerText(a)}, the app's flow refusal`; if (a.declaredCode !== undefined) return `${answerText(a)}, the hook's declared refusal ${a.declaredCode}`; + if (isUndeclaredHookRefusal(a.code)) return `${answerText(a)}, the hook's own refusal`; return `${answerText(a)}, an app-defined refusal`; }; diff --git a/packages/qa/scenarios/src/score/scenario-run-grade.ts b/packages/qa/scenarios/src/score/scenario-run-grade.ts index 82e1ed85e4f..4fafec30520 100644 --- a/packages/qa/scenarios/src/score/scenario-run-grade.ts +++ b/packages/qa/scenarios/src/score/scenario-run-grade.ts @@ -847,10 +847,58 @@ export function declines(replyText: string): boolean { * (ADR-0106 D8) every caller is served the whole schema, the field is in it, * and the same reply claims an absence that is untrue: no decline, as "blank" * or "empty" is none. + * + * A sentence about what a dataset or a report covers is no decline of the + * field ({@link datasetCoverage}): "The Approved Leave dataset can't group by + * medical note" says what a tool serves, not that the asker may not see the + * field, and a reply that goes on to group by a visible field instead has + * answered another question. Those sentences are left out before the asker and + * field-absence wordings are read; a first-person withheld write + * ({@link WITHHELD_ACT}) is read over the whole reply. + */ +function declinesWithheld(turn: RunTranscript, schemaMasking: SchemaMaskingMode): boolean { + if (WITHHELD_ACT.test(turn.replyText)) return true; + const datasets = [...datasetCitations(turn.toolCalls).values()].flatMap((d) => d.names); + const text = sentencesOf(turn.replyText) + .filter((s) => !datasetCoverage(s, datasets)) + .join('\n'); + if (ASKER_DECLINE.test(text)) return true; + return schemaMasking === 'on' && (UNRECORDED.test(text) || UNTRACKED.test(text)); +} + +/** A reply's sentences: split at a stop, a question or exclamation mark, a semicolon (each followed by a space or the end) and at every line break. */ +function sentencesOf(text: string): string[] { + return text.split(/(?<=[.!?;])(?=\s|$)|[。!?;\n]+/).map((s) => s.trim()).filter((s) => s.length > 0); +} + +/** What a reply calls a dataset or a report, the things a sentence on what a tool covers is about. */ +const DATASET_NOUN = /\b(?:datasets?|data sets?|reports?)\b|数据集|报表/i; +/** + * A sentence that binds to the asker: it addresses them, or names a permission, + * an access right or a visibility ("you can't see it", "hidden from your + * role", "no read access", "您没有权限"). Such a sentence declines even when it + * also names a dataset. + */ +const ASKER_BOUND = + /\b(?:you|your|yours|permissions?|access|visible|hidden|permitted|allowed|authori[sz]ed|restricted)\b|你|您|权限|不可见|看不到/i; + +/** + * The sentence is about what a dataset or report covers: it names one — by the + * word ({@link DATASET_NOUN}) or by a name or label of a dataset a + * `query_dataset` answer of the turn served ({@link datasetCitations}) — and + * nothing in it binds to the asker ({@link ASKER_BOUND}). "The Approved Leave + * dataset can't group by medical note" is one; "The dataset leaves out the + * medical note, which is hidden from your role" is not. + * + * The cost: a decline worded only through the dataset ("I can't group by + * medical note: the dataset doesn't expose it") reads as none. On a withheld + * field that is the reading the field-level-security ruling wants: the reply + * says nothing of the asker. */ -function declinesWithheld(replyText: string, schemaMasking: SchemaMaskingMode): boolean { - if (ASKER_DECLINE.test(replyText) || WITHHELD_ACT.test(replyText)) return true; - return schemaMasking === 'on' && (UNRECORDED.test(replyText) || UNTRACKED.test(replyText)); +function datasetCoverage(sentence: string, datasetNames: readonly string[]): boolean { + if (ASKER_BOUND.test(sentence)) return false; + const lower = sentence.toLowerCase(); + return DATASET_NOUN.test(sentence) || datasetNames.some((n) => lower.includes(n)); } /** @@ -1044,7 +1092,7 @@ export function gradePersonaRun(input: PersonaRunInput, turn: RunTranscript): Pe const reply = numbersIn(turn.replyText); if (input.personaTruth.kind === 'withheld') { - const declined = declinesWithheld(turn.replyText, input.schemaMasking ?? 'on') || refusedWithoutFigure(turn); + const declined = declinesWithheld(turn, input.schemaMasking ?? 'on') || refusedWithoutFigure(turn); const leaks = leaksOf({ figures: [] }, input.hidden, turn); const served = leaks.some((l) => !l.startsWith('reply')); const nouns = nounPattern([input.object, ...(input.objectLabels?.[input.object] ?? [])]); diff --git a/packages/qa/scenarios/src/score/scenario-tags.ts b/packages/qa/scenarios/src/score/scenario-tags.ts index 7ae784e8e52..82773bb7040 100644 --- a/packages/qa/scenarios/src/score/scenario-tags.ts +++ b/packages/qa/scenarios/src/score/scenario-tags.ts @@ -57,7 +57,7 @@ * Deterministic: no model call, no network (the cost ruling on cloud#3600). */ -import { buildEffectiveObjectPermissions, resolveStackCollection, superuserFieldVote } from '@objectstack/core'; +import { buildEffectiveObjectPermissions, holdsSuperuserBypass, resolveStackCollection, superuserFieldVote } from '@objectstack/core'; import { standaloneActionOwnerKey } from '@objectstack/objectql'; import { effectiveSharingModel } from '@objectstack/plugin-sharing'; import { @@ -77,6 +77,7 @@ import { import { objectPermissionGrants, type ObjectPermissionVerbTarget } from '@objectstack/spec/security'; import { SystemFieldName } from '@objectstack/spec/system'; +import { rowOwner } from '../row-owner.js'; import { personaPermissionSetName, ROW_SCOPE_TAG, type ScenarioCard } from '../schema.js'; import { approverExpressionRefusal, recordExpressionRefusal, rlsPredicateEnforces } from './scenario-expressions.js'; import { artifactToEvalGraph } from './scenario-graph.js'; @@ -106,7 +107,7 @@ const norm = (s: string): string => s.trim().toLowerCase(); * alone ({@link gradePersonaGrants}); a pick without them derives none. */ export type ScenarioArtifactCard = Pick & { - run: Pick & Partial>; + run: Pick & Partial>; }; /** A business action the card declares an agent must be able to call (`run.agentActions[]`). */ @@ -836,7 +837,7 @@ export const CAPABILITY_TAG_CHECKS: Readonly> = Object. 'ai.agent-actions': { asserts: - 'every business action the card declares an agent may call (`run.agentActions`) exists on its object, is opted into the AI / MCP surface (`ai.exposed`), and is confirm-gated (`ai.requiresConfirmation`) where the card says `confirm`', + 'every business action the card declares an agent may call (`run.agentActions`) exists on its object, is opted into the AI / MCP surface (`ai.exposed`), and is confirm-gated (`ai.requiresConfirmation`) where the card says `confirm`, and only there', run(f, card) { // The checks `gradeAgentActions` runs for the card's actions, counted // under this tag as well — as `dashboards.widget-measures` counts the @@ -874,7 +875,9 @@ export function gradeCapabilityTags(facts: ArtifactFacts, card: ScenarioArtifact /** * One check per declared fact of each action. A missing declaration fails all - * of its checks — the agent cannot call what the build does not expose. + * of its checks — the agent cannot call what the build does not expose. The + * gate is judged both ways: `confirm-gated` where the card says `confirm`, + * `not-confirm-gated` where it says the agent acts at once. */ export function gradeAgentActions(facts: ArtifactFacts, actions: readonly ScenarioAgentAction[]): CheckResult[] { const out: CheckResult[] = []; @@ -894,6 +897,20 @@ export function gradeAgentActions(facts: ArtifactFacts, actions: readonly Scenar ai?.requiresConfirmation === true, !decl ? 'not declared' : ai?.requiresConfirmation === true ? undefined : 'ai.requiresConfirmation is not true, so nothing gates the call', )); + } else { + // Over-gating is a build defect too: the card has the agent act at + // once, and a gated action meets the door's confirmation instead + // (`428 no_confirmation_service` where no confirmation service runs), so + // the run could only mark the write not measured. + out.push(check( + `${at}->not-confirm-gated`, + !!decl && ai?.requiresConfirmation !== true, + !decl + ? 'not declared' + : ai?.requiresConfirmation === true + ? 'ai.requiresConfirmation is true on an action the card has the agent run without asking, so the door asks for a confirmation the card never gives' + : undefined, + )); } } return out; @@ -1066,6 +1083,100 @@ function designedRoutes(facts: ArtifactFacts, card: ScenarioArtifactCard, n: Per return routes.every((r) => r.via.length > 0 || r.confirm.length > 0) ? routes : undefined; } +/** + * The platform's owner-only delete floor, read for each write a delete need + * applies or awaits ({@link PersonaGrantNeed.requiredBy}), against the row the + * operation deletes (`target`). Read off the platform, not guessed: + * + * - every member resolves `member_default`, whose wildcard + * `owner_only_deletes` policy (plugin-security + * `platform-ownership-policies.ts`) admits a delete only of a row the caller + * created. The runner loads the seed as the admin user, so no persona + * created a seeded row; + * - the floor comes off a row only where the sharing service's delete + * verdict (`SharingService.checkDelete`, plugin-sharing) answers `allow`: + * ownership (`owner_id`, the persona {@link rowOwner} loads the row as + * owned by; a write depth of `org`) or Modify All (`modifyAllRecords`). An + * edit share never opens a delete. That verdict abstains on an object + * whose org-wide default is public (`public_read_write` opens updates + * only, `owdOpenWritesCoversOperation`) or which has no `owner_id` + * (`ownership` other than `user`), and an abstain leaves the floor + * standing, Modify All included; + * - beside the floor, an app-authored row policy for deletes (`delete` or + * `all`, with a `using`) widens the rows a delete reaches (Layer 1 is an + * OR of permissive policies), and a `controlled_by_parent` detail hands its + * floor to the master's gate. Each depends on a row the artifact does not + * carry, so the write is `open`: not measured; + * - an agent action the build declares as the write's designed route (the + * one the operation names, `via`, or for a write awaiting confirmation the + * card's confirm-gated one, as {@link designedRoutes} reads them) runs + * elevated and meets no floor: `open` too, the run's to observe. + * + * Every other write is `refused`. A write whose operation names no `target`, + * or whose target is not a seed row the card carries, is judged no further. + */ +function deleteFloorReading( + facts: ArtifactFacts, + card: ScenarioArtifactCard, + set: Bag, + n: PersonaGrantNeed, +): { refused: Array<{ operation: string; row: string; why: string }>; open: Array<{ operation: string; row: string; why: string }> } { + const refused: Array<{ operation: string; row: string; why: string }> = []; + const open: Array<{ operation: string; row: string; why: string }> = []; + const schema = facts.objects.get(n.object); + const declared = schema?.sharingModel ?? (isBag(schema?.security) ? schema.security.sharingModel : undefined); + const ownerField = (schema?.ownership ?? 'user') === 'user'; + const sharingEnforces = effectiveSharingModel(schema) !== 'public' && ownerField; + const objects = isBag(set.objects) ? set.objects : {}; + const entry = objects[n.object] ?? objects['*']; + const orgDepth = isBag(entry) && entry.writeScope === 'org'; + const modifyAll = holdsSuperuserBypass(set as { objects?: Record }, n.object, 'modify'); + const authored = (Array.isArray(set.rowLevelSecurity) ? set.rowLevelSecurity : []).filter( + (r): r is Bag => + isBag(r) && + r.enabled !== false && + (r.object === '*' || r.object === n.object) && + (r.operation === 'all' || r.operation === 'delete') && + typeof r.using === 'string' && + r.using.trim().length > 0 && + !(Array.isArray(r.positions) && r.positions.length > 0), + ); + const confirmRoutes = confirmGatedRoutes(facts, card, n.object); + for (const r of n.requiredBy) { + if (!r.startsWith('operation ')) continue; + const operation = r.slice('operation '.length); + const op = (card.run.operations ?? []).find((o) => o.id === operation); + const target = op?.target; + const row = target === undefined ? undefined : (card.run.seed?.[n.object] ?? []).find((x) => x.id === target); + if (target === undefined || row === undefined) continue; + const owner = rowOwner(card, n.object, row); + if (sharingEnforces && (modifyAll || orgDepth || owner === n.persona)) continue; + if (declared === 'controlled_by_parent') { + open.push({ operation, row: target, why: `${n.object} is \`controlled_by_parent\` and its master's gate decides, which depends on the master row` }); + continue; + } + if (authored.length > 0) { + open.push({ operation, row: target, why: `only ${authored.map((p) => `row policy ${String(p.name)}`).join(', ')} could admit it, which depends on the row` }); + continue; + } + const via = n.routedVia.filter((v) => v.operation === operation && buildDeclaresAction(facts, n.object, v.action)).map((v) => v.action); + const through = [...new Set([...via, ...(n.awaitingConfirmation.includes(operation) ? confirmRoutes : [])])]; + if (through.length > 0) { + open.push({ operation, row: target, why: `the build declares ${through.join(' or ')}, a door that writes as the platform: whether the write goes through it is the run's to observe` }); + continue; + } + const whose = owner === undefined ? 'a row the admin owns' : owner === n.persona ? `a row ${n.persona} owns` : `a row ${owner} owns`; + refused.push({ + operation, + row: target, + why: sharingEnforces + ? `${whose}, and ${String(set.name)} holds no Modify All (\`modifyAllRecords\`) or \`writeScope: 'org'\` on ${n.object}` + : `${whose}, and ${n.object}'s ${ownerField ? `org-wide default (\`${String(declared ?? 'unset')}\`) is public` : 'records have no owner (`ownership` is not `user`)'}, so the sharing service abstains and nothing lifts the floor, Modify All included`, + }); + } + return { refused, open }; +} + /** * One Build check per persona × object × verb the card implies * ({@link personaGrantNeeds}), named `persona-grant:::`, @@ -1092,6 +1203,11 @@ function designedRoutes(facts: ArtifactFacts, card: ScenarioArtifactCard, n: Per * confirm-gated agent action on the object ({@link confirmGatedRoutes}). * An operation without `via` is graded as before: an applied write stays * measured whatever actions the build adds. + * A delete the set grants is also read against the platform's owner-only + * delete floor ({@link deleteFloorReading}): `allowDelete` without Modify + * All does not pass a delete of a seeded row the persona does not own. It + * fails where nothing lifts the floor on some write's row, and is not + * measured where only a row-dependent rule or an elevated route could. * - Refused `PERMISSION_DENIED` only: passes when the set refuses every such * write — it grants no verb, or it locks a field each write names * ({@link writeRefusalRoute}). When only a row rule could refuse one, the @@ -1139,6 +1255,27 @@ export function gradePersonaGrants(facts: ArtifactFacts, card: ScenarioArtifactC `${routed.join(', ')} there, a door that writes as the platform: whether ${n.requiredBy.join(', ')} goes through it is the run's to observe`, }; } + if (granted && n.verb === 'delete') { + const floor = deleteFloorReading(facts, card, set, n); + if (floor.refused.length > 0) { + return check( + name, + false, + `${setName} grants delete on ${n.object}, but the platform keeps owner-only deletes (its \`owner_only_deletes\` floor, ` + + '`created_by == current_user.id`) where nothing lifts it: ' + + floor.refused.map((r) => `operation ${r.operation} deletes ${r.row}, ${r.why}`).join('; '), + ); + } + if (floor.open.length > 0) { + return { + check: name, + pass: false, + notMeasured: + `${setName} grants delete on ${n.object}; the platform's owner-only delete floor stands on ` + + floor.open.map((r) => `operation ${r.operation} (${r.row}), where ${r.why}`).join('; '), + }; + } + } return check( name, granted, diff --git a/packages/qa/scenarios/test/export/fixture.ts b/packages/qa/scenarios/test/export/fixture.ts index 9ab7e523b64..7b70def3d30 100644 --- a/packages/qa/scenarios/test/export/fixture.ts +++ b/packages/qa/scenarios/test/export/fixture.ts @@ -67,7 +67,9 @@ export function crmArtifact(iterated: boolean) { manifest: { id: `com.example.${NS}`, namespace: NS }, objects, permissions: [ - { name: n('sdr'), objects: { [n('account')]: { allowRead: true }, [n('contact')]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, fields: { [`${n('contact')}.email`]: { readable: false } } }, + // `writeScope: 'org'` lifts the platform's owner-only delete floor for the sdr's + // card deletes of admin-owned contacts, as Modify All would without unmasking `email`. + { name: n('sdr'), objects: { [n('account')]: { allowRead: true }, [n('contact')]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, writeScope: 'org' } }, fields: { [`${n('contact')}.email`]: { readable: false } } }, { name: n('partner_user'), objects: { [n('contact')]: { allowRead: true, allowCreate: true } } }, ], }; diff --git a/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts b/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts index 5dcc841e5a9..1a8fa4f5ccb 100644 --- a/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts +++ b/packages/qa/scenarios/test/runner/mid-tier-run-readings.test.ts @@ -205,6 +205,19 @@ describe('2. the app\'s own refusal meets a declared VALIDATION_FAILED, read fro expect(refusalMeets('PERMISSION_DENIED', { kind: 'refused', code: 'VALIDATION_ERROR', status: 400, declaredCode: 'NOT_REQUESTER' })).toBe(false); }); + it("a hook's own refusal with no declared code (HOOK_ABORTED) meets a declared VALIDATION_FAILED at a client-error status, and nothing else", () => { + // order_to_cash `overpay_invoice`: the seed posture forbids a validation rule comparing a loaded payment with + // its invoice's stored balance, so a build refuses the overpayment in a hook, which answers HOOK_ABORTED at 400. + for (const status of [400, 409, 422]) { + expect(refusalMeets('VALIDATION_FAILED', { kind: 'refused', code: 'HOOK_ABORTED', status }), String(status)).toBe(true); + } + // ⛔ A sandbox fault is served 5xx, and an answer with no status is no door's: not the app's refusal. + expect(refusalMeets('VALIDATION_FAILED', { kind: 'refused', code: 'HOOK_ABORTED', status: 500 })).toBe(false); + expect(refusalMeets('VALIDATION_FAILED', { kind: 'refused', code: 'HOOK_ABORTED' })).toBe(false); + // ⛔ Only a declared VALIDATION_FAILED reads it: a declared denial stays the platform's own. + expect(refusalMeets('PERMISSION_DENIED', { kind: 'refused', code: 'HOOK_ABORTED', status: 400 })).toBe(false); + }); + it('a declared code meets its declaredCode exactly; a catalogue code with no declaredCode never meets a different declared code', () => { const served = { kind: 'refused', code: 'RESOURCE_CONFLICT', status: 409, declaredCode: 'ASSET_NOT_IN_STOCK' } as const; expect(refusalMeets('ASSET_NOT_IN_STOCK', served)).toBe(true); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 852d8d881db..d66f1298cf9 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -91,7 +91,9 @@ function artifact(opts: { degraded?: boolean; iterated?: boolean; ns?: string; b manifest: { id: `com.example.${ns}`, namespace: ns }, objects, permissions: [ - { name: n('sdr'), objects: { [n('account')]: { allowRead: true }, [n('contact')]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, fields: { [`${n('contact')}.email`]: { readable: false } } }, + // `writeScope: 'org'` lifts the platform's owner-only delete floor for the sdr's + // card deletes of admin-owned contacts, as Modify All would without unmasking `email`. + { name: n('sdr'), objects: { [n('account')]: { allowRead: true }, [n('contact')]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, writeScope: 'org' } }, fields: { [`${n('contact')}.email`]: { readable: false } } }, { name: n('partner_user'), objects: { [n('contact')]: { allowRead: true, allowCreate: true } } }, ], // A build that names a view and a dashboard bare: the objects are prefixed (defineStack insists), these are not. diff --git a/packages/qa/scenarios/test/score/scenario-cards.test.ts b/packages/qa/scenarios/test/score/scenario-cards.test.ts index 893b2ef105c..04761beaff4 100644 --- a/packages/qa/scenarios/test/score/scenario-cards.test.ts +++ b/packages/qa/scenarios/test/score/scenario-cards.test.ts @@ -133,7 +133,7 @@ describe('control cards — scored end to end against their golden builds', () = }, actions: 0, grants: 6, - passedOf: [12, 26], + passedOf: [12, 28], }, invoice_with_line_items: { tags: { @@ -146,7 +146,7 @@ describe('control cards — scored end to end against their golden builds', () = }, actions: 0, grants: 8, - passedOf: [20, 37], + passedOf: [20, 39], }, project_with_tasks: { tags: { @@ -158,7 +158,7 @@ describe('control cards — scored end to end against their golden builds', () = }, actions: 0, grants: 5, - passedOf: [20, 32], + passedOf: [20, 34], }, }; @@ -183,12 +183,14 @@ describe('control cards — scored end to end against their golden builds', () = // Each persona's own set, named as the runner grants it with no namespace // (its id): the sdr reads accounts and works contacts; the partner user // creates contacts and holds no grant on accounts, so its refused account - // edit is refused by the set. + // edit is refused by the set. The sdr's deletes are of contacts the admin + // owns, so its set also lifts the platform's owner-only delete floor + // (`writeScope: 'org'`; Modify All would unmask `email`). stack.permissions = [ { name: 'sdr', label: 'SDR', - objects: { account: { allowRead: true }, contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + objects: { account: { allowRead: true }, contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, writeScope: 'org' } }, fields: { 'contact.email': { readable: false, editable: false } }, }, { name: 'partner_user', label: 'Partner User', objects: { contact: { allowRead: true, allowCreate: true } } }, @@ -209,6 +211,7 @@ describe('control cards — scored end to end against their golden builds', () = for (const degrade of [ (a: Bag) => { a.permissions = []; }, (a: Bag) => { delete a.permissions[0].objects.contact.allowEdit; }, + (a: Bag) => { delete a.permissions[0].objects.contact.writeScope; }, (a: Bag) => { a.permissions[1].objects.account = { allowRead: true, allowEdit: true }; }, (a: Bag) => { a.actions = []; }, (a: Bag) => { delete a.actions.find((x: Bag) => x.name === 'delete_contact').ai.requiresConfirmation; }, diff --git a/packages/qa/scenarios/test/score/scenario-run-grade.test.ts b/packages/qa/scenarios/test/score/scenario-run-grade.test.ts index f173d86de9b..48e9b1dc483 100644 --- a/packages/qa/scenarios/test/score/scenario-run-grade.test.ts +++ b/packages/qa/scenarios/test/score/scenario-run-grade.test.ts @@ -1062,3 +1062,59 @@ describe('a withheld field the reply says does not exist: a decline under schema } }); }); + +describe("a sentence about what a dataset covers is no decline of a withheld field", () => { + // leave_balances `sick_by_medical_note`: `medical_note` is withheld from the + // dept_manager and the hr_officer. The 18.6.0 gallery refresh graded three + // replies that grouped by the visible certificate flag instead "declined", + // on a sentence that said what the served dataset could group by. + const HERE = dirname(fileURLToPath(import.meta.url)); + const AREAS_DIR = resolve(HERE, '../../../../../docs/qa/platform-checklist/areas'); + const { card: leave, refusals } = loadScenarioFile(resolve(HERE, '../../../../../docs/qa/scenarios/leave_balances.json'), { areas: readCapabilityAreas(AREAS_DIR), library: 'open' }); + const served = { + name: 'query_dataset', + input: { dataset: 'approved_leave' }, + output: JSON.stringify({ object: 'leave_request', provenance: { kind: 'dataset', dataset: { name: 'approved_leave', label: 'Approved Leave' } }, rows: [] }), + }; + const asManager = (reply: string, calls: RunTranscript['toolCalls'] = [], schemaMasking?: 'on' | 'off') => + gradeCardAnswer(leave!, { question: 'sick_by_medical_note', persona: 'dept_manager', turn: turn(reply, calls), ...(schemaMasking ? { schemaMasking } : {}) }); + + it('loads the card with the question withheld from the manager', () => { + expect(refusals.map(formatRefusal)).toEqual([]); + expect(leave!.personaTruths.sick_by_medical_note?.dept_manager).toEqual({ kind: 'withheld' }); + }); + + it('⛔ a dataset-coverage sentence, by the word or by a served dataset\'s name, then another grouping: no decline', () => { + for (const [reply, calls] of [ + ['The Approved Leave dataset can\'t group by medical note, so here they are by whether a certificate is attached.', []], + ['The leave report cannot break requests down by medical note. By certificate attached: yes, no.', []], + ['Approved Leave can\'t group by medical note. By certificate attached: yes, no.', [served]], + ['Approved Leave only covers approved requests and is unable to split them by medical note.', [served]], + ] as const) { + expect(asManager(reply, [...calls]), reply).toMatchObject({ correct: false, declined: false, problems: ['did not decline a question the persona may not see'] }); + } + }); + + it('⛔ masked, a dataset that "has no medical note field" is about the dataset, not the asker: no decline', () => { + expect(asManager('The Approved Leave dataset has no medical note field.')).toMatchObject({ declined: false }); + }); + + it('a decline that binds to the asker still declines, beside or inside a dataset sentence', () => { + for (const reply of [ + 'The medical note is not visible to your role, so I can\'t group by it.', + 'The Approved Leave dataset can\'t show medical notes to you: the field is hidden from your role.', + 'The dataset groups by certificate only. You don\'t have permission to read medical notes.', + '您没有权限查看就诊说明,数据集也无法按它分组。', + ]) { + expect(asManager(reply, [served]), reply).toMatchObject({ correct: true, declined: true }); + } + }); + + it('CONTROL: the same inability with no dataset named reads as before', () => { + expect(asManager("I can't group sick-leave requests by medical note.")).toMatchObject({ correct: true, declined: true }); + // Only a dataset the turn served makes its bare name one: without the tool call the sentence names nothing. + expect(asManager("Approved Leave can't group by medical note.")).toMatchObject({ correct: true, declined: true }); + // And a field-absence wording on the object itself, masked, still declines. + expect(asManager('The leave request object has no medical note field.')).toMatchObject({ correct: true, declined: true }); + }); +}); diff --git a/packages/qa/scenarios/test/score/scenario-tags.test.ts b/packages/qa/scenarios/test/score/scenario-tags.test.ts index 7ae42773387..ef59a062892 100644 --- a/packages/qa/scenarios/test/score/scenario-tags.test.ts +++ b/packages/qa/scenarios/test/score/scenario-tags.test.ts @@ -254,6 +254,8 @@ const ACTION_DEGRADATIONS: Record void> = { 'action:task.delete_task->exists': (a) => { a.actions = a.actions.filter((x: Bag) => x.name !== 'delete_task'); }, 'action:task.set_task_status->ai-exposed': (a) => { a.actions[0].ai.exposed = false; }, 'action:task.delete_task->confirm-gated': (a) => { delete a.actions[1].ai.requiresConfirmation; }, + // Over-gating: the card has the agent set a task's status at once. + 'action:task.set_task_status->not-confirm-gated': (a) => { a.actions[0].ai.requiresConfirmation = true; }, }; describe('the closed tag table', () => { @@ -294,7 +296,7 @@ describe('capability tags — discrimination over a rich build', () => { it('passes every row of the table, and every agent action, on the intact build', () => { expect(intact.tags.map((t) => [t.tag, t.status])).toEqual(ALL_TAGS.map((t) => [t, 'pass'])); expect(intact.agentActions.every((c) => c.pass)).toBe(true); - expect(intact.agentActions).toHaveLength(5); + expect(intact.agentActions).toHaveLength(6); expect(intact.score).toBe(1); }); @@ -385,6 +387,7 @@ describe('agent actions — a declared action the build does not expose fails', expect(s.agentActions.map((c) => [c.check, c.pass])).toEqual([ ['action:task.set_task_status->exists', false], ['action:task.set_task_status->ai-exposed', false], + ['action:task.set_task_status->not-confirm-gated', false], ['action:task.delete_task->exists', false], ['action:task.delete_task->ai-exposed', false], ['action:task.delete_task->confirm-gated', false], @@ -788,12 +791,15 @@ describe('persona grants — what the card has each persona read and write, agai expect(personaGrantNeeds(PROJECT).find((n) => n.verb === 'create')!.requiredBy).toEqual(['operation add_task']); }); - it('a grant present: every check passes', () => { + it('a grant present: every check passes, but a delete of a detail row, which the master gate decides', () => { + // `task` is a `controlled_by_parent` detail: the platform hands its + // owner-only delete floor to the master's gate, which the artifact cannot + // judge without the master row. expect(verdicts(built(GRANTED))).toEqual([ ['persona-grant:contractor:task:read', true], ['persona-grant:contractor:task:create', true], ['persona-grant:contractor:task:update', true], - ['persona-grant:contractor:task:delete', true], + ['persona-grant:contractor:task:delete', 'not-measured'], ['persona-grant:client_viewer:task:update', true], ]); }); @@ -838,7 +844,8 @@ describe('persona grants — what the card has each persona read and write, agai ); const s = scoreScenarioArtifact(artifact(READ_ONLY), WAITING); const g = scoreScenarioArtifact(artifact(GRANTED), WAITING); - expect([s.total, s.passed]).toEqual([g.total - 1, g.passed - 3]); + // Both builds leave the delete to the run (here the route, there the master gate on the detail). + expect([s.total, s.passed]).toEqual([g.total, g.passed - 2]); // The card's action without `confirm` is no designed route: the check is measured. const unconfirmed: ScenarioArtifactCard = { ...WAITING, @@ -952,7 +959,8 @@ describe('persona grants — what the card has each persona read and write, agai it("reads the platform's fold: a '*' wildcard covers a public object and not a private one", () => { const wildcard = { ...GRANTED, contractor: { objects: { '*': ALL_TASK_VERBS } } }; - expect(verdicts(built(wildcard)).slice(0, 4).map(([, v]) => v)).toEqual([true, true, true, true]); + // The detail's delete is the master gate's (see 'a grant present'): not measured, whatever covers the grant. + expect(verdicts(built(wildcard)).slice(0, 4).map(([, v]) => v)).toEqual([true, true, true, 'not-measured']); const privateTask = built(wildcard, (stack) => { (stack.objects as Bag[]).find((o) => o.name === 'task')!.access = { default: 'private' }; withoutAction('delete_task')(stack); @@ -965,7 +973,7 @@ describe('persona grants — what the card has each persona read and write, agai expect(verdicts(facts, PROJECT, 'demoproject').map(([, v]) => v)).toEqual([false, false, false, false, false]); expect(gradePersonaGrants(facts, PROJECT, { namespace: 'demoproject' })[0]!.detail).toBe('the build declares no permission set demoproject_contractor'); const renamed = built({ demoproject_contractor: GRANTED.contractor, demoproject_client_viewer: GRANTED.client_viewer }); - expect(verdicts(renamed, PROJECT, 'demoproject').map(([, v]) => v)).toEqual([true, true, true, true, true]); + expect(verdicts(renamed, PROJECT, 'demoproject').map(([, v]) => v)).toEqual([true, true, true, 'not-measured', true]); }); it('counts in the card score, and a card pick without questions or operations derives none', () => { @@ -977,3 +985,91 @@ describe('persona grants — what the card has each persona read and write, agai expect(scoreScenarioArtifact(richArtifact(), CARD).personaGrants).toEqual([]); }); }); + +describe("persona grants — a delete the set grants, read against the platform's owner-only delete floor", () => { + // leave_balances: the hr_officer deletes withdrawn requests LR-0100 + // (`delete_withdrawn_request`, applied) and LR-0003 (waiting on + // confirmation). Both are seed rows no persona owns: the runner loads them as + // the admin's. The platform's `owner_only_deletes` floor refuses a delete of a + // row the caller did not create, and only the sharing service's delete + // `allow` (ownership, Modify All, a write depth of `org`) on an object it + // enforces on lifts it (plugin-security `platform-ownership-policies.ts`, + // plugin-sharing `SharingService.checkDelete`). + const { card: loaded, refusals } = loadScenarioFile(resolve(SCENARIOS_DIR, 'leave_balances.json'), { areas: readCapabilityAreas(AREAS_DIR), library: 'open' }); + if (!loaded) throw new Error(refusals.map(formatRefusal).join('\n')); + const LEAVE = loaded.card; + const DELETE = 'persona-grant:hr_officer:leave_request:delete'; + const facts = (opts: { entry?: Bag; sharingModel?: string; ownership?: string; rowLevelSecurity?: Bag[]; actions?: Bag[] } = {}) => + readArtifactFacts({ + objects: [ + { + name: 'leave_request', + label: 'Leave Request', + sharingModel: opts.sharingModel ?? 'private', + ...(opts.ownership ? { ownership: opts.ownership } : {}), + fields: { name: { type: 'text', label: 'Name' }, status: { type: 'text', label: 'Status' } }, + ...(opts.actions ? { actions: opts.actions } : {}), + }, + ], + permissions: [ + { + name: 'hr_officer', + label: 'HR officer', + objects: { leave_request: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, ...opts.entry } }, + ...(opts.rowLevelSecurity ? { rowLevelSecurity: opts.rowLevelSecurity } : {}), + }, + ], + }); + const grade = (f: ReturnType, c: ScenarioArtifactCard = LEAVE) => gradePersonaGrants(f, c).find((x) => x.check === DELETE)!; + const state = (r: { pass: boolean; notMeasured?: string }) => (r.notMeasured === undefined ? r.pass : 'not-measured'); + + it('the card deletes rows the admin owns, as the hr_officer', () => { + const ops = LEAVE.run.operations!.filter((o) => o.kind === 'delete' && o.actingAs === 'hr_officer'); + expect(ops.map((o) => [o.id, o.target])).toEqual([['delete_withdrawn_request', 'lr_100'], ['delete_zoes_withdrawn_request', 'lr_003']]); + }); + + it('⛔ allowDelete without Modify All fails: the floor refuses a delete of a row the persona does not own', () => { + const r = grade(facts()); + expect(state(r)).toBe(false); + expect(r.detail).toContain('lr_100'); + expect(r.detail).toContain('lr_003'); + }); + + it('Modify All, or a write depth of org, lifts the floor on an object the sharing service enforces on', () => { + expect(state(grade(facts({ entry: { modifyAllRecords: true } })))).toBe(true); + expect(state(grade(facts({ entry: { writeScope: 'org' } })))).toBe(true); + }); + + it('⛔ on a public org-wide default, or with no record owner, nothing lifts it: the sharing service abstains, Modify All included', () => { + expect(state(grade(facts({ sharingModel: 'public_read_write', entry: { modifyAllRecords: true } })))).toBe(false); + expect(state(grade(facts({ ownership: 'none', entry: { modifyAllRecords: true } })))).toBe(false); + }); + + it('an authored delete policy beside the floor, or a detail whose master gate decides, leaves the write to the run', () => { + const policy = { name: 'hr_deletes_withdrawn', object: 'leave_request', operation: 'delete', using: "status == 'withdrawn'" }; + expect(state(grade(facts({ rowLevelSecurity: [policy] })))).toBe('not-measured'); + expect(state(grade(facts({ rowLevelSecurity: [{ ...policy, operation: 'select' }] })))).toBe(false); + expect(state(grade(facts({ sharingModel: 'controlled_by_parent' })))).toBe('not-measured'); + }); + + it("the waiting delete routed through the card's confirm-gated action the build declares is the run's; the applied one stays measured", () => { + const action = { name: 'delete_leave_request', label: 'Delete', type: 'script', target: 'delete_leave_request', ai: { exposed: true, requiresConfirmation: true } }; + const WAITING: ScenarioArtifactCard = { ...LEAVE, run: { ...LEAVE.run, operations: LEAVE.run.operations!.filter((o) => o.id !== 'delete_withdrawn_request') } }; + expect(state(grade(facts({ actions: [action] }), WAITING))).toBe('not-measured'); + expect(state(grade(facts({ actions: [action] })))).toBe(false); + }); + + it('a row the persona owns passes on the grant: ownership is the sharing service\'s own allow', () => { + // A card copy whose hr_officer is the person LR-0100 names (e04), so the runner loads the row as theirs. + const persona = LEAVE.run.personas.find((p) => p.id === 'hr_officer')!; + const OWNER: ScenarioArtifactCard = { + ...LEAVE, + run: { + ...LEAVE.run, + personas: LEAVE.run.personas.map((p) => (p === persona ? { ...p, record: { object: 'employee', id: 'e04' } } : p)), + operations: LEAVE.run.operations!.filter((o) => o.id !== 'delete_zoes_withdrawn_request'), + }, + }; + expect(state(grade(facts(), OWNER))).toBe(true); + }); +});