@happyvertical/smrt-reports 0.61.1 → 0.61.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/display.d.ts +9 -0
- package/dist/display.d.ts.map +1 -0
- package/dist/display.js +38 -0
- package/dist/display.js.map +1 -0
- package/dist/index.js +11 -1
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/runtime-compiler.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +8 -7
- package/dist/smrt-knowledge.okf.md +3 -2
- package/dist/state.js +1 -1
- package/dist/state.js.map +1 -1
- package/dist/svelte/ReportResult.svelte +23 -3
- package/dist/svelte/ReportResult.svelte.d.ts +5 -0
- package/dist/svelte/ReportResult.svelte.d.ts.map +1 -1
- package/dist/svelte/describe.d.ts +1 -3
- package/dist/svelte/describe.d.ts.map +1 -1
- package/dist/svelte/describe.js +1 -19
- package/dist/svelte/result.d.ts +1 -2
- package/dist/svelte/result.d.ts.map +1 -1
- package/dist/svelte/result.js +2 -43
- package/package.json +15 -10
package/dist/manifest.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-compiler.d.ts","sourceRoot":"","sources":["../src/runtime-compiler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AASH,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAK5E,OAAO,EAML,KAAK,mBAAmB,EAExB,KAAK,mBAAmB,EACxB,KAAK,8BAA8B,EAGpC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAIL,KAAK,iBAAiB,EACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAAuB,aAAa,EAAE,MAAM,YAAY,CAAC;AAErE,YAAY,EACV,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACnB,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAE3B,wEAAwE;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,CAAC;CACtD;AAsUD;;;;GAIG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,2BAA2B,EACpC,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,8BAA8B,CAAC,CAYzC;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,CAC5C,IAAI,EAAE,iBAAiB,EACvB,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,qBAAqB,CAAC,CA0HhC;AA0BD,MAAM,WAAW,uBAAuB;IACtC,EAAE,EAAE,iBAAiB,CAAC;IACtB,WAAW,CAAC,EAAE,cAAc,CAAC;IAC7B,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,qBAAqB,EAC/B,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,mBAAmB,CAAC,CA2D9B"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,15 +3,15 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-reports",
|
|
6
|
-
"packageVersion": "0.61.
|
|
6
|
+
"packageVersion": "0.61.2",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
10
|
+
"manifest": "2f25ea54b959f5ce2983136f8628f699de515b0d87a0e317b8eba64fbae56bb7",
|
|
11
|
+
"packageJson": "dad136f421e1b38e5dc2b4726ad77545c8ccd33156276f60b79d188bd218355e",
|
|
12
12
|
"agents": "06d19fec39775737f02dd553471e74a9f4442334138ea273ea53a0fb5e45cef4",
|
|
13
|
-
"moduleDoc:agents/runtime-report-browser.md": "
|
|
14
|
-
"moduleDoc:agents/runtime-reports.md": "
|
|
13
|
+
"moduleDoc:agents/runtime-report-browser.md": "594ba72285306ec68b956ed89e451dd2cea796dff7ae8206867c1046130e8aa6",
|
|
14
|
+
"moduleDoc:agents/runtime-reports.md": "16deaef2fdc35b1484b69477429c234255be991d68675cc9a5e335ff3c9b84e2",
|
|
15
15
|
"moduleDoc:README.md": "7c1382e820af6881b8e9a1de622fa4917d23bd3139cac0b04186c17299da2ff4"
|
|
16
16
|
},
|
|
17
17
|
"exports": [
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"./aggregate",
|
|
20
20
|
"./compiler",
|
|
21
21
|
"./decorators",
|
|
22
|
+
"./display",
|
|
22
23
|
"./manifest",
|
|
23
24
|
"./manifest.json",
|
|
24
25
|
"./playground",
|
|
@@ -1292,12 +1293,12 @@
|
|
|
1292
1293
|
{
|
|
1293
1294
|
"path": "agents/runtime-report-browser.md",
|
|
1294
1295
|
"module": "runtime-report-browser",
|
|
1295
|
-
"content": "# Runtime report browser surfaces (#3895)\n\nThe browser entry is `@happyvertical/smrt-reports/svelte`. It imports visual and\nform primitives from smrt-ui, never smrt-svelte or the reports server barrel.\n`@happyvertical/smrt-ui/charts` owns the five shared renderers; the overview\nchart and report results both consume it.\n\n- `SavedReports`: tenant-shared saved reports as a responsive grid of\n `SavedReportCard`s (title opening the report, a one-line description from\n `describeReport`, a headline figure and sparkline from a run, saved/updated\n time), Everyone's/Mine and Show archived filters (smrt-ui `SegmentedControl`,\n `Switch`), \"New report\", an empty state, and Archive in each card's \"more\"\n menu behind a confirmation. `variant: 'section'` is the Reports section page.\n The host resolves author ids (`authorLabel`), passes source labels\n (`sources`), and supplies an archive capability hint; the server authorizes\n every archive again. Each shown report runs once (three at a time).\n- \"New report\" and Edit call smrt-ui `requestAssistant` (the dock fills its\n composer); with no assistant on the page the screen says where to ask.\n- `ReportDetail`: a summary header (description, source, groupings, period\n with its dates, measures, filters, who saved it, last run), then the result\n run afresh on open and each re-run. Primary action by state: Edit, Try again\n after a failed run, Restore when archived; Export CSV (formatted,\n formula-safe) beside it; Re-run and Archive in the \"more\" menu. The transport is\n principal-scoped; replace it when viewer/tenant changes. Pending old\n responses are discarded, and result rows live only in component state.\n- `ReportResult`: validates the result shape and safe integers. `full` (a\n report's page): a Chart/Table switch, a measure switch, headline figures\n (total for sums and counts, average per bucket, peak) and a tall smrt-ui\n `Chart` with a value axis and keyboard/pointer readout. `compact` (preview\n card): a quiet table toggle. Tables format money and time buckets. Money\n fields use integer minor units and the host's ISO currency (default USD).\n- `saved-reports` widget (`SavedReportsWidget`, recipe `sectionDefault`): the\n Reports section page in any host rendering data widgets; it reads through\n the shared browser client unless the host passes `client`.\n- `ReportConfirmation`: shows the source label, groupings, measures,\n filters, and a bounded preview. Approve requires a trusted local click and\n posts the exact displayed `{ spec, specHash }` to the proposal's same-origin\n `confirmPath` once while pending. Decline never calls the server. The server\n recompiles as the confirming principal and idempotently saves the approved\n spec; the hash carries no authority by itself.\n- Answered state (#4100): after Approve or Decline the card shows an outcome\n line (\"Report saved · Open report\", \"Declined — nothing saved\") instead\n of buttons; pass `outcome` from the transcript so a reloaded card does too.\n `fields` (a source descriptor's names, labels, formats) labels groupings,\n buckets (\"Issue date by month\") and money filters; measures use the result's\n column labels. `ReportResult` labels time buckets by granularity\n (smrt-ui `formatTimeBucket`) and keeps the table toggle quiet.\n- `ReportPicker`: labelled fields (smrt-ui `FormGroup`) offering readable\n active reports and their measures and groupings by name, not alias;\n changing the report clears dependent choices.\n\n`createRuntimeReportsHttpClient()` implements the generated same-origin reads,\nthe enveloped `run`/`archive` actions, and the confirmation POST. It has no\ndatabase, tenant, or permission authority. Successful run timestamps live only\nin that browser client's session map; route hosts include an opaque active\ntenant/session scope so hints are discarded when the principal context changes. Omit the client (or set\n`serverAvailable={false}` on a route component) for a static host: the screens\nexplain that reports need a server and make no requests.\n\n`runtimeReportToolResultComponent` is the reports adapter for AssistantDock's\ngeneric component seam. Recipe routes export `RuntimeReportsRoute` and\n`RuntimeReportDetailRoute`; the `runtime-report-chart` surface exports its\nrenderer and dependent report/measure/dimension editor. The server host builds\nthe chart loader context from request-scoped `reportPrincipal`; widget options\nnever carry identity, permissions, tenant, or database authority.\n\nThe `./playground` entry has saved-list, detail, confirmation, picker, empty and\nunavailable previews. They use deterministic sample data, not a production\nbackend. All component copy registers through `smrt-ui/i18n`.\n\nThe smrt planner (#4100) renders `ReportConfirmation`, `SavedReports` and\n`ReportDetail` with its own `RuntimeReportsClient` over sample data and the\nin-memory runner from `./spec`; its `confirm` is a browser save, not this\npackage's confirmation route.\n\nThe template reference application exercises the generic dock selector, a real\ntrusted browser approval click, authenticated confirmation and generated reads,\ndetail execution, and the recipe-registered overview loader/renderer without\nmocking an endpoint.\n"
|
|
1296
|
+
"content": "# Runtime report browser surfaces (#3895)\n\nThe browser entry is `@happyvertical/smrt-reports/svelte`. It imports visual and\nform primitives from smrt-ui, never smrt-svelte or the reports server barrel.\n`@happyvertical/smrt-ui/charts` owns the five shared renderers; the overview\nchart and report results both consume it.\n\n- `SavedReports`: tenant-shared saved reports as a responsive grid of\n `SavedReportCard`s (title opening the report, a one-line description from\n `describeReport`, a headline figure and sparkline from a run, saved/updated\n time), Everyone's/Mine and Show archived filters (smrt-ui `SegmentedControl`,\n `Switch`), \"New report\", an empty state, and Archive in each card's \"more\"\n menu behind a confirmation. `variant: 'section'` is the Reports section page.\n The host resolves author ids (`authorLabel`), passes source labels\n (`sources`), and supplies an archive capability hint; the server authorizes\n every archive again. Each shown report runs once (three at a time).\n- \"New report\" and Edit call smrt-ui `requestAssistant` (the dock fills its\n composer); with no assistant on the page the screen says where to ask.\n- `ReportDetail`: a summary header (description, source, groupings, period\n with its dates, measures, filters, who saved it, last run), then the result\n run afresh on open and each re-run. Primary action by state: Edit, Try again\n after a failed run, Restore when archived; Export CSV (formatted,\n formula-safe) beside it; Re-run and Archive in the \"more\" menu. The transport is\n principal-scoped; replace it when viewer/tenant changes. Pending old\n responses are discarded, and result rows live only in component state.\n- `ReportResult`: validates the result shape and safe integers. `full` (a\n report's page): a Chart/Table switch, a measure switch, headline figures\n (total for sums and counts, average per bucket, peak) and a tall smrt-ui\n `Chart` with a value axis and keyboard/pointer readout. `compact` (preview\n card): a quiet table toggle. Tables format money and time buckets. Money\n fields use integer minor units and the host's ISO currency (default USD).\n- Hosts can pass `ReportResult.formatCell(value, column, row)` for display labels\n and formatting in tables and chart group labels, and `cellHref(column, row)`\n for same-origin record links in tables. Raw result values are preserved.\n The component-free `./display` entry exports `reportCsv` and result validation.\n `reportCsv` supplies the row to its formatter too, keeping exports consistent.\n- `saved-reports` widget (`SavedReportsWidget`, recipe `sectionDefault`): the\n Reports section page in any host rendering data widgets; it reads through\n the shared browser client unless the host passes `client`.\n- `ReportConfirmation`: shows the source label, groupings, measures,\n filters, and a bounded preview. Approve requires a trusted local click and\n posts the exact displayed `{ spec, specHash }` to the proposal's same-origin\n `confirmPath` once while pending. Decline never calls the server. The server\n recompiles as the confirming principal and idempotently saves the approved\n spec; the hash carries no authority by itself.\n- Answered state (#4100): after Approve or Decline the card shows an outcome\n line (\"Report saved · Open report\", \"Declined — nothing saved\") instead\n of buttons; pass `outcome` from the transcript so a reloaded card does too.\n `fields` (a source descriptor's names, labels, formats) labels groupings,\n buckets (\"Issue date by month\") and money filters; measures use the result's\n column labels. `ReportResult` labels time buckets by granularity\n (smrt-ui `formatTimeBucket`) and keeps the table toggle quiet.\n- `ReportPicker`: labelled fields (smrt-ui `FormGroup`) offering readable\n active reports and their measures and groupings by name, not alias;\n changing the report clears dependent choices.\n\n`createRuntimeReportsHttpClient()` implements the generated same-origin reads,\nthe enveloped `run`/`archive` actions, and the confirmation POST. It has no\ndatabase, tenant, or permission authority. Successful run timestamps live only\nin that browser client's session map; route hosts include an opaque active\ntenant/session scope so hints are discarded when the principal context changes. Omit the client (or set\n`serverAvailable={false}` on a route component) for a static host: the screens\nexplain that reports need a server and make no requests.\n\n`runtimeReportToolResultComponent` is the reports adapter for AssistantDock's\ngeneric component seam. Recipe routes export `RuntimeReportsRoute` and\n`RuntimeReportDetailRoute`; the `runtime-report-chart` surface exports its\nrenderer and dependent report/measure/dimension editor. The server host builds\nthe chart loader context from request-scoped `reportPrincipal`; widget options\nnever carry identity, permissions, tenant, or database authority.\n\nThe `./playground` entry has saved-list, detail, confirmation, picker, empty and\nunavailable previews. They use deterministic sample data, not a production\nbackend. All component copy registers through `smrt-ui/i18n`.\n\nThe smrt planner (#4100) renders `ReportConfirmation`, `SavedReports` and\n`ReportDetail` with its own `RuntimeReportsClient` over sample data and the\nin-memory runner from `./spec`; its `confirm` is a browser save, not this\npackage's confirmation route.\n\nThe template reference application exercises the generic dock selector, a real\ntrusted browser approval click, authenticated confirmation and generated reads,\ndetail execution, and the recipe-registered overview loader/renderer without\nmocking an endpoint.\n"
|
|
1296
1297
|
},
|
|
1297
1298
|
{
|
|
1298
1299
|
"path": "agents/runtime-reports.md",
|
|
1299
1300
|
"module": "runtime-reports",
|
|
1300
|
-
"content": "# Runtime reports (#3711)\n\nReports the assistant (or any caller) defines at runtime from a user request.\nA report is a **declarative spec stored as data**; there is no codegen, no new\ntable per report, and no SQL, expression, join or raw-identifier syntax in the\ngrammar. Declared (`@report`) reports are unchanged and remain the way to get a\n**materialized** report.\n\n## Files\n\n| File | Role |\n| --- | --- |\n| `src/runtime-spec.ts` | `RuntimeReportSpec` grammar, strict parser, limits, canonical JSON, Web Crypto digest (browser-safe) |\n| `src/runtime-spec-hash.ts` | `runtimeReportSpecHash()` (`node:crypto`, server only) |\n| `src/runtime-plan.ts` | Column, operator, aggregate, coercion and cell rules shared by both runners (browser-safe) |\n| `src/runtime-compiler.ts` | `compileRuntimeReportSpec()`, `describeRuntimeReportSource()`, `runRuntimeReport()` |\n| `src/runtime-dimensions.ts` | Time and grouping hints in source descriptions (browser-safe) |\n| `src/runtime-time.ts` | Time language: buckets and periods from words, against `now` (browser-safe) |\n| `src/runtime-memory.ts` | `runRuntimeReportInMemory()`, `describeRuntimeReportMemorySource()` (browser-safe) |\n| `src/spec.ts` | The `./spec` subpath: the browser-safe exports above |\n| `src/runtime-server.ts` | Same-origin confirmation, principal-bound run/archive, chart loader |\n| `src/runtime-report.ts` | `RuntimeReport` model (`runtime_reports`), `saveRuntimeReport()`, list/get/archive, `runStoredRuntimeReport()` |\n\nAssistant tools live in `@happyvertical/smrt-chat` (`createRuntimeReportTools()`,\n`src/runtime-report-tools.ts`).\n\n\nSource definitions may set `fields` (an allow-list) and `excludeFields` (a deny-list).\nBoth use exact public model field names. Omitted `fields` retains all eligible\nfields; `fields: []` exposes none. Exclusions win, and neither option bypasses\nmodel sensitivity, field permissions, or tenant restrictions. Invalid lists and\nunknown names reject the source with `unsupported_source`, including misspelled\nexclusions. Descriptions, assistant tools, confirmation and saved-report runs\nresolve this same policy on every invocation.\n\nStandard timestamps have one public spelling: `createdAt` and `updatedAt`.\nSnake-case `created_at`/`updated_at` remain physical SQL columns, not accepted\nspec or configuration field names. Existing saved specs using those aliases must\nbe proposed again with canonical names and confirmed. Model restrictions on any\nalias protect the whole physical column; host exclusions also cover aliases.\n\n```typescript\n{ id: 'incidents', className: 'Incident', collection: 'incidents',\n fields: ['id', 'title', 'createdAt', 'status'],\n excludeFields: ['signatureAssetId'] }\n```\nThe example assumes `signatureAssetId` is a declared model field; exclusions\nare validated even if an allow-list already omits that field.\n\n## Spec\n\n`version: 1`, `title`, optional `description`, `source` (a server-owned source\nid), `dimensions[]` (`field`, `as?`, `bucket?`), `measures[]` (`fn`: `count`,\n`countDistinct`, `sum`, `avg`, `min`, `max`; `field?`; `as?`), `filters[]`\n(AND-ed; ops `eq ne gt gte lt lte in notIn contains isNull isNotNull`),\n`having[]` (measure alias, numeric compare), `sort[]`, `limit` (1-1000, default\n100) and a `chart` hint (`table|bar|line|pie|stat`, `x`, `y[]`). Unknown keys\nat any level are rejected. Bounds (entries, string length, `in` list size,\nalias charset, reserved words) are in `RUNTIME_REPORT_LIMITS`.\n\nThe parser normalizes defaults and derives aliases, so equal specs hash equally\n(`runtimeReportSpecHash`). The hash is what a human confirmation binds to.\n`runtimeReportSpecDigest` computes the same hex with Web Crypto for browsers\n(async; needs a secure context).\n\n## Browser grammar and in-memory runner (#4100)\n\n`@happyvertical/smrt-reports/spec` imports no Node built-in and, of\nsmrt-core, only the import-free `@happyvertical/smrt-core/smrt-error` (the\nroot entry still reaches the registry's manifest loader), so a browser parses\nspecs with the server's own parser. `runRuntimeReportInMemory(spec,\nrows, { sources, maxRows?, now? })` evaluates a parsed spec over rows the\ncaller already holds and returns the `RuntimeReportResult` shape (`specHash`\nincluded). A `RuntimeReportMemorySource` is `{ id, label?, description?,\nschema: [{ name, type, label?, format? }], fields?, excludeFields? }`: the same\nallow/deny semantics as a server source, `_`-prefixed names and `tenantId`\nnever nameable, and a declared `deletedAt` soft-deletes.\n`describeRuntimeReportMemorySource()` is the `reports.runtime.sources`\ncounterpart.\n\nBoth runners call `runtime-plan.ts` for columns, operator/aggregate rules and\nvalue coercion, so errors carry the same codes and paths. SQL-shaped semantics:\ncomparisons and `IN`/`NOT IN` never match NULL, `contains` is case-sensitive,\ngroups without dimensions always yield one row, NULLs sort first ascending (as\nSQLite), weeks start Monday, buckets are UTC. Result datetimes are ISO-8601\n(PostgreSQL/DuckDB form; SQLite returns bucket TEXT). `runtime-memory-parity.test.ts`\nruns a spec matrix through both runners on SQLite and requires identical results.\n\n### Time and grouping hints\n\nBoth source descriptions carry `timeFields`, `defaultTimeField` (the natural\ndate \"by month\" buckets: an invoice's issue date, never `createdAt` when a\nbusiness date exists) and `dimensions` (fields worth grouping by, most useful\nfirst), and each field a `dimension` kind (`time`, `category`, `relation`) when\nit is one, plus its declared `enum`. A source definition may declare\n`timeField` and `dimensions` (canonical names; unknown names are\n`unsupported_source`, hidden ones are dropped for that principal). Otherwise\n`runtime-dimensions.ts` derives them: a business date\n(`@field({ ui: { format: 'date' } })`) else the first non-bookkeeping datetime;\nclosed text fields, booleans and foreign keys as groupings, never `id`, free\ntext or names marking plumbing (`…Hash`, `…Json`, `…Authority`, `external…`,\n`historical…`). They are hints for choosing, not authority: a spec may still\ngroup by any exposed field.\n\n`parseRuntimeReportTime(text, now)` reads a request's time words (\"by month\",\n\"weekly\", \"over time\", \"last quarter by week\") into a bucket, a period and\nwhether time came up; `resolveRuntimeReportTimeRange(phrase, now)` resolves\n\"last month\", \"this year\", \"last 90 days\", \"Q3\", \"December\" to `[from, to)`\ndates (UTC). Assistants resolve time with these rather than asking a model to\ndo date arithmetic.\n\n**It is a browser preview and test runner, not an authority boundary.** It has\nno registry field policy, principal, RBAC or tenant: whoever supplies the rows\nhas already decided they may be seen. Production reports compile on the server\nfor the live principal and save only through the confirmed `saveRuntimeReport()`.\n\n## Authority model\n\nA spec carries **no authority**. Everything is decided at compile time from\ninputs the caller cannot supply through the spec:\n\n- **Sources.** `RuntimeReportCompileContext.sources` is a server allow-list of\n `{ id, className, collection }`. The spec names an id; unknown and\n not-offered answer identically (`unknown_source`). `authorizeSource` is the\n host's RBAC hook (the chat tools call `run.assertOperation(collection,\n 'read')`) and runs before any field is enumerated. A host should also narrow\n `sources` to those the principal may read before compiling (the chat tools do),\n because `authorizeSource` only runs for an id that is in the list: otherwise\n an RBAC refusal for a configured id and `unknown_source` for an absent one are\n different answers, and a caller can enumerate the configured source ids. `collection` is the\n permission-catalog collection **slug** (the `<collection>` of\n `<collection>.read`, for example `runtimereports`), or the registered model\n class, which resolves to that slug through the catalog's own helper. It is\n never a class name string: `Invoice` derives `Invoice.read`, which no\n catalog contains, so every read is denied and the source is silently not\n offered.\n- **Field policy.** Names are resolved from the ObjectRegistry, never from the\n spec. Not nameable: `sensitive` / `sensitivity: sensitive|secret` fields,\n `readPermission` fields unless `context.permissions` holds that permission,\n `transient`, `json`/relationship fields, `_`-prefixed internals and the tenant\n column. A hidden field is reported exactly like an absent one\n (`unknown_field`), so the compiler is not an existence oracle.\n- **Types.** `sum`/`avg` need numeric fields, `min`/`max` numeric or datetime,\n `bucket` needs datetime, `contains` needs text, id fields accept only UUIDs\n and equality-style ops. Values are coerced to the field type, then bound.\n- **Tenancy.** Raw aggregates bypass collection interceptors, so the compiler\n adds the tenant predicate itself (same column resolution as refresh).\n Tenant-scoped source with no tenant in scope reads only NULL-tenant rows;\n there is no cross-tenant option and `withSystemContext()`/super-admin bypass\n are deliberately not honored. Sources without a tenant column are global by\n definition. `deletedAt` and STI-child discriminators are applied when the\n source has them.\n- **SQL safety.** The plan is an `AggregateSpec` executed by the SDK\n `buildAggregate()`: identifiers are registry-derived and re-validated by the\n builder, values are `$N` parameters, and output aliases are prefixed `r_`\n inside the SQL so an alias can never shadow a source column.\n- **Re-validation.** A stored report is re-parsed (hash-checked) and\n re-compiled against the **running** principal on every run, so policy changes\n apply immediately and a viewer without a permission cannot run a report saved\n by someone who had it.\n- **Stored-report storage.** The tenancy interceptor filters by the AMBIENT\n tenant, while compilation uses the principal's tenant. The chat tools bind the\n two: they enter the principal's tenant context for `list`/`get`/`save` (as the\n data-surface guard does), refuse when an ambient tenant disagrees with the\n principal (on `apply`, before the human is asked to confirm, #3768), require\n a tenant for any stored-report use, and pass the principal\n tenant as an explicit owner filter (`getRuntimeReport`/`listRuntimeReports`\n accept `tenantId`) that still holds under a system context.\n\n`listRuntimeReports` also accepts exact `createdByUserId` and `specHash`\npredicates. They are ANDed with status and explicit/ambient tenant filters before\nlimiting results, so hosts can list a principal's saved reports or find a previous\nsave of the compiled normalized spec without retrieving other authors' reports.\nThese filters never replace authorization. See the\n[list-filter contract and test matrix](runtime-report-list-filters.md).\n\n## Storage and surface\n\n`RuntimeReport` is `@TenantScoped({ mode: 'required' })` with `spec` (normalized\nJSON text), `specHash`, denormalized `title`/`description`/`sourceId`,\n`status` (`active|archived`) and `createdByUserId`. `validateBeforeSave()` parses\nwhatever was written and re-derives every denormalized column, so columns\ncannot disagree with the spec. `getSpec()` throws if the JSON no longer matches\n`specHash` (out-of-band edit). Adopting apps need a `db:migrate` for the new\n`runtime_reports` table; runtime never creates schema. Existing deployments also\nrun `db:migrate` for the confirmation lookup index `idx_runtime_reports_confirm`\nbefore enabling browser confirmation.\n\n**Invariant: no row is inserted, and no spec/title/source/description/author is\nchanged, except through the confirmed save.** It is enforced in the model layer,\nnot by which surfaces exist. `validateBeforeSave()` refuses (`confirmation_required`,\n403) every insert, and every update that changes those columns, unless the\ninstance carries a confirmation proof. The proof is a symbol-keyed constructor\noption plus a module-private `WeakMap`; only `saveRuntimeReport()` can mint it,\nand only when `confirmedSpecHash` equals the compiled plan's hash (the value\nhanded to the application's `RuntimeReportConfirmationHost`). It is single use\nand tied to that exact spec hash. A REST body, a manifest tool call or\n`new RuntimeReport({...}).save()` cannot carry it, so it is refused whatever\nsurface delivered it. A reused id on an insert is refused the same way, so it\ncannot overwrite a stored spec. Archiving or unarchiving (a `status` change with\nthe stored columns untouched) is allowed for an authorised writer.\n\n**Exposed operations** (these decide the permission catalog and RLS grants):\n\n| Surface | Operations |\n| --- | --- |\n| REST (`api`) | `list`, `get`, `create`, `run`, `archive` |\n| CLI | `list`, `get`, `run`, `archive` |\n| MCP | `list`, `get`, `run`, `archive` |\n\nThe permission catalog therefore holds exactly `<collection>.read` and\n`<collection>.create` for `RuntimeReport` (the collection slug is\n`runtimereports`). `update` and `delete` exist on no surface, so they are not in\nthe catalog, not grantable to a role and not nameable in a persona's\n`allowedTools`. REST `create` exists only so the catalog knows the operation the\nconfirmed save performs (`assertOperation(RuntimeReport, 'create')`); its body is\nalways refused by the invariant above. The generic manifest tool dispatcher in\n`@happyvertical/smrt-chat` additionally never offers or runs a write operation on\n`RuntimeReport` (`isRuntimeReportWriteOperation`), so the assistant persists a\nreport only through `reports.runtime.define` (apply).\n\n**Result rows are never persisted.** A result computed for one principal must\nnot be served to another, so the table stores definitions only.\n\n## Why not materialize\n\nDeclared reports materialize into a build-time `@smrt()` table and refresh\nthrough the lock/watermark engine. Runtime schema creation is forbidden here, so\na runtime spec runs as a bounded live aggregate on the same `AggregateSpec`\ncompile target instead. Promoting a proven runtime spec to a declared,\nmaterialized `@report` (codegen plus a migration) is a maintainer decision and\nis tracked as a follow-up.\n\n## Money\n\nMoney fields are integer minor units; `sum`/`min`/`max` keep the integer type and\nthe source field's `format` hint is carried onto the result column. Integer\nresults beyond the JavaScript safe range throw `invalid_result` rather than\nlosing precision. `avg` is decimal.\n\n## Assistant and browser flow (#3878)\n\n`reports.runtime.sources` describes fields available to the assistant principal.\n`reports.runtime.define` with `phase: 'preview'` compiles and runs a bounded\nsample. `phase: 'apply'` requires the preview's exact normalized `specHash`.\nWithout an in-process confirmation host it returns:\n\n```ts\n{ status: 'awaiting_confirmation', specHash, spec, sourceLabel, preview,\n confirmPath: '/api/_reports/runtime/confirm' }\n```\n\nNothing is saved by that response, and model-supplied consent is ignored. The\nbrowser shows the proposal and only a person's approval posts `{ spec, specHash }`\nto `createRuntimeReportConfirmHandler()`. The handler checks same origin, the\nverified session user and tenant, `runtimereports.create`, the normalized hash,\nand compilation under the **confirming** principal's current permissions.\nAnother principal may approve the same public spec only under their own\npermissions and tenant; a hash is data, not a transferable authorization token.\n\nThe template mounts `POST /api/_reports/runtime/confirm`. Hosts pass the verified\nprincipal and the request's database (including the RLS transaction), never\nbody-supplied identity. Success is `201 { id, specHash, title }`; a retry of an\nactive definition with the same principal/hash returns the same response with\n200. Compilation happens again even on retries. Concurrent approvals use core's\ntransactional `runOnce` claim, keyed by tenant, principal and normalized spec.\nA failed write rolls back the claim; an audit\ncallback failure returns a generic 500 and a retry finds the already saved row.\nNo result rows are stored in the idempotency record. After archiving, approving\nthe same definition returns 409 `report_archived`; restore it through the archive\naction before retrying.\n\nErrors are JSON `{ code, message }`: 401 without a session; 403 for cross-origin,\nmissing permission, mismatched ambient tenant, or an active retry invalidated by\ncurrent source/field access; 409 for an archived retry; 422 for a malformed new\nspec or `spec_hash_mismatch`; generic 500 for unexpected provider failures. There is\nno cross-tenant or system bypass. Configure an optional `audit` callback on the\nfactory to receive confirmed principal/hash/report identity and whether reused.\n\nFor CLI and other in-process hosts, `RuntimeReportConfirmationHost.confirmSave()`\nremains available: it must resolve only after a person approves that exact hash.\nThe single-use model proof is unchanged in both paths. The assistant tools use\nthe persona's fail-closed `allowedTools` gates.\n\n## Server configuration and actions\n\nConfigure `packages.reports.runtime.sources` in `smrt.config.ts`:\n\n```ts\npackages: {\n reports: { runtime: { sources: [\n { id: 'invoices', className: '@acme/app:Invoice', collection: 'invoices', label: 'Invoices' }\n ] } }\n}\n```\n\nAn absent source list exposes nothing. A source's `collection` is a catalog slug\nand requires `<collection>.read`; the server narrows the allow-list before\ncompiling. Give the assistant the same server-owned source definitions. The\nconfirm factory can instead take explicit `{ sources, audit? }` options.\n\n`POST /api/runtimereports/:id/run` takes no body and returns\n`{ action: 'run', result: RuntimeReportResult }`. Its CLI/MCP counterparts call\nthe same model action. It requires `runtimereports.read`, reloads the definition\nin the principal's tenant, and recompiles on every call. Tenant peers can run\nshared reports; use `createdByUserId` for an Only mine list filter. Missing and\nforeign-tenant ids return 404; revoked source/field access returns 403; archived\nreports return 409 `report_archived`; invalid results return 422. Rows stay\nephemeral and integer money stays in minor units.\n\n`POST /api/runtimereports/:id/archive` takes `{ archived: boolean }` and returns\n`{ action: 'archive', result: { id, status } }`. It requires\n`runtimereports.create`, changes status only, and\nrepeating the same state does not write again. `operationPermissions` metadata\naliases run to read and archive to create consistently across generated routes,\nCLI/MCP guards and the permission catalog. The archive alias adds SELECT and\nUPDATE SQL-policy bindings to create: the authorized action must look up the\nsame-tenant row before changing its status. Adopted PostgreSQL RLS policies must\nbe regenerated. Neither `.run`, `.archive`, `.update` nor `.delete` becomes a\nnew grantable permission for this model.\n\n`loadRuntimeReportChart(options, context)` is the server loader for the dependent\nbrowser recipe widget. Options are `{ reportId, measure, dimension? }`; the host\nsupplies `context.reportPrincipal` from its authenticated request and optionally\n`currency`. It runs afresh as the viewer and returns structural chart data:\n`{ points: [{label, value}], format, currency?, href }`. The loader has no\nsmrt-svelte dependency and receives no authority from widget options.\n\n## Recipe UI\n\n`reports.runtime` declares the RuntimeReport model, Reports navigation, the\n`/reports` routes and `runtime-report-chart` widget. The widget options are only\n`{ reportId, measure, dimension? }`; the authenticated server host supplies the\nloader's `reportPrincipal`. Static hosts render the Reports route unavailable.\nRename, scheduling and manual report construction remain deferred.\n"
|
|
1301
|
+
"content": "# Runtime reports (#3711)\n\nReports the assistant (or any caller) defines at runtime from a user request.\nA report is a **declarative spec stored as data**; there is no codegen, no new\ntable per report, and no SQL, expression, join or raw-identifier syntax in the\ngrammar. Declared (`@report`) reports are unchanged and remain the way to get a\n**materialized** report.\n\n## Files\n\n| File | Role |\n| --- | --- |\n| `src/runtime-spec.ts` | `RuntimeReportSpec` grammar, strict parser, limits, canonical JSON, Web Crypto digest (browser-safe) |\n| `src/runtime-spec-hash.ts` | `runtimeReportSpecHash()` (`node:crypto`, server only) |\n| `src/runtime-plan.ts` | Column, operator, aggregate, coercion and cell rules shared by both runners (browser-safe) |\n| `src/runtime-compiler.ts` | `compileRuntimeReportSpec()`, `describeRuntimeReportSource()`, `runRuntimeReport()` |\n| `src/runtime-dimensions.ts` | Time and grouping hints in source descriptions (browser-safe) |\n| `src/runtime-time.ts` | Time language: buckets and periods from words, against `now` (browser-safe) |\n| `src/runtime-memory.ts` | `runRuntimeReportInMemory()`, `describeRuntimeReportMemorySource()` (browser-safe) |\n| `src/spec.ts` | The `./spec` subpath: the browser-safe exports above |\n| `src/runtime-server.ts` | Same-origin confirmation, principal-bound run/archive, chart loader |\n| `src/runtime-report.ts` | `RuntimeReport` model (`runtime_reports`), `saveRuntimeReport()`, list/get/archive, `runStoredRuntimeReport()` |\n\nAssistant tools live in `@happyvertical/smrt-chat` (`createRuntimeReportTools()`,\n`src/runtime-report-tools.ts`).\n\n\nSource definitions may set `fields` (an allow-list) and `excludeFields` (a deny-list).\nBoth use exact public model field names. Omitted `fields` retains all eligible\nfields; `fields: []` exposes none. Exclusions win, and neither option bypasses\nmodel sensitivity, field permissions, or tenant restrictions. Invalid lists and\nunknown names reject the source with `unsupported_source`, including misspelled\nexclusions. Descriptions, assistant tools, confirmation and saved-report runs\nresolve this same policy on every invocation.\n\nStandard timestamps have one public spelling: `createdAt` and `updatedAt`.\nSnake-case `created_at`/`updated_at` remain physical SQL columns, not accepted\nspec or configuration field names. Existing saved specs using those aliases must\nbe proposed again with canonical names and confirmed. Model restrictions on any\nalias protect the whole physical column; host exclusions also cover aliases.\n\n```typescript\n{ id: 'incidents', className: 'Incident', collection: 'incidents',\n fields: ['id', 'title', 'createdAt', 'status'],\n excludeFields: ['signatureAssetId'] }\n```\nThe example assumes `signatureAssetId` is a declared model field; exclusions\nare validated even if an allow-list already omits that field.\n\n## Spec\n\n`version: 1`, `title`, optional `description`, `source` (a server-owned source\nid), `dimensions[]` (`field`, `as?`, `bucket?`), `measures[]` (`fn`: `count`,\n`countDistinct`, `sum`, `avg`, `min`, `max`; `field?`; `as?`), `filters[]`\n(AND-ed; ops `eq ne gt gte lt lte in notIn contains isNull isNotNull`),\n`having[]` (measure alias, numeric compare), `sort[]`, `limit` (1-1000, default\n100) and a `chart` hint (`table|bar|line|pie|stat`, `x`, `y[]`). Unknown keys\nat any level are rejected. Bounds (entries, string length, `in` list size,\nalias charset, reserved words) are in `RUNTIME_REPORT_LIMITS`.\n\nThe parser normalizes defaults and derives aliases, so equal specs hash equally\n(`runtimeReportSpecHash`). The hash is what a human confirmation binds to.\n`runtimeReportSpecDigest` computes the same hex with Web Crypto for browsers\n(async; needs a secure context).\n\n## Browser grammar and in-memory runner (#4100)\n\n`@happyvertical/smrt-reports/spec` imports no Node built-in and, of\nsmrt-core, only the import-free `@happyvertical/smrt-core/smrt-error` (the\nroot entry still reaches the registry's manifest loader), so a browser parses\nspecs with the server's own parser. `runRuntimeReportInMemory(spec,\nrows, { sources, maxRows?, now? })` evaluates a parsed spec over rows the\ncaller already holds and returns the `RuntimeReportResult` shape (`specHash`\nincluded). A `RuntimeReportMemorySource` is `{ id, label?, description?,\nschema: [{ name, type, label?, format? }], fields?, excludeFields? }`: the same\nallow/deny semantics as a server source, `_`-prefixed names and `tenantId`\nnever nameable, and a declared `deletedAt` soft-deletes.\n`describeRuntimeReportMemorySource()` is the `reports.runtime.sources`\ncounterpart.\n\nBoth runners call `runtime-plan.ts` for columns, operator/aggregate rules and\nvalue coercion, so errors carry the same codes and paths. SQL-shaped semantics:\ncomparisons and `IN`/`NOT IN` never match NULL, `contains` is case-sensitive,\ngroups without dimensions always yield one row, NULLs sort first ascending (as\nSQLite), weeks start Monday, buckets are UTC. Result datetimes are ISO-8601\n(PostgreSQL/DuckDB form; SQLite returns bucket TEXT). `runtime-memory-parity.test.ts`\nruns a spec matrix through both runners on SQLite and requires identical results.\n\n### Time and grouping hints\n\nBoth source descriptions carry `timeFields`, `defaultTimeField` (the natural\ndate \"by month\" buckets: an invoice's issue date, never `createdAt` when a\nbusiness date exists) and `dimensions` (fields worth grouping by, most useful\nfirst), and each field a `dimension` kind (`time`, `category`, `relation`) when\nit is one, plus its declared `enum`. A source definition may declare\n`timeField` and `dimensions` (canonical names; unknown names are\n`unsupported_source`, hidden ones are dropped for that principal). Otherwise\n`runtime-dimensions.ts` derives them: a business date\n(`@field({ ui: { format: 'date' } })`) else the first non-bookkeeping datetime;\nclosed text fields, booleans and foreign keys as groupings, never `id`, free\ntext or names marking plumbing (`…Hash`, `…Json`, `…Authority`, `external…`,\n`historical…`). They are hints for choosing, not authority: a spec may still\ngroup by any exposed field.\n\n`parseRuntimeReportTime(text, now)` reads a request's time words (\"by month\",\n\"weekly\", \"over time\", \"last quarter by week\") into a bucket, a period and\nwhether time came up; `resolveRuntimeReportTimeRange(phrase, now)` resolves\n\"last month\", \"this year\", \"last 90 days\", \"Q3\", \"December\" to `[from, to)`\ndates (UTC). Assistants resolve time with these rather than asking a model to\ndo date arithmetic.\n\n**It is a browser preview and test runner, not an authority boundary.** It has\nno registry field policy, principal, RBAC or tenant: whoever supplies the rows\nhas already decided they may be seen. Production reports compile on the server\nfor the live principal and save only through the confirmed `saveRuntimeReport()`.\n\n## Authority model\n\nA spec carries **no authority**. Everything is decided at compile time from\ninputs the caller cannot supply through the spec:\n\n- **Sources.** `RuntimeReportCompileContext.sources` is a server allow-list of\n `{ id, className, collection }`. The spec names an id; unknown and\n not-offered answer identically (`unknown_source`). `authorizeSource` is the\n host's RBAC hook (the chat tools call `run.assertOperation(collection,\n 'read')`) and runs before any field is enumerated. A host should also narrow\n `sources` to those the principal may read before compiling (the chat tools do),\n because `authorizeSource` only runs for an id that is in the list: otherwise\n an RBAC refusal for a configured id and `unknown_source` for an absent one are\n different answers, and a caller can enumerate the configured source ids. `collection` is the\n permission-catalog collection **slug** (the `<collection>` of\n `<collection>.read`, for example `runtimereports`), or the registered model\n class, which resolves to that slug through the catalog's own helper. It is\n never a class name string: `Invoice` derives `Invoice.read`, which no\n catalog contains, so every read is denied and the source is silently not\n offered.\n- **Field policy.** Names are resolved from the ObjectRegistry, never from the\n spec. Not nameable: `sensitive` / `sensitivity: sensitive|secret` fields,\n `readPermission` fields unless `context.permissions` holds that permission,\n `transient`, `json`/relationship fields, `_`-prefixed internals and the tenant\n column. A hidden field is reported exactly like an absent one\n (`unknown_field`), so the compiler is not an existence oracle.\n- **Types.** `sum`/`avg` need numeric fields, `min`/`max` numeric or datetime,\n `bucket` needs datetime, `contains` needs text, id fields accept only UUIDs\n and equality-style ops. Values are coerced to the field type, then bound.\n- **Tenancy.** Raw aggregates bypass collection interceptors, so the compiler\n adds the tenant predicate itself (same column resolution as refresh).\n Tenant-scoped source with no tenant in scope reads only NULL-tenant rows;\n there is no cross-tenant option and `withSystemContext()`/super-admin bypass\n are deliberately not honored. Sources without a tenant column are global by\n definition. `deletedAt` and STI-child discriminators are applied when the\n source has them.\n- **SQL safety.** The plan is an `AggregateSpec` executed by the SDK\n `buildAggregate()`: identifiers are registry-derived and re-validated by the\n builder, values are `$N` parameters, and output aliases are prefixed `r_`\n inside the SQL so an alias can never shadow a source column.\n- **Re-validation.** A stored report is re-parsed (hash-checked) and\n re-compiled against the **running** principal on every run, so policy changes\n apply immediately and a viewer without a permission cannot run a report saved\n by someone who had it.\n- **Stored-report storage.** The tenancy interceptor filters by the AMBIENT\n tenant, while compilation uses the principal's tenant. The chat tools bind the\n two: they enter the principal's tenant context for `list`/`get`/`save` (as the\n data-surface guard does), refuse when an ambient tenant disagrees with the\n principal (on `apply`, before the human is asked to confirm, #3768), require\n a tenant for any stored-report use, and pass the principal\n tenant as an explicit owner filter (`getRuntimeReport`/`listRuntimeReports`\n accept `tenantId`) that still holds under a system context.\n\n`listRuntimeReports` also accepts exact `createdByUserId` and `specHash`\npredicates. They are ANDed with status and explicit/ambient tenant filters before\nlimiting results, so hosts can list a principal's saved reports or find a previous\nsave of the compiled normalized spec without retrieving other authors' reports.\nThese filters never replace authorization. See the\n[list-filter contract and test matrix](runtime-report-list-filters.md).\n\n## Storage and surface\n\n`RuntimeReport` is `@TenantScoped({ mode: 'required' })` with `spec` (normalized\nJSON text), `specHash`, denormalized `title`/`description`/`sourceId`,\n`status` (`active|archived`) and `createdByUserId`. `validateBeforeSave()` parses\nwhatever was written and re-derives every denormalized column, so columns\ncannot disagree with the spec. `getSpec()` throws if the JSON no longer matches\n`specHash` (out-of-band edit). Adopting apps need a `db:migrate` for the new\n`runtime_reports` table; runtime never creates schema. Existing deployments also\nrun `db:migrate` for the confirmation lookup index `idx_runtime_reports_confirm`\nbefore enabling browser confirmation.\n\n**Invariant: no row is inserted, and no spec/title/source/description/author is\nchanged, except through the confirmed save.** It is enforced in the model layer,\nnot by which surfaces exist. `validateBeforeSave()` refuses (`confirmation_required`,\n403) every insert, and every update that changes those columns, unless the\ninstance carries a confirmation proof. The proof is a symbol-keyed constructor\noption plus a module-private `WeakMap`; only `saveRuntimeReport()` can mint it,\nand only when `confirmedSpecHash` equals the compiled plan's hash (the value\nhanded to the application's `RuntimeReportConfirmationHost`). It is single use\nand tied to that exact spec hash. A REST body, a manifest tool call or\n`new RuntimeReport({...}).save()` cannot carry it, so it is refused whatever\nsurface delivered it. A reused id on an insert is refused the same way, so it\ncannot overwrite a stored spec. Archiving or unarchiving (a `status` change with\nthe stored columns untouched) is allowed for an authorised writer.\n\n**Exposed operations** (these decide the permission catalog and RLS grants):\n\n| Surface | Operations |\n| --- | --- |\n| REST (`api`) | `list`, `get`, `create`, `run`, `archive` |\n| CLI | `list`, `get`, `run`, `archive` |\n| MCP | `list`, `get`, `run`, `archive` |\n\nThe permission catalog therefore holds exactly `<collection>.read` and\n`<collection>.create` for `RuntimeReport` (the collection slug is\n`runtimereports`). `update` and `delete` exist on no surface, so they are not in\nthe catalog, not grantable to a role and not nameable in a persona's\n`allowedTools`. REST `create` exists only so the catalog knows the operation the\nconfirmed save performs (`assertOperation(RuntimeReport, 'create')`); its body is\nalways refused by the invariant above. The generic manifest tool dispatcher in\n`@happyvertical/smrt-chat` additionally never offers or runs a write operation on\n`RuntimeReport` (`isRuntimeReportWriteOperation`), so the assistant persists a\nreport only through `reports.runtime.define` (apply).\n\n**Result rows are never persisted.** A result computed for one principal must\nnot be served to another, so the table stores definitions only.\n\n## Why not materialize\n\nDeclared reports materialize into a build-time `@smrt()` table and refresh\nthrough the lock/watermark engine. Runtime schema creation is forbidden here, so\na runtime spec runs as a bounded live aggregate on the same `AggregateSpec`\ncompile target instead. Promoting a proven runtime spec to a declared,\nmaterialized `@report` (codegen plus a migration) is a maintainer decision and\nis tracked as a follow-up.\n\n## Money\n\nMoney fields are integer minor units; `sum`/`min`/`max` keep the integer type and\nthe source field's `format` hint is carried onto the result column. Integer\nresults beyond the JavaScript safe range throw `invalid_result` rather than\nlosing precision. `avg` is decimal.\n\n## Assistant and browser flow (#3878)\n\n`reports.runtime.sources` describes fields available to the assistant principal.\n`reports.runtime.define` with `phase: 'preview'` compiles and runs a bounded\nsample. `phase: 'apply'` requires the preview's exact normalized `specHash`.\nWithout an in-process confirmation host it returns:\n\n```ts\n{ status: 'awaiting_confirmation', specHash, spec, sourceLabel, preview,\n confirmPath: '/api/_reports/runtime/confirm' }\n```\n\nNothing is saved by that response, and model-supplied consent is ignored. The\nbrowser shows the proposal and only a person's approval posts `{ spec, specHash }`\nto `createRuntimeReportConfirmHandler()`. The handler checks same origin, the\nverified session user and tenant, `runtimereports.create`, the normalized hash,\nand compilation under the **confirming** principal's current permissions.\nAnother principal may approve the same public spec only under their own\npermissions and tenant; a hash is data, not a transferable authorization token.\n\nThe template mounts `POST /api/_reports/runtime/confirm`. Hosts pass the verified\nprincipal and the request's database (including the RLS transaction), never\nbody-supplied identity. Success is `201 { id, specHash, title }`; a retry of an\nactive definition with the same principal/hash returns the same response with\n200. Compilation happens again even on retries. Concurrent approvals use core's\ntransactional `runOnce` claim, keyed by tenant, principal and normalized spec.\nA failed write rolls back the claim; an audit\ncallback failure returns a generic 500 and a retry finds the already saved row.\nNo result rows are stored in the idempotency record. After archiving, approving\nthe same definition returns 409 `report_archived`; restore it through the archive\naction before retrying.\n\nErrors are JSON `{ code, message }`: 401 without a session; 403 for cross-origin,\nmissing permission, mismatched ambient tenant, or an active retry invalidated by\ncurrent source/field access; 409 for an archived retry; 422 for a malformed new\nspec or `spec_hash_mismatch`; generic 500 for unexpected provider failures. There is\nno cross-tenant or system bypass. Configure an optional `audit` callback on the\nfactory to receive confirmed principal/hash/report identity and whether reused.\n\nFor CLI and other in-process hosts, `RuntimeReportConfirmationHost.confirmSave()`\nremains available: it must resolve only after a person approves that exact hash.\nThe single-use model proof is unchanged in both paths. The assistant tools use\nthe persona's fail-closed `allowedTools` gates.\n\n## Server configuration and actions\n\nConfigure `packages.reports.runtime.sources` in `smrt.config.ts`:\n\n```ts\npackages: {\n reports: { runtime: { sources: [\n { id: 'invoices', className: '@acme/app:Invoice', collection: 'invoices', label: 'Invoices' }\n ] } }\n}\n```\n\nAn absent source list exposes nothing. A source's `collection` is a catalog slug\nand requires `<collection>.read`; the server narrows the allow-list before\ncompiling. Give the assistant the same server-owned source definitions. The\nconfirm factory can instead take explicit `{ sources, audit? }` options.\n\n`POST /api/runtimereports/:id/run` takes no body and returns\n`{ action: 'run', result: RuntimeReportResult }`. Its CLI/MCP counterparts call\nthe same model action. It requires `runtimereports.read`, reloads the definition\nin the principal's tenant, and recompiles on every call. Tenant peers can run\nshared reports; use `createdByUserId` for an Only mine list filter. Missing and\nforeign-tenant ids return 404; revoked source/field access returns 403; archived\nreports return 409 `report_archived`; invalid results return 422. Rows stay\nephemeral and integer money stays in minor units.\n\n`POST /api/runtimereports/:id/archive` takes `{ archived: boolean }` and returns\n`{ action: 'archive', result: { id, status } }`. It requires\n`runtimereports.create`, changes status only, and\nrepeating the same state does not write again. `operationPermissions` metadata\naliases run to read and archive to create consistently across generated routes,\nCLI/MCP guards and the permission catalog. The archive alias adds SELECT and\nUPDATE SQL-policy bindings to create: the authorized action must look up the\nsame-tenant row before changing its status. Adopted PostgreSQL RLS policies must\nbe regenerated. Neither `.run`, `.archive`, `.update` nor `.delete` becomes a\nnew grantable permission for this model.\n\n`loadRuntimeReportChart(options, context)` is the server loader for the dependent\nbrowser recipe widget. Options are `{ reportId, measure, dimension? }`; the host\nsupplies `context.reportPrincipal` from its authenticated request and optionally\n`currency`. It runs afresh as the viewer and returns structural chart data:\n`{ points: [{label, value}], format, currency?, href }`. The loader has no\nsmrt-svelte dependency and receives no authority from widget options.\n\n## Recipe UI\n\n`reports.runtime` declares the RuntimeReport model, Reports navigation, the\n`/reports` routes and `runtime-report-chart` widget. The widget options are only\n`{ reportId, measure, dimension? }`; the authenticated server host supplies the\nloader's `reportPrincipal`. Static hosts render the Reports route unavailable.\nRename, scheduling and manual report construction remain deferred.\n\nSQLite integer outputs travel from SQL to the runner as exact text, after\nnumeric aggregation, filtering and sorting. Cell normalization returns safe\nJavaScript numbers and raises `RuntimeReportError` (`invalid_result`, with the\noutput column id as `path`) for integers outside the exact range. This keeps\nthe driver from rejecting the value before the report error can be classified.\n\nGenerated-field aggregation parity uses the ordinary SQLite suite and `pnpm test:pglite` for in-process PostgreSQL through core's isolated SDK/PGlite fixture. Keep the optional peer outside the workspace, as main's core tests do.\n"
|
|
1301
1302
|
},
|
|
1302
1303
|
{
|
|
1303
1304
|
"path": "README.md",
|
|
@@ -5,10 +5,10 @@ description: "Materialized aggregate report models for SMRT"
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-14T02:10:08Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:e4d08c521c6b8653e0def1443695385c6ec95f73dbf4a7e942627712013a51e4"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/reports/package.json"
|
|
@@ -64,6 +64,7 @@ sources:
|
|
|
64
64
|
- `./aggregate`
|
|
65
65
|
- `./compiler`
|
|
66
66
|
- `./decorators`
|
|
67
|
+
- `./display`
|
|
67
68
|
- `./manifest`
|
|
68
69
|
- `./manifest.json`
|
|
69
70
|
- `./playground`
|