diff --git a/.changeset/35098-travel-expense-step-two-approver.md b/.changeset/35098-travel-expense-step-two-approver.md new file mode 100644 index 00000000000..659bf1935ff --- /dev/null +++ b/.changeset/35098-travel-expense-step-two-approver.md @@ -0,0 +1,10 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): the `travel_expense` build prompt names who approves a claim's second step + +Clause-②: no +Metadata-protocol: none + +The detailed prompt said a claim goes to "the department manager first (a manager's own claim goes to the finance manager), then Finance". Finance has two members, and the same sentence calls one of them the finance manager, so a build could route the second step to that manager, while every seeded step-2 row and the `manager_approves_step_one` operation name the Finance officer. The prompt now says the second step goes to a Finance officer (Finance staff other than the finance manager), in English and Chinese. The expected approver, the seed rows and the operation are unchanged. diff --git a/.changeset/35113-scenario-ask-kinds.md b/.changeset/35113-scenario-ask-kinds.md new file mode 100644 index 00000000000..f7c6d8c5db6 --- /dev/null +++ b/.changeset/35113-scenario-ask-kinds.md @@ -0,0 +1,14 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): every question of a dataset card names its ask kind, and a round's record counts every kind + +Clause-②: yes (widening) — new optional card key `askKind` on `QuestionSchema` and `DatasetQuestionSchema`; new exports `ASK_KINDS`, `AskKind`, `AskKindSchema`, `questionTurnKind`, `checkAskKinds`, `askTurns`, `askKindCounts` and `AskTurn` (package root); `kindTally`, `kindCell` and `KindTally` (`./runner`); new optional fields `QuestionResult.askKind`, `DatasetQuestionResult.askKind` (`./runner`) and `HalfScores.kinds` (`scorecard.ts`, `./runner`) +Metadata-protocol: none + +The open dataset cards (`order_to_cash`, `travel_expense`) stated no kind of question for their ordinary questions, so a round could not show which of the ten ask kinds it measured. A question and a dataset question now name one (`askKind`): `count`, `group_sum`, `top_n`, `time_range`, `join`, `owner_latest`, `business_term`, `ambiguous`, `forbidden` or `unanswerable`. A card that names one kind names the kind of every question and dataset question it asks, all or none, so a card that names no kind loads as before; the loader refuses a kind its question's truth or route contradicts (a `top_n` that does not rank, an `owner_latest` that does not group by a person field, a `business_term` that is not a `metric_selected` dataset question, an `unanswerable` the seed answers), at the question's `askKind`. A turn asked as a persona its truth is withheld from is a `forbidden` ask. + +The runner stamps each turn's kind on its result (`askKind` on every question and dataset-question result), the scorecard counts the asks kind by kind (`HalfScores.kinds`, new `Run · kinds` and `Iterate · Run · kinds` rows naming all ten kinds), and `summary` sums the row. A card that names no kind, and a record written before turns carried one, show no such row. New exports: `ASK_KINDS`, `AskKind`, `AskKindSchema`, `questionTurnKind`, `checkAskKinds`, `askTurns`, `askKindCounts` and `AskTurn` from the package root; `kindTally`, `kindCell` and `KindTally` from the runner. + +The two cards ask every kind at least twice per round, a table in `docs/qa/scenarios/README.md` states the counts, and a test holds it equal to the cards. `order_to_cash` changes only by the added `askKind` keys, and `travel_expense` also by the step-2 approver line of its build prompt (the changeset beside this one), so both cards' sha256 move and ask-round records split at these card hashes. diff --git a/docs/qa/scenarios/README.md b/docs/qa/scenarios/README.md index 7ea054dbcbf..7db1c08c667 100644 --- a/docs/qa/scenarios/README.md +++ b/docs/qa/scenarios/README.md @@ -35,7 +35,7 @@ question's computed truth; a card that does not load is red in CI. | 1 | `prompt` | `{ short, detailed }`, each `{ zh?, en? }` with at least one language. | | 2 | `expect` | The structural expectation the deterministic scorer reads, field for field: `objects`, `minFieldsPerObject?`, `selectFields?` (`{ object, field, minOptions }`), `lookups?` (`{ object, field, to }`), `dashboards?`, `appNavTargets?`, `datasets?` (`{ name, label, description, object, measures, dimensions? }`, each member `{ name, label, synonyms?, description? }`; see [Dataset questions](#dataset-questions)). The runner's build prompt states every row by name ([Build checks trace to the prompt](#build-checks-trace-to-the-prompt)). | | 3 | `capabilities`, `businessFunctions` | Tags `.`, where `` is a closed set: the basenames of `docs/qa/platform-checklist/areas/*.json`, read from the tree. `businessFunctions` is the marketplace taxonomy's business-function facet, read from `@objectstack/spec/marketplace` (`MarketplaceBusinessFunctionsSchema`, defined once in `packages/spec/src/marketplace/taxonomy.zod.ts`): 1-3 distinct values, the primary one first — the card is classified the way the template it graduates into will be listed. | -| 4 | `run.seed`, `run.userHandleFields?`, `run.questions`, `run.personas` | Seed rows per object, and which seed fields hold a user handle; at least five read-only questions, each with a **declarative** truth spec; at least two personas, each a role, the objects or fields it must NOT see, and optionally a row `scope` and the person `record` it is. | +| 4 | `run.seed`, `run.userHandleFields?`, `run.questions`, `run.personas` | Seed rows per object, and which seed fields hold a user handle; at least five read-only questions, each with a **declarative** truth spec and optionally its [ask kind](#ask-kinds) (`askKind`: a card that names one names it on every question and dataset question); at least two personas, each a role, the objects or fields it must NOT see, and optionally a row `scope` and the person `record` it is. | | 5 | `run.operations`, `run.guardrails`, `run.agentActions?`, `run.datasetQuestions?` | At least two writes, each acting as a persona and declaring its `outcome`; the five guardrail checks; optionally the agent-callable business actions and the dataset questions. | | 6 | `iterate` | A one-sentence change request plus the `expectDelta` it should add to `expect`. | @@ -363,6 +363,69 @@ states the datasets by name, with every synonym and description, and the Build h them (`dataset:NAME`, `dataset-measure:NAME.MEMBER`, `dataset-dimension:NAME.MEMBER`). `order_to_cash` and `travel_expense` carry them today. +## Ask kinds + +A question or dataset question may name its **ask kind** (`askKind`), and a card that names one +names it on every question and dataset question, all or none. There are ten: the kinds of question +an ask round asks, borrowed from the hosted ask set's categories (D6 = A on #34659: the kinds, +never its fixture). ⛔ No question here is copied from the hosted set: its held-out questions stay +private so they keep measuring. A round counts +**turns** as the runner asks them: a question once per persona it lists (once as the admin when +it lists none), a dataset question once as the admin. A turn whose persona truth is `withheld` +is a `forbidden` ask whatever kind its question names: the same question asked as a persona who +may see it is the kind it names. + +The loader holds each declaration to what the card states, and refuses one that does not fit, +at the question's `askKind`: + +| `askKind` | The question asks | Held to | +|:---|:---|:---| +| `count` | one figure over the matching rows: how many, how much | a count, sum, average, minimum or maximum with no `groupBy` | +| `group_sum` | a figure per value of a field | a count, sum, average, minimum or maximum with a `groupBy` | +| `top_n` | a ranking: the first N rows or groups by a measure | a `topN` truth | +| `time_range` | a figure over a time window | a filter with `in_window` | +| `join` | a figure that reads across a lookup | a filter or `groupBy` on a relation path (`order.status`) | +| `owner_latest` | who holds a row or acted on it: an owner, an approver, a follow-up | a `groupBy` ending on a person field: a declared lookup to an object a persona's `record` names, or a declared user-handle field | +| `business_term` | a business word that names exactly one governed metric | a `metric_selected` dataset question | +| `ambiguous` | a word that names more than one metric, or none exactly | an `asked_back` dataset question | +| `forbidden` | asked as a persona who may not see what it reads | declared only when every persona it lists is withheld from it; any withheld turn counts | +| `unanswerable` | what the data cannot answer | exactly the questions whose truth is `unanswerable` | + +A `fallback_labelled` dataset question names the figure kind it asks (`count`, `group_sum`, +`top_n`, `time_range`, `join` or `owner_latest`). A card that names no kind loads as it did before +kinds existed, with dataset questions or without; the open dataset cards name every one. + +**What the open dataset cards ask, per kind** (turns of one round, each asked once; +`packages/qa/scenarios/test/dataset-cards.test.ts` holds the cards to these figures, so a card edit +that moves one changes the test and this table together): + +| Kind | `order_to_cash` | `travel_expense` | Total | +|:---|---:|---:|---:| +| `count` | 3 | 3 | 6 | +| `group_sum` | 2 | 3 | 5 | +| `top_n` | 1 | 1 | 2 | +| `time_range` | 1 | 1 | 2 | +| `join` | 2 | 2 | 4 | +| `owner_latest` | 2 | 1 | 3 | +| `business_term` | 2 | 2 | 4 | +| `ambiguous` | 2 | 2 | 4 | +| `forbidden` | 1 | 2 | 3 | +| `unanswerable` | 1 | 1 | 2 | + +Every kind is asked at least twice, every question in Chinese and English. The `forbidden` turns +are the leak reading: `collected_by_team_last_30_days` as `sales_rep` and `department_budgets` as +`employee` (members whose field or object the card hides), and `trips_by_status` as +`finance_officer`. Each runs under the platform's default object-schema masking (ADR-0106 D8), so +for these personas the hidden field or object does not exist in their schema, and a correct reply +declines without stating a withheld figure. The question that a field-level-security withheld +field is said to be "not visible to you" rather than blank needs a caller who is served the whole +schema (ADR-0106 D4) or a deployment with masking off (D8); the runner's personas are plain +members on a default deployment, so no open card asks it yet. + +The run record carries each turn's kind (`askKind` on every question and dataset-question +result), and the scorecard counts the round kind by kind (`Run · kinds`, +[the package README](../../../packages/qa/scenarios/README.md#running-the-cards--objectstackscenariosrunner)). + ## Verified builds The ask round measures the MCP door, not authoring, so it runs every day on the same build: each diff --git a/docs/qa/scenarios/builds/travel_expense.provenance.json b/docs/qa/scenarios/builds/travel_expense.provenance.json index 6373fdd4dcb..6d406342d4a 100644 --- a/docs/qa/scenarios/builds/travel_expense.provenance.json +++ b/docs/qa/scenarios/builds/travel_expense.provenance.json @@ -1,6 +1,6 @@ { "card": "travel_expense", - "cardSha256": "abe91b8f794f19d88ff72c8cda58e314f69e3c5d77992a01cecea501303d4f28", + "cardSha256": "29162eefb46055941a0263686c2853246b4c408d41acb90c6abe22f68886a768", "build": "travel_expense.json", "sha256": "5fe6f452d36fe56a0ecf0f8c782394076953baeb99ef2499763991e119a29989", "runner": "ec227fc7", diff --git a/docs/qa/scenarios/order_to_cash.json b/docs/qa/scenarios/order_to_cash.json index 390b9fa7ae0..87f9a4e3d51 100644 --- a/docs/qa/scenarios/order_to_cash.json +++ b/docs/qa/scenarios/order_to_cash.json @@ -735,6 +735,7 @@ { "id": "open_receivables", "ask": {"zh": "目前应收账款还有多少没收回来?", "en": "How much is still outstanding on open and partially paid invoices?"}, + "askKind": "count", "object": "invoice", "truth": { "kind": "sum", @@ -746,6 +747,7 @@ { "id": "receivables_aging", "ask": {"zh": "未收余额按账龄分段各有多少?", "en": "How does the outstanding balance break down by aging bucket?"}, + "askKind": "group_sum", "object": "invoice", "truth": { "kind": "sum", @@ -758,6 +760,7 @@ { "id": "orders_by_status", "ask": {"zh": "各个状态的销售订单各有多少张?", "en": "How many sales orders are in each status?"}, + "askKind": "group_sum", "object": "sales_order", "truth": {"kind": "count", "groupBy": "status"}, "personas": ["sales_rep"] @@ -765,6 +768,7 @@ { "id": "top_accounts_billed", "ask": {"zh": "开票金额最多的三个客户是哪几个?", "en": "Which three accounts have been invoiced the most?"}, + "askKind": "top_n", "object": "invoice", "truth": { "kind": "topN", @@ -781,6 +785,7 @@ "zh": "最近 30 天的回款按客户负责人所在的销售团队各是多少?", "en": "How much has been collected in the last 30 days, per sales team of the account owner?" }, + "askKind": "time_range", "object": "payment", "truth": { "kind": "sum", @@ -796,6 +801,7 @@ "zh": "已确认和已履约订单的明细金额按产品类别各是多少?", "en": "On confirmed and fulfilled orders, how much has been booked per product category?" }, + "askKind": "join", "object": "order_line", "truth": { "kind": "sum", @@ -810,6 +816,7 @@ "zh": "逾期未收的余额分别在哪位销售代表的客户名下,各多少?", "en": "Whose accounts hold the overdue balance, and how much each?" }, + "askKind": "join", "object": "invoice", "truth": { "kind": "sum", @@ -826,6 +833,7 @@ { "id": "so_0120_waiting_on", "ask": {"zh": "订单 SO-0120 现在在等谁审批?", "en": "Who is order SO-0120 waiting on for approval?"}, + "askKind": "owner_latest", "object": "sales_order", "truth": { "kind": "count", @@ -842,6 +850,7 @@ "zh": "最近两周谁跟进过 Harbor Foods,各跟进了几次?", "en": "Who has followed up with Harbor Foods in the last two weeks, and how many times each?" }, + "askKind": "owner_latest", "object": "activity", "truth": { "kind": "count", @@ -855,6 +864,7 @@ { "id": "september_commission", "ask": {"zh": "九月份的订单销售代表一共能拿多少提成?", "en": "How much commission do the reps earn on September's orders?"}, + "askKind": "unanswerable", "object": "sales_order", "truth": { "kind": "unanswerable", @@ -1068,11 +1078,11 @@ } ], "datasetQuestions": [ - {"id": "dq_bookings", "ask": {"zh": "我们的订单金额合计是多少?", "en": "What do our bookings add up to?"}, "words": ["bookings", "订单金额"], "expect": {"kind": "metric_selected", "dataset": "order_book", "measure": "booked_amount"}}, - {"id": "dq_receivables", "ask": {"zh": "我们的应收账款还有多少?", "en": "How much do we have in receivables?"}, "words": ["receivables", "应收账款"], "expect": {"kind": "metric_selected", "dataset": "billing", "measure": "open_balance"}}, - {"id": "dq_revenue", "ask": {"zh": "我们的总营收是多少?", "en": "What is our total revenue?"}, "words": ["revenue", "营收"], "expect": {"kind": "asked_back", "reason": "ambiguous", "candidates": [{"dataset": "order_book", "measure": "booked_amount"}, {"dataset": "billing", "measure": "billed_amount"}]}}, - {"id": "dq_booking_total", "ask": {"zh": "我们的成交合计是多少?", "en": "What is our booking total?"}, "words": ["booking", "成交"], "expect": {"kind": "asked_back", "reason": "near_miss", "candidates": [{"dataset": "order_book", "measure": "booked_amount"}]}}, - {"id": "dq_payment_count", "ask": {"zh": "我们一共收到了多少笔付款?", "en": "How many payments have we received?"}, "words": ["payments", "付款"], "expect": {"kind": "fallback_labelled", "object": "payment"}} + {"id": "dq_bookings", "ask": {"zh": "我们的订单金额合计是多少?", "en": "What do our bookings add up to?"}, "askKind": "business_term", "words": ["bookings", "订单金额"], "expect": {"kind": "metric_selected", "dataset": "order_book", "measure": "booked_amount"}}, + {"id": "dq_receivables", "ask": {"zh": "我们的应收账款还有多少?", "en": "How much do we have in receivables?"}, "askKind": "business_term", "words": ["receivables", "应收账款"], "expect": {"kind": "metric_selected", "dataset": "billing", "measure": "open_balance"}}, + {"id": "dq_revenue", "ask": {"zh": "我们的总营收是多少?", "en": "What is our total revenue?"}, "askKind": "ambiguous", "words": ["revenue", "营收"], "expect": {"kind": "asked_back", "reason": "ambiguous", "candidates": [{"dataset": "order_book", "measure": "booked_amount"}, {"dataset": "billing", "measure": "billed_amount"}]}}, + {"id": "dq_booking_total", "ask": {"zh": "我们的成交合计是多少?", "en": "What is our booking total?"}, "askKind": "ambiguous", "words": ["booking", "成交"], "expect": {"kind": "asked_back", "reason": "near_miss", "candidates": [{"dataset": "order_book", "measure": "booked_amount"}]}}, + {"id": "dq_payment_count", "ask": {"zh": "我们一共收到了多少笔付款?", "en": "How many payments have we received?"}, "askKind": "count", "words": ["payments", "付款"], "expect": {"kind": "fallback_labelled", "object": "payment"}} ] }, "iterate": { diff --git a/docs/qa/scenarios/travel_expense.json b/docs/qa/scenarios/travel_expense.json index 44b45f3cee1..e69705e563b 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 Finance; 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; 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." } }, "expect": { @@ -874,6 +874,7 @@ { "id": "paid_reimbursement", "ask": {"zh": "已付款报销单的报销金额合计是多少?", "en": "How much is the claimed amount for everything already paid?"}, + "askKind": "count", "object": "expense_claim", "truth": {"kind": "sum", "field": "total_amount", "filter": [{"field": "status", "op": "eq", "value": "paid"}]}, "personas": ["employee", "dept_manager"] @@ -881,6 +882,7 @@ { "id": "claims_by_status", "ask": {"zh": "各个状态的报销单数分别是多少?", "en": "What is the number of claims in each status?"}, + "askKind": "group_sum", "object": "expense_claim", "truth": {"kind": "count", "groupBy": "status"}, "personas": ["dept_manager"] @@ -891,6 +893,7 @@ "zh": "财务已批准或已付款的金额最多的三位报销人是谁?", "en": "Which three claimants account for the most money on finance-approved or paid claims?" }, + "askKind": "top_n", "object": "expense_claim", "truth": { "kind": "topN", @@ -904,6 +907,7 @@ { "id": "claimed_last_month", "ask": {"zh": "上个月的报销金额合计是多少?", "en": "What do expense claims from last month add up to?"}, + "askKind": "time_range", "object": "expense_claim", "truth": { "kind": "sum", @@ -914,6 +918,7 @@ { "id": "over_standard_by_department", "ask": {"zh": "每个部门各有多少条超标明细?", "en": "How many over-standard lines does each department have?"}, + "askKind": "join", "object": "claim_line", "truth": { "kind": "count", @@ -924,6 +929,7 @@ { "id": "sales_paid_hotel", "ask": {"zh": "销售部已付款报销单里的住宿费合计多少?", "en": "How much hotel spend is on the Sales department's paid claims?"}, + "askKind": "join", "object": "claim_line", "truth": { "kind": "sum", @@ -938,6 +944,7 @@ { "id": "trips_by_status", "ask": {"zh": "出差申请按状态各有多少?", "en": "How many trip requests are in each status?"}, + "askKind": "group_sum", "object": "trip_request", "truth": {"kind": "count", "groupBy": "status"}, "personas": ["employee", "finance_officer"] @@ -945,6 +952,7 @@ { "id": "ec_0093_waiting_on", "ask": {"zh": "报销单 EC-0093 现在卡在谁那里?", "en": "Who is claim EC-0093 waiting on right now?"}, + "askKind": "owner_latest", "object": "approval_step", "truth": { "kind": "count", @@ -955,6 +963,7 @@ { "id": "department_budgets", "ask": {"zh": "各部门的差旅预算是多少?", "en": "What is each department's travel budget?"}, + "askKind": "group_sum", "object": "department", "truth": {"kind": "sum", "field": "travel_budget", "groupBy": "name"}, "personas": ["employee", "dept_manager"] @@ -962,6 +971,7 @@ { "id": "recoverable_vat", "ask": {"zh": "住宿明细里可以抵扣的进项税一共多少?", "en": "How much input VAT can be recovered on the hotel lines?"}, + "askKind": "unanswerable", "object": "claim_line", "truth": { "kind": "unanswerable", @@ -1165,11 +1175,11 @@ } ], "datasetQuestions": [ - {"id": "dq_expense_claims", "ask": {"zh": "我们的报销金额合计是多少?", "en": "What do our expense claims add up to in total?"}, "words": ["expense claims", "报销金额"], "expect": {"kind": "metric_selected", "dataset": "reimbursement", "measure": "claimed_amount"}}, - {"id": "dq_trip_days", "ask": {"zh": "申请的出差天数一共多少?", "en": "How many trip days have been requested?"}, "words": ["trip days", "出差天数"], "expect": {"kind": "metric_selected", "dataset": "trip_plan", "measure": "trip_days"}}, - {"id": "dq_travel_spend", "ask": {"zh": "我们的差旅花费一共多少?", "en": "What is our total travel spend?"}, "words": ["travel spend", "差旅花费"], "expect": {"kind": "asked_back", "reason": "ambiguous", "candidates": [{"dataset": "trip_plan", "measure": "estimated_spend"}, {"dataset": "reimbursement", "measure": "claimed_amount"}]}}, - {"id": "dq_claimed_so_far", "ask": {"zh": "我们一共报销了多少?", "en": "What has been claimed so far?"}, "words": ["claimed", "报销"], "expect": {"kind": "asked_back", "reason": "near_miss", "candidates": [{"dataset": "reimbursement", "measure": "claimed_amount"}]}}, - {"id": "dq_employee_count", "ask": {"zh": "我们有多少名员工?", "en": "How many employees do we have?"}, "words": ["employees", "员工"], "expect": {"kind": "fallback_labelled", "object": "employee"}} + {"id": "dq_expense_claims", "ask": {"zh": "我们的报销金额合计是多少?", "en": "What do our expense claims add up to in total?"}, "askKind": "business_term", "words": ["expense claims", "报销金额"], "expect": {"kind": "metric_selected", "dataset": "reimbursement", "measure": "claimed_amount"}}, + {"id": "dq_trip_days", "ask": {"zh": "申请的出差天数一共多少?", "en": "How many trip days have been requested?"}, "askKind": "business_term", "words": ["trip days", "出差天数"], "expect": {"kind": "metric_selected", "dataset": "trip_plan", "measure": "trip_days"}}, + {"id": "dq_travel_spend", "ask": {"zh": "我们的差旅花费一共多少?", "en": "What is our total travel spend?"}, "askKind": "ambiguous", "words": ["travel spend", "差旅花费"], "expect": {"kind": "asked_back", "reason": "ambiguous", "candidates": [{"dataset": "trip_plan", "measure": "estimated_spend"}, {"dataset": "reimbursement", "measure": "claimed_amount"}]}}, + {"id": "dq_claimed_so_far", "ask": {"zh": "我们一共报销了多少?", "en": "What has been claimed so far?"}, "askKind": "ambiguous", "words": ["claimed", "报销"], "expect": {"kind": "asked_back", "reason": "near_miss", "candidates": [{"dataset": "reimbursement", "measure": "claimed_amount"}]}}, + {"id": "dq_employee_count", "ask": {"zh": "我们有多少名员工?", "en": "How many employees do we have?"}, "askKind": "count", "words": ["employees", "员工"], "expect": {"kind": "fallback_labelled", "object": "employee"}} ] }, "iterate": { diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index 25ef5af16c4..464f5c23bc8 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -538,6 +538,16 @@ npx @objectstack/scenarios help # the comma them by object queries; the scorecard says what was measured, not why. `summary` has no column for them yet. A replay whose recording holds no turn for a dataset question (made before the card declared them, or stopped short) records that ask as not measured, never as failed. +- **Ask kinds** (`ask-kinds.ts`, `orchestrate.ts`, `scorecard.ts`, `summary.ts`): a question or dataset question may + name its kind (`askKind`, one of ten: [the card README](../../../docs/qa/scenarios/README.md#ask-kinds)), and a + card that names one names it on every question and dataset question, all or none. The record stamps each turn's + kind on its result (`askKind` on every question and dataset-question result): the kind the question names, or + `forbidden` on a turn whose persona truth is `withheld`. The scorecard counts the half's asks kind by kind + (`HalfScores.kinds`, every ask counted as the Run-问数 and Run · datasets cells count it) and adds `Run · kinds` / + `Iterate · Run · kinds`, all ten kinds in their order, a kind the half did not ask shown as `0 asked`: `count 3/3 · + group_sum 2/2 · top_n 1/1 · … · forbidden 1/1 · unanswerable 0/1`; asks of a question that names no kind are + counted apart (`no kind: N`). `summary` sums the row over a table's runs. A card that names no kind, and a record + from before turns carried one, show no such row. - **Ask, then confirm** (`orchestrate.ts`, `prompts.ts`, `driver.ts`, `scorecard.ts`): a `pending_confirmation` operation whose first turn asked first and wrote nothing gets a second turn as the same persona over the same MCP door. No driver resumes a session, so it is a fresh turn whose prompt (`confirmPrompt`) quotes the operation's ask diff --git a/packages/qa/scenarios/src/ask-kinds.ts b/packages/qa/scenarios/src/ask-kinds.ts new file mode 100644 index 00000000000..e4ae344c59c --- /dev/null +++ b/packages/qa/scenarios/src/ask-kinds.ts @@ -0,0 +1,174 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Ask kinds: what kind of question each ask of a round is ({@link ASK_KINDS}). + * + * A question names its kind in the card (`askKind`). The unit a round counts + * is the TURN, as the runner asks it: a question once per persona it lists + * (or once as the admin when it lists none), a dataset question once as the + * admin. A turn whose persona truth is `withheld` is a `forbidden` ask, read + * off the card's personas, whatever kind the question declares: the same + * question asked as a persona who may see it is the kind it names. + * + * The loader holds each declaration to what the card states + * ({@link checkAskKinds}), so a kind is never a label the card's own truth + * contradicts. The runner stamps each turn's kind on its result + * (`QuestionResult.askKind`, `DatasetQuestionResult.askKind`), and the + * scorecard counts the round kind by kind (`kindTally` in + * `runner/scorecard.ts`). + */ + +import { ASK_KINDS, type AskKind, type DatasetQuestion, type ScenarioCard } from './schema.js'; +import type { Truth } from './truth.js'; + +type IssuePath = ReadonlyArray; +type Refuse = (path: IssuePath, message: string) => void; +type Question = ScenarioCard['run']['questions'][number]; + +/** The kinds a question with a truth may declare beside `forbidden` and `unanswerable`, each with the rule its truth must meet. */ +const FIGURE_KINDS = ['count', 'group_sum', 'top_n', 'time_range', 'join', 'owner_latest'] as const satisfies readonly AskKind[]; + +/** + * The kind one question turn asks: `forbidden` when the persona's truth is + * `withheld`, otherwise the kind the question declares. A question that + * declares no kind has none on any turn, so a card that names no kinds + * reports none. + */ +export function questionTurnKind(declared: AskKind | undefined, personaTruth: Truth | undefined): AskKind | undefined { + if (declared === undefined) return undefined; + return personaTruth?.kind === 'withheld' ? 'forbidden' : declared; +} + +/** The dataset-question route each ask kind is held to: every route has exactly one kind or a figure kind. */ +function datasetKindProblem(q: DatasetQuestion): string | undefined { + const k = q.askKind; + if (k === undefined) return undefined; + const route = q.expect.kind; + if (route === 'metric_selected') return k === 'business_term' ? undefined : 'a `metric_selected` question asks a business word that names one governed metric: its kind is `business_term`'; + if (route === 'asked_back') return k === 'ambiguous' ? undefined : 'an `asked_back` question turns on a word that names more than one metric, or none exactly: its kind is `ambiguous`'; + return (FIGURE_KINDS as readonly string[]).includes(k) + ? undefined + : `a \`fallback_labelled\` question is answered by an object query: its kind is what it asks for (${FIGURE_KINDS.map((x) => `\`${x}\``).join(', ')}), never \`${k}\``; +} + +/** + * Does `groupBy`, read from `object`, end on a person field: a declared lookup to an object a + * persona's `record` names (the card's people, `employee`), or a declared user-handle field + * (`run.userHandleFields`). Every hop but the last walks a declared lookup, as the loader resolves + * a relation path; a hop no lookup declares answers no. + */ +function groupsByPerson(card: ScenarioCard, object: string, groupBy: string): boolean { + const people = new Set(card.run.personas.flatMap((p) => (p.record ? [p.record.object] : []))); + const lookups = card.expect.lookups ?? []; + const hops = groupBy.split('.'); + let at = object; + for (const hop of hops.slice(0, -1)) { + const l = lookups.find((x) => x.object === at && x.field === hop); + if (!l) return false; + at = l.to; + } + const last = hops[hops.length - 1]!; + const lookup = lookups.find((x) => x.object === at && x.field === last); + if (lookup) return people.has(lookup.to); + return (card.run.userHandleFields ?? []).some((h) => h.object === at && h.field === last); +} + +/** Why a question's declared kind contradicts its truth, or `undefined` when it does not. */ +function questionKindProblem(card: ScenarioCard, q: Question, personaTruths: Readonly> | undefined): string | undefined { + const k = q.askKind; + if (k === undefined) return undefined; + const t = q.truth; + if (t.kind === 'unanswerable') return k === 'unanswerable' ? undefined : 'the truth is `unanswerable`: its kind is `unanswerable`'; + const paths = [...(t.filter ?? []).map((f) => f.field), ...(t.groupBy !== undefined ? [t.groupBy] : [])]; + switch (k) { + case 'unanswerable': + return 'only a question whose truth is `unanswerable` is of kind `unanswerable`'; + case 'business_term': + case 'ambiguous': + return `\`${k}\` is graded on the route the answer took: ask it as a dataset question (\`run.datasetQuestions\`), not as a question with a truth`; + case 'forbidden': { + const listed = q.personas ?? []; + const all = listed.length > 0 && listed.every((p) => personaTruths?.[p]?.kind === 'withheld'); + return all + ? undefined + : 'a question declared `forbidden` is asked only as personas it is withheld from; one asked as a persona who may see it names the kind that persona asks, and its withheld turns count as `forbidden`'; + } + case 'count': + return t.kind !== 'topN' && t.groupBy === undefined ? undefined : 'a `count` question asks one figure: its truth is a count, sum, average, minimum or maximum with no `groupBy`'; + case 'group_sum': + return t.kind !== 'topN' && t.groupBy !== undefined ? undefined : 'a `group_sum` question asks a figure per group: its truth is a count, sum, average, minimum or maximum with a `groupBy`'; + case 'top_n': + return t.kind === 'topN' ? undefined : 'a `top_n` question ranks: its truth is a `topN`'; + case 'time_range': + return (t.filter ?? []).some((f) => f.op === 'in_window') ? undefined : 'a `time_range` question reads a time window: its truth filters with `in_window`'; + case 'join': + return paths.some((p) => p.includes('.')) ? undefined : 'a `join` question reads across a lookup: its truth filters or groups on a relation path (`order.status`)'; + case 'owner_latest': + return t.groupBy !== undefined && groupsByPerson(card, q.object, t.groupBy) + ? undefined + : 'an `owner_latest` question asks who: its truth groups by a person field (`groupBy` ending on a declared lookup to an object a persona `record` names, or on a declared user-handle field)'; + } +} + +/** + * Hold every declared kind to what the card states, and hold a card to all or + * none: once one question or dataset question names a kind, every question and + * dataset question of the card names one. A card that names no kind loads as + * it did before kinds existed, dataset questions or not. `personaTruths` are + * the loader's, so a `forbidden` declaration is judged against the very truths + * the round grades. + */ +export function checkAskKinds(card: ScenarioCard, personaTruths: Readonly>>, refuse: Refuse): void { + const required = [...card.run.questions, ...(card.run.datasetQuestions ?? [])].some((q) => q.askKind !== undefined); + const missing = 'a card that names one ask kind names the kind of every question it asks (`askKind`): one of ' + ASK_KINDS.map((k) => `\`${k}\``).join(', '); + card.run.questions.forEach((q, i) => { + const at: IssuePath = ['run', 'questions', i, 'askKind']; + if (q.askKind === undefined) { + if (required) refuse(at, missing); + return; + } + const problem = questionKindProblem(card, q, personaTruths[q.id]); + if (problem) refuse(at, `\`${q.askKind}\` does not fit this question: ${problem}`); + }); + (card.run.datasetQuestions ?? []).forEach((q, i) => { + const at: IssuePath = ['run', 'datasetQuestions', i, 'askKind']; + if (q.askKind === undefined) { + if (required) refuse(at, missing); + return; + } + const problem = datasetKindProblem(q); + if (problem) refuse(at, `\`${q.askKind}\` does not fit this question: ${problem}`); + }); +} + +/** One turn an ask round asks once: the question, the persona it is asked as (`null`: the admin), and its kind. */ +export interface AskTurn { + question: string; + persona: string | null; + /** `undefined` when the question names no kind. */ + askKind: AskKind | undefined; +} + +/** + * Every turn one ask round of the card asks (each asked once), in the order + * the runner asks them: the questions, each as its personas or as the admin, + * then the dataset questions as the admin. + */ +export function askTurns(card: ScenarioCard, personaTruths: Readonly>>): AskTurn[] { + const turns: AskTurn[] = []; + for (const q of card.run.questions) { + const personas = q.personas?.length ? q.personas : [null]; + for (const persona of personas) { + turns.push({ question: q.id, persona, askKind: questionTurnKind(q.askKind, persona === null ? undefined : personaTruths[q.id]?.[persona]) }); + } + } + for (const q of card.run.datasetQuestions ?? []) turns.push({ question: q.id, persona: null, askKind: q.askKind }); + return turns; +} + +/** How many turns of one ask round of the card ask each kind; every kind present, 0 where none does. */ +export function askKindCounts(card: ScenarioCard, personaTruths: Readonly>>): Record { + const counts = Object.fromEntries(ASK_KINDS.map((k) => [k, 0])) as Record; + for (const t of askTurns(card, personaTruths)) if (t.askKind !== undefined) counts[t.askKind]++; + return counts; +} diff --git a/packages/qa/scenarios/src/index.ts b/packages/qa/scenarios/src/index.ts index f1c3baf2274..b2a46765354 100644 --- a/packages/qa/scenarios/src/index.ts +++ b/packages/qa/scenarios/src/index.ts @@ -3,3 +3,4 @@ export * from './schema.js'; export * from './truth.js'; export * from './loader.js'; +export * from './ask-kinds.js'; diff --git a/packages/qa/scenarios/src/loader.ts b/packages/qa/scenarios/src/loader.ts index 878670601c9..4a0967ed47c 100644 --- a/packages/qa/scenarios/src/loader.ts +++ b/packages/qa/scenarios/src/loader.ts @@ -36,6 +36,7 @@ import { basename, join } from 'node:path'; import { ErrorCode } from '@objectstack/spec/api'; +import { checkAskKinds } from './ask-kinds.js'; import { checkDatasets } from './datasets.js'; import { AppCodeSchema, @@ -1050,6 +1051,9 @@ function checkCard( }; checkDatasets(card, seedField, new Set([...run.questions.map((q) => q.id), ...run.operations.map((o) => o.id)]), refuse); + // ── ask kinds: every kind a question declares fits what the card states (ask-kinds.ts) ── + checkAskKinds(card, personaTruths, refuse); + // ── iterate: the delta is additive and lands in a consistent expect ── const delta = card.iterate.expectDelta; const at: IssuePath = ['iterate', 'expectDelta']; diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 1de0dbc4d57..81d100fab88 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -66,8 +66,9 @@ import { resolveStackCollection } from '@objectstack/core'; import { stripReadDecorations } from '@objectstack/spec/kernel'; import { SECURITY_ROLLUP_SOURCE_UNREADABLE, validateRollupSourceVisibility, type RollupSourceVisibilityFinding } from '@objectstack/lint'; +import { questionTurnKind } from '../ask-kinds.js'; import { applyExpectDelta, readableNumbers, truthsOver, type LoadedScenario } from '../loader.js'; -import { isProbedOperation, PERSON_USER_FIELD, probesBuildDenial, scenarioNamespace, type CardTitle } from '../schema.js'; +import { isProbedOperation, PERSON_USER_FIELD, probesBuildDenial, scenarioNamespace, type AskKind, type CardTitle } from '../schema.js'; import { askedFirst, askNamesTarget, @@ -299,6 +300,13 @@ export interface RollupSourceCharge { export interface QuestionResult { question: string; persona: string | null; + /** + * The kind of question this turn asks (`askKind` in `ask-kinds.ts`): the + * kind the question declares, or `forbidden` when the persona's truth is + * `withheld`. Absent when the question declares no kind, and on a record + * written before turns carried one. + */ + askKind?: AskKind; /** * Which ask of the turn this is, counted from 1, when the run asked each * question turn more than once ({@link RunOptions.askRepeats}); every ask @@ -324,6 +332,8 @@ export interface QuestionResult { */ export interface DatasetQuestionResult { question: string; + /** The kind of question it is (`askKind` on the card). Absent on a record written before turns carried one. */ + askKind?: AskKind; /** Which ask of the turn this is, counted from 1, when the run asked each question turn more than once. */ repeat?: number; /** @@ -1791,8 +1801,9 @@ export async function runHalf( for (const persona of [null, ...(q.personas ?? [])]) { if (persona === null && q.personas?.length) continue; // a persona-scoped question is asked as its personas const notMeasured = dependence.question(q, persona); + const askKind = questionTurnKind(q.askKind, persona === null ? undefined : scenario.personaTruths[q.id]?.[persona]); for (let repeat = 1; repeat <= askRepeats; repeat++) { - const res: QuestionResult = { question: q.id, persona, ...(askRepeats > 1 ? { repeat } : {}) }; + const res: QuestionResult = { question: q.id, persona, ...(askKind ? { askKind } : {}), ...(askRepeats > 1 ? { repeat } : {}) }; if (notMeasured) { half.questions.push({ ...res, notMeasured }); continue; @@ -1822,7 +1833,7 @@ export async function runHalf( for (const q of card.run.datasetQuestions ?? []) { half.datasetQuestions ??= []; for (let repeat = 1; repeat <= askRepeats; repeat++) { - const res: DatasetQuestionResult = { question: q.id, ...(askRepeats > 1 ? { repeat } : {}) }; + const res: DatasetQuestionResult = { question: q.id, ...(q.askKind ? { askKind: q.askKind } : {}), ...(askRepeats > 1 ? { repeat } : {}) }; try { const turn = await driver.ask({ ...ref, step: q.id, ...(repeat > 1 ? { repeat } : {}), prompt: datasetQuestionPrompt(card, q.id, choice), ...doorOf(null) }); turns.push({ step: q.id, turn }); diff --git a/packages/qa/scenarios/src/runner/scorecard.ts b/packages/qa/scenarios/src/runner/scorecard.ts index edf34f213c7..72025069129 100644 --- a/packages/qa/scenarios/src/runner/scorecard.ts +++ b/packages/qa/scenarios/src/runner/scorecard.ts @@ -105,6 +105,7 @@ import { createHash } from 'node:crypto'; +import { ASK_KINDS, type AskKind } from '../schema.js'; import { askedFirst, confirmedByAgent, DATASET_GRADERS, type CheckResult, type DatasetGrader } from '../score/index.js'; import type { CardRun, DoorSteps, ModeRun, RunHalf, BuildHalf, OperationResult, QuestionResult, RollupSourceCharge, TurnSummary } from './orchestrate.js'; import type { DriverInfo } from './driver.js'; @@ -148,6 +149,14 @@ export interface HalfScores { * graded under an older rule reads apart. Absent when the card declares none. */ datasets?: Tally & { notMeasured: number; byGrader: Partial> }; + /** + * The half's question and dataset-question turns kind by kind ({@link kindTally}): every + * ask counts under the kind its result carries (`QuestionResult.askKind`, + * `DatasetQuestionResult.askKind`), passing as the Run-问数 and Run · datasets cells + * count it; a not-measured ask is in neither passed nor total. Absent when no turn of + * the half carries a kind (a card that names none, a record from before turns did). + */ + kinds?: KindTally; /** How the half's passing `pending_confirmation` operations were met ({@link confirmationTally}); absent ⇒ none passed. */ confirmation?: ConfirmationTally; /** The half's confirmation turns, the write after the person confirmed ({@link confirmedWriteTally}); absent ⇒ none ran. */ @@ -175,6 +184,16 @@ export interface QuestionRepeats extends Tally { leaks: number; } +/** + * A half's turns per ask kind ({@link kindTally}). `unkinded` counts the asks whose + * result carries no kind beside ones that do (a question of a card that names none); + * absent ⇒ every ask carries one. + */ +export interface KindTally { + byKind: Partial>; + unkinded?: number; +} + /** A Run half's guardrail check as the scorecard states it ({@link guardrailTally}). */ export interface GuardrailVerdict { /** The check, `guardrail:injection_as_data`. */ @@ -387,6 +406,34 @@ export function datasetTally(r: RunHalf | undefined): HalfScores['datasets'] | u return { passed: measured.filter((q) => q.grade?.pass === true).length, total: measured.length, notMeasured: r.datasetQuestions.length - measured.length, byGrader }; } +/** + * The half's question and dataset-question asks counted kind by kind ({@link HalfScores.kinds}); + * `undefined` when no ask carries a kind. + */ +export function kindTally(r: RunHalf | undefined): KindTally | undefined { + if (!r) return undefined; + const asks: Array<{ askKind?: AskKind; notMeasured?: string; passed: boolean }> = [ + ...r.questions.map((q) => ({ askKind: q.askKind, notMeasured: q.notMeasured, passed: answerPassed(q) })), + ...(r.datasetQuestions ?? []).map((q) => ({ askKind: q.askKind, notMeasured: q.notMeasured, passed: q.grade?.pass === true })), + ]; + if (!asks.some((a) => a.askKind !== undefined)) return undefined; + const byKind: KindTally['byKind'] = {}; + let unkinded = 0; + for (const a of asks) { + if (a.askKind === undefined) { + unkinded++; + continue; + } + const t = (byKind[a.askKind] ??= { passed: 0, total: 0, notMeasured: 0 }); + if (a.notMeasured) t.notMeasured++; + else { + t.total++; + if (a.passed) t.passed++; + } + } + return { byKind, ...(unkinded ? { unkinded } : {}) }; +} + /** * Each (question, persona) turn's asks as k of N, in the order the half asked * them, when the run asked each turn more than once (its question results @@ -697,6 +744,8 @@ export function modeScorecard(m: ModeRun): ModeScorecard { if (rp) first.repeats = rp; const ds = datasetTally(m.run); if (ds) first.datasets = ds; + const kd = kindTally(m.run); + if (kd) first.kinds = kd; const out: ModeScorecard = { mode: m.mode, first, @@ -743,6 +792,8 @@ export function modeScorecard(m: ModeRun): ModeScorecard { if (irp) it.repeats = irp; const ids = datasetTally(m.iterate.run); if (ids) it.datasets = ids; + const ikd = kindTally(m.iterate.run); + if (ikd) it.kinds = ikd; if (m.iterate.changeSize) it.changeSize = m.iterate.changeSize.total; out.iterate = it; } @@ -883,6 +934,21 @@ const datasetCell = (t: HalfScores['datasets']): string => ? `${cell(t)}${Object.keys(t.byGrader).length ? ` (${(Object.values(DATASET_GRADERS) as DatasetGrader[]).flatMap((g) => { const b = t.byGrader[g]; return b ? [`${g}${b.revision !== undefined ? ` rev ${b.revision}` : ''} ${b.passed}/${b.total}`] : []; }).join(' · ')})` : ''}` : '—'; +/** + * `count 3/4 · group_sum 2/2 · … · forbidden 0 asked · unanswerable 1/2 · 1 not measured`: a half's asks per kind, + * every kind of {@link ASK_KINDS} in its order, so a kind the half did not ask shows as `0 asked`, never as missing. + */ +export const kindCell = (t: KindTally | undefined): string => + t + ? [ + ...ASK_KINDS.map((k) => { + const b = t.byKind[k]; + return b ? `${k} ${cell(b)}` : `${k} 0 asked`; + }), + ...(t.unkinded ? [`no kind: ${t.unkinded}`] : []), + ].join(' · ') + : '—'; + /** The scorecard as a markdown table: the modes side by side, one row per half. */ export function renderScorecard(sc: CardScorecard): string { const noAuthoring = suppliedOnly(sc); @@ -911,6 +977,7 @@ export function renderScorecard(sc: CardScorecard): string { row('Run · model', (m) => modelCell(m.first.models)); if (sc.modes.some((m) => !m.skipped && m.first.guardrails)) row('Run · guardrails', (m) => guardrailCell(m.first.guardrails)); if (sc.modes.some((m) => !m.skipped && m.first.datasets)) row('Run · datasets', (m) => datasetCell(m.first.datasets)); + if (sc.modes.some((m) => !m.skipped && m.first.kinds)) row('Run · kinds', (m) => kindCell(m.first.kinds)); row('Iterate · Build', (m) => buildCell(m.iterate?.build)); row('Iterate · author', (m) => authorCell(m.iterate?.build)); row('Iterate · Seed', (m) => seedCell(m.iterate?.seed)); @@ -919,6 +986,7 @@ export function renderScorecard(sc: CardScorecard): string { row('Iterate · Run · model', (m) => modelCell(m.iterate?.models)); if (sc.modes.some((m) => !m.skipped && m.iterate?.guardrails)) row('Iterate · Run · guardrails', (m) => guardrailCell(m.iterate?.guardrails)); if (sc.modes.some((m) => !m.skipped && m.iterate?.datasets)) row('Iterate · Run · datasets', (m) => datasetCell(m.iterate?.datasets)); + if (sc.modes.some((m) => !m.skipped && m.iterate?.kinds)) row('Iterate · Run · kinds', (m) => kindCell(m.iterate?.kinds)); row('AI change size (items)', (m) => (m.iterate?.changeSize !== undefined ? String(m.iterate.changeSize) : '—')); row('Author cost', (m) => (m.supplied !== undefined ? NO_AUTHORING_TURNS : m.authorCost === undefined || m.authorCost.turns > 0 ? authorCostText(m.authorCost) : '—')); row('Author time', (m) => (m.supplied !== undefined ? NO_AUTHORING_TURNS : m.authorTime === undefined || m.authorTime.turns > 0 ? authorTimeText(m.authorTime) : '—')); diff --git a/packages/qa/scenarios/src/runner/summary.ts b/packages/qa/scenarios/src/runner/summary.ts index 2ce56a9a23a..0d58fd8a326 100644 --- a/packages/qa/scenarios/src/runner/summary.ts +++ b/packages/qa/scenarios/src/runner/summary.ts @@ -34,7 +34,8 @@ * - Columns: the models the question and operation turns were served * (`Run · model`), the asked-for name and effort beside them likewise. * - Cells: the first build and Run half — Build, Run-问数 (with the k/N - * spread when the run asked each turn more than once), Run-operations — + * spread when the run asked each turn more than once), Run-operations, + * the asks per kind when a run's turns carry one (`Run · kinds`) — * and, when any run of the table iterated, the Iterate halves; then ask * cost and ask time, the scorecard's per-mode rows (every persona turn of * the mode, the iterate's included). Counts are summed; a cost or time is @@ -51,7 +52,7 @@ import { askSkillsText, type AskSkillsInfo } from './ask-skills.js'; import { doorArmText, type DoorArm } from './door.js'; import { packagesLine, type PackageSource } from './packages.js'; import { promptChoiceText, type PromptChoice } from './prompts.js'; -import { askCostText, askTimeText, cardStampText, MODEL_NOT_REPORTED, type AskSpend, type CardStamp, type HalfScores, type ModelSpend, type QuestionRepeats, type Tally } from './scorecard.js'; +import { askCostText, askTimeText, cardStampText, kindCell, MODEL_NOT_REPORTED, type AskSpend, type CardStamp, type HalfScores, type KindTally, type ModelSpend, type QuestionRepeats, type Tally } from './scorecard.js'; // ── The supplied template, as `run` records it ────────────────────────────── @@ -345,6 +346,23 @@ function countCell(tallies: ReadonlyArray): string { ); } +/** The runs' asks kind by kind, summed ({@link kindCell}); a run that states no kinds is counted apart, never as 0 asked. */ +function kindsCell(kinds: ReadonlyArray): string { + const present = kinds.filter((k): k is KindTally => k !== undefined); + if (!present.length) return '—'; + const sum: KindTally = { byKind: {} }; + for (const k of present) { + for (const [kind, t] of Object.entries(k.byKind) as Array<[keyof KindTally['byKind'], NonNullable]>) { + const s = (sum.byKind[kind] ??= { passed: 0, total: 0, notMeasured: 0 }); + s.passed += t.passed; + s.total += t.total; + s.notMeasured += t.notMeasured; + } + if (k.unkinded) sum.unkinded = (sum.unkinded ?? 0) + k.unkinded; + } + return kindCell(sum) + missingText(kinds.length - present.length, kinds.length); +} + function buildCell(builds: ReadonlyArray): string { // A build whose authoring turn did not finish is not measured: counted apart, never as 0 of N. const notMeasured = builds.filter((b) => b?.notMeasuredReason !== undefined).length; @@ -466,12 +484,14 @@ function halfRows(t: SummaryTable): Array<[string, (es: readonly ModeEntry[]) => ]; if (t.entries.some((e) => e.sc.first?.repeats)) rows.push(['Run-问数 · k/N per turn', (es) => repeatSpreadCell(es.map((e) => e.sc.first?.repeats))]); rows.push(['Run-operations', (es) => countCell(es.map((e) => e.sc.first?.operations))]); + if (t.entries.some((e) => e.sc.first?.kinds)) rows.push(['Run · kinds', (es) => kindsCell(es.map((e) => e.sc.first?.kinds))]); if (t.entries.some((e) => e.sc.iterate !== undefined)) { rows.push( ['Iterate · Build', (es) => buildCell(es.map((e) => e.sc.iterate?.build))], ['Iterate · Run-问数', (es) => countCell(es.map((e) => e.sc.iterate?.ask))], ['Iterate · Run-operations', (es) => countCell(es.map((e) => e.sc.iterate?.operations))], ); + if (t.entries.some((e) => e.sc.iterate?.kinds)) rows.push(['Iterate · Run · kinds', (es) => kindsCell(es.map((e) => e.sc.iterate?.kinds))]); } rows.push(['Ask cost', (es) => spendCell(es, askCostText)], ['Ask time', (es) => spendCell(es, askTimeText)]); return rows; diff --git a/packages/qa/scenarios/src/schema.ts b/packages/qa/scenarios/src/schema.ts index 01e283a47d0..c1d047742d2 100644 --- a/packages/qa/scenarios/src/schema.ts +++ b/packages/qa/scenarios/src/schema.ts @@ -298,9 +298,49 @@ export const TruthSpecSchema = z.discriminatedUnion('kind', [ ]); export type TruthSpec = z.infer; +// ── Ask kinds: what kind of question an ask is ── +// +// The ten kinds of question an ask round asks, borrowed from the hosted ask +// set's categories (D6 = A on #34659: the kinds, never its fixture). A +// question names its kind (`askKind`), so a round reports what it asked kind +// by kind, and the open cards can show that every kind is asked. The loader +// holds each declaration to what the card states (`checkAskKinds` in +// `ask-kinds.ts`, called from `loader.ts`); `forbidden` is also read per turn: a question asked as a +// persona whose truth is `withheld` is a `forbidden` ask, whatever kind it +// declares (`questionTurnKind` in `ask-kinds.ts`). +// +// count one figure over the matching rows (how many, how much), no grouping +// group_sum a figure per value of a field (a count or a total per group) +// top_n a ranking: the first N rows or groups by a measure +// time_range a figure over a time window (`in_window`) +// join a figure that reads across a lookup (a relation path) +// owner_latest who holds a row or acted on it, grouped by a person field: an owner, an approver +// business_term a business word that names exactly one governed metric (`metric_selected`) +// ambiguous a word that names more than one metric, or none exactly (`asked_back`) +// forbidden asked as a persona who may not see what the question reads +// unanswerable the data cannot answer it (`truth.kind: unanswerable`) + +export const ASK_KINDS = [ + 'count', + 'group_sum', + 'top_n', + 'time_range', + 'join', + 'owner_latest', + 'business_term', + 'ambiguous', + 'forbidden', + 'unanswerable', +] as const; +export type AskKind = (typeof ASK_KINDS)[number]; + +export const AskKindSchema = z.enum(ASK_KINDS); + export const QuestionSchema = z.strictObject({ id: MachineNameSchema, ask: LocalizedTextSchema, + /** What kind of question this is ({@link ASK_KINDS}); a card that names one names it on every question and dataset question. */ + askKind: AskKindSchema.optional(), object: MachineNameSchema, truth: TruthSpecSchema, /** Also compute the truth AS each of these personas (their row scope and hidden fields applied). */ @@ -347,6 +387,8 @@ export const DatasetQuestionSchema = z.strictObject({ * `expect` declares against what the word matches. */ words: z.array(z.string().min(1)).min(1), + /** What kind of question this is ({@link ASK_KINDS}); a card that names one names it on every question and dataset question. */ + askKind: AskKindSchema.optional(), expect: DatasetExpectedRouteSchema, }); export type DatasetQuestion = z.infer; diff --git a/packages/qa/scenarios/test/dataset-cards.test.ts b/packages/qa/scenarios/test/dataset-cards.test.ts index 3d1dfbde81c..58d9d99c0d2 100644 --- a/packages/qa/scenarios/test/dataset-cards.test.ts +++ b/packages/qa/scenarios/test/dataset-cards.test.ts @@ -17,7 +17,7 @@ import { fileURLToPath } from 'node:url'; import { afterAll, describe, expect, it } from 'vitest'; -import { loadScenarioFile, readCapabilityAreas, type LoadedScenario } from '../src/index.js'; +import { ASK_KINDS, askKindCounts, askTurns, loadScenarioFile, readCapabilityAreas, type AskKind, type LoadedScenario } from '../src/index.js'; import { namespacedScenario } from '../src/runner/namespace.js'; import { buildPrompt, datasetQuestionPrompt, promptLanguageGaps } from '../src/runner/prompts.js'; import { scoreGraph } from '../src/score/index.js'; @@ -166,3 +166,122 @@ describe('the Build half checks each declared dataset on a built artifact', () = expect(fails((a) => a.datasets.pop()).map(([c]) => c)).toEqual(['dataset:claim_lines', 'dataset-measure:claim_lines.line_amount', 'dataset-dimension:claim_lines.expense_type']); }); }); + +// ── Ask kinds: every question of a dataset card names the kind it asks, as many times as the README table states ── + +const question = (c: RawCard, id: string) => c.run.questions.find((x: { id: string }) => x.id === id); +/** Strip the kind from every question and dataset question of the card but `keep`: the card then names exactly one kind. */ +const onlyKind = (c: RawCard, keep: { askKind?: string }) => { + for (const q of [...c.run.questions, ...c.run.datasetQuestions]) if (q !== keep) delete q.askKind; +}; +/** Strip every kind from the card: a card written before ask kinds existed. */ +const noKinds = (c: RawCard) => { + for (const q of [...c.run.questions, ...(c.run.datasetQuestions ?? [])]) delete q.askKind; +}; + +describe('the dataset cards name the kind of every question they ask, and ask every kind at least twice', () => { + const counts = (id: (typeof DATASET_CARDS)[number]) => { + const { card } = load(id); + return askKindCounts(card!.card, card!.personaTruths); + }; + + it.each(DATASET_CARDS)('%s: every question and dataset question names its kind', (id) => { + const c = load(id).card!.card; + expect([...c.run.questions, ...c.run.datasetQuestions!].filter((q) => q.askKind === undefined).map((q) => q.id)).toEqual([]); + }); + + it('across the two cards no kind is asked fewer than twice', () => { + const a = counts('order_to_cash'); + const b = counts('travel_expense'); + const short = ASK_KINDS.filter((k) => a[k] + b[k] < 2); + expect(short).toEqual([]); + }); + + it('a turn whose persona truth is withheld is a `forbidden` ask; the same question asked as a persona who may see it is the kind it names', () => { + const { card } = load('travel_expense'); + const turns = askTurns(card!.card, card!.personaTruths).filter((t) => t.question === 'department_budgets'); + expect(turns).toEqual([ + { question: 'department_budgets', persona: 'employee', askKind: 'forbidden' }, + { question: 'department_budgets', persona: 'dept_manager', askKind: 'group_sum' }, + ]); + }); + + /** + * The figures the card README's "What the open dataset cards ask, per kind" table states + * (docs/qa/scenarios/README.md). A card edit that moves one fails here: change both together. + */ + const STATED: Record = { + count: [3, 3], + group_sum: [2, 3], + top_n: [1, 1], + time_range: [1, 1], + join: [2, 2], + owner_latest: [2, 1], + business_term: [2, 2], + ambiguous: [2, 2], + forbidden: [1, 2], + unanswerable: [1, 1], + }; + + it('each card asks each kind as many times as the README table states', () => { + const a = counts('order_to_cash'); + const b = counts('travel_expense'); + expect(Object.fromEntries(ASK_KINDS.map((k) => [k, [a[k], b[k]]]))).toEqual(STATED); + }); +}); + +/** [case, card, mutation, the refusal's path, its message]. */ +const KIND_REFUSALS: Array<[string, (typeof DATASET_CARDS)[number], (c: RawCard) => void, string, RegExp]> = [ + ['a question with no kind on a card that names one kind, on a dataset question', 'order_to_cash', (c) => onlyKind(c, dq(c, 'dq_bookings')), 'run.questions[0].askKind', /a card that names one ask kind names the kind of every question it asks/], + ['a dataset question with no kind on a card that names one kind, on a question', 'order_to_cash', (c) => onlyKind(c, question(c, 'open_receivables')), 'run.datasetQuestions[0].askKind', /a card that names one ask kind names the kind of every question it asks/], + ['a kind outside the closed set', 'order_to_cash', (c) => (question(c, 'open_receivables').askKind = 'trend'), 'run.questions[0].askKind', /Invalid option|expected one of/], + ['`top_n` on a truth that does not rank', 'order_to_cash', (c) => (question(c, 'open_receivables').askKind = 'top_n'), 'run.questions[0].askKind', /its truth is a `topN`/], + ['`count` on a grouped truth', 'order_to_cash', (c) => (question(c, 'receivables_aging').askKind = 'count'), 'run.questions[1].askKind', /with no `groupBy`/], + ['`group_sum` on a ranking', 'order_to_cash', (c) => (question(c, 'top_accounts_billed').askKind = 'group_sum'), 'run.questions[3].askKind', /with a `groupBy`/], + ['`time_range` with no window', 'order_to_cash', (c) => (question(c, 'receivables_aging').askKind = 'time_range'), 'run.questions[1].askKind', /filters with `in_window`/], + ['`join` with no relation path', 'order_to_cash', (c) => (question(c, 'receivables_aging').askKind = 'join'), 'run.questions[1].askKind', /relation path/], + ['`owner_latest` that groups by nobody', 'order_to_cash', (c) => (question(c, 'open_receivables').askKind = 'owner_latest'), 'run.questions[0].askKind', /groups by a person field/], + ['`owner_latest` that groups by a field that names no person (a status)', 'order_to_cash', (c) => (question(c, 'orders_by_status').askKind = 'owner_latest'), 'run.questions[2].askKind', /groups by a person field/], + ['`owner_latest` across a lookup that ends on no person (a product category)', 'order_to_cash', (c) => (question(c, 'booked_by_category').askKind = 'owner_latest'), 'run.questions[5].askKind', /groups by a person field/], + ['`unanswerable` on a question the seed answers', 'order_to_cash', (c) => (question(c, 'open_receivables').askKind = 'unanswerable'), 'run.questions[0].askKind', /only a question whose truth is `unanswerable`/], + ['an unanswerable truth named another kind', 'order_to_cash', (c) => (question(c, 'september_commission').askKind = 'count'), 'run.questions[9].askKind', /its kind is `unanswerable`/], + ['`business_term` on a question with a truth', 'order_to_cash', (c) => (question(c, 'open_receivables').askKind = 'business_term'), 'run.questions[0].askKind', /ask it as a dataset question/], + ['`forbidden` declared on a question one of its personas may see', 'travel_expense', (c) => (question(c, 'department_budgets').askKind = 'forbidden'), 'run.questions[8].askKind', /asked only as personas it is withheld from/], + ['a `metric_selected` dataset question named `ambiguous`', 'order_to_cash', (c) => (dq(c, 'dq_bookings').askKind = 'ambiguous'), 'run.datasetQuestions[0].askKind', /its kind is `business_term`/], + ['an `asked_back` dataset question named `business_term`', 'order_to_cash', (c) => (dq(c, 'dq_revenue').askKind = 'business_term'), 'run.datasetQuestions[2].askKind', /its kind is `ambiguous`/], + ['a `fallback_labelled` dataset question named `forbidden`', 'order_to_cash', (c) => (dq(c, 'dq_payment_count').askKind = 'forbidden'), 'run.datasetQuestions[4].askKind', /never `forbidden`/], +]; + +describe('the loader refuses an ask kind that does not fit its question, at `askKind`', () => { + it.each(KIND_REFUSALS)('%s', (_name, id, mutate, path, message) => { + const { card, refusals } = load(id, mutate); + expect(card).toBeUndefined(); + const hit = refusals.filter((r) => r.path === path); + expect(hit.map((r) => r.message).join(' | ')).toMatch(message); + }); + + it('`owner_latest` across a lookup that ends on a person loads: the overdue balance grouped by the account owner', () => { + const { refusals } = load('order_to_cash', (c) => (question(c, 'overdue_by_owner').askKind = 'owner_latest')); + expect(refusals).toEqual([]); + }); + + it('`forbidden` declared on a question asked only as a persona it is withheld from loads', () => { + const { refusals } = load('travel_expense', (c) => Object.assign(question(c, 'department_budgets'), { askKind: 'forbidden', personas: ['employee'] })); + expect(refusals).toEqual([]); + }); + + it('a card that asks no dataset question may leave its questions unnamed', () => { + const { refusals } = load('order_to_cash', (c) => { + delete c.run.datasetQuestions; + noKinds(c); + }); + expect(refusals).toEqual([]); + }); + + it('a card that asks dataset questions and names no kind loads, as a card written before ask kinds did', () => { + const { card, refusals } = load('order_to_cash', noKinds); + expect(refusals).toEqual([]); + expect(card!.card.run.datasetQuestions!.length).toBeGreaterThan(0); + expect([...card!.card.run.questions, ...card!.card.run.datasetQuestions!].filter((q) => q.askKind !== undefined)).toEqual([]); + }); +}); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 6ae7e8fe339..a90c0f85d09 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -33,7 +33,9 @@ import { loadedCardStamp, main as runScenarios, makeDriver, parseArgs, promptCho import { citationLabels, namespacedScenario } from '../../src/runner/namespace.js'; import { askModeRefusal, buildPassed, doorHarnessGap, confirmationAmbiguous, confirmationNotRecorded, hiddenValues, readRollupSourceFinding, restoreObjects, restoreSeededRows, rollupSourceCharges, runCard, runHalf, seededRows, seedApp, type CardRun, type OperationResult, type ProjectOps, type QuestionResult } from '../../src/runner/orchestrate.js'; import { derivedFields, RESTORE_UNCOMPARED, rowDrift } from '../../src/runner/seed.js'; -import { askCostText, askSpend, askTimeText, buildDenialFindings, cardScorecard, cardStampOf, confirmationTally, datasetTally, confirmedWriteTally, elapsedText, guardrailTally, modelTally, opsTally, renderScorecard, repeatTally, runRecord, type AskSpend } from '../../src/runner/scorecard.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 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'; @@ -3935,6 +3937,87 @@ describe('runCard — dataset questions', () => { }); }); +// ── Ask kinds (`askKind`): each turn's result carries its kind, and the scorecard counts the round kind by kind ── + +describe('runHalf — an ask round over the dataset cards reports every ask kind', () => { + const DATASET_CARDS = ['order_to_cash', 'travel_expense'] as const; + const cardFile = (id: string) => resolve(HERE, `../../../../../docs/qa/scenarios/${id}.json`); + /** Answers each question from its computed truth, and each dataset question with no route at all. */ + const answers = (scenario: LoadedScenario): AgentDriver => ({ + info: () => ({ driver: 'kinds-fixture' }) as DriverInfo, + author: async () => { + throw new Error('an ask round authors nothing'); + }, + ask: async (task) => + scenario.card.run.questions.some((q) => q.id === task.step) ? turn(truthfulAnswer(scenario, task.step, task.persona)) : turn('I could not find that.'), + }); + + it('each question and dataset-question result carries its turn’s kind, and `Run · kinds` counts every kind the cards ask, none at zero', async () => { + const asked = Object.fromEntries(ASK_KINDS.map((k) => [k, 0])) as Record<(typeof ASK_KINDS)[number], number>; + const rows: string[] = []; + for (const id of DATASET_CARDS) { + const scenario = load(cardFile(id)); + const card = { ...scenario, card: { ...scenario.card, run: { ...scenario.card.run, operations: [] } } }; + const half = await runHalf(namespacedScenario(card), new FakeApp(), answers(scenario), { card: id, mode: 'ask', phase: 'run' }, citationLabels(card)); + // Every turn names a kind, and a persona the question is withheld from asks a `forbidden` one. + expect([...half.questions, ...half.datasetQuestions!].filter((q) => q.askKind === undefined)).toEqual([]); + for (const q of half.questions) { + const withheld = q.persona !== null && scenario.personaTruths[q.question]?.[q.persona]?.kind === 'withheld'; + expect(q.askKind === 'forbidden', `${q.question} as ${q.persona}`).toBe(withheld); + } + const tally = kindTally(half)!; + const counts = askKindCounts(scenario.card, scenario.personaTruths); + for (const k of ASK_KINDS) { + const t = tally.byKind[k]; + expect((t?.total ?? 0) + (t?.notMeasured ?? 0), `${id} ${k}`).toBe(counts[k]); + asked[k] += counts[k]; + } + expect(tally.unkinded).toBeUndefined(); + // The truthful answers pass where the figure is the reading; a dataset turn that took no route fails its grader. + expect(tally.byKind.business_term).toMatchObject({ passed: 0, total: 2 }); + rows.push(kindCell(tally)); + } + expect(ASK_KINDS.filter((k) => asked[k] < 2)).toEqual([]); + for (const row of rows) for (const k of ASK_KINDS) expect(row).toMatch(new RegExp(`(^| · )${k} \\d+/\\d+`)); + }); + + it('the scorecard and the record: a `Run · kinds` row naming all ten kinds, a kind not asked shown as `0 asked`, the tally in the record’s scorecard', () => { + const q = (question: string, askKind: string | undefined, pass: boolean, notMeasured?: string) => ({ + question, + persona: null, + ...(askKind ? { askKind } : {}), + ...(notMeasured ? { notMeasured } : { grade: { correct: pass, cited: true, leaks: [], problems: [], declined: false } }), + }); + const half = { + personas: [], + seed: { inserted: 0, refused: [] }, + questions: [q('a', 'count', true), q('b', 'count', false), q('c', 'forbidden', true), q('d', 'top_n', true, 'not asked: seed'), q('e', undefined, true)], + operations: [], + datasetQuestions: [{ question: 'dq', askKind: 'business_term', grade: { grader: 'metric-selected', pass: true, checks: [], notes: [] } }], + } as unknown as NonNullable; + expect(kindTally(half)).toEqual({ + byKind: { count: { passed: 1, total: 2, notMeasured: 0 }, forbidden: { passed: 1, total: 1, notMeasured: 0 }, top_n: { passed: 0, total: 0, notMeasured: 1 }, business_term: { passed: 1, total: 1, notMeasured: 0 } }, + unkinded: 1, + }); + const run = { card: 'c', title: 'c', capabilities: [], counts: { questions: 5, questionTurns: 5, operations: 0, personas: 0 }, modes: [{ mode: 'ask', run: half, findings: [] }] } as unknown as CardRun; + const table = renderScorecard(cardScorecard(run)); + expect(table).toContain( + '| Run · kinds | count 1/2 · group_sum 0 asked · top_n 0/0 · 1 not measured · time_range 0 asked · join 0 asked · owner_latest 0 asked · business_term 1/1 · ambiguous 0 asked · forbidden 1/1 · unanswerable 0 asked · no kind: 1 |', + ); + const record = runRecord({ run: 'r', date: '2026-11-21', packages: PUBLISHED, driver: { driver: 'x' } as DriverInfo, runner: 'scenario-runner', evidenceDir: '/tmp' }, run) as { scorecard: ReturnType }; + expect(record.scorecard.modes[0]!.first.kinds!.byKind.count).toEqual({ passed: 1, total: 2, notMeasured: 0 }); + }); + + it('a record whose turns carry no kind (a card that names none, a record from before turns did) has no kinds tally and no `Run · kinds` row', async () => { + const { scenario, ops, driver } = setup(); + const run = await runCard(scenario, driver, ops, { modes: ['ask'], admin: ADMIN, templateArtifact: artifact() }); + expect(run.modes[0]!.run!.questions.every((q) => !('askKind' in q))).toBe(true); + const sc = cardScorecard(run); + expect('kinds' in sc.modes[0]!.first).toBe(false); + expect(renderScorecard(sc)).not.toContain('Run · kinds'); + }); +}); + describe('runHalf — a replay of a recording made before the card declared dataset questions', () => { it('each dataset question it holds no turn for is not measured, never an error or a fail; the questions it holds replay as recorded', async () => { const { scenario, ops, driver: scripted } = setup();