diff --git a/.changeset/34771-skills-json-forms-served-sections.md b/.changeset/34771-skills-json-forms-served-sections.md new file mode 100644 index 00000000000..7ffc0d4f8ed --- /dev/null +++ b/.changeset/34771-skills-json-forms-served-sections.md @@ -0,0 +1,18 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the sections served to MCP clients show their examples as JSON, and a check pins their headings + +Clause-②: no +Metadata-protocol: none + +A client that builds through MCP writes JSON, and the sections of `objectstack-data`, `objectstack-ui` and `objectstack-automation` that the hosted MCP door serves showed their examples in TypeScript. Those sections now give each example as JSON, with one line on how a TypeScript project wraps the same literal: + +- `objectstack-data`: the object in Object Definition, the `state_machine` rule in State Machine Validation, and the `summary` field and the permission set in Roll-up Summaries. Field Type Selection names the `{ dialect: 'cel', source }` envelope beside the TypeScript tag. +- `objectstack-ui`: the write-button action in Actions. +- `objectstack-automation`: the `notify` node (its key notes are a list under the block), the `script` and `update_record` pair in Valid-but-silently-wrong, the whole approval flow in Approvals (Flow Nodes), and the start node and window filter of the time-relative trigger, beside its TypeScript flow. + +The other served sections are prose and tables and read the same to both kinds of client; three of them drop a TypeScript-only phrase. + +Every JSON block in a served section is parsed and validated against the spec schema for its kind in CI, and a renamed, removed or duplicated heading of a served section now fails there. diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 11970a2f7d7..768d938a91b 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -5336,6 +5336,16 @@ jobs: continue-on-error: true run: pnpm --filter @objectstack/spec check:skill-refs + # Rationale: `packages/spec/scripts/check-skill-served-sections.ts` header. + # The hosted MCP door reads 24 sections of the published skills by exact + # heading text; a rename, removal or duplicate fails that product at + # start. Also holds every JSON example in those sections to the spec. + # Reads packages/spec/src via tsx and needs no build, as its neighbours. + - name: Check the skill sections served to MCP clients keep their headings and valid JSON + id: check-the-skill-sections-served-to-mcp-clients + continue-on-error: true + run: pnpm --filter @objectstack/spec check:skill-served-sections + # Rationale: `scripts/check-skill-frame-sync.mjs` header (#5130, #5451, #5799). - name: Check the decision frame is in sync across its four copies id: check-the-decision-frame-is-in-sync-across diff --git a/packages/spec/package.json b/packages/spec/package.json index 53ca016d38c..523b20de576 100644 --- a/packages/spec/package.json +++ b/packages/spec/package.json @@ -314,6 +314,7 @@ "check:strictness-ledger": "tsx scripts/check-strictness-ledger.mts", "gen:react-blocks": "tsx scripts/build-react-blocks-contract.ts", "check:react-blocks": "tsx scripts/build-react-blocks-contract.ts --check", + "check:skill-served-sections": "tsx scripts/check-skill-served-sections.ts --self-test && tsx scripts/check-skill-served-sections.ts", "check:skill-examples": "tsx scripts/check-skill-examples.ts --self-test && tsx scripts/check-skill-examples.ts", "check:yaml-examples": "tsx scripts/check-yaml-examples.ts --self-test && tsx scripts/check-yaml-examples.ts", "check:template-manifests": "tsx scripts/check-template-manifests.ts --self-test && tsx scripts/check-template-manifests.ts", diff --git a/packages/spec/scripts/check-generated.ts b/packages/spec/scripts/check-generated.ts index 630f8b56aee..7fa7ee79929 100644 --- a/packages/spec/scripts/check-generated.ts +++ b/packages/spec/scripts/check-generated.ts @@ -213,6 +213,7 @@ const NO_GENERATOR: ReadonlyArray<{ check: string; why: string }> = [ // above. The audit half is unchanged and is still the bulk of what it reports. { check: 'check:empty-state', why: 'audits empty-state coverage — no artifact' }, { check: 'check:skill-examples', why: 'validates skill examples parse — no artifact' }, + { check: 'check:skill-served-sections', why: 'audits the skill sections the hosted MCP door serves (headings, JSON examples) against a hand-kept list — no artifact' }, // #13086 — the YAML half of the surface `check:skill-examples` covers for // TypeScript: tagged ```yaml blocks in skills/ + content/docs/ are safeParsed // against the live spec schemas. Reads src/ through tsx (no dist), writes diff --git a/packages/spec/scripts/check-skill-served-sections.ts b/packages/spec/scripts/check-skill-served-sections.ts new file mode 100644 index 00000000000..dc7e5a92a1d --- /dev/null +++ b/packages/spec/scripts/check-skill-served-sections.ts @@ -0,0 +1,426 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * check-skill-served-sections — the sections of the published skills that the + * hosted MCP door serves keep their headings, and the JSON they show is JSON + * the spec accepts. + * + * tsx scripts/check-skill-served-sections.ts # the gate + * tsx scripts/check-skill-served-sections.ts --self-test # verify the checker + * + * ## The contract it guards + * + * The hosted door finds a section by its exact heading text, outside code + * fences; the heading must occur exactly once in its file, and the section runs + * to the next heading of the same or a higher level. A renamed, removed or + * duplicated heading fails that product at module load, and nothing in this + * repository knew which headings are read. The list is + * `skill-served-sections.json`, beside this file; `readSection` below is that + * rule, line for line, so a verdict here is the verdict there. + * + * A client served these sections writes JSON, so each row also declares the + * form its section takes (`forms` in the list) and, in document order, the + * validator every ```json fence of the section must pass. A fence the row does + * not declare is red, and so is a declared one that is gone: a JSON example + * cannot enter a served section unvalidated. + * + * ## What is judged + * + * heading occurs exactly once in its file, outside fences + * item a row naming a numbered list item: `N. ` starts exactly one line + * form `neutral` carries no TypeScript fence; `json` carries JSON and no + * TypeScript fence; `json+ts` carries both + * json each fence parses, and the spec schema its validator names + * accepts it (a flow node also against its node type's config + * contract, which is what refuses it at registration) + * + * Not judged: the passages the hosted door replaces inside two sections. They + * are that product's strings and only it can check them. + * + * Reads `src/` through tsx and needs no build. + */ + +import fs from 'fs'; +import path from 'path'; + +import { + FlowNodeSchema, + FlowSchema, + TimeRelativeTriggerSchema, + flowNodeConfigRefusals, +} from '../src/automation'; +import { FieldSchema, ObjectSchema, ValidationRuleSchema } from '../src/data'; +import { PermissionSetSchema } from '../src/security'; +import { ActionSchema } from '../src/ui'; + +const REPO_ROOT = path.resolve(__dirname, '../../..'); +const LIST_FILE = path.resolve(__dirname, 'skill-served-sections.json'); + +/** + * The files this gate READS, declared for `scripts/pm/dispatch-gates.mjs` as a + * LITERAL array (its hint extractor reads source text). Eleven files, not the + * skills root: the gate opens only the files the list names, and + * `assertWatchHintsNameTheList` holds this declaration equal to the list. + */ +const DECLARED_WATCH_HINTS = [ + 'skills/objectstack-automation/SKILL.md', + 'skills/objectstack-automation/references/examples-flows.md', + 'skills/objectstack-automation/references/state-machines-and-approvals.md', + 'skills/objectstack-data/SKILL.md', + 'skills/objectstack-data/references/seeds.md', + 'skills/objectstack-data/rules/lifecycle.md', + 'skills/objectstack-data/rules/naming.md', + 'skills/objectstack-data/rules/relationships.md', + 'skills/objectstack-data/rules/validation.md', + 'skills/objectstack-ui/SKILL.md', + 'skills/objectstack-ui/rules/list-views.md', +]; + +const FORMS = ['json', 'json+ts', 'neutral'] as const; +type Form = (typeof FORMS)[number]; + +interface ServedSection { + /** Repository-relative path of the skill file. */ + file: string; + heading: string; + item?: number; + form: Form; + json: string[]; +} + +/** A validator answers with the reasons it refuses a parsed JSON value; none means accepted. */ +type Validator = (value: unknown) => string[]; +type SafeParser = { + safeParse(value: unknown): { success: boolean; error?: { issues: Array<{ path: PropertyKey[]; message: string }> } }; +}; + +function bySchema(schema: SafeParser): Validator { + return (value) => { + const result = schema.safeParse(value); + if (result.success) return []; + return (result.error?.issues ?? []).map((issue) => `${issue.path.map(String).join('.') || '(root)'}: ${issue.message}`); + }; +} + +const flowNode: Validator = (value) => { + const shape = bySchema(FlowNodeSchema)(value); + if (shape.length > 0) return shape; + const node = value as { type: string; config?: { timeRelative?: unknown } }; + const out = flowNodeConfigRefusals(node.type, node.config).map((refusal) => refusal.message); + if (node.config?.timeRelative !== undefined) { + out.push(...bySchema(TimeRelativeTriggerSchema)(node.config.timeRelative).map((m) => `config.timeRelative.${m}`)); + } + return out; +}; + +const VALIDATORS: Readonly> = { + Object: bySchema(ObjectSchema), + Field: bySchema(FieldSchema), + ValidationRule: bySchema(ValidationRuleSchema), + PermissionSet: bySchema(PermissionSetSchema), + Action: bySchema(ActionSchema), + Flow: bySchema(FlowSchema), + FlowNode: flowNode, + FlowNodeList: (value) => + Array.isArray(value) && value.length > 0 + ? value.flatMap((node, at) => flowNode(node).map((m) => `[${at}] ${m}`)) + : ['expected a non-empty array of flow nodes'], + /** A CRUD node's `filter` value, judged where the engine judges it: inside a `get_record` config. */ + FlowFilter: (value) => + flowNode({ id: 'probe', type: 'get_record', label: 'Probe', config: { objectName: 'probe', filter: value } }), +}; + +const HEADING = /^(#{1,6})\s+(.*?)\s*$/; +const FENCE = /^\s*(```|~~~)/; + +/** The hosted door's rule: every match of `heading` outside fences, each with the lines of its section. */ +function readSection(text: string, heading: string): string[][] { + const lines = text.split('\n'); + const headings: Array<{ at: number; level: number; text: string }> = []; + let fenced = false; + lines.forEach((line, at) => { + if (FENCE.test(line)) fenced = !fenced; + if (fenced) return; + const m = HEADING.exec(line); + if (m) headings.push({ at, level: m[1].length, text: m[2] }); + }); + return headings + .filter((h) => h.text === heading) + .map((start) => { + const next = headings.find((h) => h.at > start.at && h.level <= start.level); + return lines.slice(start.at, next ? next.at : lines.length); + }); +} + +/** The fences of a section, in order: the info string's first word and the body. */ +function fencesOf(section: string[]): Array<{ lang: string; body: string }> { + const out: Array<{ lang: string; body: string }> = []; + let open: { lang: string; lines: string[] } | undefined; + for (const line of section) { + if (FENCE.test(line)) { + if (open) { + out.push({ lang: open.lang, body: open.lines.join('\n') }); + open = undefined; + } else { + open = { lang: (/^\s*(?:```|~~~)\s*([^\s`~]*)/.exec(line)?.[1] ?? '').toLowerCase(), lines: [] }; + } + } else if (open) { + open.lines.push(line); + } + } + if (open) out.push({ lang: open.lang, body: open.lines.join('\n') }); + return out; +} + +const TS_LANGS = new Set(['ts', 'typescript', 'tsx', 'js', 'javascript', 'jsx']); + +/** Every problem with `rows`, read through `read` (a repository-relative path, or undefined when absent). */ +function judge( + rows: readonly ServedSection[], + read: (rel: string) => string | undefined, + validators: Readonly> = VALIDATORS, +): string[] { + const problems: string[] = []; + if (rows.length === 0) problems.push('the list names no section: a gate with nothing to read must not pass'); + const seen = new Set(); + for (const row of rows) { + const rel = row.file; + const label = `${rel} § ${row.heading}`; + const key = label; + if (seen.has(key)) { + problems.push(`${label}: listed more than once`); + continue; + } + seen.add(key); + if (!FORMS.includes(row.form)) { + problems.push(`${label}: form ${JSON.stringify(row.form)} is not one of ${FORMS.join(', ')}`); + continue; + } + const text = read(rel); + if (text === undefined) { + problems.push(`${label}: the file does not exist`); + continue; + } + const found = readSection(text, row.heading); + if (found.length !== 1) { + problems.push( + `${label}: the heading must occur exactly once in its file, outside code fences; found ${found.length}` + + (found.length === 0 ? ' (renamed or removed)' : ' (duplicated)') + + '. The hosted MCP door reads this section by that exact text and fails at start otherwise: restore the ' + + 'heading, or change it together with the hosted table and this list.', + ); + continue; + } + const section = found[0]; + if (row.item !== undefined) { + const starts = section.filter((line) => new RegExp(`^${row.item}\\.\\s`).test(line)).length; + if (starts !== 1) problems.push(`${label}: list item ${row.item} must start exactly one line of the section; found ${starts}`); + } + const fences = fencesOf(section); + const json = fences.filter((f) => f.lang === 'json'); + const ts = fences.filter((f) => TS_LANGS.has(f.lang)).length; + if (row.form === 'neutral' && (json.length > 0 || ts > 0)) { + problems.push(`${label}: form "neutral" but the section carries ${json.length} JSON and ${ts} TypeScript fence(s): declare its form and validators`); + } + if (row.form === 'json' && ts > 0) { + problems.push(`${label}: form "json" but the section carries ${ts} TypeScript fence(s): give the example as JSON, or declare "json+ts"`); + } + if (row.form === 'json+ts' && ts === 0) { + problems.push(`${label}: form "json+ts" but the section carries no TypeScript fence: declare "json"`); + } + if (row.form !== 'neutral' && json.length === 0) { + problems.push(`${label}: form "${row.form}" but the section carries no JSON fence`); + } + if (json.length !== row.json.length) { + problems.push(`${label}: ${json.length} JSON fence(s) in the section, ${row.json.length} validator(s) declared: every JSON fence names its validator, in document order`); + continue; + } + json.forEach((fence, at) => { + const name = row.json[at]; + const validate = validators[name]; + if (!validate) { + problems.push(`${label}: JSON fence ${at + 1} names validator ${JSON.stringify(name)}, which is not one of ${Object.keys(validators).join(', ')}`); + return; + } + let value: unknown; + try { + value = JSON.parse(fence.body); + } catch (error) { + problems.push(`${label}: JSON fence ${at + 1} does not parse: ${(error as Error).message}`); + return; + } + for (const reason of validate(value)) problems.push(`${label}: JSON fence ${at + 1} is refused as ${name}: ${reason}`); + }); + } + return problems; +} + +function readList(): ServedSection[] { + const parsed = JSON.parse(fs.readFileSync(LIST_FILE, 'utf8')) as { sections?: ServedSection[] }; + if (!Array.isArray(parsed.sections)) throw new Error(`${LIST_FILE}: no "sections" array`); + return parsed.sections; +} + +/** A file the list names and the declaration does not (or the reverse) is a hint that went stale. */ +function assertWatchHintsNameTheList(rows: readonly ServedSection[]): void { + const expected = [...new Set(rows.map((row) => row.file))].sort(); + if (expected.join('|') !== [...DECLARED_WATCH_HINTS].sort().join('|')) { + throw new Error( + `check-skill-served-sections: DECLARED_WATCH_HINTS no longer names the files the list reads ` + + `(${JSON.stringify(expected)}): update the declaration, as a LITERAL array.`, + ); + } +} + +function readSkillFile(rel: string): string | undefined { + const abs = path.resolve(REPO_ROOT, rel); + return fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : undefined; +} + +// ── Self-test ──────────────────────────────────────────────────────────────── + +let selfTestReachedVerdict = false; + +/** Battery name → minimum case count. A battery that stops registering its cases is red by name. */ +const SELF_TEST_BATTERIES: Readonly> = Object.freeze({ + 'heading — one match is green': 3, + 'heading — renamed, removed or duplicated is red': 5, + 'heading — the door\'s fence and level rule': 4, + 'item — a numbered item occurs exactly once': 3, + 'form — the declared form matches the fences': 5, + 'json — fence count, parse and schema': 7, + 'list — empty, repeated row, unknown form, missing file': 4, + 'real tree — the list is read and names real validators': 2, +}); +const SELF_TEST_BATTERY_FLOOR = 8; + +function selfTest(): void { + let failed = 0; + const batterySeen = new Map(); + const row = (over: Partial = {}): ServedSection => ({ + file: 'f.md', heading: 'Target', form: 'neutral', json: [], ...over, + }); + const expect = (battery: string, label: string, text: string | undefined, rows: ServedSection[], want: 'green' | RegExp) => { + batterySeen.set(battery, (batterySeen.get(battery) ?? 0) + 1); + const problems = judge(rows, () => text); + const ok = want === 'green' ? problems.length === 0 : problems.some((p) => want.test(p)); + if (ok) { + console.log(` ✓ ${label}`); + } else { + failed += 1; + console.error(` ✗ ${label}\n wanted ${want === 'green' ? 'no problem' : String(want)}; got ${JSON.stringify(problems)}`); + } + }; + const node = '{ "id": "n", "type": "notify", "label": "N", "config": { "recipients": "u1", "title": "T" } }'; + const fence = (lang: string, body: string) => `\`\`\`${lang}\n${body}\n\`\`\`\n`; + + let b = 'heading — one match is green'; + expect(b, 'a heading that occurs once', '# Doc\n\n## Target\n\nbody\n', [row()], 'green'); + expect(b, 'trailing whitespace after the heading text still matches', '## Target \nbody\n', [row()], 'green'); + expect(b, 'a heading whose text is a code span', '### `notify`\nbody\n', [row({ heading: '`notify`' })], 'green'); + + b = 'heading — renamed, removed or duplicated is red'; + expect(b, 'renamed', '## Targets\nbody\n', [row()], /found 0 \(renamed or removed\)/); + expect(b, 'removed', '# Doc\nbody\n', [row()], /found 0/); + expect(b, 'duplicated at one level', '## Target\na\n## Target\nb\n', [row()], /found 2 \(duplicated\)/); + expect(b, 'duplicated across levels', '## Target\na\n#### Target\nb\n', [row()], /found 2/); + expect(b, 'a different case is a different heading', '## target\nbody\n', [row()], /found 0/); + + b = 'heading — the door\'s fence and level rule'; + expect(b, 'a heading only inside a fence is not a heading', fence('md', '## Target'), [row()], /found 0/); + expect(b, 'a fenced copy beside the real one is not a duplicate', `## Target\n${fence('md', '## Target')}`, [row()], 'green'); + expect(b, 'a deeper heading stays inside the section', `## Target\n### Sub\n${fence('ts', 'x')}`, [row()], /form "neutral"/); + expect(b, 'a heading of the same level ends the section', `## Target\nbody\n## Next\n${fence('ts', 'x')}`, [row()], 'green'); + + b = 'item — a numbered item occurs exactly once'; + expect(b, 'the item is there', '## Target\n1. a\n2. b\n', [row({ item: 2 })], 'green'); + expect(b, 'the item is gone', '## Target\n1. a\n', [row({ item: 2 })], /list item 2 .* found 0/); + expect(b, 'the item number repeats', '## Target\n2. a\n2. b\n', [row({ item: 2 })], /list item 2 .* found 2/); + + b = 'form — the declared form matches the fences'; + expect(b, 'neutral with a TypeScript fence', `## Target\n${fence('typescript', 'x')}`, [row()], /form "neutral"/); + expect(b, 'json with a TypeScript fence beside it', `## Target\n${fence('json', node)}${fence('ts', 'x')}`, [row({ form: 'json', json: ['FlowNode'] })], /form "json" but/); + expect(b, 'json+ts with no TypeScript fence', `## Target\n${fence('json', node)}`, [row({ form: 'json+ts', json: ['FlowNode'] })], /no TypeScript fence/); + expect(b, 'json with no JSON fence', '## Target\nbody\n', [row({ form: 'json' })], /no JSON fence/); + expect(b, 'json+ts with both', `## Target\n${fence('json', node)}${fence('ts', 'x')}`, [row({ form: 'json+ts', json: ['FlowNode'] })], 'green'); + + b = 'json — fence count, parse and schema'; + expect(b, 'a valid node', `## Target\n${fence('json', node)}`, [row({ form: 'json', json: ['FlowNode'] })], 'green'); + expect(b, 'an undeclared JSON fence', `## Target\n${fence('json', node)}${fence('json', node)}`, [row({ form: 'json', json: ['FlowNode'] })], /2 JSON fence\(s\) in the section, 1 validator/); + expect(b, 'a declared fence that is gone', `## Target\n${fence('json', node)}`, [row({ form: 'json', json: ['FlowNode', 'Flow'] })], /1 JSON fence\(s\) in the section, 2 validator/); + expect(b, 'JSON that does not parse', `## Target\n${fence('json', "{ id: 'n' }")}`, [row({ form: 'json', json: ['FlowNode'] })], /does not parse/); + expect(b, 'a node the schema refuses', `## Target\n${fence('json', '{ "id": "n", "type": "notify" }')}`, [row({ form: 'json', json: ['FlowNode'] })], /refused as FlowNode/); + expect(b, 'a node its config contract refuses', `## Target\n${fence('json', '{ "id": "n", "type": "notify", "label": "N", "config": { "recipientz": "u1" } }')}`, [row({ form: 'json', json: ['FlowNode'] })], /refused as FlowNode: .*recipients/); + expect(b, 'a validator the checker does not have', `## Target\n${fence('json', node)}`, [row({ form: 'json', json: ['Nope'] })], /names validator "Nope"/); + + b = 'list — empty, repeated row, unknown form, missing file'; + expect(b, 'an empty list', '## Target\n', [], /names no section/); + expect(b, 'a row listed twice', '## Target\n', [row(), row()], /listed more than once/); + expect(b, 'an unknown form', '## Target\n', [row({ form: 'ts' as Form })], /is not one of/); + expect(b, 'a file that does not exist', undefined, [row()], /does not exist/); + + b = 'real tree — the list is read and names real validators'; + const real = readList(); + assertWatchHintsNameTheList(real); + const count = (label: string, ok: boolean) => { + batterySeen.set(b, (batterySeen.get(b) ?? 0) + 1); + if (ok) console.log(` ✓ ${label}`); + else { + failed += 1; + console.error(` ✗ ${label}`); + } + }; + count(`the list file holds ${real.length} row(s)`, real.length > 0); + count('every validator a row names exists', real.every((r) => r.json.every((name) => name in VALIDATORS))); + + const declared = Object.keys(SELF_TEST_BATTERIES); + if (declared.length < SELF_TEST_BATTERY_FLOOR) { + failed += 1; + console.error(`✗ self-test floor: ${declared.length} batteries declared, below the pinned ${SELF_TEST_BATTERY_FLOOR}`); + } + for (const [name, seen] of batterySeen) { + if (declared.includes(name)) continue; + failed += 1; + console.error(`✗ self-test floor: battery "${name}" registered ${seen} case(s) but is not declared`); + } + for (const name of declared) { + const seen = batterySeen.get(name) ?? 0; + if (seen >= SELF_TEST_BATTERIES[name]) continue; + failed += 1; + console.error(`✗ self-test floor: battery "${name}" registered ${seen} case(s), below its pinned ${SELF_TEST_BATTERIES[name]}`); + } + + if (failed > 0) { + console.error(`\n✗ check-skill-served-sections self-test: ${failed} failure(s) (cases and floor).`); + process.exit(1); + } + console.log(`\n✓ check-skill-served-sections self-test: ${[...batterySeen.values()].reduce((a, n) => a + n, 0)} cases pass in ${declared.length} batteries.`); + selfTestReachedVerdict = true; +} + +function main(): void { + if (process.argv.includes('--self-test')) { + selfTest(); + if (!selfTestReachedVerdict) { + console.error('\n✗ check-skill-served-sections self-test: selfTest() returned without reaching its verdict.'); + process.exit(1); + } + return; + } + const rows = readList(); + assertWatchHintsNameTheList(rows); + const problems = judge(rows, readSkillFile); + if (problems.length > 0) { + console.error(`✗ check-skill-served-sections: ${problems.length} problem(s)\n`); + for (const problem of problems) console.error(` - ${problem}`); + process.exit(1); + } + const fences = rows.reduce((n, r) => n + r.json.length, 0); + const byForm = FORMS.map((form) => `${rows.filter((r) => r.form === form).length} ${form}`).join(', '); + console.log( + `✓ check-skill-served-sections: ${rows.length} served section(s), each heading exactly once in its file (${byForm}); ` + + `${fences} JSON fence(s) parse and pass their spec validators.`, + ); +} + +main(); diff --git a/packages/spec/scripts/skill-served-sections.json b/packages/spec/scripts/skill-served-sections.json new file mode 100644 index 00000000000..01aa9751708 --- /dev/null +++ b/packages/spec/scripts/skill-served-sections.json @@ -0,0 +1,34 @@ +{ + "about": "The sections of the published skills that the hosted MCP door serves by exact heading text. Read by check-skill-served-sections.ts, whose header states the matching rule. The hosted table is the cloud repository's packages/service-ai-studio/src/skills/published-refs.ts; when that table moves, its owner updates this list by pull request.", + "forms": { + "json": "the item's example is a JSON block; a one-line note says how TypeScript wraps the same literal", + "json+ts": "a JSON block beside a TypeScript block that carries what JSON cannot (a function, or lines the hosted door replaces)", + "neutral": "prose and tables only: no fenced TypeScript to translate" + }, + "sections": [ + { "file": "skills/objectstack-data/rules/naming.md", "heading": "Critical Rules", "item": 6, "form": "neutral", "json": [] }, + { "file": "skills/objectstack-data/SKILL.md", "heading": "Object Definition", "form": "json", "json": ["Object"] }, + { "file": "skills/objectstack-data/SKILL.md", "heading": "Field Type Selection", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-data/SKILL.md", "heading": "Relationship Patterns", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-data/SKILL.md", "heading": "Validation Patterns", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-data/rules/validation.md", "heading": "State Machine Validation", "form": "json", "json": ["ValidationRule"] }, + { "file": "skills/objectstack-data/rules/relationships.md", "heading": "Roll-up Summaries", "form": "json", "json": ["Field", "PermissionSet"] }, + { "file": "skills/objectstack-data/references/seeds.md", "heading": "Seed best practices", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-data/rules/lifecycle.md", "heading": "Save Notice", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-ui/SKILL.md", "heading": "List Views", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-ui/SKILL.md", "heading": "Actions", "form": "json", "json": ["Action"] }, + { "file": "skills/objectstack-ui/rules/list-views.md", "heading": "Adding a board, calendar, gallery or gantt beside the list", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "Data Operations", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "External Integration", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "`notify`", "form": "json", "json": ["FlowNode"] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "Failure routing & `runAs`", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "Filter operands (`config.filter`)", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "Valid-but-silently-wrong (passes build, fails at runtime)", "form": "json+ts", "json": ["FlowNodeList"] }, + { "file": "skills/objectstack-automation/SKILL.md", "heading": "Integrations are declared, not coded", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/references/examples-flows.md", "heading": "Time-relative triggers — scheduled per-record date sweep", "form": "json+ts", "json": ["FlowNode", "FlowFilter"] }, + { "file": "skills/objectstack-automation/references/state-machines-and-approvals.md", "heading": "Approvals (Flow Nodes)", "form": "json", "json": ["Flow"] }, + { "file": "skills/objectstack-automation/references/state-machines-and-approvals.md", "heading": "Approver Types", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/references/state-machines-and-approvals.md", "heading": "Node Config (`ApprovalNodeConfigSchema`)", "form": "neutral", "json": [] }, + { "file": "skills/objectstack-automation/references/state-machines-and-approvals.md", "heading": "Approval Best Practices", "form": "neutral", "json": [] } + ] +} diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 6884c22ed64..4bfd13e0d44 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -651,7 +651,16 @@ export const CEILINGS = new Map([ // ceil(27968 / 4) = 6992; the ceiling moves +89, the measured addition only. // Pinned AT the measurement. // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(27968 / 4) - ['skills/objectstack-automation/SKILL.md', 6992], + // 6992 -> 7045 (#34771): the JSON forms #34691 S3 = A orders into the sections the + // hosted MCP door serves. `### \`notify\`` trades its TypeScript block for the node + // as JSON plus a key list carrying the block's comments; item 3 of `## Valid-but- + // silently-wrong` shows its two nodes as a JSON array (each now with the `label` the + // schema requires) and says the function registration has no JSON form. Raise path: + // ruling record 6513306068, letter B, 「A:先削重复,余额按实测提高」. Paid down first: the block's import line, type annotation and check marker + // went with it. The file is 27988 -> 28199 bytes (27968 -> 28179 priced); the row + // moves +53, the measured remainder, pinned AT the measurement. + // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(28179 / 4) + ['skills/objectstack-automation/SKILL.md', 7045], // 13783 -> 13892 (2026-08-31 app-repo-principles raise, see the block above). // The invariant-vs-transition-gate choice, placed in the field-conditional-rule // bullet list where the tool is actually picked. Both wrong picks are silent: @@ -700,7 +709,15 @@ export const CEILINGS = new Map([ // public skills … The private corpus's rules of that kind move there". The // raise path is the standing 2026-10-27 ruling, verbatim and untranslated: // 「A:先削重复,余额按实测提高」 (ruling record 6513306068). - ['skills/objectstack-data/SKILL.md', 6665], + // 6665 -> 6710 (#34771): `### Object Definition` gains the object as JSON and + // `### Field Type Selection` names the `expression` envelope beside the TypeScript + // tag (#34691 S3 = A). Raise path: ruling record 6513306068, letter B, 「A:先削重复,余额按实测提高」. Paid down first, in the same section: the + // sentence restating the `sharingModel` row (omitted resolves to `private`, the + // publish door refuses first) and the `namespace` row's `ObjectSchema.create()` + // clause and `name` example, which the JSON now shows. 26678 -> 26859 bytes (26658 + // -> 26839 priced); the row moves +45, the measured remainder, pinned AT it. + // ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 20) / 4) == ceil(26839 / 4) + ['skills/objectstack-data/SKILL.md', 6710], // 5997 -> 6008 (the formula skills follow-ups of PRs #34443 and #34447): the // `label(record.f)` row teaches a multi-select (`multiple: true`) reading each // selected label in stored order, joined with `, `, and the built-ins line @@ -937,7 +954,12 @@ export const CEILINGS = new Map([ // (15684 priced) -> 8974 (8954 priced) -> 2239 tokens; the ceiling follows the file down // to the measurement, the ratchet's ordinary direction. // ceil(($(wc -c < skills/objectstack-ui/SKILL.md) - 20) / 4) == ceil(8954 / 4) - ['skills/objectstack-ui/SKILL.md', 2239], + // 2239 -> 2277 (#34771): `## Actions` shows the write-button action as one JSON + // object (#34691 S3 = A); the inline `type` / `body` fragment it replaces left the + // paragraph. Raise path: ruling record 6513306068, letter B, 「A:先削重复,余额按实测提高」. 8974 -> 9128 bytes (8954 -> 9108 priced); the row + // moves +38, the measured remainder, pinned AT the measurement. + // ceil(($(wc -c < skills/objectstack-ui/SKILL.md) - 20) / 4) == ceil(9108 / 4) + ['skills/objectstack-ui/SKILL.md', 2277], // 8333 -> 6193: RE-LOCK at the landed count after the #19715 split (decision // batch #213 item 1, maintainer 「1 2 4 同意」): the worked R1, the report // template and the v17-canonical shapes block moved VERBATIM into @@ -1125,7 +1147,11 @@ export const CEILINGS = new Map([ // assignment per pair", "On the PARENT object", the second "On the CHILD object's FK // field", the contact example's "independent lifecycle"). 16916 -> 16884 bytes -> // ceil(16884 / 4) = 4221; the row follows the measurement down. - ['skills/objectstack-data/rules/relationships.md', 4221], + // 4221 -> 4203 (#34771): RE-LOCK at the landed count. `## Roll-up Summaries` gives + // the summary field and the permission set as JSON; the commented-out alternatives + // became a sentence and a second field entry. 16884 -> 16811 bytes. + // ceil($(wc -c < skills/objectstack-data/rules/relationships.md) / 4) == ceil(16811 / 4) + ['skills/objectstack-data/rules/relationships.md', 4203], // NEW FILE (#14296 item 1 = A, condition (b)): the entry's Security & Access // Control block moved here whole. Pinned at its landed count — no headroom, // because a split that arrives with budget is a raise wearing a new path. @@ -1518,7 +1544,15 @@ export const CEILINGS = new Map([ // measurement. Same authority as the SKILL.md row above: cloud#3659 letter A // (ruling comment 6682024726) orders the text in; the raise path is the // standing 2026-10-27 ruling (record 6513306068), quoted in the PR body. - ['skills/objectstack-automation/references/examples-flows.md', 1494], + // 1494 -> 1543 (#34771): the time-relative section gains its start node as JSON + // beside the TypeScript flow, whose `type` / `runAs` lines the hosted door replaces + // and which therefore stay byte for byte, and its window filter becomes JSON + // (#34691 S3 = A). Raise path: ruling record 6513306068, letter B, 「A:先削重复,余额按实测提高」. Paid down first: two clauses restating the + // paragraph and the block above them (the daily sweep never missing a threshold; + // each bound being a CEL envelope). 5957 -> 6170 bytes; the row moves +49, the + // measured remainder, pinned AT the measurement. + // ceil($(wc -c < skills/objectstack-automation/references/examples-flows.md) / 4) == ceil(6170 / 4) + ['skills/objectstack-automation/references/examples-flows.md', 1543], // NEW FILE (card #27223): one recipe per integration archetype — OpenAPI with // a static key, remote MCP with a static header, plain REST, the vendor // callback, a hand-written document for a spec-less vendor — plus the two @@ -1646,7 +1680,13 @@ export const CEILINGS = new Map([ // 23661 bytes -> ceil(23661 / 4) = 5916; the ceiling moves +91, the measured // remainder only. Pinned AT the measurement. // ceil($(wc -c < skills/objectstack-automation/references/state-machines-and-approvals.md) / 4) == ceil(23661 / 4) - ['skills/objectstack-automation/references/state-machines-and-approvals.md', 5916], + // 5916 -> 5936 (#34771): `### Approvals (Flow Nodes)` gives its flow as JSON, with + // the block's comments as three list items above it (#34691 S3 = A). Raise path: + // ruling record 6513306068, letter B, 「A:先削重复,余额按实测提高」. Paid down first: the import line, the `defineFlow` wrapper and the check + // marker went with the TypeScript block. 23652 -> 23744 bytes; the row moves +20, + // the measured remainder (main carried 3 of headroom), pinned AT the measurement. + // ceil($(wc -c < skills/objectstack-automation/references/state-machines-and-approvals.md) / 4) == ceil(23744 / 4) + ['skills/objectstack-automation/references/state-machines-and-approvals.md', 5936], // 1779 -> 1769 (#26297): RE-LOCK at the landed count after a net cut — two // stale `{ type: 'lookup', reference: 'user' }` fields (an object that does // not exist) became `type: 'user'`; -10 tokens, the row follows the @@ -1685,7 +1725,9 @@ export const CEILINGS = new Map([ // objectstack-ai/cloud#3659, letter A, maintainer 「A」 (ruling comment // 6682024726); raise path the 2026-10-27 ruling 「A:先削重复,余额按实测提高」 // (ruling record 6513306068). - ['skills/objectstack-data/references/seeds.md', 1747], + // 1747 -> 1746 (#34771): RE-LOCK at the landed count; the `defineSeed()` row of + // `### Seed best practices` says it is the TypeScript form. 6985 -> 6984 bytes. + ['skills/objectstack-data/references/seeds.md', 1746], // 1351 -> 1343: the body-pin values left the count (#31115, ruling B; see // BODY_PIN_REPIN); the file's count fell by the same 8, headroom unchanged. ['skills/objectstack-platform/references/bootstrap.md', 1343], diff --git a/skills/objectstack-automation/SKILL.md b/skills/objectstack-automation/SKILL.md index 30db1443575..8f80f832581 100644 --- a/skills/objectstack-automation/SKILL.md +++ b/skills/objectstack-automation/SKILL.md @@ -111,26 +111,35 @@ Built-in (plugins register more): ### `notify` An undeclared key is a named parse error. **RAW** keys are read as written: -a `{token}` in one is refused. - - -```ts -import type { FlowNode } from '@objectstack/spec/automation'; -const notify: FlowNode = { id: 'tell_owner', type: 'notify', label: 'Notify Owner', config: { - recipients: { dialect: 'cel', source: 'record.owner_id' }, // REQUIRED — id, list, or envelope; a CSV is ONE id. - // 4th form `{ emailField: 'applicant_email' }`: an `email` field of the trigger record, for a non-user — - // then `channels: 'email'` alone. An envelope must yield USER ids: an address no user holds fails the node - title: 'Done: {{ record.title }}', // inline; XOR `template` (RAW, localizable) - message: 'Closed {{ record.closed_at | date:long }}', // body; only with inline `title` - topic: 'task', // RAW; default 'notify' - severity: 'warning', // RAW; CLOSED enum info|warning|critical - channels: ['inbox'], // RAW; default inbox - sourceObject: 'task', // link: PAIR, else dropped; none of the 3 ⇒ the - sourceId: { dialect: 'cel', source: 'record.id' }, // trigger record (not on delete/before-create), if any - actionUrl: '/tasks/{{ record.id }}', // overrides the pair -} }; +a `{token}` in one is refused. The node as JSON (TypeScript: the same +literal, a `FlowNode`): + +```json +{ "id": "tell_owner", "type": "notify", "label": "Notify Owner", "config": { + "recipients": { "dialect": "cel", "source": "record.owner_id" }, + "title": "Done: {{ record.title }}", + "message": "Closed {{ record.closed_at | date:long }}", + "topic": "task", + "severity": "warning", + "channels": ["inbox"], + "sourceObject": "task", + "sourceId": { "dialect": "cel", "source": "record.id" }, + "actionUrl": "/tasks/{{ record.id }}" +} } ``` +- `recipients` — REQUIRED: id, list, or envelope; a CSV is ONE id. 4th form + `{ "emailField": "applicant_email" }`: an `email` field of the trigger record, + for a non-user — then `channels: 'email'` alone. An envelope must yield USER + ids: an address no user holds fails the node. +- `title` — inline; XOR `template` (RAW, localizable). `message` — body; only + with inline `title`. +- RAW: `topic` (default `'notify'`), `severity` (CLOSED enum + `info` | `warning` | `critical`), `channels` (default inbox). +- `sourceObject` + `sourceId` — the link: a PAIR, else dropped; none of the 3 ⇒ + the trigger record (not on delete/before-create), if any. `actionUrl` + overrides the pair. + A recipient string, written or evaluated, may be an audience selector: - `team:ID` — that team's members. @@ -288,21 +297,22 @@ Most are caught by `objectstack build`: database.** It receives `ctx.input` and **returns** a value; a later **declarative** node persists its `outputVariable`: - ```ts - { id: 'ai', type: 'script', config: { - function: 'helpdesk.aiTriageStub', - inputs: { ticketId: { dialect: 'cel', source: 'record.id' } }, - outputVariable: 'ai', - } }, - { id: 'apply', type: 'update_record', config: { - objectName: 'helpdesk_ticket', - filter: { id: { dialect: 'cel', source: 'record.id' } }, - fields: { ai_category: { dialect: 'cel', source: 'ai.ai_category' } }, - } }, + ```json + [ + { "id": "ai", "type": "script", "label": "AI Triage", "config": { + "function": "helpdesk.aiTriageStub", + "inputs": { "ticketId": { "dialect": "cel", "source": "record.id" } }, + "outputVariable": "ai" } }, + { "id": "apply", "type": "update_record", "label": "Apply Category", "config": { + "objectName": "helpdesk_ticket", + "filter": { "id": { "dialect": "cel", "source": "record.id" } }, + "fields": { "ai_category": { "dialect": "cel", "source": "ai.ai_category" } } } } + ] ``` A function that writes where the platform cannot see **declares** it, so the - run reports "cannot say" rather than `acted: 0`: + run reports "cannot say" rather than `acted: 0` (project code — a function + has no JSON form): ```ts defineStack({ functions: { diff --git a/skills/objectstack-automation/references/examples-flows.md b/skills/objectstack-automation/references/examples-flows.md index fdbf04436eb..c2a13bcafa4 100644 --- a/skills/objectstack-automation/references/examples-flows.md +++ b/skills/objectstack-automation/references/examples-flows.md @@ -80,8 +80,7 @@ record *happens to change*, so unattended it almost never fires. Use a carries a **`timeRelative`** descriptor is swept on a schedule (daily by default) and launched **once per record** whose date field falls in the window. The record is on the context, so the start `condition` and a `record.*` CEL value envelope work -exactly as for a record-change flow — and because the window is evaluated every -day, a threshold is never missed. +exactly as for a record-change flow. ```typescript @@ -113,23 +112,31 @@ defineFlow({ }); ``` +As JSON the flow is that literal without `defineFlow(...)`; its start node: + +```json +{ "id": "start", "type": "start", "label": "Daily Sweep", "config": { "timeRelative": { + "object": "contracts", "dateField": "end_date", "offsetDays": [60, 30, 7], + "filter": { "status": "active" } } } } +``` + **Date EQUALITY never matches**, so a hand-rolled sweep filters windows, not days: a `date` field carries a time component, so `field == daysFromNow(N)` (or `{ $in: [...] }`) compares two differently-timed timestamps and silently returns nothing (build warns `flow-date-equality-filter`). Tier each threshold as a -one-day **window** (`$gte`/`$lt`): +one-day **window** (`$gte`/`$lt`) — this `filter`, plus the same window at +30 / 31 and at 60 / 61 as further `$or` entries: -```ts -filter: { status: 'active', $or: [ - { end_date: { $gte: { dialect: 'cel', source: 'isoDate(daysFromNow(7))' }, - $lt: { dialect: 'cel', source: 'isoDate(daysFromNow(8))' } } }, - // …and the same one-day window at 30 / 31 and at 60 / 61 +```json +{ "status": "active", "$or": [ + { "end_date": { "$gte": { "dialect": "cel", "source": "isoDate(daysFromNow(7))" }, + "$lt": { "dialect": "cel", "source": "isoDate(daysFromNow(8))" } } } ] } ``` Abutting windows tile the timeline, so each record matches exactly one tier — -fires once, idempotent, no guard field. Each bound is a CEL value envelope -(`isoDate(daysFromNow(N))`), evaluated before the query; any `{…}` token but a +fires once, idempotent, no guard field. Each bound is evaluated before the +query; any `{…}` token but a query placeholder such as `{today}` is refused there (`expression-invalid`). For "days remaining" in a message, use `daysBetween(today(), record.end_date)`. diff --git a/skills/objectstack-automation/references/state-machines-and-approvals.md b/skills/objectstack-automation/references/state-machines-and-approvals.md index c20afabc2b9..4395a266bac 100644 --- a/skills/objectstack-automation/references/state-machines-and-approvals.md +++ b/skills/objectstack-automation/references/state-machines-and-approvals.md @@ -69,74 +69,54 @@ is one diagram a reviewer (or AI) can read end-to-end. > `sys_approval_action`, the record lock, the status mirror, approver > resolution) is owned by `plugin-approvals`. - -```typescript -import { cel, defineFlow } from '@objectstack/spec'; -// A record-triggered flow: high-value opportunities need manager sign-off, -// and director sign-off too when the amount clears 500k. -defineFlow({ - name: 'crm_opportunity_discount_approval', - label: 'Opportunity Discount Approval', - type: 'record_change', - nodes: [ - // The trigger is the START node's config. - { - id: 'start', - type: 'start', - label: 'On Opportunity Update', - config: { - objectName: 'opportunity', - triggerType: 'record-after-update', - condition: cel`record.amount != null && record.amount > 100000`, - }, - }, - { - id: 'manager_review', - type: 'approval', - label: 'Sales Manager Review', - config: { - approvers: [{ type: 'position', value: 'crm_sales_manager' }], - behavior: 'first_response', - lockRecord: true, - approvalStatusField: 'approval_status', - }, - }, - // Decision routing lives on the OUT-EDGES, not in node config: the engine - // evaluates each out-edge's `condition` and follows every match — and an - // out-edge with NO condition ALWAYS runs (all such edges execute in - // PARALLEL). Guard every branch with a condition — see e4/e5 below. - { id: 'needs_director', type: 'decision', label: 'Needs Director?' }, - { - id: 'director_signoff', - type: 'approval', - label: 'Sales Director Sign-off', - config: { - approvers: [{ type: 'position', value: 'crm_sales_director' }], - behavior: 'unanimous', - approvalStatusField: 'approval_status', - }, - }, - { id: 'mark_won', type: 'update_record', label: 'Mark Won', - config: { objectName: 'opportunity', filter: { id: { dialect: 'cel', source: 'record.id' } }, - fields: { stage: 'closed_won' } } }, - { id: 'approved', type: 'end', label: 'Approved' }, - { id: 'rejected', type: 'end', label: 'Rejected' }, - ], - edges: [ - { id: 'e1', source: 'start', target: 'manager_review', - // entry criteria re-homes onto the edge entering the approval node: - condition: cel`record.amount > 100000` }, - { id: 'e2', source: 'manager_review', target: 'needs_director', label: 'approve' }, - { id: 'e3', source: 'manager_review', target: 'rejected', label: 'reject' }, - { id: 'e4', source: 'needs_director', target: 'director_signoff', label: 'true', - condition: cel`record.amount > 500000` }, - { id: 'e5', source: 'needs_director', target: 'mark_won', label: 'false', - condition: cel`record.amount <= 500000` }, - { id: 'e6', source: 'director_signoff', target: 'mark_won', label: 'approve' }, - { id: 'e7', source: 'director_signoff', target: 'rejected', label: 'reject' }, - { id: 'e8', source: 'mark_won', target: 'approved' }, +A record-triggered flow, as JSON: high-value opportunities need manager +sign-off, and director sign-off too when the amount clears 500k. In TypeScript +the same literal goes inside `defineFlow(...)`, and `` cel`…` `` builds each +`{ dialect, source }` envelope. + +- The trigger is the START node's config. +- Decision routing lives on the OUT-EDGES, not in node config: the engine + evaluates each out-edge's `condition` and follows every match — and an + out-edge with NO condition ALWAYS runs (all such edges execute in PARALLEL). + Guard every branch with a condition — `e4` / `e5`. +- Entry criteria re-home onto the edge entering the approval node — `e1`. + +```json +{ + "name": "crm_opportunity_discount_approval", + "label": "Opportunity Discount Approval", + "type": "record_change", + "nodes": [ + { "id": "start", "type": "start", "label": "On Opportunity Update", "config": { + "objectName": "opportunity", "triggerType": "record-after-update", + "condition": { "dialect": "cel", "source": "record.amount != null && record.amount > 100000" } } }, + { "id": "manager_review", "type": "approval", "label": "Sales Manager Review", "config": { + "approvers": [{ "type": "position", "value": "crm_sales_manager" }], + "behavior": "first_response", "lockRecord": true, "approvalStatusField": "approval_status" } }, + { "id": "needs_director", "type": "decision", "label": "Needs Director?" }, + { "id": "director_signoff", "type": "approval", "label": "Sales Director Sign-off", "config": { + "approvers": [{ "type": "position", "value": "crm_sales_director" }], + "behavior": "unanimous", "approvalStatusField": "approval_status" } }, + { "id": "mark_won", "type": "update_record", "label": "Mark Won", "config": { + "objectName": "opportunity", "filter": { "id": { "dialect": "cel", "source": "record.id" } }, + "fields": { "stage": "closed_won" } } }, + { "id": "approved", "type": "end", "label": "Approved" }, + { "id": "rejected", "type": "end", "label": "Rejected" } ], -}); + "edges": [ + { "id": "e1", "source": "start", "target": "manager_review", + "condition": { "dialect": "cel", "source": "record.amount > 100000" } }, + { "id": "e2", "source": "manager_review", "target": "needs_director", "label": "approve" }, + { "id": "e3", "source": "manager_review", "target": "rejected", "label": "reject" }, + { "id": "e4", "source": "needs_director", "target": "director_signoff", "label": "true", + "condition": { "dialect": "cel", "source": "record.amount > 500000" } }, + { "id": "e5", "source": "needs_director", "target": "mark_won", "label": "false", + "condition": { "dialect": "cel", "source": "record.amount <= 500000" } }, + { "id": "e6", "source": "director_signoff", "target": "mark_won", "label": "approve" }, + { "id": "e7", "source": "director_signoff", "target": "rejected", "label": "reject" }, + { "id": "e8", "source": "mark_won", "target": "approved" } + ] +} ``` ### Send-back for revision (ADR-0044) diff --git a/skills/objectstack-data/SKILL.md b/skills/objectstack-data/SKILL.md index 2ea9c8a81c1..37b2a1b4370 100644 --- a/skills/objectstack-data/SKILL.md +++ b/skills/objectstack-data/SKILL.md @@ -56,7 +56,14 @@ metadata: ### Object Definition An **Object** is the fundamental data entity in ObjectStack. It maps to a -database table and exposes automatic CRUD APIs. +database table and exposes automatic CRUD APIs. As JSON (in TypeScript the +same literal goes inside `ObjectSchema.create({...})`): + +```json +{ "name": "crm_account", "label": "Account", "pluralLabel": "Accounts", "icon": "building", + "sharingModel": "public_read_write", + "fields": { "name": { "type": "text", "label": "Name", "required": true } } } +``` **Required properties:** @@ -67,8 +74,7 @@ database table and exposes automatic CRUD APIs. | `sharingModel` | enum | one of the four below | Org-wide default record visibility (OWD). Zod marks it optional, but **a publish with no authored `sharingModel` is refused** with the 422 lint envelope `security-owd-unset` — absence is not a decision. Author it on every object | **`sharingModel` — the four canonical values** (ADR-0090 D4; legacy aliases -removed). A *custom* object that omits it resolves to `private` at runtime, but -the publish door rejects it before that: +removed): | Value | Who can read / write | |:--|:--| @@ -93,7 +99,7 @@ all (Relationship Patterns below). | `pluralLabel` | — | Plural form (e.g., "Accounts") — on 31/31 objects in the reference apps; author it alongside `label` | | `icon` | — | Icon name for nav, list headers and lookup pickers — on 31/31 objects in the reference apps | | `highlightFields` | derived | Ordered field keys used as a record's compact face: the columns a **related list** renders on the parent's detail page, and what a lookup picker shows. Declare it on the CHILD object (see [Relationships](./rules/relationships.md)) | -| `namespace` | — | **Not a schema key** — `ObjectSchema.create()` rejects unknown keys, so authoring it is a build error. Embed the prefix directly in `name` instead (e.g. `name: 'crm_account'`) | +| `namespace` | — | **Not a schema key** — an unknown key is refused, so authoring it is a build error. Embed the prefix directly in `name` instead | | `datasource` | `'default'` | Target datasource ID for virtualized data | | `nameField` | derived (e.g. `'name'`/`'title'`) | **Canonical** record-title field — the stored field used as the record's display name. Use a single text/email field; a composite title to import, sort or search by is a stored computed field (a non-`formula` field with an `expression`); a text formula is display-only | | `displayNameField` | — | **Deprecated** alias for `nameField` (still honored as a fallback) | @@ -279,8 +285,8 @@ lowercase option values — incorrect/correct examples: [rules/naming.md](./rule The full table, per-type config and traps: [rules/field-types.md](./rules/field-types.md). From here, three to get right: credentials are `secret` (**encrypted-at-rest**, ADR-0100) — never `password`, which on a generic object is **plaintext at rest**; `user` is the person -picker; `formula` takes CEL in `expression` (`F\`...\`` from `@objectstack/spec`; see -**objectstack-formula**). +picker; `formula` takes CEL in `expression` (a `{ dialect: 'cel', source }` envelope — +`F\`...\`` in TypeScript; see **objectstack-formula**). - A yes/no flag (`is_*`, `has_*`, "done?", "active?") is `{ type: 'boolean', defaultValue: false }` and never `required`: a checkbox always holds one of its two values, so diff --git a/skills/objectstack-data/references/seeds.md b/skills/objectstack-data/references/seeds.md index 68f2753827f..25c68675dc9 100644 --- a/skills/objectstack-data/references/seeds.md +++ b/skills/objectstack-data/references/seeds.md @@ -155,7 +155,7 @@ produce byte-identical `dist/objectstack.json`. | Practice | Why | |:---------|:----| -| Always use `defineSeed()`, never `SeedSchema.parse()` | Lose compile-time field checking otherwise | +| TypeScript: `defineSeed()`, never `SeedSchema.parse()` | Lose compile-time field checks otherwise | | Prefer natural keys (`code` / `email` / `slug`) | Portable across environments | | Leave `mode` unset; `upsert` only for reference data | Replays keep customer edits | | Scope demo data with `env: ['dev','test']` | Keep noise out of prod | diff --git a/skills/objectstack-data/rules/naming.md b/skills/objectstack-data/rules/naming.md index 6b432356d96..dedd43c8672 100644 --- a/skills/objectstack-data/rules/naming.md +++ b/skills/objectstack-data/rules/naming.md @@ -15,7 +15,7 @@ ObjectStack enforces strict naming conventions to ensure consistency and machine ## Critical Rules 1. **Never** use `camelCase` or `PascalCase` for object names or field keys -2. **Always** use `camelCase` for TypeScript configuration property keys +2. **Always** use `camelCase` for configuration property keys 3. **Option values** must be lowercase machine identifiers (use snake_case for multi-word) 4. **Option labels** can use any case for display purposes 5. **Machine names are immutable** — changing them requires data migration diff --git a/skills/objectstack-data/rules/relationships.md b/skills/objectstack-data/rules/relationships.md index 347e846b4a7..8cad00d2b0a 100644 --- a/skills/objectstack-data/rules/relationships.md +++ b/skills/objectstack-data/rules/relationships.md @@ -183,21 +183,18 @@ A parent `summary` field aggregates a child collection. The engine recomputes it **server-side** whenever a child is inserted/updated/deleted (inside the same transaction as the write, so it's consistent). -```typescript +```json { - type: 'summary', - summaryOperations: { - object: 'invoice_line', // child object to aggregate - field: 'amount', // child field to aggregate (ignored for count) - function: 'sum', // 'count' | 'sum' | 'min' | 'max' | 'avg' - // relationshipField: 'invoice' // optional; auto-detected from the child's - // master_detail/lookup field referencing - // this parent when omitted - // filter: { status: 'received' } // optional; see below - }, + "type": "summary", + "summaryOperations": { "object": "invoice_line", "field": "amount", "function": "sum" } } ``` +`object` is the child object to aggregate, `field` its field (ignored for +`count`), `function` one of `count` / `sum` / `min` / `max` / `avg`. Optional: +`relationshipField` (auto-detected from the child's `master_detail`/`lookup` +field referencing this parent when omitted) and `filter` (below). + Empty collections roll up to `0` for `count`/`sum`, `null` for `min`/`max`/`avg`. **Pick the function from the request's own words, and put every qualifier in @@ -233,14 +230,19 @@ blank or beside `readable: false`); neither → mask the summary on that set, after removing any Modify All it holds on the parent (it overrides the mask). Never add the reason to silence a total the request withholds: mask it. -```typescript -definePermissionSet({ - name: 'client_viewer', - objects: { project: { allowRead: true } }, // no `task` read: warned - fields: { 'project.task_count': { readable: false } }, // the mask: resolved - // or, clients are meant to see the count: acknowledged, a note - // fields: { 'project.task_count': { readable: true, rollupSourceUnreadableReason: 'Clients see progress counts, not tasks' } }, -}) +A permission set (in TypeScript, the argument of `definePermissionSet(...)`) +with no `task` read — warned; `task_count` masked — resolved; `hours_total`, +which clients are meant to see, acknowledged — a note: + +```json +{ + "name": "client_viewer", + "objects": { "project": { "allowRead": true } }, + "fields": { + "project.task_count": { "readable": false }, + "project.hours_total": { "readable": true, "rollupSourceUnreadableReason": "Clients see progress totals, not tasks" } + } +} ``` ## Inline Editing (Master-Detail Entry) diff --git a/skills/objectstack-data/rules/validation.md b/skills/objectstack-data/rules/validation.md index 0ab8ed31741..ff3182abfea 100644 --- a/skills/objectstack-data/rules/validation.md +++ b/skills/objectstack-data/rules/validation.md @@ -100,26 +100,27 @@ driver layer. See [indexing.md](./indexing.md) for index options. ## State Machine Validation -```typescript -validations: [ - { - name: 'status_flow', - type: 'state_machine', - field: 'status', - initialStates: ['draft'], // the one state a record may be CREATED in - transitions: { - draft: ['submitted', 'cancelled'], - submitted: ['in_review', 'cancelled'], - in_review: ['approved', 'rejected'], - approved: ['published'], - rejected: ['draft'], - published: [], // Terminal state - cancelled: [], // Terminal state - }, - message: 'Invalid status transition', - severity: 'error', +A `validations[]` entry. `initialStates` holds the one state a record may be +CREATED in; `[]` marks a terminal state: + +```json +{ + "name": "status_flow", + "type": "state_machine", + "field": "status", + "initialStates": ["draft"], + "transitions": { + "draft": ["submitted", "cancelled"], + "submitted": ["in_review", "cancelled"], + "in_review": ["approved", "rejected"], + "approved": ["published"], + "rejected": ["draft"], + "published": [], + "cancelled": [] }, -] + "message": "Invalid status transition", + "severity": "error" +} ``` ## Format Validation diff --git a/skills/objectstack-ui/SKILL.md b/skills/objectstack-ui/SKILL.md index 1f880f8cb7d..f8ae01588ba 100644 --- a/skills/objectstack-ui/SKILL.md +++ b/skills/objectstack-ui/SKILL.md @@ -130,13 +130,18 @@ type's keys: [Navigation](./rules/navigation.md). ## Actions **An operation is an `action`, never a view, and a write button must write.** -"Mark as done", "approve", "set status to X" is `defineAction` with -`objectName` and `locations`; with neither `locations` nor a view naming it, +"Mark as done", "approve", "set status to X" is an action (`defineAction` in +TypeScript) with `objectName` and `locations`; with neither `locations` nor a view naming it, it renders nowhere. `ctx.record` is a read-only snapshot and the body's return value is applied to nothing: a body that returns or assigns the new values -reports success and changes nothing. Call the API: `type: 'script'`, -`body: { language: 'js', source: "await ctx.api.object('task').update({ id: ctx.recordId, status: 'done' });", capabilities: ['api.write'] }`, -with the option `value`, never its label ([Actions](./rules/actions.md)). +reports success and changes nothing. Call the API, with the option `value`, +never its label ([Actions](./rules/actions.md)): + +```json +{ "name": "mark_done", "label": "Mark as done", "objectName": "task", "locations": ["record_header"], + "type": "script", "body": { "language": "js", "capabilities": ["api.write"], + "source": "await ctx.api.object('task').update({ id: ctx.recordId, status: 'done' });" } } +``` ### Action Types