@crasi/bisque-spec 0.0.0-stage → 0.3.0

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.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/schema.ts", "../src/validate.ts", "../src/describe.ts", "../src/adjust.ts", "../src/diagnostics.ts", "../src/args.ts", "../src/migrate.ts", "../src/catalog.ts", "../src/protocol.ts", "../src/automation.ts", "../src/theme.ts", "../src/template.ts"],
4
+ "sourcesContent": ["import { z } from \"zod\";\nimport { IRSchema, Literal } from \"@crasi/bisque-ir\";\n\n/** Display strings, per locale. Length caps are part of P6 (chrome integrity). */\nexport const Title = z.record(z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/), z.string().min(1).max(80));\nexport const Label = z.record(z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/), z.string().min(1).max(40));\n\nexport const FORMATS = [\"number\", \"money\", \"percent\", \"date\", \"month\", \"text\"] as const;\nexport const Format = z.enum(FORMATS);\n\n/**\n * How an action or navigation argument is computed from the row the user\n * acts on. Pure data: no expressions, no code.\n */\nexport type ArgExpr =\n | { field: string }\n | { input: string }\n | { param: string }\n | { literal: z.infer<typeof Literal> | z.infer<typeof Literal>[] }\n | { today: number }\n | { template: string }\n | { list: ArgExpr[] };\n\nexport const ArgExprSchema: z.ZodType<ArgExpr> = z.lazy(() =>\n z.union([\n z.object({ field: z.string() }).strict(),\n z.object({ input: z.string() }).strict(),\n z.object({ param: z.string() }).strict(),\n z.object({ literal: z.union([Literal, z.array(Literal).max(50)]) }).strict(),\n z.object({ today: z.number().int().min(-3660).max(3660) }).strict(),\n /** `\"Clearance {products.name}\"`: row columns interpolated as text. */\n z.object({ template: z.string().max(120) }).strict(),\n z.object({ list: z.array(ArgExprSchema).max(50) }).strict(),\n ]),\n);\n\nexport const Args = z.record(z.string(), ArgExprSchema);\n\nexport const ParamSchema = z.union([\n /** Follow the page: `host.context.month`. */\n z.object({ bind: z.string().regex(/^host\\.context\\.[A-Za-z_]\\w*$/) }).strict(),\n z.object({ control: z.literal(\"slider\"), label: Label, min: z.number(), max: z.number(), step: z.number().positive().optional(), default: z.number() }).strict(),\n z\n .object({\n control: z.literal(\"select\"),\n label: Label,\n options: z\n .array(z.object({ value: Literal, label: Label }).strict())\n .min(1)\n .max(30),\n default: Literal,\n })\n .strict(),\n z.object({ control: z.literal(\"toggle\"), label: Label, default: z.boolean() }).strict(),\n]);\nexport type Param = z.infer<typeof ParamSchema>;\n\nconst Column = z.object({ field: z.string(), label: Label.optional(), format: Format.optional() }).strict();\n\nconst OnClick = z.object({ navigate: z.string(), args: Args }).strict();\n\nconst common = {\n title: Title,\n data: IRSchema,\n params: z.record(z.string().regex(/^[A-Za-z_]\\w*$/), ParamSchema).optional(),\n onClick: OnClick.optional(),\n};\n\nexport const SankeySpec = z\n .object({\n component: z.literal(\"sankey\"),\n ...common,\n encode: z.object({ source: z.string(), target: z.string(), value: z.string(), label: z.enum([\"value\", \"share-of-source\", \"share-of-total\"]).optional() }).strict(),\n otherBucket: z\n .object({ maxTargets: z.number().int().min(2).max(50) })\n .strict()\n .optional(),\n })\n .strict();\n\nconst XY = z\n .object({\n x: z.string(),\n y: z.union([z.string(), z.array(z.string()).min(1).max(4)]),\n series: z.string().optional(),\n stacked: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n format: Format.optional(),\n })\n .strict();\n\nexport const BarSpec = z\n .object({\n component: z.literal(\"bar\"),\n ...common,\n encode: XY,\n otherBucket: z\n .object({ maxCategories: z.number().int().min(2).max(50) })\n .strict()\n .optional(),\n })\n .strict();\nexport const LineSpec = z.object({ component: z.literal(\"line\"), ...common, encode: XY }).strict();\nexport const AreaSpec = z.object({ component: z.literal(\"area\"), ...common, encode: XY }).strict();\nexport const TableSpec = z.object({ component: z.literal(\"table\"), ...common, encode: z.object({ columns: z.array(Column).min(1).max(12) }).strict() }).strict();\nexport const KpiSpec = z\n .object({\n component: z.literal(\"kpi\"),\n ...common,\n encode: z.object({ value: z.string(), format: Format.optional(), label: Label.optional() }).strict(),\n })\n .strict();\n\nconst EditableColumn = Column.extend({\n /** Editing this cell invokes the intent; `value` names the arg that receives the new value. */\n edit: z.object({ intent: z.string(), value: z.string(), args: Args }).strict().optional(),\n}).strict();\n\nexport const GridSpec = z\n .object({\n component: z.literal(\"grid\"),\n ...common,\n encode: z.object({ rowKey: z.string(), columns: z.array(EditableColumn).min(1).max(12) }).strict(),\n })\n .strict();\n\nexport const RowInput = z\n .object({\n name: z.string().regex(/^[A-Za-z_]\\w*$/),\n label: Label,\n type: z.enum([\"number\", \"text\"]),\n default: z.union([z.number(), z.string()]).optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n })\n .strict();\n\nexport const ActionTableSpec = z\n .object({\n component: z.literal(\"actionTable\"),\n ...common,\n encode: z\n .object({\n rowKey: z.string(),\n columns: z.array(Column).min(1).max(10),\n inputs: z.array(RowInput).max(4).optional(),\n /** One intent call per selected row; one host confirm covers the batch (I12). */\n action: z.object({ intent: z.string(), label: Label, args: Args }).strict(),\n })\n .strict(),\n })\n .strict();\n\nexport const SpecBody = z.discriminatedUnion(\"component\", [SankeySpec, BarSpec, LineSpec, AreaSpec, TableSpec, KpiSpec, GridSpec, ActionTableSpec]);\nexport type Spec = z.infer<typeof SpecBody>;\nexport type ComponentName = Spec[\"component\"];\n\nexport const Placement = z\n .object({\n slot: z.string(),\n /** Required when the slot holds pages (a nav entry): the entry's label. */\n label: Label.optional(),\n })\n .strict();\nexport type Placement = z.infer<typeof Placement>;\n\nexport const ArtifactManifestSchema = z\n .object({\n reads: z.array(z.string()).max(12),\n acts: z.array(z.string()).max(12),\n /** Contribution points are an L3 feature (after v1); specs contribute nothing beyond their placement. */\n contributes: z.object({}).strict().optional(),\n })\n .strict();\nexport type ArtifactManifest = z.infer<typeof ArtifactManifestSchema>;\n\n/** What the conductor proposes and what Apply saves (Definition 2 minus id and revision). */\nexport const DraftSchema = z\n .object({\n kind: z.literal(\"spec\"),\n body: SpecBody,\n manifest: ArtifactManifestSchema,\n placement: Placement,\n })\n .strict();\nexport type Draft = z.infer<typeof DraftSchema>;\n", "import { nest, problem, type Problem, type Role } from \"@crasi/bisque-core\";\nimport { canAct, type ContractManifest, type FieldType } from \"@crasi/bisque-contract\";\nimport { validateIR, zodProblems, type Column } from \"@crasi/bisque-ir\";\nimport { DraftSchema, type ArgExpr, type Draft, type Spec } from \"./schema\";\n\nexport type DraftValidation = {\n ok: boolean;\n problems: Problem[];\n /** Non-blocking: shown in the card, not sent for repair. */\n warnings: Problem[];\n draft?: Draft;\n columns: Record<string, Column>;\n touched: string[];\n};\n\nexport type DraftValidateOptions = {\n /** The acting user's role. Reads and acts are checked against it (P2, P3). */\n role: Role;\n};\n\n/** Keys that belong to automations, not views: a view runs only while it is open. */\nconst DEFERRED_KEYS = [\"schedule\", \"channel\", \"cron\", \"notify\"];\n\n/**\n * Invariant 7: specs never carry CSS, URLs or HTML. Field names and labels\n * cannot legitimately contain any of these, so the check is a blunt scan of\n * every string in the body.\n */\nconst UNSAFE = [/<\\s*\\/?\\s*[a-z!]/i, /[a-z][a-z0-9+.-]*:\\/\\//i, /javascript:/i, /data:[a-z]+\\//i, /url\\s*\\(/i, /expression\\s*\\(/i, /@import/i, /\\bstyle\\s*=/i, /\\bon[a-z]+\\s*=/i];\n\nconst at = (path: string, k: string | number) => (path ? `${path}.${k}` : String(k));\n\nfunction scanStrings(v: unknown, path: string, out: Problem[], deferred = true) {\n if (typeof v === \"string\") {\n if (UNSAFE.some((re) => re.test(v))) out.push(problem(path, \"unsafe_text\", \"text may not contain HTML, CSS or URLs\"));\n return;\n }\n if (Array.isArray(v)) return v.forEach((x, i) => scanStrings(x, at(path, i), out, deferred));\n if (v && typeof v === \"object\")\n for (const [k, x] of Object.entries(v)) {\n if (deferred && DEFERRED_KEYS.includes(k))\n out.push(problem(at(path, k), \"deferred\", \"a view runs only while it is open; schedules and delivery are automations (propose_automation), not part of a view\"));\n scanStrings(x, at(path, k), out, deferred);\n }\n}\n\n/** Invariant 7 for any proposal: no HTML, CSS or URLs in any string. */\nexport function unsafeTextProblems(input: unknown): Problem[] {\n const out: Problem[] = [];\n scanStrings(input, \"\", out, false);\n return out;\n}\n\nfunction paramTypes(spec: Spec, m: ContractManifest): Record<string, FieldType | \"any\"> {\n const out: Record<string, FieldType | \"any\"> = {};\n for (const [name, p] of Object.entries(spec.params ?? {})) {\n if (\"bind\" in p) out[name] = m.context[p.bind.slice(\"host.context.\".length)]?.type.type ?? \"any\";\n else out[name] = p.control === \"slider\" ? \"number\" : p.control === \"toggle\" ? \"boolean\" : \"any\";\n }\n return out;\n}\n\n/** Every column the encode block refers to. */\nexport function encodeColumns(spec: Spec): { path: string; col: string; numeric?: boolean }[] {\n const e = spec.encode as Record<string, unknown>;\n switch (spec.component) {\n case \"sankey\":\n return [\n { path: \"encode.source\", col: spec.encode.source },\n { path: \"encode.target\", col: spec.encode.target },\n { path: \"encode.value\", col: spec.encode.value, numeric: true },\n ];\n case \"bar\":\n case \"line\":\n case \"area\": {\n const ys = Array.isArray(spec.encode.y) ? spec.encode.y : [spec.encode.y];\n return [\n { path: \"encode.x\", col: spec.encode.x },\n ...ys.map((y, i) => ({ path: Array.isArray(spec.encode.y) ? `encode.y.${i}` : \"encode.y\", col: y, numeric: true })),\n ...(spec.encode.series ? [{ path: \"encode.series\", col: spec.encode.series }] : []),\n ];\n }\n case \"kpi\":\n return [{ path: \"encode.value\", col: spec.encode.value, numeric: true }];\n case \"table\":\n return spec.encode.columns.map((c, i) => ({ path: `encode.columns.${i}.field`, col: c.field }));\n case \"grid\":\n case \"actionTable\":\n return [{ path: \"encode.rowKey\", col: e.rowKey as string }, ...(e.columns as { field: string }[]).map((c, i) => ({ path: `encode.columns.${i}.field`, col: c.field }))];\n }\n}\n\nfunction argRefs(expr: ArgExpr, path: string, out: { path: string; kind: \"field\" | \"input\" | \"param\"; name: string }[]) {\n if (\"field\" in expr) out.push({ path, kind: \"field\", name: expr.field });\n else if (\"input\" in expr) out.push({ path, kind: \"input\", name: expr.input });\n else if (\"param\" in expr) out.push({ path, kind: \"param\", name: expr.param });\n else if (\"template\" in expr) for (const m of expr.template.matchAll(/\\{([^}]+)\\}/g)) out.push({ path, kind: \"field\", name: m[1] });\n else if (\"list\" in expr) expr.list.forEach((x, i) => argRefs(x, `${path}.list.${i}`, out));\n}\n\n/** Intents and navigations a spec invokes. */\nexport function invoked(spec: Spec): { intents: string[]; navigations: string[] } {\n const intents = new Set<string>();\n if (spec.component === \"actionTable\") intents.add(spec.encode.action.intent);\n if (spec.component === \"grid\") for (const c of spec.encode.columns) if (c.edit) intents.add(c.edit.intent);\n return { intents: [...intents], navigations: spec.onClick ? [spec.onClick.navigate] : [] };\n}\n\n/**\n * The host-side validator: the authority on whether a proposal is\n * acceptable (Invariant 3). The conductor runs the same function for a fast\n * repair loop, but only this run, in the host, decides what renders.\n */\nexport function validateDraft(input: unknown, m: ContractManifest, opts: DraftValidateOptions): DraftValidation {\n const out: DraftValidation = { ok: false, problems: [], warnings: [], columns: {}, touched: [] };\n const P = out.problems;\n scanStrings(input, \"\", P);\n const parsed = DraftSchema.safeParse(input);\n if (!parsed.success) {\n P.push(...zodProblems(parsed.error));\n return dedupe(out);\n }\n const draft = parsed.data;\n out.draft = draft;\n const spec = draft.body;\n\n // Placement (S): the slot must exist and accept this kind.\n const slot = m.slots[draft.placement.slot];\n if (!slot) P.push(problem(\"placement.slot\", \"unknown_slot\", `unknown slot \"${draft.placement.slot}\" (slots: ${Object.keys(m.slots).join(\", \")})`));\n else {\n const asPage = slot.accepts.includes(\"page\") && !slot.accepts.includes(\"spec\");\n if (!asPage && !slot.accepts.includes(\"spec\")) P.push(problem(\"placement.slot\", \"slot_kind\", `slot ${draft.placement.slot} does not accept specs`));\n if (asPage && !draft.placement.label?.[m.defaultLocale]) P.push(problem(\"placement.label\", \"schema\", `a page in ${draft.placement.slot} needs a label in ${m.defaultLocale}`));\n }\n\n // Params: bindings must name context the slot actually provides (I5).\n for (const [name, p] of Object.entries(spec.params ?? {})) {\n if (\"bind\" in p) {\n const key = p.bind.slice(\"host.context.\".length);\n if (!m.context[key]) P.push(problem(`body.params.${name}.bind`, \"context\", `the host declares no context \"${key}\"`));\n else if (slot && !slot.context.includes(key))\n P.push(\n problem(`body.params.${name}.bind`, \"context\", `slot ${draft.placement.slot} does not provide context \"${key}\" (it provides: ${slot.context.join(\", \") || \"nothing\"})`),\n );\n } else if (p.control === \"slider\" && (p.min >= p.max || p.default < p.min || p.default > p.max)) {\n P.push(problem(`body.params.${name}`, \"schema\", \"slider needs min < max and a default between them\"));\n }\n }\n\n // Data (Q): validated with the manifest's reads and the user's role (P2).\n const v = validateIR(spec.data, m, { reads: draft.manifest.reads, role: opts.role, params: paramTypes(spec, m) });\n P.push(...nest(\"body.data\", v.problems));\n out.columns = v.columns;\n out.touched = v.touched;\n for (const r of draft.manifest.reads)\n if (!v.touched.includes(r)) P.push(problem(\"manifest.reads\", \"unused_read\", `declares ${r} but never reads it; list exactly what the query touches`));\n\n // Encode: every referenced column must be an output column of the query.\n if (v.ir) {\n for (const { path, col, numeric } of encodeColumns(spec)) {\n const c = v.columns[col];\n if (!c) P.push(problem(`body.${path}`, \"encode\", `\"${col}\" is not a column of the query (columns: ${Object.keys(v.columns).join(\", \")})`));\n else if (numeric && c.type !== \"number\") P.push(problem(`body.${path}`, \"encode\", `\"${col}\" must be a number column`));\n }\n if (spec.component === \"kpi\" && v.ir.groupBy?.length) P.push(problem(\"body.data.groupBy\", \"encode\", \"a KPI shows one number; remove groupBy\"));\n if (spec.component === \"sankey\" && spec.encode.source === spec.encode.target) P.push(problem(\"body.encode.target\", \"encode\", \"source and target must differ\"));\n }\n\n // Acts (I): every invoked intent must be declared in the manifest, exist, and be allowed (P3).\n const { intents, navigations } = invoked(spec);\n for (const i of intents) {\n if (!m.intents[i]) P.push(problem(\"body\", \"unknown_intent\", `unknown intent \"${i}\" (intents: ${Object.keys(m.intents).join(\", \") || \"none\"})`));\n else if (!draft.manifest.acts.includes(i)) P.push(problem(\"manifest.acts\", \"undeclared_act\", `invokes ${i}, which the manifest does not declare`));\n else if (!canAct(m, opts.role, i)) P.push(problem(\"manifest.acts\", \"role_denied\", `role ${opts.role} cannot use ${i}`));\n }\n for (const a of draft.manifest.acts) if (!intents.includes(a)) P.push(problem(\"manifest.acts\", \"unused_read\", `declares ${a} but never invokes it`));\n for (const n of navigations)\n if (!m.navigation[n]) P.push(problem(\"body.onClick.navigate\", \"unknown_intent\", `unknown navigation \"${n}\" (navigations: ${Object.keys(m.navigation).join(\", \") || \"none\"})`));\n\n // Arguments: names must exist in the intent's schema; references must resolve.\n const inputs = new Set(spec.component === \"actionTable\" ? (spec.encode.inputs ?? []).map((x) => x.name) : []);\n const checkArgs = (args: Record<string, ArgExpr>, schema: Record<string, unknown> | undefined, path: string, extra: string[] = []) => {\n const props = Object.keys((schema?.properties ?? {}) as Record<string, unknown>);\n const required = ((schema?.required ?? []) as string[]).filter((r) => !extra.includes(r));\n for (const k of Object.keys(args)) if (!props.includes(k)) P.push(problem(`${path}.${k}`, \"schema\", `unknown argument \"${k}\" (arguments: ${props.join(\", \")})`));\n for (const r of required) if (!(r in args)) P.push(problem(path, \"schema\", `missing argument \"${r}\"`));\n const refs: Parameters<typeof argRefs>[2] = [];\n for (const [k, e] of Object.entries(args)) argRefs(e, `${path}.${k}`, refs);\n for (const r of refs) {\n if (r.kind === \"field\" && !v.columns[r.name]) P.push(problem(r.path, \"encode\", `\"${r.name}\" is not a column of the query`));\n if (r.kind === \"input\" && !inputs.has(r.name)) P.push(problem(r.path, \"encode\", `\"${r.name}\" is not a declared row input`));\n if (r.kind === \"param\" && !spec.params?.[r.name]) P.push(problem(r.path, \"unknown_param\", `param \"${r.name}\" is not declared`));\n }\n };\n if (spec.component === \"actionTable\") checkArgs(spec.encode.action.args, m.intents[spec.encode.action.intent]?.args, \"body.encode.action.args\");\n if (spec.component === \"grid\")\n spec.encode.columns.forEach((c, i) => c.edit && checkArgs(c.edit.args, m.intents[c.edit.intent]?.args, `body.encode.columns.${i}.edit.args`, [c.edit.value]));\n if (spec.onClick) checkArgs(spec.onClick.args, m.navigation[spec.onClick.navigate]?.args, \"body.onClick.args\");\n\n // Locales (I16): the default locale is required by the card; missing others fall back.\n if (!spec.title[m.defaultLocale]) P.push(problem(\"body.title\", \"locale\", `title needs a ${m.defaultLocale} entry`));\n for (const l of m.locales) if (!spec.title[l]) out.warnings.push(problem(\"body.title\", \"locale\", `no ${l} title; ${m.defaultLocale} is shown instead`));\n\n return dedupe(out, true);\n}\n\nfunction dedupe(out: DraftValidation, done = false): DraftValidation {\n const seen = new Set<string>();\n out.problems = out.problems.filter((p) => {\n const k = `${p.path}|${p.message}`;\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n out.ok = done && out.problems.length === 0;\n return out;\n}\n", "import type { ContractManifest } from \"@crasi/bisque-contract\";\nimport { fieldLabel, resourceLabel } from \"@crasi/bisque-contract\";\nimport { measureOf, type IR, type IRCond, type IRScalar } from \"@crasi/bisque-ir\";\nimport type { Draft, Spec } from \"./schema\";\nimport { invoked } from \"./validate\";\n\n/**\n * The plain-language card text (Fig. 8b), generated from the spec by code.\n * The model never writes descriptions (Invariant 4), so what the card says\n * cannot drift from what the chart does.\n *\n * Templates are English in v1; other locales get the spec's own localized\n * title and English sentences.\n */\nexport type Description = {\n title: string;\n /** \"Sum of sales value (RON) in October 2026, from each key account to each product.\" */\n lines: string[];\n reads: string[];\n changes: string[];\n placed: string;\n};\n\nexport type DescribeOptions = {\n locale?: string;\n /** Current values of host context, so \"in the month being viewed\" can become \"in October 2026\". */\n context?: Record<string, unknown>;\n /** Current param values (control defaults if absent). */\n params?: Record<string, unknown>;\n};\n\nexport function localize(text: Record<string, string> | undefined, locale: string, fallback: string): string {\n if (!text) return \"\";\n return text[locale] ?? text[fallback] ?? Object.values(text)[0] ?? \"\";\n}\n\ntype Ctx = { m: ContractManifest; spec: Spec; opts: DescribeOptions; locale: string };\n\nfunction columnLabel(c: Ctx, col: string): string {\n const ir = c.spec.data;\n for (const raw of ir.measures ?? []) {\n const { agg, field, as } = measureOf(raw);\n if (as === col) return measurePhrase(c, agg, field, true);\n }\n const [res, f] = col.includes(\".\") ? [col.slice(0, col.indexOf(\".\")), col.slice(col.indexOf(\".\") + 1)] : [ir.scan, col];\n return fieldLabel(c.m, res, f);\n}\n\nfunction fieldOf(c: Ctx, name: string): { res: string; f: string } {\n return name.includes(\".\") ? { res: name.slice(0, name.indexOf(\".\")), f: name.slice(name.indexOf(\".\") + 1) } : { res: c.spec.data.scan, f: name };\n}\n\nfunction measurePhrase(c: Ctx, agg: string, field: string, short = false): string {\n if (agg === \"count\" && field === \"*\") return short ? `number of ${resourceLabel(c.m, c.spec.data.scan)}` : `Number of ${resourceLabel(c.m, c.spec.data.scan)}`;\n const { res, f } = fieldOf(c, field);\n const label = fieldLabel(c.m, res, f);\n const isDate = [\"date\", \"datetime\"].includes(c.m.resources[res]?.fields[f]?.type ?? \"\");\n const words: Record<string, string> = {\n sum: short ? label : `Sum of ${label}`,\n avg: `${short ? \"average\" : \"Average\"} ${label}`,\n count: `${short ? \"number\" : \"Number\"} of ${label}`,\n countDistinct: `${short ? \"number\" : \"Number\"} of distinct ${label}`,\n min: `${short ? (isDate ? \"earliest\" : \"lowest\") : isDate ? \"Earliest\" : \"Lowest\"} ${label}`,\n max: `${short ? (isDate ? \"latest\" : \"highest\") : isDate ? \"Latest\" : \"Highest\"} ${label}`,\n };\n return words[agg];\n}\n\nconst MONTH = /^\\d{4}-\\d{2}(-01)?$/;\n/** A date, or an ISO date-time whose date part is shown (2026-06-10T09:00:00Z). */\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}(T[\\d:.]+(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\nfunction formatValue(v: unknown, locale: string): string {\n if (typeof v === \"string\" && MONTH.test(v)) return new Date(`${v.slice(0, 7)}-01T00:00:00Z`).toLocaleDateString(locale, { month: \"long\", year: \"numeric\", timeZone: \"UTC\" });\n if (typeof v === \"string\" && DATE.test(v))\n return new Date(`${v.slice(0, 10)}T00:00:00Z`).toLocaleDateString(locale, { day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" });\n if (Array.isArray(v)) return v.map((x) => formatValue(x, locale)).join(\", \");\n return String(v);\n}\n\nfunction scalarText(c: Ctx, v: IRScalar): { text: string; follows?: string } {\n if (v && typeof v === \"object\" && \"param\" in v) {\n const p = c.spec.params?.[v.param];\n if (p && \"bind\" in p) {\n const key = p.bind.slice(\"host.context.\".length);\n const cur = c.opts.context?.[key];\n const follows = c.m.context[key]?.label ?? `the ${key} you are viewing`;\n return { text: cur !== undefined ? formatValue(cur, c.locale) : `the ${key} being viewed`, follows };\n }\n const cur = c.opts.params?.[v.param] ?? (p && \"default\" in p ? p.default : undefined);\n return { text: cur !== undefined ? `${formatValue(cur, c.locale)} (adjustable)` : `the chosen ${v.param}` };\n }\n if (v && typeof v === \"object\" && \"today\" in v) {\n return { text: v.today === 0 ? \"today\" : v.today > 0 ? `${v.today} days from today` : `${-v.today} days ago` };\n }\n return { text: formatValue(v, c.locale) };\n}\n\nfunction filterPhrase(c: Ctx, cond: IRCond, follows: Set<string>): string {\n const [field, op] = cond;\n const { res, f } = fieldOf(c, field);\n const label = fieldLabel(c.m, res, f);\n if (op === \"isNull\") return `where ${label} is empty`;\n if (op === \"notNull\") return `where ${label} is set`;\n const raw = cond[2]!;\n const vals = (Array.isArray(raw) ? raw : [raw]).map((x) => {\n const t = scalarText(c, x);\n if (t.follows) follows.add(t.follows);\n return t.text;\n });\n const isMonth = f === \"month\";\n switch (op) {\n case \"=\":\n return isMonth ? `in ${vals[0]}` : `where ${label} is ${vals[0]}`;\n case \"!=\":\n return `where ${label} is not ${vals[0]}`;\n case \"in\":\n return `where ${label} is ${vals.join(\", \")}`;\n case \"notIn\":\n return `excluding ${label} ${vals.join(\", \")}`;\n case \"match\":\n return `for ${vals.join(\", \")}`;\n case \"<\": {\n const today = Array.isArray(raw) ? undefined : raw;\n if (today && typeof today === \"object\" && \"today\" in today && today.today < 0) return `where ${label} is more than ${-today.today} days ago`;\n return `where ${label} is before ${vals[0]}`.replace(/before (\\d+(\\.\\d+)?)$/, \"below $1\");\n }\n case \"<=\": {\n const today = Array.isArray(raw) ? undefined : raw;\n if (today && typeof today === \"object\" && \"today\" in today && today.today >= 0) return `with ${label} within the next ${today.today} days`;\n return `where ${label} is at most ${vals[0]}`;\n }\n case \">\":\n return `where ${label} is above ${vals[0]}`;\n case \">=\": {\n const today = Array.isArray(raw) ? undefined : raw;\n if (today && typeof today === \"object\" && \"today\" in today && today.today <= 0) return `in the last ${-today.today} days`;\n return `where ${label} is at least ${vals[0]}`;\n }\n }\n return \"\";\n}\n\nfunction groupingPhrase(c: Ctx): string {\n const s = c.spec;\n const L = (col: string) => columnLabel(c, col);\n switch (s.component) {\n case \"sankey\":\n return `from each ${L(s.encode.source)} to each ${L(s.encode.target)}`;\n case \"bar\":\n return `by ${L(s.encode.x)}${s.encode.series ? `, split by ${L(s.encode.series)}` : \"\"}`;\n case \"line\":\n case \"area\":\n return `over ${L(s.encode.x)}${s.encode.series ? `, one line per ${L(s.encode.series)}` : \"\"}`;\n case \"kpi\":\n return \"\";\n default: {\n const g = withoutKeys(c, s.data.groupBy ?? []);\n return g.length\n ? `one row per ${g.map(L).join(\" and \")}`\n : `listing ${withoutKeys(c, s.data.select ?? [])\n .map(L)\n .join(\", \")}`;\n }\n }\n}\n\n/** Drops key columns (`products.id`) that ride along beside a readable column of the same resource. */\nfunction withoutKeys(c: Ctx, cols: string[]): string[] {\n const resOf = (col: string) => fieldOf(c, col).res;\n const isKey = (col: string) => {\n const { res, f } = fieldOf(c, col);\n return f === (c.m.resources[res]?.key ?? \"id\");\n };\n return cols.filter((col) => !isKey(col) || !cols.some((o) => o !== col && resOf(o) === resOf(col) && !isKey(o)));\n}\n\nfunction headline(c: Ctx, follows: Set<string>): string {\n const ir: IR = c.spec.data;\n const measures = (ir.measures ?? []).map((raw) => {\n const { agg, field } = measureOf(raw);\n return measurePhrase(c, agg, field);\n });\n const lead = measures.length\n ? [measures[0], ...measures.slice(1).map((x) => x.charAt(0).toLowerCase() + x.slice(1))].join(\" and \")\n : `${resourceLabel(c.m, ir.scan).replace(/^./, (x) => x.toUpperCase())}`;\n const filters = (ir.where ?? []).map((w) => filterPhrase(c, w, follows)).filter(Boolean);\n // \"Sum of pieces of stock lots with expiry date within\u2026\": name what is filtered when a measure leads.\n if (measures.length && filters.length && /^(with|where) /.test(filters[0])) filters[0] = `of ${resourceLabel(c.m, ir.scan)} ${filters[0]}`;\n const grouping = groupingPhrase(c);\n return `${[lead, ...filters].join(\" \")}${grouping ? `, ${grouping}` : \"\"}.`;\n}\n\nfunction placedText(m: ContractManifest, d: Draft, locale: string): string {\n const slot = m.slots[d.placement.slot];\n const where = slot?.label ?? d.placement.slot;\n return d.placement.label ? `${where} as \u201C${localize(d.placement.label, locale, m.defaultLocale)}\u201D` : where;\n}\n\nfunction intentLabel(m: ContractManifest, name: string, locale: string): string {\n const l = m.intents[name]?.label;\n if (!l) return name;\n return typeof l === \"string\" ? l : localize(l, locale, m.defaultLocale);\n}\n\nexport function describeDraft(d: Draft, m: ContractManifest, opts: DescribeOptions = {}): Description {\n const locale = opts.locale ?? m.defaultLocale;\n const spec = d.body;\n const c: Ctx = { m, spec, opts, locale };\n const follows = new Set<string>();\n const lines = [headline(c, follows)];\n const ir = spec.data;\n if (spec.component === \"sankey\" && spec.encode.label === \"share-of-source\")\n lines.push(`Each flow is labelled with its share of the ${columnLabel(c, spec.encode.source)}'s total.`);\n if (spec.component === \"sankey\" && spec.otherBucket)\n lines.push(`${capitalize(plural(columnLabel(c, spec.encode.target)))} after the top ${spec.otherBucket.maxTargets} are grouped as Other.`);\n if (spec.component === \"bar\" && spec.otherBucket)\n lines.push(`${capitalize(plural(columnLabel(c, spec.encode.x)))} after the top ${spec.otherBucket.maxCategories} are grouped as Other.`);\n const order = ir.orderBy?.[0];\n if (order && ir.limit <= 50 && spec.component !== \"sankey\") lines.push(`Top ${ir.limit} by ${columnLabel(c, order[0])}${order[1] === \"asc\" ? \", lowest first\" : \"\"}.`);\n for (const [, p] of Object.entries(spec.params ?? {})) if (!(\"bind\" in p)) lines.push(`Adjustable: ${localize(p.label, locale, m.defaultLocale)}.`);\n for (const f of follows) lines.push(`Follows ${f}.`);\n if (spec.onClick) {\n const n = m.navigation[spec.onClick.navigate];\n lines.push(`Click an item to ${n?.describe ? n.describe.charAt(0).toLowerCase() + n.describe.slice(1) : `open ${spec.onClick.navigate}`}.`);\n }\n const changes: string[] = [];\n if (spec.component === \"actionTable\") {\n const i = m.intents[spec.encode.action.intent];\n changes.push(`${intentLabel(m, spec.encode.action.intent, locale)} for each selected row${i?.policy === \"confirm\" ? \" (asks you first)\" : \"\"}`);\n }\n if (spec.component === \"grid\")\n for (const col of spec.encode.columns)\n if (col.edit) {\n const i = m.intents[col.edit.intent];\n changes.push(`Editing ${columnLabel(c, col.field)} calls ${intentLabel(m, col.edit.intent, locale)}${i?.policy === \"confirm\" ? \" (asks you first)\" : \"\"}`);\n }\n return {\n title: localize(spec.title, locale, m.defaultLocale),\n lines,\n reads: d.manifest.reads.map((r) => resourceLabel(m, r)),\n changes: changes.length ? changes : invoked(spec).intents.length ? invoked(spec).intents.map((i) => intentLabel(m, i, locale)) : [],\n placed: placedText(m, d, locale),\n };\n}\n\nconst capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);\nconst plural = (s: string) => (s.endsWith(\"s\") ? s : s.endsWith(\"y\") ? `${s.slice(0, -1)}ies` : `${s}s`);\n\n/**\n * Diff lines for a refinement (Flow A step A5): \"Measure: sales value (RON) \u2192\n * pieces\", \"Filter: + Metro, TABAC\". Computed from the two specs.\n */\nexport function diffDrafts(a: Draft, b: Draft, m: ContractManifest, opts: DescribeOptions = {}): string[] {\n const locale = opts.locale ?? m.defaultLocale;\n const ca: Ctx = { m, spec: a.body, opts, locale };\n const cb: Ctx = { m, spec: b.body, opts, locale };\n const out: string[] = [];\n if (a.body.component !== b.body.component) out.push(`Chart: ${a.body.component} \u2192 ${b.body.component}`);\n const ms = (c: Ctx) =>\n (c.spec.data.measures ?? []).map((raw) => {\n const x = measureOf(raw);\n return measurePhrase(c, x.agg, x.field, true);\n });\n const [ma, mb] = [ms(ca), ms(cb)];\n if (ma.join(\"|\") !== mb.join(\"|\")) out.push(`Measure: ${ma.join(\", \") || \"none\"} \u2192 ${mb.join(\", \") || \"none\"}`);\n const fs = (c: Ctx) => (c.spec.data.where ?? []).map((w) => ({ key: JSON.stringify(w), text: filterPhrase(c, w, new Set()) }));\n const [fa, fb] = [fs(ca), fs(cb)];\n const fbKeys = new Set(fb.map((x) => x.key)),\n faKeys = new Set(fa.map((x) => x.key));\n for (const x of fb) if (!faKeys.has(x.key)) out.push(`Filter: + ${x.text.replace(/^(for|where|in) /, \"\")}`);\n for (const x of fa) if (!fbKeys.has(x.key)) out.push(`Filter: \u2212 ${x.text.replace(/^(for|where|in) /, \"\")}`);\n const ga = groupingPhrase(ca),\n gb = groupingPhrase(cb);\n if (ga !== gb && a.body.component === b.body.component) out.push(`Grouping: ${ga || \"none\"} \u2192 ${gb || \"none\"}`);\n const ta = localize(a.body.title, locale, m.defaultLocale),\n tb = localize(b.body.title, locale, m.defaultLocale);\n if (ta !== tb) out.push(`Title: ${ta} \u2192 ${tb}`);\n const ob = (s: Spec) => (s.component === \"sankey\" ? s.otherBucket?.maxTargets : s.component === \"bar\" ? s.otherBucket?.maxCategories : undefined);\n if (ob(a.body) !== ob(b.body)) out.push(`Top: ${ob(a.body) ?? \"all\"} \u2192 ${ob(b.body) ?? \"all\"}`);\n if (a.body.data.limit !== b.body.data.limit) out.push(`Rows: at most ${a.body.data.limit} \u2192 ${b.body.data.limit}`);\n if (a.placement.slot !== b.placement.slot) out.push(`Placed: ${placedText(m, a, locale)} \u2192 ${placedText(m, b, locale)}`);\n const ia = invoked(a.body).intents.join(\", \"),\n ib = invoked(b.body).intents.join(\", \");\n if (ia !== ib) out.push(`Changes: ${ia || \"nothing\"} \u2192 ${ib || \"nothing\"}`);\n return out;\n}\n", "import { MAX_ROWS } from \"@crasi/bisque-core\";\nimport type { ContractManifest } from \"@crasi/bisque-contract\";\nimport { measureOf } from \"@crasi/bisque-ir\";\nimport type { ComponentName, Draft, Spec } from \"./schema\";\n\n/**\n * The Adjust panel (issue I8): small edits generated from the spec itself and\n * applied without a model call. Each control maps to one path in the spec.\n */\nexport type Adjustable =\n | { id: string; label: string; type: \"number\"; value: number; min: number; max: number; step?: number }\n | { id: string; label: string; type: \"select\"; value: string; options: { value: string; label: string }[] };\n\nconst COMPONENT_LABEL: Record<ComponentName, string> = {\n sankey: \"Sankey\",\n bar: \"Bar chart\",\n line: \"Line chart\",\n area: \"Area chart\",\n table: \"Table\",\n kpi: \"Number\",\n grid: \"Editable grid\",\n actionTable: \"Action table\",\n};\n\n/** Components a spec can switch to without changing its query. */\nexport function compatibleComponents(spec: Spec): ComponentName[] {\n if (spec.component === \"grid\" || spec.component === \"actionTable\") return [spec.component];\n const groups = spec.data.groupBy?.length ?? 0;\n const measures = spec.data.measures?.length ?? 0;\n if (!measures) return [\"table\"];\n if (groups === 0) return [\"kpi\", \"table\"];\n if (groups === 1) return [\"bar\", \"line\", \"area\", \"table\"];\n return [\"sankey\", \"bar\", \"table\"];\n}\n\nexport function adjustables(d: Draft, m: ContractManifest): Adjustable[] {\n const s = d.body;\n const out: Adjustable[] = [];\n const comps = compatibleComponents(s);\n if (comps.length > 1) out.push({ id: \"component\", label: \"Show as\", type: \"select\", value: s.component, options: comps.map((c) => ({ value: c, label: COMPONENT_LABEL[c] })) });\n if (s.component === \"sankey\") {\n out.push({ id: \"otherBucket\", label: \"Top targets\", type: \"number\", value: s.otherBucket?.maxTargets ?? 12, min: 2, max: 50 });\n out.push({\n id: \"sankeyLabel\",\n label: \"Labels\",\n type: \"select\",\n value: s.encode.label ?? \"value\",\n options: [\n { value: \"value\", label: \"Values\" },\n { value: \"share-of-source\", label: \"Share of source\" },\n { value: \"share-of-total\", label: \"Share of total\" },\n ],\n });\n }\n if (s.component === \"bar\") {\n out.push({ id: \"otherBucket\", label: \"Top categories\", type: \"number\", value: s.otherBucket?.maxCategories ?? 12, min: 2, max: 50 });\n if (s.encode.series)\n out.push({\n id: \"stacked\",\n label: \"Bars\",\n type: \"select\",\n value: s.encode.stacked ? \"stacked\" : \"grouped\",\n options: [\n { value: \"stacked\", label: \"Stacked\" },\n { value: \"grouped\", label: \"Side by side\" },\n ],\n });\n }\n const cap = Math.min(m.resources[s.data.scan]?.cap ?? MAX_ROWS, MAX_ROWS);\n out.push({ id: \"limit\", label: \"Rows at most\", type: \"number\", value: s.data.limit, min: 1, max: cap });\n if (s.data.orderBy?.length)\n out.push({\n id: \"order\",\n label: \"Order\",\n type: \"select\",\n value: s.data.orderBy[0][1],\n options: [\n { value: \"desc\", label: \"Highest first\" },\n { value: \"asc\", label: \"Lowest first\" },\n ],\n });\n return out;\n}\n\n/** Applies one Adjust control. The result must still pass host validation. */\nexport function applyAdjustment(d: Draft, id: string, value: string | number): Draft {\n const s = structuredClone(d.body) as Spec;\n switch (id) {\n case \"component\":\n return { ...d, body: switchComponent(s, value as ComponentName) };\n case \"otherBucket\":\n if (s.component === \"sankey\") s.otherBucket = { maxTargets: Number(value) };\n if (s.component === \"bar\") s.otherBucket = { maxCategories: Number(value) };\n break;\n case \"sankeyLabel\":\n if (s.component === \"sankey\") s.encode.label = value as \"value\";\n break;\n case \"stacked\":\n if (s.component === \"bar\") s.encode.stacked = value === \"stacked\";\n break;\n case \"limit\":\n s.data.limit = Math.max(1, Math.floor(Number(value)));\n break;\n case \"order\":\n if (s.data.orderBy?.length) s.data.orderBy[0] = [s.data.orderBy[0][0], value as \"asc\" | \"desc\"];\n break;\n }\n return { ...d, body: s };\n}\n\n/** Re-encodes the same query for another component. */\nexport function switchComponent(s: Spec, to: ComponentName): Spec {\n if (s.component === to) return s;\n const groups = s.data.groupBy ?? [];\n const measures = (s.data.measures ?? []).map((x) => measureOf(x).as);\n const base = { title: s.title, data: s.data, params: s.params, onClick: s.onClick };\n const value = measures[0];\n switch (to) {\n case \"sankey\":\n return { component: \"sankey\", ...base, encode: { source: groups[0], target: groups[1], value }, otherBucket: { maxTargets: 12 } };\n case \"bar\":\n return { component: \"bar\", ...base, encode: { x: groups[0], y: value, ...(groups[1] ? { series: groups[1], stacked: true } : {}) } };\n case \"line\":\n case \"area\":\n return { component: to, ...base, encode: { x: groups[0], y: measures.length > 1 ? measures : value, ...(groups[1] ? { series: groups[1] } : {}) } };\n case \"kpi\":\n return { component: \"kpi\", ...base, encode: { value } };\n case \"table\":\n return { component: \"table\", ...base, encode: { columns: [...groups, ...measures, ...(s.data.select ?? [])].map((field) => ({ field })) } };\n default:\n return s;\n }\n}\n", "import { z } from \"zod\";\nimport { bucketCount, bucketShare, COUNT_BUCKETS } from \"@crasi/bisque-core\";\nimport type { QueryResult } from \"@crasi/bisque-ir\";\nimport type { Spec } from \"./schema\";\n\n/**\n * Render diagnostics (issue I1, \u00A76.8): the shape of a preview, never its\n * values. This is the only thing derived from records that crosses to the\n * conductor (P1 exception b), so the schema is strict: buckets, rounded\n * shares, fixed error codes, and column names taken from the spec.\n */\nexport const RENDER_ERRORS = [\"empty\", \"too_many_categories\", \"all_null\", \"unresolved_names\", \"ambiguous_names\", \"component_error\"] as const;\n\nconst Bucket = z.enum(COUNT_BUCKETS);\nconst ColumnName = z\n .string()\n .regex(/^[a-z_][a-z0-9_]*(\\.[a-z_][a-z0-9_]*)?$/i)\n .max(80);\n\nexport const DiagnosticsSchema = z\n .object({\n proposal: z.string().max(64),\n valid: z.boolean(),\n rows: Bucket,\n distinct: z.record(ColumnName, Bucket),\n nullShare: z.record(ColumnName, z.number().min(0).max(1).multipleOf(0.1)),\n otherBucket: z.enum([\"applied\", \"not needed\", \"not set\"]),\n truncated: z.boolean(),\n renderErrors: z.array(z.enum(RENDER_ERRORS)).max(RENDER_ERRORS.length),\n })\n .strict();\nexport type Diagnostics = z.infer<typeof DiagnosticsSchema>;\n\nfunction categorical(spec: Spec): string[] {\n switch (spec.component) {\n case \"sankey\":\n return [spec.encode.source, spec.encode.target];\n case \"bar\":\n case \"line\":\n case \"area\":\n return [spec.encode.x, ...(spec.encode.series ? [spec.encode.series] : [])];\n default:\n return spec.data.groupBy ?? [];\n }\n}\n\nfunction numeric(spec: Spec): string[] {\n switch (spec.component) {\n case \"sankey\":\n return [spec.encode.value];\n case \"bar\":\n case \"line\":\n case \"area\":\n return Array.isArray(spec.encode.y) ? spec.encode.y : [spec.encode.y];\n case \"kpi\":\n return [spec.encode.value];\n default:\n return (spec.data.measures ?? []).map((m) => m.as);\n }\n}\n\nexport function renderDiagnostics(proposal: string, spec: Spec, res: QueryResult, opts: { valid: boolean; renderError?: boolean }): Diagnostics {\n const distinct: Record<string, (typeof COUNT_BUCKETS)[number]> = {};\n const counts: Record<string, number> = {};\n for (const col of categorical(spec)) {\n counts[col] = new Set(res.rows.map((r) => String(r[col]))).size;\n distinct[col] = bucketCount(counts[col]);\n }\n const nullShare: Record<string, number> = {};\n for (const col of numeric(spec)) nullShare[col] = res.rows.length ? bucketShare(res.rows.filter((r) => r[col] == null).length / res.rows.length) : 0;\n const errors = new Set<(typeof RENDER_ERRORS)[number]>();\n if (res.total === 0) errors.add(\"empty\");\n if (Object.values(nullShare).some((s) => s === 1) && res.rows.length) errors.add(\"all_null\");\n if (res.resolution.some((r) => r.status === \"unmatched\")) errors.add(\"unresolved_names\");\n if (res.resolution.some((r) => r.status === \"ambiguous\")) errors.add(\"ambiguous_names\");\n if (opts.renderError) errors.add(\"component_error\");\n let otherBucket: Diagnostics[\"otherBucket\"] = \"not set\";\n const cap = spec.component === \"sankey\" ? spec.otherBucket?.maxTargets : spec.component === \"bar\" ? spec.otherBucket?.maxCategories : undefined;\n const bucketCol = spec.component === \"sankey\" ? spec.encode.target : spec.component === \"bar\" ? spec.encode.x : undefined;\n if (cap && bucketCol) otherBucket = counts[bucketCol] > cap ? \"applied\" : \"not needed\";\n else if (bucketCol && counts[bucketCol] > 50) errors.add(\"too_many_categories\");\n return {\n proposal,\n valid: opts.valid,\n rows: bucketCount(res.total),\n distinct,\n nullShare,\n otherBucket,\n truncated: res.truncated,\n renderErrors: [...errors],\n };\n}\n\n/** Whether diagnostics justify the one repair turn (and what to tell the model). */\nexport function repairReason(d: Diagnostics): string | null {\n const reasons: string[] = [];\n if (d.renderErrors.includes(\"empty\")) reasons.push(\"the query returned no rows on the user's data; check filters and that the month or names exist\");\n if (d.renderErrors.includes(\"all_null\")) reasons.push(\"the measure is empty for every row; it may be the wrong field\");\n if (d.renderErrors.includes(\"too_many_categories\")) reasons.push(\"there are more than 50 categories; add otherBucket or a tighter filter\");\n if (d.renderErrors.includes(\"component_error\")) reasons.push(\"the component failed to render this data shape\");\n return reasons.length ? reasons.join(\"; \") : null;\n}\n", "import { addDaysIso, type Row } from \"@crasi/bisque-ir\";\nimport type { ArgExpr } from \"./schema\";\n\nexport type ArgScope = {\n row?: Row;\n inputs?: Record<string, unknown>;\n params?: Record<string, unknown>;\n today?: string;\n};\n\n/** Evaluates an argument expression against the row the user acted on. */\nexport function evalArg(e: ArgExpr, s: ArgScope): unknown {\n if (\"field\" in e) return s.row?.[e.field] ?? null;\n if (\"input\" in e) return s.inputs?.[e.input] ?? null;\n if (\"param\" in e) return s.params?.[e.param] ?? null;\n if (\"literal\" in e) return e.literal;\n if (\"today\" in e) return addDaysIso(s.today ?? new Date().toISOString().slice(0, 10), e.today);\n if (\"template\" in e) return e.template.replace(/\\{([^}]+)\\}/g, (_, k: string) => String(s.row?.[k] ?? \"\")).slice(0, 200);\n return e.list.map((x) => evalArg(x, s));\n}\n\nexport function evalArgs(args: Record<string, ArgExpr>, s: ArgScope): Record<string, unknown> {\n return Object.fromEntries(Object.entries(args).map(([k, e]) => [k, evalArg(e, s)]));\n}\n", "import type { ContractDiff } from \"@crasi/bisque-contract\";\nimport type { Draft } from \"./schema\";\n\n/**\n * Applies `renamedFrom` renames to a saved artifact without a model (issue\n * I13). Rewrites field references in the query and every column name that\n * was a field. Returns null when nothing changed.\n */\nexport function migrateDraft(d: Draft, renames: ContractDiff[\"renames\"]): Draft | null {\n if (!Object.keys(renames).length) return null;\n const scan = d.body.data.scan;\n const rename = (name: string): string => {\n const [res, f] = name.includes(\".\") ? [name.slice(0, name.indexOf(\".\")), name.slice(name.indexOf(\".\") + 1)] : [scan, name];\n const to = renames[res]?.[f];\n if (!to) return name;\n return name.includes(\".\") ? `${res}.${to}` : to;\n };\n let changed = false;\n const walk = (v: unknown, key?: string): unknown => {\n if (typeof v === \"string\" && key && FIELD_KEYS.has(key)) {\n const r = rename(v);\n if (r !== v) changed = true;\n return r;\n }\n if (Array.isArray(v)) {\n // where conditions and orderBy keys: the first element is a field.\n if ((key === \"cond\" || key === \"order\") && typeof v[0] === \"string\") {\n const r = rename(v[0]);\n if (r !== v[0]) changed = true;\n return [r, ...v.slice(1).map((x) => walk(x))];\n }\n const childKey = key === \"where\" ? \"cond\" : key === \"orderBy\" ? \"order\" : key === \"groupBy\" || key === \"select\" || key === \"y\" ? \"field\" : undefined;\n return v.map((x) => walk(x, childKey));\n }\n if (v && typeof v === \"object\") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x, k)]));\n return v;\n };\n const body = walk(d.body) as Draft[\"body\"];\n return changed ? { ...d, body } : null;\n}\n\nconst FIELD_KEYS = new Set([\"field\", \"on\", \"sum\", \"avg\", \"min\", \"max\", \"count\", \"countDistinct\", \"source\", \"target\", \"value\", \"x\", \"y\", \"series\", \"rowKey\"]);\n", "/**\n * The L1 catalog as the model sees it. Kept next to the schema it documents\n * so the two change together; the conductor puts it in the cached system\n * prompt.\n */\nexport const CATALOG_LINE =\n \"catalog: sankey(source,target,value,otherBucket) bar(x,y,series,stacked) line(x,y,series) area(x,y,series) table(columns) kpi(value) grid(rowKey,columns[edit\u2192intent]) actionTable(rowKey,columns,inputs,action\u2192intent) params(bind host.context.*|slider|select|toggle)\";\n\nexport const SPEC_GUIDE = `## Spec format (propose_spec.draft)\n\n{\n \"kind\": \"spec\",\n \"body\": {\n \"component\": \"sankey\" | \"bar\" | \"line\" | \"area\" | \"table\" | \"kpi\" | \"grid\" | \"actionTable\",\n \"title\": { \"<locale>\": \"\u226480 chars\", ... one entry per host locale },\n \"data\": <query>,\n \"encode\": <per component, below>,\n \"params\": { \"<name>\": { \"bind\": \"host.context.<key>\" } | { \"control\": \"slider\", \"label\": {..}, \"min\": n, \"max\": n, \"step\": n, \"default\": n } | { \"control\": \"select\", \"label\": {..}, \"options\": [{ \"value\": v, \"label\": {..} }], \"default\": v } | { \"control\": \"toggle\", \"label\": {..}, \"default\": bool } },\n \"onClick\": { \"navigate\": \"<navigation name>\", \"args\": { \"<arg>\": <argExpr> } },\n \"otherBucket\": { \"maxTargets\": n } // sankey only; bar uses { \"maxCategories\": n }\n },\n \"manifest\": { \"reads\": [exactly the resources the query touches], \"acts\": [exactly the intents the spec invokes] },\n \"placement\": { \"slot\": \"<slot id>\", \"label\": { \"<locale>\": \"\u226440 chars\" } } // label only for page slots such as nav.primary\n}\n\n<query>:\n{\n \"scan\": \"<resource>\",\n \"join\": [{ \"on\": \"<field of scan, or resource.field of an already joined resource>\", \"to\": \"<the resource that field references>\" }],\n \"where\": [[\"<field>\", \"=\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"notIn\", <value>], [\"<field>\", \"match\", [\"Name\", ...]], [\"<field>\", \"isNull\" | \"notNull\"]],\n \"groupBy\": [\"<field>\", ...],\n \"measures\": [{ \"sum\" | \"avg\" | \"min\" | \"max\" | \"count\" | \"countDistinct\": \"<field>\" | \"*\" (count only), \"as\": \"<name>\" }],\n \"select\": [\"<field>\", ...], // instead of groupBy/measures, for plain row lists\n \"orderBy\": [[\"<output column>\", \"asc\" | \"desc\"]],\n \"limit\": <integer, required, \u2264 the resource's row cap>\n}\nField names: unqualified = field of scan; fields of joined resources are qualified (\"products.name\").\nJoins may only follow declared references (fields shown as \"-> resource\"). Each resource joins once.\n<value>: a literal, a list of literals, { \"param\": \"<name>\" } (declared in params), or { \"today\": <days offset> } for dates.\n\"match\" filters take the user's own words for names (e.g. [\"Metro\", \"TABAC\"]); the host resolves them to its real values and asks the user if a name is ambiguous. Use match for any name the user mentions; never guess ids.\nOutput columns are named exactly as written in groupBy/select, plus each measure's \"as\".\n\nencode by component (every referenced name must be an output column):\n- sankey: { \"source\": col, \"target\": col, \"value\": number col, \"label\": \"value\" | \"share-of-source\" | \"share-of-total\" }\n- bar: { \"x\": col, \"y\": number col | [number cols], \"series\": col?, \"stacked\": bool?, \"horizontal\": bool? }\n- line, area: { \"x\": col, \"y\": number col | [number cols], \"series\": col? }\n- table: { \"columns\": [{ \"field\": col, \"label\": {..}?, \"format\": \"number\"|\"money\"|\"percent\"|\"date\"|\"month\"|\"text\"? }] }\n- kpi: { \"value\": number col } \u2014 query has measures and no groupBy\n- grid: { \"rowKey\": col, \"columns\": [{ \"field\": col, \"label\"?, \"format\"?, \"edit\": { \"intent\": \"<intent>\", \"value\": \"<arg that receives the edited value>\", \"args\": { \"<arg>\": <argExpr> } }? }] }\n- actionTable: { \"rowKey\": col, \"columns\": [...], \"inputs\": [{ \"name\": id, \"label\": {..}, \"type\": \"number\"|\"text\", \"default\"?, \"min\"?, \"max\"? }], \"action\": { \"intent\": \"<intent>\", \"label\": {..}, \"args\": { \"<arg>\": <argExpr> } } }\n One intent call per selected row; the host shows one confirmation for the whole batch.\n\n<argExpr>: { \"field\": col } | { \"input\": \"<row input name>\" } | { \"param\": \"<name>\" } | { \"literal\": v | [v] } | { \"today\": days } | { \"template\": \"text with {col} placeholders\" } | { \"list\": [<argExpr>, ...] }\n\nNever put HTML, CSS, URLs or scripts in any string. Do not write descriptions: the host generates the card text from the spec.`;\n", "import { z } from \"zod\";\nimport { DraftSchema } from \"./schema\";\nimport { AutomationSchema } from \"./automation\";\n\n/**\n * Wire protocol between the composer (host origin) and the conductor\n * (Bisque cloud). Every field here crosses the custody boundary, so each one\n * is listed in Table 1b of the paper and nothing else may be added casually.\n */\nconst ContextValue = z.union([z.string().max(64), z.number(), z.boolean(), z.null()]);\n\nexport const ProposeRequestSchema = z\n .object({\n /** What the user typed: their own disclosure (\u00A73.4). */\n prompt: z.string().min(1).max(4000),\n context: z\n .object({\n page: z.string().max(200).optional(),\n slot: z.string().max(80).optional(),\n locale: z.string().max(10),\n /** Only keys the contract declares in `context`; the conductor rejects others. */\n values: z.record(z.string().max(40), ContextValue).default({}),\n })\n .strict(),\n contract: z.object({ app: z.string().max(80), version: z.string().max(40), hash: z.string().regex(/^[0-9a-f]{64}$/) }).strict(),\n /** Prior turns as text the user typed and short assistant replies; no data. */\n history: z\n .array(z.object({ role: z.enum([\"user\", \"assistant\"]), text: z.string().max(4000) }).strict())\n .max(20)\n .default([]),\n /** The draft being refined, when the user is revising a proposal or a saved artifact. */\n current: DraftSchema.optional(),\n /** Values of fields the host marks `values: \"share\"` (P1 exception a), keyed `resource.field`. */\n sharedValues: z.record(z.string().max(80), z.array(z.string().max(120)).max(500)).optional(),\n /**\n * Current values of the contract's theme tokens, sent only when the host\n * lets users change the theme by asking. Host settings, not records:\n * typed colours, lengths and options.\n */\n theme: z.record(z.string().max(40), z.string().max(64)).optional(),\n /**\n * True when the host takes automation proposals here and this user may\n * make them. Absent or false: the conductor answers schedule and\n * delivery requests with explain_limit.\n */\n automations: z.boolean().optional(),\n /** The automation being refined, when the user is revising one. */\n currentAutomation: AutomationSchema.optional(),\n })\n .strict();\nexport type ProposeRequest = z.input<typeof ProposeRequestSchema>;\n\nexport type ProposeResponse =\n | { type: \"proposal\"; proposalId: string; draft: z.infer<typeof DraftSchema>; repaired: boolean; note?: string }\n | { type: \"theme\"; proposalId: string; tokens: Record<string, string>; repaired: boolean; note?: string }\n | { type: \"automation\"; proposalId: string; automation: z.infer<typeof AutomationSchema>; repaired: boolean; note?: string }\n | { type: \"ask\"; question: string; options: string[] }\n | { type: \"answer\"; text: string }\n | { type: \"limit\"; message: string; capability: string; nearest?: string }\n | { type: \"error\"; message: string; problems?: { path: string; message: string }[] };\n\nexport type DiagnosticsResponse = { type: \"ok\"; note?: string } | Extract<ProposeResponse, { type: \"proposal\" | \"error\" }>;\n\nexport const PushRequestSchema = z\n .object({\n manifest: z.record(z.string(), z.unknown()),\n review: z.object({ contractHash: z.string().regex(/^[0-9a-f]{64}$/), signer: z.string().min(1).max(200), signedAt: z.string() }).passthrough(),\n })\n .strict();\nexport type PushRequest = z.infer<typeof PushRequestSchema>;\n", "import { z } from \"zod\";\nimport { BisqueError, canonicalJson, nest, problem, type Problem, type Role } from \"@crasi/bisque-core\";\nimport { canAutomate, canAutomateIntent, channelLabel, type ContractManifest } from \"@crasi/bisque-contract\";\nimport { IRSchema, runIR, validateIR, zodProblems, type Column, type IR, type QueryResult, type Row } from \"@crasi/bisque-ir\";\nimport { evalArgs } from \"./args\";\nimport { describeDraft, localize } from \"./describe\";\nimport { Args, Format, Label, Title, type ArgExpr, type Draft } from \"./schema\";\nimport { unsafeTextProblems } from \"./validate\";\n\n/**\n * Automations: saved rules the host runs on its own server, on a schedule.\n * \"Every morning, email me critical cards that have been open for more than\n * a week.\" An automation is data, like a spec: a query (what to look for),\n * a schedule (when to look), and what to do: tell the owner on a channel the\n * host declared, call an intent the host marked `automate`, or a short\n * workflow of several intents per row followed by one message.\n *\n * Custody is unchanged. The model proposes the rule from the contract; the\n * host's scheduler loads rows, runs the query and delivers, and the rows\n * never leave the host. Delivery is always to the automation's owner: the\n * rule names a channel, never an address.\n */\n\nexport const WEEKDAYS = [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"] as const;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\nexport const ScheduleSchema = z.discriminatedUnion(\"every\", [\n z.object({ every: z.literal(\"hour\") }).strict(),\n z.object({ every: z.literal(\"day\"), at: z.number().int().min(0).max(23).optional() }).strict(),\n z.object({ every: z.literal(\"weekday\"), at: z.number().int().min(0).max(23).optional() }).strict(),\n z.object({ every: z.literal(\"week\"), on: z.enum(WEEKDAYS), at: z.number().int().min(0).max(23).optional() }).strict(),\n z.object({ every: z.literal(\"month\"), day: z.number().int().min(1).max(28), at: z.number().int().min(0).max(23).optional() }).strict(),\n]);\nexport type Schedule = z.infer<typeof ScheduleSchema>;\n\nconst AutoColumn = z.object({ field: z.string(), label: Label.optional(), format: Format.optional() }).strict();\n\nexport const AutomationActionSchema = z.union([\n /** Tell the owner, on a channel the host declares (`email`). */\n z.object({ notify: z.string().max(40) }).strict(),\n /** Call an intent the host marked `automate`, once per reported row. */\n z.object({ intent: z.string().max(80), args: Args }).strict(),\n]);\nexport type AutomationAction = z.infer<typeof AutomationActionSchema>;\n\n/** Most steps in one workflow. */\nexport const MAX_STEPS = 4;\n\n/**\n * One action, or a workflow: intents run in order for each row, a row moves\n * on only when the step before it succeeded, and an optional last `notify`\n * reports the rows that made it through every step.\n */\nexport const AutomationThenSchema = z.union([AutomationActionSchema, z.array(AutomationActionSchema).min(1).max(MAX_STEPS)]);\n\n/** An automation's steps as a list, whichever form `then` was written in. */\nexport function automationSteps(a: Pick<Automation, \"then\">): AutomationAction[] {\n return Array.isArray(a.then) ? a.then : [a.then];\n}\n\ntype IntentStep = Extract<AutomationAction, { intent: string }>;\ntype NotifyStep = Extract<AutomationAction, { notify: string }>;\nconst isNotify = (s: AutomationAction): s is NotifyStep => \"notify\" in s;\n\nexport const AutomationSchema = z\n .object({\n kind: z.literal(\"automation\"),\n title: Title,\n /** When to look. */\n schedule: ScheduleSchema,\n /** What to look for: the rows this query returns are the rows the automation reports. */\n data: IRSchema,\n /**\n * `rows`: act only when the query returns rows to report.\n * `always`: deliver every time, even \"nothing today\" (a digest). Notify only.\n */\n when: z.enum([\"rows\", \"always\"]),\n /**\n * `new`: report a row once, the first time it matches (needs `key`).\n * `all`: report every matching row every time.\n */\n repeat: z.enum([\"new\", \"all\"]),\n /** Output column that identifies a row, for `repeat: \"new\"`. */\n key: z.string().optional(),\n /** What a notification shows, in order. */\n columns: z.array(AutoColumn).min(1).max(8),\n then: AutomationThenSchema,\n manifest: z\n .object({\n reads: z.array(z.string()).max(12),\n acts: z.array(z.string()).max(MAX_STEPS),\n channels: z.array(z.string()).max(1),\n })\n .strict(),\n })\n .strict();\nexport type Automation = z.infer<typeof AutomationSchema>;\n\nexport type AutomationValidation = { ok: boolean; problems: Problem[]; automation?: Automation; columns: Record<string, Column> };\n\n/** Most rows one run reports or acts on; the rest wait for the next run (`repeat: \"new\"`) or are counted. */\nexport const MAX_REPORTED_ROWS = 50;\n\n/**\n * The host-side validator for automations: same authority as\n * `validateDraft` (Invariant 3). The conductor runs it for its repair turn;\n * the composer runs it before Apply; the host's runner runs it again before\n * every run, against the contract and the owner's role as they are then.\n */\nexport function validateAutomation(input: unknown, m: ContractManifest, opts: { role: Role }): AutomationValidation {\n const out: AutomationValidation = { ok: false, problems: [], columns: {} };\n const P = out.problems;\n if (!m.automations) {\n P.push(problem(\"\", \"deferred\", \"this app does not run automations: it declares no automations block\"));\n return out;\n }\n P.push(...unsafeTextProblems(input));\n const parsed = AutomationSchema.safeParse(input);\n if (!parsed.success) {\n P.push(...zodProblems(parsed.error));\n return out;\n }\n const a = parsed.data;\n out.automation = a;\n if (!canAutomate(m, opts.role)) P.push(problem(\"\", \"role_denied\", `role ${opts.role} cannot create automations`));\n\n // Schedule: hours only when the host's scheduler runs hourly.\n if (m.automations.cadence === \"day\") {\n if (a.schedule.every === \"hour\") P.push(problem(\"schedule.every\", \"schema\", \"this app checks automations once a day; use day, weekday, week or month\"));\n if (\"at\" in a.schedule && a.schedule.at !== undefined) P.push(problem(\"schedule.at\", \"schema\", \"this app checks automations once a day, in the morning; leave out at\"));\n }\n\n // Data: the same query rules as a view, with the owner's role.\n const v = validateIR(a.data, m, { reads: a.manifest.reads, role: opts.role });\n P.push(...nest(\"data\", v.problems));\n out.columns = v.columns;\n for (const r of a.manifest.reads)\n if (!v.touched.includes(r)) P.push(problem(\"manifest.reads\", \"unused_read\", `declares ${r} but never reads it; list exactly what the query touches`));\n if (v.params.length) P.push(problem(\"data\", \"unknown_param\", \"an automation runs on its own, with no page to follow: use fixed values or {today: n}, not params\"));\n if (v.ir) {\n a.columns.forEach((c, i) => {\n if (!v.columns[c.field]) P.push(problem(`columns.${i}.field`, \"encode\", `\"${c.field}\" is not a column of the query (columns: ${Object.keys(v.columns).join(\", \")})`));\n });\n if (a.key && !v.columns[a.key]) P.push(problem(\"key\", \"encode\", `\"${a.key}\" is not a column of the query`));\n }\n if (a.repeat === \"new\" && !a.key) P.push(problem(\"key\", \"schema\", 'repeat \"new\" needs key: the column that identifies a row, such as id'));\n\n // Steps: declared channels, and intents the host lets run unattended.\n const steps = automationSteps(a);\n const at = (i: number) => (Array.isArray(a.then) ? `then.${i}` : \"then\");\n const intents = steps.filter((x): x is IntentStep => !isNotify(x));\n const notifies = steps.filter(isNotify);\n if (notifies.length > 1) P.push(problem(\"then\", \"schema\", \"a workflow sends at most one message: keep one notify step\"));\n if (notifies.length && !isNotify(steps[steps.length - 1]))\n P.push(problem(\"then\", \"schema\", \"notify must be the last step: it reports the rows that went through the steps before it\"));\n if (a.when === \"always\" && !notifies.length) P.push(problem(\"when\", \"schema\", 'when \"always\" is for notifications; an intent runs only for rows'));\n steps.forEach((step, i) => {\n if (isNotify(step)) {\n if (!m.automations?.channels[step.notify])\n P.push(problem(`${at(i)}.notify`, \"unknown_field\", `unknown channel \"${step.notify}\" (channels: ${Object.keys(m.automations?.channels ?? {}).join(\", \") || \"none\"})`));\n return;\n }\n const name = step.intent;\n const intent = m.intents[name];\n if (!intent) P.push(problem(`${at(i)}.intent`, \"unknown_intent\", `unknown intent \"${name}\"`));\n else if (!intent.automate) P.push(problem(`${at(i)}.intent`, \"role_denied\", `${name} is not marked automate in the contract, so it only runs when a person clicks`));\n else if (!canAutomateIntent(m, opts.role, name)) P.push(problem(`${at(i)}.intent`, \"role_denied\", `role ${opts.role} cannot use ${name} in an automation`));\n if (intent) {\n const props = Object.keys((intent.args.properties ?? {}) as Record<string, unknown>);\n const required = (intent.args.required ?? []) as string[];\n for (const k of Object.keys(step.args)) if (!props.includes(k)) P.push(problem(`${at(i)}.args.${k}`, \"schema\", `unknown argument \"${k}\" (arguments: ${props.join(\", \")})`));\n for (const r of required) if (!(r in step.args)) P.push(problem(`${at(i)}.args`, \"schema\", `missing argument \"${r}\"`));\n for (const [k, e] of Object.entries(step.args)) argProblems(e, `${at(i)}.args.${k}`, v.columns, P);\n }\n });\n const acts = [...new Set(intents.map((x) => x.intent))];\n const channels = notifies.map((x) => x.notify);\n if (a.manifest.acts.join() !== acts.join())\n P.push(problem(\"manifest.acts\", \"undeclared_act\", `manifest.acts must be ${JSON.stringify(acts)}: the intents the steps call, in order`));\n if (a.manifest.channels.join() !== channels.join()) P.push(problem(\"manifest.channels\", \"undeclared_act\", `manifest.channels must be ${JSON.stringify(channels)}`));\n\n if (!a.title[m.defaultLocale]) P.push(problem(\"title\", \"locale\", `title needs a ${m.defaultLocale} entry`));\n out.ok = P.length === 0;\n return out;\n}\n\nfunction argProblems(e: ArgExpr, path: string, columns: Record<string, Column>, P: Problem[]) {\n if (\"field\" in e && !columns[e.field]) P.push(problem(path, \"encode\", `\"${e.field}\" is not a column of the query`));\n if (\"input\" in e || \"param\" in e) P.push(problem(path, \"schema\", \"an automation has no inputs or params; use field, literal, today or template\"));\n if (\"template\" in e) for (const m of e.template.matchAll(/\\{([^}]+)\\}/g)) if (!columns[m[1]]) P.push(problem(path, \"encode\", `\"${m[1]}\" is not a column of the query`));\n if (\"list\" in e) e.list.forEach((x, i) => argProblems(x, `${path}.list.${i}`, columns, P));\n}\n\n// \u2500\u2500 Words \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst DAY_NAMES: Record<Weekday, string> = { mon: \"Monday\", tue: \"Tuesday\", wed: \"Wednesday\", thu: \"Thursday\", fri: \"Friday\", sat: \"Saturday\", sun: \"Sunday\" };\nconst ordinal = (n: number) => `${n}${n % 10 === 1 && n !== 11 ? \"st\" : n % 10 === 2 && n !== 12 ? \"nd\" : n % 10 === 3 && n !== 13 ? \"rd\" : \"th\"}`;\n\n/** \"Every Monday at 09:00 (Europe/Bucharest)\", \"Every weekday morning\". */\nexport function describeSchedule(s: Schedule, m: ContractManifest): string {\n if (s.every === \"hour\") return \"Every hour\";\n const hour = \"at\" in s ? s.at : undefined;\n const daily = m.automations?.cadence !== \"hour\";\n const when = hour === undefined && daily ? \" morning\" : ` at ${String(hour ?? 0).padStart(2, \"0\")}:00 (${m.automations?.timeZone ?? \"UTC\"})`;\n switch (s.every) {\n case \"day\":\n return when === \" morning\" ? \"Every morning\" : `Every day${when}`;\n case \"weekday\":\n return `Every weekday${when}`;\n case \"week\":\n return `Every ${DAY_NAMES[s.on]}${when}`;\n case \"month\":\n return `On the ${ordinal(s.day)} of every month${when === \" morning\" ? \", in the morning\" : when}`;\n }\n}\n\n/** The automation's query as a table: for the card text and the composer's preview. */\nexport function automationAsDraft(a: Automation): Draft {\n return {\n kind: \"spec\",\n body: { component: \"table\", title: a.title, data: a.data, encode: { columns: a.columns } },\n manifest: { reads: a.manifest.reads, acts: [] },\n placement: { slot: \"automation\" },\n };\n}\n\nexport type AutomationDescription = { title: string; lines: string[]; reads: string[]; changes: string[] };\n\n/**\n * The card text, generated by code (Invariant 4): what it looks for, when,\n * and what it does. The model never writes it.\n */\nexport function describeAutomation(a: Automation, m: ContractManifest, opts: { locale?: string } = {}): AutomationDescription {\n const locale = opts.locale ?? m.defaultLocale;\n const d = describeDraft(automationAsDraft(a), m, { locale });\n const looks = d.lines[0].replace(/\\.$/, \"\");\n const lines = [`${describeSchedule(a.schedule, m)}, checks: ${looks.charAt(0).toLowerCase()}${looks.slice(1)}.`];\n const changes: string[] = [];\n const steps = automationSteps(a);\n const notify = steps.find(isNotify);\n const intents = steps.filter((x): x is IntentStep => !isNotify(x));\n const each = a.repeat === \"new\" ? \"new \" : \"\";\n const labelOf = (name: string) => {\n const i = m.intents[name];\n return typeof i?.label === \"string\" ? i.label : i?.label ? localize(i.label, locale, m.defaultLocale) : name;\n };\n if (intents.length) {\n const labels = intents.map((x) => labelOf(x.intent));\n lines.push(`For each ${each}matching row, runs ${labels.join(\", then \")} without asking.`);\n if (intents.length > 1) lines.push(\"A row goes to the next step only when the one before it succeeded; one that fails resumes there on the next run.\");\n for (const l of labels) changes.push(`${l} for each ${each}row, unattended`);\n }\n if (notify) {\n const ch = channelLabel(m, notify.notify);\n if (intents.length) lines.push(`${a.when === \"always\" ? \"Every time, even when there were none, sends\" : \"Then sends\"} you the rows it handled by ${ch}.`);\n else if (a.when === \"always\")\n lines.push(`Sends you ${a.repeat === \"new\" ? \"the rows that are new since last time\" : \"the matching rows\"} by ${ch} every time, even when there are none.`);\n else lines.push(`If ${a.repeat === \"new\" ? \"any row is new since last time\" : \"any rows match\"}, sends ${a.repeat === \"new\" ? \"them\" : \"them all\"} to you by ${ch}.`);\n changes.push(`Sends ${ch} to you only`);\n }\n if (a.repeat === \"new\") lines.push(\"A row is reported once, the first time it matches.\");\n const cap = Math.min(MAX_REPORTED_ROWS, ...intents.map((x) => m.intents[x.intent]?.batch ?? 1));\n lines.push(`At most ${cap} ${cap === 1 ? \"row\" : \"rows\"} per run.`);\n return { title: localize(a.title, locale, m.defaultLocale), lines, reads: d.reads, changes };\n}\n\n// \u2500\u2500 Schedule \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ntype Local = { date: string; hour: number; weekday: Weekday };\n\nfunction localParts(at: Date, timeZone: string): Local {\n const f = new Intl.DateTimeFormat(\"en-CA\", { timeZone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\", hour: \"2-digit\", hourCycle: \"h23\", weekday: \"short\" });\n const parts = Object.fromEntries(f.formatToParts(at).map((p) => [p.type, p.value]));\n return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) % 24, weekday: parts.weekday.toLowerCase().slice(0, 3) as Weekday };\n}\n\nfunction shiftDate(date: string, days: number): { date: string; weekday: Weekday } {\n const d = new Date(`${date}T00:00:00Z`);\n d.setUTCDate(d.getUTCDate() + days);\n return { date: d.toISOString().slice(0, 10), weekday: WEEKDAYS[(d.getUTCDay() + 6) % 7] };\n}\n\n/** `YYYY-MM-DDTHH` of the most recent scheduled run at or before `now`, in the host's zone. */\nexport function lastSlot(s: Schedule, now: Date, timeZone = \"UTC\"): string {\n const here = localParts(now, timeZone);\n const key = (date: string, hour: number) => `${date}T${String(hour).padStart(2, \"0\")}`;\n if (s.every === \"hour\") return key(here.date, here.hour);\n const at = s.at ?? 0;\n for (let back = 0; back < 40; back++) {\n const { date, weekday } = shiftDate(here.date, -back);\n if (back === 0 && here.hour < at) continue;\n const ok =\n s.every === \"day\" ||\n (s.every === \"weekday\" && ![\"sat\", \"sun\"].includes(weekday)) ||\n (s.every === \"week\" && weekday === s.on) ||\n (s.every === \"month\" && Number(date.slice(8, 10)) === s.day);\n if (ok) return key(date, at);\n }\n return key(here.date, at);\n}\n\n/**\n * Whether an automation should run now: its most recent slot is later than\n * its last run (or, before its first run, than when it was created). A\n * scheduler that ticks late or misses a tick catches up once, not once per\n * missed slot.\n */\nexport function isDue(s: Schedule, opts: { now: Date; lastRunAt?: string | null; createdAt: string; timeZone?: string }): boolean {\n const tz = opts.timeZone ?? \"UTC\";\n const slot = lastSlot(s, opts.now, tz);\n const since = localParts(new Date(opts.lastRunAt ?? opts.createdAt), tz);\n // Created during the current slot's hour counts as already seen: the first run waits for the next slot.\n return `${since.date}T${String(since.hour).padStart(2, \"0\")}` < slot;\n}\n\n// \u2500\u2500 Running \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** What the host keeps per automation between runs. */\nexport type AutomationState = {\n lastRunAt?: string;\n /** Keys already reported, newest last; bounded. */\n seen?: string[];\n lastStatus?: \"sent\" | \"acted\" | \"quiet\" | \"broken\" | \"error\";\n lastMessage?: string;\n lastCount?: number;\n /** Workflow rows that stopped at a failed step: row key \u2192 index of the step to resume at. */\n progress?: Record<string, number>;\n /** Runs in a row that ended in \"error\"; reset by any run that does not. */\n failures?: number;\n};\n\n/** Runs in a row that must fail before the owner is told. */\nexport const ALERT_AFTER_FAILURES = 3;\n\n/**\n * Something the owner should hear about, returned once per episode: when a\n * rule turns broken, and when it has failed ALERT_AFTER_FAILURES runs in a\n * row. The host delivers it to the owner however it likes (it is not the\n * automation's own channel, which an intent-only rule does not have).\n */\nexport type AutomationAlert = { kind: \"broken\" | \"failing\"; automationId: string; title: string; message: string };\n\n/** One delivery, for the host's channel to render. Rows are the host's own, and go only to the owner. */\nexport type AutomationMessage = {\n channel: string;\n automationId: string;\n title: string;\n /** The card text, so the message says why it was sent. */\n lines: string[];\n columns: { field: string; label: string; format?: string }[];\n rows: Row[];\n /** Matching rows in all, before `repeat` and the per-run cap. */\n matched: number;\n /** Rows not shown because of the per-run cap. */\n more: number;\n};\n\nexport type RunnableAutomation = {\n id: string;\n /** The owner's role at run time, from the host, never from the automation. */\n role: Role;\n automation: unknown;\n createdAt: string;\n state?: AutomationState;\n};\n\nexport type RunAutomationOptions = {\n manifest: ContractManifest;\n now?: Date;\n /** Rows of one resource for the owner, scoped and capped by the host, as for `serveQuery`. Give this or `query`. */\n load?: (resource: string) => Promise<Row[]>;\n /**\n * Runs the automation's validated query as the owner, in place of `load`,\n * for hosts whose data is in a database: `(ir, { today }) => runSql(ir, { ...db, manifest, today })`\n * with `runSql` from @crasi/bisque-sql. `today` is the owner's date in the contract's time zone.\n */\n query?: (ir: IR, opts: { today: string }) => Promise<QueryResult>;\n /** Delivers a message on one of the contract's channels, to the owner. */\n notify?: (message: AutomationMessage) => Promise<void>;\n /** Calls an intent as the owner, through the host's own write path. */\n act?: (intent: string, args: Record<string, unknown>) => Promise<{ ok: boolean; message?: string }>;\n /** Run even if not due (a \"Run now\" button). */\n force?: boolean;\n locale?: string;\n};\n\nexport type RunOutcome = { ran: boolean; state: AutomationState; problems?: Problem[]; alert?: AutomationAlert };\n\nconst MAX_SEEN = 2000;\n\n/**\n * Runs one automation if it is due, on the host's server. Re-validates it\n * against the contract and role as they are now; a rule that no longer\n * fits is marked broken and does nothing. Returns the state to store.\n */\nexport async function runAutomation(r: RunnableAutomation, opts: RunAutomationOptions): Promise<RunOutcome> {\n const out = await runOnce(r, opts);\n const before = r.state ?? {};\n const s = out.state;\n if (s.lastStatus === \"broken\") {\n if (before.lastStatus !== \"broken\") out.alert = { kind: \"broken\", automationId: r.id, title: titleOf(r.automation, opts), message: s.lastMessage ?? \"\" };\n return out;\n }\n if (!out.ran) return out;\n s.failures = s.lastStatus === \"error\" ? (before.failures ?? 0) + 1 : undefined;\n if (s.failures === ALERT_AFTER_FAILURES) out.alert = { kind: \"failing\", automationId: r.id, title: titleOf(r.automation, opts), message: s.lastMessage ?? \"\" };\n return out;\n}\n\nfunction titleOf(a: unknown, opts: RunAutomationOptions): string {\n const m = opts.manifest;\n const t = (a as { title?: unknown } | null)?.title;\n if (t && typeof t === \"object\") return localize(t as Record<string, string>, opts.locale ?? m.defaultLocale, m.defaultLocale) || \"Automation\";\n return \"Automation\";\n}\n\nasync function queryRows(ir: IR, today: string, opts: RunAutomationOptions): Promise<QueryResult> {\n if (opts.query) return opts.query(ir, { today });\n const load = opts.load;\n if (!load) throw new BisqueError(\"runAutomation needs load or query\");\n const touched = [ir.scan, ...(ir.join ?? []).map((j) => j.to)];\n const loaded = new Map<string, Row[]>();\n await Promise.all(touched.map(async (res) => loaded.set(res, await load(res))));\n return runIR(\n ir,\n (res) => {\n const rows = loaded.get(res);\n if (!rows) throw new BisqueError(`resource ${res} was not loaded`);\n return rows;\n },\n { manifest: opts.manifest, today },\n );\n}\n\nasync function runOnce(r: RunnableAutomation, opts: RunAutomationOptions): Promise<RunOutcome> {\n const m = opts.manifest;\n const now = opts.now ?? new Date();\n const state: AutomationState = { ...r.state };\n const v = validateAutomation(r.automation, m, { role: r.role });\n if (!v.ok || !v.automation) {\n return {\n ran: false,\n state: {\n ...state,\n lastStatus: \"broken\",\n lastMessage: v.problems\n .map((p) => p.message)\n .join(\"; \")\n .slice(0, 500),\n },\n problems: v.problems,\n };\n }\n const a = v.automation;\n const tz = m.automations?.timeZone ?? \"UTC\";\n if (!opts.force && !isDue(a.schedule, { now, lastRunAt: state.lastRunAt, createdAt: r.createdAt, timeZone: tz })) return { ran: false, state };\n\n const done = (s: Partial<AutomationState>): RunOutcome => ({ ran: true, state: { ...state, ...s, lastRunAt: now.toISOString() } });\n try {\n const today = localParts(now, tz).date;\n const result = await queryRows(a.data, today, opts);\n\n const keyOf = (row: Row) => (a.key ? String(row[a.key] ?? \"\") : canonicalJson(row));\n const seen = new Set(state.seen ?? []);\n const fresh = a.repeat === \"new\" ? result.rows.filter((row) => !seen.has(keyOf(row))) : result.rows;\n const report = fresh.slice(0, MAX_REPORTED_ROWS);\n const nextSeen = a.repeat === \"new\" ? [...(state.seen ?? []), ...report.map(keyOf)].slice(-MAX_SEEN) : state.seen;\n\n if (!report.length && a.when === \"rows\") return done({ lastStatus: \"quiet\", lastCount: 0, lastMessage: undefined, seen: nextSeen });\n\n const steps = automationSteps(a);\n const notify = steps.find(isNotify);\n const intents = steps.filter((x): x is IntentStep => !isNotify(x));\n const sendTo = async (rows: Row[]) => {\n if (!notify) return;\n if (!opts.notify) throw new BisqueError(\"this host has no channel sender\");\n const d = describeAutomation(a, m, { locale: opts.locale });\n const columns = a.columns.map((c) => ({\n field: c.field,\n label: c.label ? localize(c.label, opts.locale ?? m.defaultLocale, m.defaultLocale) : columnLabel(v.columns[c.field], c.field),\n format: c.format,\n }));\n await opts.notify({ channel: notify.notify, automationId: r.id, title: d.title, lines: d.lines, columns, rows, matched: result.total, more: fresh.length - rows.length });\n };\n\n if (!intents.length) {\n await sendTo(report);\n return done({ lastStatus: \"sent\", lastCount: report.length, lastMessage: undefined, seen: nextSeen, progress: undefined });\n }\n\n if (!opts.act) throw new BisqueError(\"this host cannot run intents from automations\");\n // The smallest batch of any step bounds how many rows one run takes on.\n const cap = Math.min(...intents.map((x) => m.intents[x.intent]?.batch ?? 1), MAX_REPORTED_ROWS);\n const batch = report.slice(0, cap);\n const progress: Record<string, number> = { ...state.progress };\n const failed: string[] = [];\n const finished: Row[] = [];\n for (const row of batch) {\n const k = keyOf(row);\n let step = progress[k] ?? 0;\n for (; step < intents.length; step++) {\n const res = await opts.act(intents[step].intent, evalArgs(intents[step].args, { row, today }));\n if (!res.ok) {\n failed.push(res.message ?? \"failed\");\n break;\n }\n }\n if (step < intents.length) progress[k] = step;\n else {\n delete progress[k];\n finished.push(row);\n }\n }\n // Only rows that went through every step count as seen: a failed row resumes at its failed step next run.\n const finishedKeys = finished.map(keyOf);\n const seenAfter = a.repeat === \"new\" ? [...(state.seen ?? []), ...finishedKeys].slice(-MAX_SEEN) : state.seen;\n // Rows that left the query (closed by hand, say) need no resuming.\n const live = new Set(result.rows.map(keyOf));\n for (const k of Object.keys(progress)) if (!live.has(k)) delete progress[k];\n if (notify && (finished.length || a.when === \"always\")) await sendTo(finished);\n return done({\n lastStatus: failed.length ? \"error\" : notify && (finished.length || a.when === \"always\") ? \"sent\" : \"acted\",\n lastCount: finished.length,\n lastMessage: failed.length ? `${failed.length} of ${batch.length} failed: ${failed[0]}`.slice(0, 500) : undefined,\n seen: seenAfter,\n progress: Object.keys(progress).length ? progress : undefined,\n });\n } catch (e) {\n const problems = e instanceof BisqueError ? e.problems : [];\n return { ran: true, state: { ...state, lastRunAt: now.toISOString(), lastStatus: \"error\", lastMessage: (e instanceof Error ? e.message : String(e)).slice(0, 500) }, problems };\n }\n}\n\nfunction columnLabel(c: Column | undefined, field: string): string {\n if (c?.label) return c.label;\n const base = field.includes(\".\") ? field.slice(field.indexOf(\".\") + 1) : field;\n return base.replace(/_/g, \" \");\n}\n\n/** Text for the conductor's prompt: the automation format. Only sent to hosts that declare automations. */\nexport const AUTOMATION_GUIDE = `## Automation format (propose_automation.automation)\n\n{\n \"kind\": \"automation\",\n \"title\": { \"<locale>\": \"\u226480 chars\", ... },\n \"schedule\": { \"every\": \"day\" } | { \"every\": \"weekday\" } | { \"every\": \"week\", \"on\": \"mon\"|\"tue\"|\"wed\"|\"thu\"|\"fri\"|\"sat\"|\"sun\" } | { \"every\": \"month\", \"day\": 1-28 } | { \"every\": \"hour\" },\n // add \"at\": 0-23 (hour) only when the reference says automations are checked every hour\n \"data\": <query>, // same query format as a spec; no params: use { \"today\": n } for relative dates\n \"when\": \"rows\" | \"always\", // rows: only when there is something to report; always: a digest every time (notify only)\n \"repeat\": \"new\" | \"all\", // new: report each row once, the first time it matches; all: every matching row every time\n \"key\": \"<output column that identifies a row, e.g. id>\", // required for repeat \"new\"\n \"columns\": [{ \"field\": col, \"label\"?: {..}, \"format\"?: \"number\"|\"money\"|\"percent\"|\"date\"|\"month\"|\"text\" }], // what the message shows, 1-8\n \"then\": <step> | [<step>, ...], // one step, or a workflow of up to 4: intents run in order per row, then at most one notify, last\n // <step>: { \"notify\": \"<channel>\" } | { \"intent\": \"<automatable intent>\", \"args\": { \"<arg>\": <argExpr without input/param> } }\n \"manifest\": { \"reads\": [resources the query touches], \"acts\": [the intents the steps call, in order, no repeats], \"channels\": [the notify step's channel, if any] }\n}\nNotifications always go to the user who owns the automation; never ask for or write an address.\n\"for more than N days\" on a date field is [\"<field>\", \"<\", { \"today\": -N }]. Prefer repeat \"new\" with key \"id\" for alerts, so the user is told once per row.\n\"Do X, then email me\" is a workflow: [{ \"intent\": \"x\", ... }, { \"notify\": \"email\" }]; the message lists the rows every intent step succeeded for.`;\n\n/** Equality of two automations as saved data (for \"no change\" checks). */\nexport function sameAutomation(a: Automation, b: Automation): boolean {\n return canonicalJson(a) === canonicalJson(b);\n}\n", "import { problem, type Problem, type Role } from \"@crasi/bisque-core\";\nimport { canWorkspace, themeLabel, type ContractManifest } from \"@crasi/bisque-contract\";\n\n/**\n * Theme proposals: the user asks \"use our company colours\" and the model\n * proposes values for the host's declared theme tokens. A token is a name\n * and a typed value (colour, length or one of a list), never CSS text\n * (Invariant 7), so nothing a model or a user supplies can become a\n * selector, a URL or a property. The host turns validated values into\n * styles itself.\n *\n * Changing the theme is a workspace-wide change, so it needs a role that\n * `canWorkspace` allows.\n */\nexport type ThemeTokens = Record<string, string>;\n\nexport const THEME_COLOR = /^(#[0-9a-f]{3,4}|#[0-9a-f]{6}|#[0-9a-f]{8}|(rgb|hsl)a?\\(\\s*[\\d.]+%?\\s*,?\\s*[\\d.]+%?\\s*,?\\s*[\\d.]+%?\\s*([,/]\\s*[\\d.]+%?\\s*)?\\))$/i;\nexport const THEME_LENGTH = /^\\d{1,3}(\\.\\d{1,2})?(px|rem|em)$/;\nconst MAX_TOKENS = 32;\n\n/** Whether one value fits its token's declared type. */\nexport function themeValueOk(m: ContractManifest, token: string, value: unknown): boolean {\n const t = m.theme?.[token];\n if (!t || typeof value !== \"string\" || value.length > 64) return false;\n if (t === \"color\") return THEME_COLOR.test(value);\n if (t === \"length\") return THEME_LENGTH.test(value);\n return Array.isArray(t) && t.includes(value);\n}\n\nexport type ThemeValidation = { ok: boolean; problems: Problem[]; tokens: ThemeTokens };\n\nexport function validateThemeTokens(input: unknown, m: ContractManifest, opts: { role: Role }): ThemeValidation {\n const P: Problem[] = [];\n const tokens: ThemeTokens = {};\n const declared = Object.keys(m.theme ?? {});\n if (!declared.length) return { ok: false, problems: [problem(\"\", \"deferred\", \"this app declares no theme tokens, so its look cannot be changed by asking\")], tokens };\n if (!input || typeof input !== \"object\" || Array.isArray(input))\n return { ok: false, problems: [problem(\"tokens\", \"schema\", \"tokens must be an object of token name to value\")], tokens };\n const entries = Object.entries(input as Record<string, unknown>);\n if (!entries.length) P.push(problem(\"tokens\", \"schema\", \"propose at least one token\"));\n if (entries.length > MAX_TOKENS) P.push(problem(\"tokens\", \"limit\", `at most ${MAX_TOKENS} tokens`));\n for (const [k, v] of entries) {\n const path = `tokens.${k}`;\n const t = m.theme[k];\n if (!t) {\n P.push(problem(path, \"unknown_field\", `\"${k}\" is not a theme token (tokens: ${declared.join(\", \")})`));\n continue;\n }\n if (!themeValueOk(m, k, v)) {\n const want = Array.isArray(t) ? `one of ${t.join(\", \")}` : t === \"color\" ? \"a hex colour like #0f5c8a\" : \"a length like 8px\";\n P.push(problem(path, \"type\", `${k} must be ${want}`));\n continue;\n }\n tokens[k] = v as string;\n }\n if (!canWorkspace(m, opts.role)) P.push(problem(\"\", \"role_denied\", `role ${opts.role} cannot change the workspace theme; only workspace admins can`));\n return { ok: P.length === 0, problems: P, tokens };\n}\n\n/**\n * The card text for a theme proposal, generated by code from the two token\n * sets (Invariant 4): \"Brand colour: #0f5c8a \u2192 #1d4ed8\".\n */\nexport function describeTheme(before: ThemeTokens, after: ThemeTokens, m: ContractManifest): string[] {\n const lines: string[] = [];\n for (const k of Object.keys(m.theme ?? {})) {\n if (!(k in after) || after[k] === before[k]) continue;\n const label = themeLabel(m, k);\n lines.push(`${label.charAt(0).toUpperCase()}${label.slice(1)}: ${before[k] ?? \"default\"} \u2192 ${after[k]}`);\n }\n return lines.length ? lines : [\"No change.\"];\n}\n\n/** Current values with a proposal laid over them; unknown or ill-typed values are dropped. */\nexport function mergeTheme(current: ThemeTokens | undefined, proposed: ThemeTokens, m: ContractManifest): ThemeTokens {\n const out: ThemeTokens = {};\n for (const [k, v] of Object.entries({ ...current, ...proposed })) if (themeValueOk(m, k, v)) out[k] = v;\n return out;\n}\n", "import { z } from \"zod\";\nimport { problem, type Problem, type Role } from \"@crasi/bisque-core\";\nimport type { ContractDiff, ContractManifest } from \"@crasi/bisque-contract\";\nimport { DraftSchema, type ArgExpr, type Draft } from \"./schema\";\nimport { migrateDraft } from \"./migrate\";\nimport { validateDraft } from \"./validate\";\n\n/**\n * Templates: a saved spec shared beyond its tenant, e.g. in a host's gallery\n * of views other workspaces can add. A spec is pure data that every host\n * re-validates against its own contract and the installer's role, and that\n * runs on the installer's own data, so sharing one is not sharing code.\n *\n * What a template can carry from its author's tenant is text: titles,\n * labels and the literal values in filters (\"Metro\", \"TABAC\"). Those may be\n * names of the author's customers, so {@link templateDisclosure} lists them\n * for the author to see before publishing.\n */\nexport const TemplateSchema = z\n .object({\n format: z.literal(1),\n kind: z.literal(\"template\"),\n app: z.string().min(1).max(80),\n /** The contract version the template was made against. */\n contractVersion: z.string().max(40),\n draft: DraftSchema,\n })\n .strict();\nexport type Template = z.infer<typeof TemplateSchema>;\n\n/** Strips everything tenant-specific: owner, history, revision, visibility. Only the draft travels. */\nexport function toTemplate(draft: Draft, m: ContractManifest): Template {\n return { format: 1, kind: \"template\", app: m.app, contractVersion: m.version, draft: structuredClone(draft) };\n}\n\nexport type TemplateDisclosure = {\n /** Titles and labels, in every locale. */\n text: string[];\n /** Literal values the query filters on or passes to actions. */\n values: string[];\n};\n\nconst DISPLAY_KEYS = new Set([\"title\", \"label\"]);\n\n/** Every piece of text a template would publish, for the author's consent. */\nexport function templateDisclosure(draft: Draft): TemplateDisclosure {\n const text = new Set<string>();\n const values = new Set<string>();\n const walkDisplay = (v: unknown, display: boolean) => {\n if (typeof v === \"string\") {\n if (display) text.add(v);\n return;\n }\n if (Array.isArray(v)) return v.forEach((x) => walkDisplay(x, display));\n if (v && typeof v === \"object\") for (const [k, x] of Object.entries(v)) walkDisplay(x, display || DISPLAY_KEYS.has(k));\n };\n walkDisplay(draft.body, false);\n walkDisplay(draft.placement, false);\n for (const c of draft.body.data.where ?? []) {\n if (c.length < 3) continue;\n const raw = c[2];\n for (const x of Array.isArray(raw) ? raw : [raw]) if (typeof x === \"string\") values.add(x);\n }\n const walkArgs = (e: ArgExpr) => {\n if (\"literal\" in e)\n for (const x of Array.isArray(e.literal) ? e.literal : [e.literal]) {\n if (typeof x === \"string\") values.add(x);\n }\n else if (\"template\" in e) text.add(e.template);\n else if (\"list\" in e) e.list.forEach(walkArgs);\n };\n const b = draft.body;\n if (b.onClick) Object.values(b.onClick.args).forEach(walkArgs);\n if (b.component === \"actionTable\") Object.values(b.encode.action.args).forEach(walkArgs);\n if (b.component === \"grid\") for (const col of b.encode.columns) if (col.edit) Object.values(col.edit.args).forEach(walkArgs);\n return { text: [...text], values: [...values] };\n}\n\nexport type TemplateImport = { ok: boolean; problems: Problem[]; draft?: Draft; migrated: boolean };\n\n/**\n * Turns a template into a draft for this host and this user: same app,\n * renames applied, then the full host validation with the installer's role.\n * The result is previewed and saved like any proposal.\n */\nexport function fromTemplate(input: unknown, m: ContractManifest, opts: { role: Role; renames?: ContractDiff[\"renames\"] }): TemplateImport {\n const parsed = TemplateSchema.safeParse(input);\n if (!parsed.success) return { ok: false, migrated: false, problems: parsed.error.issues.map((i) => problem(i.path.join(\".\"), \"schema\", i.message)) };\n const t = parsed.data;\n if (t.app !== m.app) return { ok: false, migrated: false, problems: [problem(\"app\", \"schema\", `this template is for ${t.app}, not ${m.app}`)] };\n const migrated = opts.renames ? migrateDraft(t.draft, opts.renames) : null;\n const v = validateDraft(migrated ?? t.draft, m, { role: opts.role });\n return { ok: v.ok, problems: v.problems, draft: v.draft, migrated: !!migrated };\n}\n"],
5
+ "mappings": ";AAAA,SAAS,SAAS;AAClB,SAAS,UAAU,eAAe;AAG3B,IAAM,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;AAC5F,IAAM,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;AAE5F,IAAM,UAAU,CAAC,UAAU,SAAS,WAAW,QAAQ,SAAS,MAAM;AACtE,IAAM,SAAS,EAAE,KAAK,OAAO;AAe7B,IAAM,gBAAoC,EAAE;AAAA,EAAK,MACtD,EAAE,MAAM;AAAA,IACN,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO;AAAA,IACvC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO;AAAA,IACvC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO;AAAA,IACvC,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO;AAAA,IAC3E,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,KAAK,EAAE,IAAI,IAAI,EAAE,CAAC,EAAE,OAAO;AAAA;AAAA,IAElE,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,CAAC,EAAE,OAAO;AAAA,IACnD,EAAE,OAAO,EAAE,MAAM,EAAE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Ac;AAAQ,eAAW,OAAO,EAAE,OAAO,QAAS,KAAI,IAAI,KAAM,QAAO,OAAO,IAAI,KAAK,IAAI,EAAE,QAAQ,QAAQ;AAAA;AAC3H,SAAO,EAAE,MAAM,CAAC,GAAG,IAAI,GAAG,QAAQ,CAAC,GAAG,MAAM,EAAE;AAChD;AASO,SAAS,aAAa,OAAgB,GAAqB,MAAyE;AACzI,QAAM,SAAS,eAAe,UAAU,KAAK;AAC7C,MAAI,CAAC,OAAO,QAAS,QAAO,EAAE,IAAI,OAAO,UAAU,OAAO,UAAU,OAAO,MAAM,OAAO,IAAI,CAAC,MAAMC,SAAQ,EAAE,KAAK,KAAK,GAAG,GAAG,UAAU,EAAE,OAAO,CAAC,EAAE;AACnJ,QAAM,IAAI,OAAO;AACjB,MAAI,EAAE,QAAQ,EAAE,IAAK,QAAO,EAAE,IAAI,OAAO,UAAU,OAAO,UAAU,CAACA,SAAQ,OAAO,UAAU,wBAAwB,EAAE,GAAG,SAAS,EAAE,GAAG,EAAE,CAAC,EAAE;AAC9I,QAAM,WAAW,KAAK,UAAU,aAAa,EAAE,OAAO,KAAK,OAAO,IAAI;AACtE,QAAM,IAAI,cAAc,YAAY,EAAE,OAAO,GAAG,EAAE,MAAM,KAAK,KAAK,CAAC;AACnE,SAAO,EAAE,IAAI,EAAE,IAAI,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO,UAAU,CAAC,CAAC,SAAS;AAChF;",
6
+ "names": ["numeric", "cur", "measureOf", "z", "z", "z", "nest", "problem", "IRSchema", "validateIR", "zodProblems", "z", "IRSchema", "problem", "zodProblems", "validateIR", "nest", "at", "columnLabel", "z", "problem", "z", "problem", "z", "problem"]
7
+ }
@@ -0,0 +1,31 @@
1
+ import type { ContractManifest } from "@crasi/bisque-contract";
2
+ import type { ComponentName, Draft, Spec } from "./schema.js";
3
+ /**
4
+ * The Adjust panel (issue I8): small edits generated from the spec itself and
5
+ * applied without a model call. Each control maps to one path in the spec.
6
+ */
7
+ export type Adjustable = {
8
+ id: string;
9
+ label: string;
10
+ type: "number";
11
+ value: number;
12
+ min: number;
13
+ max: number;
14
+ step?: number;
15
+ } | {
16
+ id: string;
17
+ label: string;
18
+ type: "select";
19
+ value: string;
20
+ options: {
21
+ value: string;
22
+ label: string;
23
+ }[];
24
+ };
25
+ /** Components a spec can switch to without changing its query. */
26
+ export declare function compatibleComponents(spec: Spec): ComponentName[];
27
+ export declare function adjustables(d: Draft, m: ContractManifest): Adjustable[];
28
+ /** Applies one Adjust control. The result must still pass host validation. */
29
+ export declare function applyAdjustment(d: Draft, id: string, value: string | number): Draft;
30
+ /** Re-encodes the same query for another component. */
31
+ export declare function switchComponent(s: Spec, to: ComponentName): Spec;
@@ -0,0 +1,11 @@
1
+ import { type Row } from "@crasi/bisque-ir";
2
+ import type { ArgExpr } from "./schema.js";
3
+ export type ArgScope = {
4
+ row?: Row;
5
+ inputs?: Record<string, unknown>;
6
+ params?: Record<string, unknown>;
7
+ today?: string;
8
+ };
9
+ /** Evaluates an argument expression against the row the user acted on. */
10
+ export declare function evalArg(e: ArgExpr, s: ArgScope): unknown;
11
+ export declare function evalArgs(args: Record<string, ArgExpr>, s: ArgScope): Record<string, unknown>;
@@ -0,0 +1,33 @@
1
+ import type { ArtifactStatus, Visibility } from "@crasi/bisque-core";
2
+ import type { Draft } from "./schema.js";
3
+ /**
4
+ * A saved artifact revision: a = (k, b, m, p, v) plus scope (Definition 2).
5
+ * Holds a spec and its manifest, never data.
6
+ */
7
+ export type Artifact = {
8
+ id: string;
9
+ /** Monotone revision number. Undo writes an old body forward as a new revision (P5). */
10
+ rev: number;
11
+ tenant: string;
12
+ owner: string;
13
+ /** Display name for attribution. Stored with the host, never sent to the conductor. */
14
+ ownerName?: string;
15
+ visibility: Visibility;
16
+ status: ArtifactStatus;
17
+ draft: Draft;
18
+ contractVersion: string;
19
+ /** Format of `draft`; independent of SDK versions. */
20
+ format: 1;
21
+ createdAt: string;
22
+ updatedAt: string;
23
+ updatedBy: string;
24
+ /** Users who hid a workspace artifact for themselves. */
25
+ hiddenBy?: string[];
26
+ /** The prompt history that produced it, kept with the host so revising keeps context. */
27
+ history?: {
28
+ role: "user" | "assistant";
29
+ text: string;
30
+ }[];
31
+ };
32
+ /** `visibility` is absent on revisions saved before it was recorded. */
33
+ export type ArtifactRevision = Pick<Artifact, "id" | "rev" | "draft" | "updatedAt" | "updatedBy"> & Partial<Pick<Artifact, "visibility">>;