Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/36206-decide-through-action.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/scenarios': patch
---

feat(scenarios): a scenario card names the agent action an operation goes through (`via`)

Clause-②: yes (widening) — `OperationSchema` (exported from the package's `.` entry, and through it `ScenarioCardSchema`) accepts an optional `via`; `PersonaGrantNeed` (the `./score` entry) gains `routedVia`
Metadata-protocol: none

- A card operation may name, as `via`, the card's own agent action the write is designed to go through (one of `run.agentActions` on the operation's object). The loader refuses a `via` that is not such an action, and a `via` on a `refused` operation.
- The Build check `persona-grant:<persona>:<object>:<verb>` is not measured, never a pass, when the persona's set withholds the verb and every operation needing it names a `via` action the build declares (or, as before, waits on confirmation behind the card's confirm-gated action the build declares). A set that grants the verb still passes; an operation without `via` is graded as before.
- leave_balances `manager_approves_step_one`, requisition_to_receipt `manager_approves_level_one` and travel_expense `manager_approves_step_one` name `decide_approval_step` as their route.
- Card data: order_to_cash's PAY-0044 is paid on 2026-10-02, not 2026-10-01, so no payment sits on the day the platform's `last_30_days` preset counts and the card's 30-day window does not (`collected_by_team_last_30_days` west is now 58300).
1 change: 1 addition & 0 deletions docs/qa/scenarios/leave_balances.json
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,7 @@
"target": "as_102_1",
"values": {"decision": "approved", "decided_on": "2026-09-30"},
"actingAs": "dept_manager",
"via": "decide_approval_step",
"outcome": {
"kind": "applied",
"state": [
Expand Down
4 changes: 2 additions & 2 deletions docs/qa/scenarios/order_to_cash.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"$comment": "Seed rule (so every truth can be worked by hand), as of 2026-10-31: account a(k), k = 1..12, is owned by rep [e02, e03, e04, e06, e07, e08][(k-1) mod 6] (team east: e02-e04 under manager e01; team west: e06-e08 under e05) on net_45 terms when k mod 4 = 0, else net_30. Order i = 1..120 is for a((i-1) mod 12 + 1), owned by that account's owner, dated 2026-07..10 day ((i-1) mod 30)+1 (i 1-30 July, 31-60 August, 61-90 September, 91-120 October), with two lines: hardware p((i-1) mod 3 + 1) x (10 + 5(i mod 5)) at list price, 20% off when i mod 10 = 0, and service p(4 + i mod 3) x (1 + i mod 4) at list price. A line discount above 10% routes the order to the owner's manager (`approver`; `approved_on` the next day once approved). Status: i 1-90 cancelled when i mod 20 = 13, else fulfilled; i 91-120 by i mod 10: 1-3 fulfilled, 4, 5 and 9 confirmed, 6-7 draft, 8 cancelled, 0 pending_approval. A fulfilled order is invoiced 7 days after its order date as INV-(1000+i), due after the account's terms. Payments as of asOf: Harbor Foods (a05) has paid nothing; Ironwood Labs (a09) pays half on the due date; Cedar Logistics (a02) pays in full 20 days after the due date; every other account pays in full 3 days before it; method by k mod 3: 0 wire, 1 ach, 2 check. Activities: one touchpoint per account per month on day 30 - 2k by the owner (July meeting, August call, September email, October call), plus a collection_call by e09 on the day an invoice is 15 days past due when it is not fully paid by then.",
"$comment": "Seed rule (so every truth can be worked by hand), as of 2026-10-31: account a(k), k = 1..12, is owned by rep [e02, e03, e04, e06, e07, e08][(k-1) mod 6] (team east: e02-e04 under manager e01; team west: e06-e08 under e05) on net_45 terms when k mod 4 = 0, else net_30. Order i = 1..120 is for a((i-1) mod 12 + 1), owned by that account's owner, dated 2026-07..10 day ((i-1) mod 30)+1 (i 1-30 July, 31-60 August, 61-90 September, 91-120 October), with two lines: hardware p((i-1) mod 3 + 1) x (10 + 5(i mod 5)) at list price, 20% off when i mod 10 = 0, and service p(4 + i mod 3) x (1 + i mod 4) at list price. A line discount above 10% routes the order to the owner's manager (`approver`; `approved_on` the next day once approved). Status: i 1-90 cancelled when i mod 20 = 13, else fulfilled; i 91-120 by i mod 10: 1-3 fulfilled, 4, 5 and 9 confirmed, 6-7 draft, 8 cancelled, 0 pending_approval. A fulfilled order is invoiced 7 days after its order date as INV-(1000+i), due after the account's terms. Payments as of asOf: Harbor Foods (a05) has paid nothing; Ironwood Labs (a09) pays half on the due date; Cedar Logistics (a02) pays in full 20 days after the due date; every other account pays in full 3 days before it, except PAY-0044 (INV-1058, due 2026-10-04), paid 2026-10-02 so no payment sits on 2026-10-01, the day the platform's last_30_days preset (31 days ending on asOf) counts and the card's 30-day window does not; method by k mod 3: 0 wire, 1 ach, 2 check. Activities: one touchpoint per account per month on day 30 - 2k by the owner (July meeting, August call, September email, October call), plus a collection_call by e09 on the day an invoice is 15 days past due when it is not fully paid by then.",
"id": "order_to_cash",
"code": "order",
"tier": "starter",
Expand Down Expand Up @@ -634,7 +634,7 @@
{"id": "pay041", "name": "PAY-0041", "invoice": "inv054", "amount": 3600, "payment_date": "2026-09-27", "method": "wire", "bank_reference": "WT-0927-054"},
{"id": "pay042", "name": "PAY-0042", "invoice": "inv040", "amount": 1560, "payment_date": "2026-09-28", "method": "ach", "bank_reference": "ACH-0928-040"},
{"id": "pay043", "name": "PAY-0043", "invoice": "inv055", "amount": 3600, "payment_date": "2026-09-28", "method": "ach", "bank_reference": "ACH-0928-055"},
{"id": "pay044", "name": "PAY-0044", "invoice": "inv058", "amount": 4800, "payment_date": "2026-10-01", "method": "ach", "bank_reference": "ACH-1001-058"},
{"id": "pay044", "name": "PAY-0044", "invoice": "inv058", "amount": 4800, "payment_date": "2026-10-02", "method": "ach", "bank_reference": "ACH-1002-058"},
{"id": "pay045", "name": "PAY-0045", "invoice": "inv044", "amount": 8400, "payment_date": "2026-10-02", "method": "check", "bank_reference": "CHK-1002-044"},
{"id": "pay046", "name": "PAY-0046", "invoice": "inv059", "amount": 11100, "payment_date": "2026-10-02", "method": "check", "bank_reference": "CHK-1002-059"},
{"id": "pay047", "name": "PAY-0047", "invoice": "inv057", "amount": 1200, "payment_date": "2026-10-03", "method": "wire", "bank_reference": "WT-1003-057"},
Expand Down
1 change: 1 addition & 0 deletions docs/qa/scenarios/requisition_to_receipt.json
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,7 @@
"target": "as_111_1",
"values": {"decision": "approved", "decided_on": "2026-10-31"},
"actingAs": "dept_manager",
"via": "decide_approval_step",
"outcome": {
"kind": "applied",
"state": [
Expand Down
1 change: 1 addition & 0 deletions docs/qa/scenarios/travel_expense.json
Original file line number Diff line number Diff line change
Expand Up @@ -1076,6 +1076,7 @@
"target": "as_111_1",
"values": {"decision": "approved", "decided_on": "2026-10-31"},
"actingAs": "dept_manager",
"via": "decide_approval_step",
"outcome": {
"kind": "applied",
"state": [
Expand Down
7 changes: 7 additions & 0 deletions packages/qa/scenarios/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,13 @@ function checkCard(
checkRef(op.object, field, value, [...at, 'values', field]);
}
if (!personas.has(op.actingAs)) refuse([...at, 'actingAs'], `no persona \`${op.actingAs}\``);
if (op.via !== undefined) {
if (op.outcome.kind === 'refused') {
refuse([...at, 'via'], `a \`refused\` write goes through no route: \`via\` names the agent action an applied or confirmation-gated write is designed to go through`);
} else if (!(run.agentActions ?? []).some((a) => a.name === op.via && a.object === op.object)) {
refuse([...at, 'via'], `\`${op.via}\` is not one of the card's \`run.agentActions\` on \`${op.object}\``);
}
}
const actor = run.personas.find((p) => p.id === op.actingAs);
if (actor !== undefined) checkReach(op, actor, at);
const out = op.outcome;
Expand Down
10 changes: 10 additions & 0 deletions packages/qa/scenarios/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,16 @@ export const OperationSchema = z
values: z.record(MachineNameSchema, ScalarSchema).optional(),
/** The persona the agent acts for. */
actingAs: MachineNameSchema,
/**
* The card's own agent action this write is designed to go through
* (`run.agentActions[].name`, on this operation's object; the loader holds
* that). An action body writes as the platform, so a build may withhold
* the verb from the persona's set and route the write through it: the
* Build grant check then leaves the write to the run, never a pass
* (`gradePersonaGrants` in `score/scenario-tags.ts`). Absent ⇒ the write
* is measured against the persona's grant. A `refused` write takes none.
*/
via: MachineNameSchema.optional(),
outcome: OutcomeSchema,
})
.superRefine((op, ctx) => {
Expand Down
64 changes: 53 additions & 11 deletions packages/qa/scenarios/src/score/scenario-tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,8 @@ export interface PersonaGrantNeed {
requiredBy: string[];
/** The operations among those whose outcome is `pending_confirmation`: the write waits on a person's confirmation. */
awaitingConfirmation: string[];
/** The operations among those that name the card's agent action they go through (`via`), each with that action. */
routedVia: Array<{ operation: string; action: string }>;
/** The writes the card declares refused `PERMISSION_DENIED`, each with the fields it names. */
refusedBy: Array<{ operation: string; fields: string[] }>;
}
Expand All @@ -941,7 +943,8 @@ export interface PersonaGrantNeed {
* persona that must not read the object declines the question, it reads
* nothing;
* - an operation whose outcome is `applied` or `pending_confirmation` needs
* its kind on its object, for the persona it acts as;
* its kind on its object, for the persona it acts as; one that names the
* card's agent action it goes through (`via`) is recorded with it;
* - an operation refused `PERMISSION_DENIED` must be refused by that
* persona's set. Any other refusal (`VALIDATION_FAILED`) implies nothing
* about the grant.
Expand All @@ -951,7 +954,7 @@ export function personaGrantNeeds(card: ScenarioArtifactCard): PersonaGrantNeed[
const need = (persona: string, object: string, verb: PersonaGrantVerb): PersonaGrantNeed => {
const key = `${persona}:${object}:${verb}`;
let n = needs.get(key);
if (!n) needs.set(key, (n = { persona, object, verb, requiredBy: [], awaitingConfirmation: [], refusedBy: [] }));
if (!n) needs.set(key, (n = { persona, object, verb, requiredBy: [], awaitingConfirmation: [], routedVia: [], refusedBy: [] }));
return n;
};
const hidesObject = new Map(card.run.personas.map((p) => [p.id, new Set(p.hidden.objects ?? [])]));
Expand All @@ -967,6 +970,7 @@ export function personaGrantNeeds(card: ScenarioArtifactCard): PersonaGrantNeed[
const n = need(op.actingAs, op.object, op.kind);
n.requiredBy.push(`operation ${op.id}`);
if (outcome.kind === 'pending_confirmation') n.awaitingConfirmation.push(op.id);
if (op.via !== undefined) n.routedVia.push({ operation: op.id, action: op.via });
} else if (outcome.code === 'PERMISSION_DENIED') {
need(op.actingAs, op.object, op.kind).refusedBy.push({ operation: op.id, fields: Object.keys(op.values ?? {}) });
}
Expand Down Expand Up @@ -1028,15 +1032,40 @@ function writeRefusalRoute(
* build may withhold a write the card has wait on a person's confirmation from
* the persona's set and route it through such an action: the lock and the
* door ruling A on #31999 item 9 accepts on the Run side, here offered by the
* card itself. Only the confirm-gated door counts: a write the card applies
* outright stays measured against the grant, whatever actions the build adds.
* card itself. For a write the card applies outright only the action the
* operation names as its route (`via`) counts ({@link designedRoutes}):
* without one it stays measured against the grant, whatever actions the
* build adds.
*/
function confirmGatedRoutes(facts: ArtifactFacts, card: ScenarioArtifactCard, object: string): string[] {
return (card.run.agentActions ?? [])
.filter((a) => a.confirm === true && a.object === object && facts.actions.some((x) => x.object === object && x.action.name === a.name))
.filter((a) => a.confirm === true && a.object === object && buildDeclaresAction(facts, object, a.name))
.map((a) => a.name);
}

/** Whether the build declares an action named `name` on `object`. */
function buildDeclaresAction(facts: ArtifactFacts, object: string, name: string): boolean {
return facts.actions.some((x) => x.object === object && x.action.name === name);
}

/**
* Each write the need's grant is withheld from, with the routes the card
* designs for it that the build declares: the agent action the operation
* names (`via`, any `confirm`) and, for a write that waits on confirmation,
* the card's confirm-gated actions ({@link confirmGatedRoutes}). `undefined`
* when one write has no such route: the grant is then measured. The card's
* other actions on the object are no route, whatever the build declares.
*/
function designedRoutes(facts: ArtifactFacts, card: ScenarioArtifactCard, n: PersonaGrantNeed): Array<{ operation: string; via: string[]; confirm: string[] }> | undefined {
const confirm = confirmGatedRoutes(facts, card, n.object);
const routes = n.requiredBy.map((r) => {
const operation = r.replace(/^operation /, '');
const via = n.routedVia.filter((v) => v.operation === operation && buildDeclaresAction(facts, n.object, v.action)).map((v) => v.action);
return { operation, via, confirm: n.awaitingConfirmation.includes(operation) ? confirm : [] };
});
return routes.every((r) => r.via.length > 0 || r.confirm.length > 0) ? routes : undefined;
}

/**
* One Build check per persona × object × verb the card implies
* ({@link personaGrantNeeds}), named `persona-grant:<persona>:<object>:<verb>`,
Expand All @@ -1056,10 +1085,13 @@ function confirmGatedRoutes(facts: ArtifactFacts, card: ScenarioArtifactCard, ob
* set grants the verb. A refused write of the same persona, object and verb
* beside it is refused by a row or a field, not the grant; it is named in
* the detail and judged no further. One exception, not measured and never
* a pass: a write verb the set withholds that only `pending_confirmation`
* operations need, where the card's confirm-gated agent action on the
* object is declared by the build ({@link confirmGatedRoutes}) — the route
* the card itself designs for a write that asks before acting.
* a pass: a write verb the set withholds where every operation needing it
* has a route the card designs and the build declares
* ({@link designedRoutes}) — the agent action the operation names as its
* route (`via`), or, for a `pending_confirmation` operation, the card's
* 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.
* - 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
Expand All @@ -1086,8 +1118,18 @@ export function gradePersonaGrants(facts: ArtifactFacts, card: ScenarioArtifactC

if (n.requiredBy.length > 0) {
const beside = refused.length > 0 ? `; ${refused.join(', ')} is refused by a row or a field, not the grant` : '';
const onlyAwaiting = n.awaitingConfirmation.length === n.requiredBy.length;
const routed = granted || n.verb === 'read' || !onlyAwaiting ? [] : confirmGatedRoutes(facts, card, n.object);
const routes = granted || n.verb === 'read' ? undefined : designedRoutes(facts, card, n);
if (routes !== undefined && routes.some((r) => r.via.length > 0)) {
const through = routes.map((r) => `operation ${r.operation} through ${[...new Set([...r.via, ...r.confirm])].join(' or ')}`);
return {
check: name,
pass: false,
notMeasured:
`${setName} grants no ${n.verb} on ${n.object}, and the build declares the card's agent action each write names as its route (\`via\`) ` +
`or its confirm-gated one, a door that writes as the platform: whether ${through.join(', ')} goes through it is the run's to observe`,
};
}
const routed = routes === undefined ? [] : routes[0]!.confirm;
if (routed.length > 0) {
return {
check: name,
Expand Down
17 changes: 15 additions & 2 deletions packages/qa/scenarios/test/library.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,21 @@ describe('the open scenario library (docs/qa/scenarios)', () => {
if (JSON.stringify([wide.truths[id], wide.personaTruths[id]]) !== JSON.stringify([loaded.truths[id], loaded.personaTruths[id]])) ambiguous.push(`${loaded.card.id}/${id}`);
}
}
// order_to_cash's PAY-0044 (2026-10-01) is the one left: the same defect, outside this change's cards.
expect(ambiguous).toEqual(['order_to_cash/collected_by_team_last_30_days']);
expect(ambiguous).toEqual([]);
});

it('names its decide action as the route (`via`) of each manager approval the card decides through it, and only those', () => {
// The Build grant check leaves these writes to the run when the set withholds the verb and the build
// declares the action. asset_lifecycle manager_approves_scrap and order_to_cash approve_discount have
// the same shape but no measured run behind them, so they stay measured until one exists.
const routed = result.cards.flatMap(({ card }) =>
card.run.operations.filter((o) => o.via !== undefined).map((o) => `${card.id}/${o.id} via ${o.via}`),
);
expect(routed.sort()).toEqual([
'leave_balances/manager_approves_step_one via decide_approval_step',
'requisition_to_receipt/manager_approves_level_one via decide_approval_step',
'travel_expense/manager_approves_step_one via decide_approval_step',
]);
});

it('every card tagged for a report asks for one in its detailed prompt, in both languages', () => {
Expand Down
6 changes: 3 additions & 3 deletions packages/qa/scenarios/test/order-to-cash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ const EXPECTED_TRUTHS: Record<string, Truth> = {
// 59950. The fourth, a08, has 44950: no tie at the cut-off.
top_accounts_billed: ranking(['a02', 62350], ['a11', 60200], ['a05', 59950]),
// Payments dated 2026-10-02..31. East: a01 5400, a02 21350, a03 9200,
// a07 10800, a08 20200, a09 3800. West: a04 7200, a06 5600, a10 6960,
// a11 28300, a12 5440 (Harbor Foods paid nothing).
collected_by_team_last_30_days: groups(['east', 70750], ['west', 53500]),
// a07 10800, a08 20200, a09 3800. West: a04 7200, a06 5600, a10 11760
// (PAY-0044 on 2026-10-02 included), a11 28300, a12 5440 (Harbor Foods paid nothing).
collected_by_team_last_30_days: groups(['east', 70750], ['west', 58300]),
// The 104 confirmed or fulfilled orders. Subscription is p5, the service line
// when i mod 3 = 1: 40 such orders carry 100 units (1 + i mod 4 cycles
// 2, 1, 4, 3); the 6 not counted (13, 73, 97, 100, 106, 118) carry 13, so
Expand Down
6 changes: 6 additions & 0 deletions packages/qa/scenarios/test/refusals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,12 @@ const CASES: Array<[string, (c: RawCard) => void, string, RegExp]> = [
['fewer than 8 questions without a stated reason', (c) => c.run.questions.splice(7), 'run.countsReason', /7 questions \/ 6 operations is below the default 8 \/ 4/],
['agent actions with none confirm-gated', (c) => c.run.agentActions.forEach((a: { confirm: boolean }) => (a.confirm = false)), 'run.agentActions', /at least one confirm-gated/],
['an agent action on an unexpected object', (c) => (c.run.agentActions[0].object = 'lead'), 'run.agentActions[0].object', /`lead` is not in expect.objects/],
['a write routed through an action the card does not declare', (c) => (op(c, 'move_eli').via = 'approve_contact'), 'run.operations[1].via', /`approve_contact` is not one of the card's `run.agentActions` on `contact`/],
['a write routed through the card\'s action on another object', (c) => {
c.run.agentActions[0].object = 'account';
op(c, 'add_contact').via = 'create_contact';
}, 'run.operations[0].via', /`create_contact` is not one of the card's `run.agentActions` on `contact`/],
['a refused write that names a route', (c) => (op(c, 'contact_bad_email').via = 'create_contact'), 'run.operations[3].via', /a `refused` write goes through no route/],
['an iterate delta that re-adds an expected object', (c) => (c.iterate.expectDelta = { objects: ['account'] }), 'iterate.expectDelta.objects[0]', /already in expect.objects/],
];

Expand Down
Loading
Loading