diff --git a/.changeset/34686-skill-single-source.md b/.changeset/34686-skill-single-source.md new file mode 100644 index 00000000000..cde459ac788 --- /dev/null +++ b/.changeset/34686-skill-single-source.md @@ -0,0 +1,20 @@ +--- +'@objectstack/mcp': patch +--- + +fix(mcp): the data loop on `GET /mcp/skill` is the published `objectstack-ask` skill's text + +Clause-②: no +Metadata-protocol: none + +The page an open server serves at `GET /mcp/skill` taught the governed-metric procedure in its own hand-written words, and those words had drifted from the published `objectstack-ask` skill. The page now carries the skill's own steps, generated from `skills/objectstack-ask/SKILL.md` into the package, under a new section **Answering a business question**. A test fails when the two differ. + +What a connected client now reads on that page, where it reads differently from before: + +- Each word for a thing measured is decided on its own: two words with one measure each are two metrics, computed both, not a question for the user. One word that matches several measures is still a question. +- A word with no match that is a loose form of several listed measures (a bare "revenue" beside Won Revenue, Annual Revenue and Planned Revenue) is a question too, with nothing computed yet. One near form selects nothing. +- `membersWithheld: true` is reported as members (measures or groupings) the user may not read, and the metric asked for may be among them. +- The fallback to object queries reads the object's fields first, uses `aggregate_records` rather than adding pages up, opens with a line saying the answer is not from a governed metric, and names a listed dataset on that object when there is one. +- The answer is written in the user's language, with labels rather than machine names, and states its filter and time window. + +The two dataset tool entries in the page's tool list now give only each tool's signature and what its answer carries. The section renders where it did before and nowhere else: only when the host carries the dataset tools and the grant has `data:read` (or names no scopes). Pages for other hosts and grants are byte-identical to before. diff --git a/packages/mcp/src/ask-skill.generated.ts b/packages/mcp/src/ask-skill.generated.ts new file mode 100644 index 00000000000..6ba5fb44d5e --- /dev/null +++ b/packages/mcp/src/ask-skill.generated.ts @@ -0,0 +1,93 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// GENERATED by scripts/gen-mcp-ask-skill.mjs from skills/objectstack-ask/SKILL.md. +// Do not edit this file: change the skill, then run `node scripts/gen-mcp-ask-skill.mjs`. + +/** + * The ask-data skill's data loop: its body after the title, served under its + * own heading by `renderSkillMarkdown` (`skill-md.ts`) where the dataset tools + * register for the grant. One source: the published skill. + */ +export const ASK_SKILL_DATA_LOOP: string = [ + 'You are connected to a live environment through its MCP tools, and the user', + 'asked for a figure or a list from its data. Work these steps in order for every', + 'question. Never skip step 1: a governed metric (a dataset measure whose owner', + 'wrote its business definition) outranks a number you work out yourself.', + '', + '## 1. Lift the business words and look for a governed metric', + '', + '- Lift the question\'s business words: the thing measured ("win rate", "营收",', + ' "商机数") and what it is grouped or filtered by ("by stage", "按行业").', + '- Call `list_datasets({ terms })` with those words, as the user wrote them and', + ' in the user\'s language. Do not translate or reword a term: a match on a word', + ' you supplied is your reading, not the user\'s.', + '- Each dataset in the answer carries `matches`: one entry per hit, with the', + ' `term`, the `member` it names (`measures.` or `dimensions.`) and', + ' `matchedOn`. A word matches only when it equals a member\'s name, label or', + ' synonym (case, spacing, `_` and `-` aside), never by similarity.', + '- No `list_datasets` among your tools: this environment serves you no governed', + ' metrics. Go to step 4.', + '', + '## 2. Decide by the matches', + '', + '| What the answer shows | What you do |', + '|:--|:--|', + '| Each word for a thing measured matches exactly one measure | Compute: step 3. Two words with one measure each ("营收和赢单率") are two metrics, not a choice: compute both, with one `query_dataset` per dataset. |', + '| One word matches several measures, in one dataset or in two | Ask the user which one they mean. List each candidate\'s label, its dataset\'s label and its description. Do not pick one. |', + '| Only a dimension matches | That is a grouping ("by stage"), not a number. You still need a measure match; without one, ask which number is meant. |', + '| Nothing matches, and the word is a loose form of several listed measures | Ask the user which one they mean, listing the same three things. Do not pick one, and compute nothing yet. |', + '| Nothing matches, and the listed measures do not offer several readings of the word | Step 4, and say in the answer that no governed metric was used. One near form is not a match either: it selects nothing. |', + '| `membersWithheld: true` on a dataset | Say that it has members (measures or groupings) you may not read; the metric asked for may be among them. Do not say the metric does not exist. |', + '', + 'The same answer lists every dataset you may query with all its measures,', + 'matched or not (a call without `terms` returns that catalogue too), so the', + 'loose-form check needs no second read. A loose form is a word a listed', + 'measure\'s name, label or description contains, directly or in translation:', + '"revenue" against Won Revenue, Annual Revenue and Planned Revenue; "金额"', + 'against several amounts.', + '', + 'When you ask, the reply is the question alone: no figure, and no tool call', + 'until the user answers. `partial: true` on the answer means the catalogue may', + 'be incomplete; `warning` says why, and you repeat it when you fall back.', + '', + '## 3. Compute a governed metric', + '', + '- `query_dataset({ datasetName, selection })`. `selection.measures` and', + ' `selection.dimensions` take the names `list_datasets` gave;', + ' `selection.runtimeFilter` filters; `selection.dateGranularity` buckets a date', + ' dimension for a trend; `selection.order` and `selection.limit` rank.', + '- Cite the source from the answer\'s `provenance` (the dataset\'s label and each', + ' measure\'s label, as in 「指标:营收(数据集:销售分析)」), not from memory.', + '- Use the measure\'s `description` to say what the number includes and excludes.', + '- `truncated: true`: more rows existed than came back. Say the result is', + ' partial. A `warning` on the answer narrows what you were allowed to read:', + ' repeat it.', + '', + '## 4. Fallback: object queries', + '', + '- `list_objects`, then `describe_object({ objectName })` on the object you will', + ' read. Read its fields before you filter: a field with `options` is filtered', + ' by the option\'s `value`, never its label.', + '- Use `aggregate_records` for a count, sum, average or breakdown. Never page', + ' through `query_records` to add numbers up yourself. `truncated: true` on its', + ' answer means groups were cut off: say so.', + '- Open the answer with one line saying it is not from a governed metric', + ' (非指标口径), and name the object and fields you computed it from.', + '- When that object is a listed dataset\'s `object`, add one line naming the', + ' dataset and its measures, so the user can ask for the governed figure.', + '', + '## 5. When the data cannot answer', + '', + '- No metric, object or field records what the question needs: say the data you', + ' can read does not record it, name what is missing (such as a shipment\'s', + ' weight), and offer the computation if the user supplies it.', + '- Never fill the gap with an assumed value, and never draw a conclusion from', + ' one.', + '', + '## 6. Writing the answer', + '', + '- Answer in the user\'s language.', + '- Show labels, not machine names or raw option values.', + '- Every figure comes from a tool answer in this conversation.', + '- State the filter and the time window you used, in words.', +].join('\n'); diff --git a/packages/mcp/src/mcp-dataset-tools.test.ts b/packages/mcp/src/mcp-dataset-tools.test.ts index 01401a281a0..83b1c21a62e 100644 --- a/packages/mcp/src/mcp-dataset-tools.test.ts +++ b/packages/mcp/src/mcp-dataset-tools.test.ts @@ -26,7 +26,7 @@ import { RETIRED_KEY_UPGRADE_GUIDE_SENTENCE } from '@objectstack/spec/shared'; import { MCPServerRuntime } from './mcp-server-runtime.js'; import { hasDatasetTools, type McpDataBridge } from './mcp-http-tools.js'; import { createStdioDataBridge, type StdioDatasetToolsService } from './stdio-data-bridge.js'; -import { renderSkillMarkdown } from './skill-md.js'; +import { ASK_SECTION_HEADING, renderSkillMarkdown } from './skill-md.js'; const DATASET_TOOLS = [LIST_DATASETS_TOOL_NAME, QUERY_DATASET_TOOL_NAME].sort(); @@ -273,23 +273,22 @@ describe('[ADR-0149 D2] dataset tools on MCP — calls', () => { }); describe('[ADR-0149 D3] the SKILL.md teaches the selection rule where the pair registers', () => { - it('renders both tools and the rule for a host whose bridge carries them', () => { + it('renders both tools and the ask-data data loop for a host whose bridge carries them', () => { const md = renderSkillMarkdown({ datasetTools: true }); for (const name of DATASET_TOOLS) expect(md).toContain(`**${name}(`); - expect(md).toContain('Choosing between a metric and an object query'); + expect(md).toContain(`\n${ASK_SECTION_HEADING}\n`); }); - it('renders the rule for a question the data cannot answer beside the selection rule', () => { + // [#34686] The data loop's words (the selection rule, the fallback, and a + // question the data cannot answer) are the published ask-data skill's, and + // skill-single-source-34686.test.ts pins the served section byte-equal to + // it. What stays here is where the section sits and when it is absent. + it('renders the data loop after the tool entries, and not without the pair', () => { const md = renderSkillMarkdown({ datasetTools: true }); - const rule = md.indexOf('**When the data cannot answer.**'); - expect(rule).toBeGreaterThan(md.indexOf('Choosing between a metric and an object query')); - const text = md.slice(rule, md.indexOf('\n- ', rule) === -1 ? undefined : md.indexOf('\n- ', rule)); - expect(text).toContain('say the data you can read does not record it'); - expect(text).toContain('offer the computation'); - expect(text).toContain('Never fill the gap with an assumed value'); - expect(text).toContain('nor draw a conclusion from one'); - expect(text).toContain('Any figure you add comes from a tool answer; cite it.'); - expect(renderSkillMarkdown({})).not.toContain('When the data cannot answer'); + const section = md.indexOf(`\n${ASK_SECTION_HEADING}\n`); + expect(section).toBeGreaterThan(md.indexOf('**query_dataset(')); + expect(section).toBeLessThan(md.indexOf('\n## Conventions & gotchas')); + expect(renderSkillMarkdown({})).not.toContain(ASK_SECTION_HEADING); }); it('renders them for a data:read grant, and not without one or without the pair', () => { diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index f7962db531b..48e6ec71a2d 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1802,10 +1802,12 @@ const DEFAULT_HTTP_INSTRUCTIONS = * (ADR-0149 D3), in the few lines `initialize` carries. It rides the * instructions because a client reads a tool's description only after it has * chosen that tool (#34659 ruling D5 = A); the full procedure stays in the - * tools' own descriptions and in the served skill (`DATASET_TOOL_LINES` in - * `skill-md.ts`), which say the same thing: an exact name, label or synonym is - * the only match, one measure match answers, several are a question for the - * user, none falls back to the object tools with the answer labelled. + * tools' own descriptions and in the served skill's data loop + * (`ASK_SKILL_DATA_LOOP`, generated from `skills/objectstack-ask/SKILL.md` and + * rendered by `skill-md.ts`). All three hold an exact name, label or synonym as + * the only match, one measure match as the answer, and several matches on one + * word as a question for the user; the skill also asks before it falls back + * when a word with no match is a loose form of several listed measures. * Sent only where both dataset tools register ({@link datasetToolsServed}). */ const DATASET_SELECTION_RULE = diff --git a/packages/mcp/src/skill-md.ts b/packages/mcp/src/skill-md.ts index 15da3d35bb0..a4e15c8be99 100644 --- a/packages/mcp/src/skill-md.ts +++ b/packages/mcp/src/skill-md.ts @@ -32,6 +32,7 @@ import type { AIToolDefinition } from '@objectstack/spec/contracts'; import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE, MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; +import { ASK_SKILL_DATA_LOOP } from './ask-skill.generated.js'; import { DELETE_AMBIGUOUS_ASKS_FIRST, DELETE_NAMED_RECORD_IS_APPROVAL, @@ -125,7 +126,8 @@ export interface RenderSkillOptions { /** * [ADR-0149 D2] Whether the host's bridge carries the dataset pair * (`list_datasets` / `query_dataset`, `registerDatasetTools`). The entries, - * and the D3 selection rule that teaches a client when to use them, render + * and the ask-data skill's data loop that teaches a client when to use them + * (#34686: generated from the published skill), render * only when this is true AND {@link grantedScopes} admit `data:read`, so the * skill names them exactly where `tools/list` lists them. Default false: the * renderer cannot see the bridge, so the host says so. @@ -253,50 +255,55 @@ const NEW_RECORD_UPLOAD_LINK_LINES = ` For a record you have not created yet (a `; /** - * [ADR-0149 D2/D3] The dataset pair's entries and the selection rule that - * tells a client when a governed metric answers instead of an object query. - * The rule is ADR-0149 D3's, in the client's terms: an exact word match - * (after normalization) is the only hit, one hit wins, several hits are a - * question for the user, no hit falls back to the object tools with the - * answer labelled as not a governed metric, and a dimension alone is not an - * answer. The last entry covers a question no tool can answer: name what the - * data lacks, never answer from an assumed value. + * [ADR-0149 D2] The dataset pair's entries in the tool list: each tool's + * signature and what its answer carries, in a sentence. When to call them and + * how to read their answers (ADR-0149 D3's selection rule, the fallback, and a + * question the data cannot answer) is {@link ASK_SECTION_HEADING}'s section, + * which the published skill writes. */ const DATASET_TOOL_LINES = `- **list_datasets({ terms? })** — the governed datasets (business metrics) you may query: each dataset's measures and dimensions with their business - labels, descriptions and synonyms. Pass the business words of the question - as \`terms\`; the answer's \`matches\` says which member each word names - exactly. \`membersWithheld: true\` means some measures exist that you may not - read: say so rather than saying the metric does not exist. -- **query_dataset({ datasetName, selection })** — compute a governed metric: - \`selection\` takes \`measures\`, \`dimensions\` and a \`runtimeFilter\`, by - the names \`list_datasets\` gives. The answer carries \`provenance\` (the - dataset and measures used); cite the source from it, not from memory, and - use a measure's \`description\` to explain what the number includes. -- **Choosing between a metric and an object query.** Call \`list_datasets\` - with the question's business words first. A word matches only when it - equals a member's name, label or synonym (case, spacing, \`_\` and \`-\` - aside), never by similarity. One measure match: answer with - \`query_dataset\`. Several matches (two datasets or two members): ask the - user which one they mean, listing each candidate's label, dataset and - description; do not pick. No match: fall back to \`query_records\` / - \`aggregate_records\` and say the answer is not from a governed metric. A - dimension match alone (a grouping such as "by stage") is not an answer: you - still need a measure match, or ask. -- **When the data cannot answer.** No metric, object or field records what the - question needs: say the data you can read does not record it and name what - is missing (such as a shipment's weight), and offer the computation if the - user supplies it. Never fill the gap with an assumed value, - nor draw a conclusion from one ("under a typical term, none would…"). - Any figure you add comes from a tool answer; cite it. + labels, descriptions and synonyms, and, for the \`terms\` you pass, the + \`matches\` each word made. +- **query_dataset({ datasetName, selection })** — compute a governed metric + by the names \`list_datasets\` gives; the answer carries \`provenance\`. + When to call these two, and how to read their answers: the section + **Answering a business question** below. `; -/** The dataset pair's entries for a host whose bridge carries them, under the grant that registers them. */ -function renderDatasetToolLines(options: RenderSkillOptions): string { - if (options.datasetTools !== true) return ''; +/** + * [#34686] The heading the served page gives the ask-data skill's data loop. + * The text under it is {@link ASK_SKILL_DATA_LOOP}, generated from + * `skills/objectstack-ask/SKILL.md` (`scripts/gen-mcp-ask-skill.mjs`) and pinned + * equal to it by `skill-single-source-34686.test.ts`: the published skill is + * the one source, and nothing here restates it. + */ +export const ASK_SECTION_HEADING = '## Answering a business question'; + +/** + * Whether this render teaches the dataset pair: a host whose bridge carries + * them, under a grant that registers them. + */ +function datasetToolsTaught(options: RenderSkillOptions): boolean { + if (options.datasetTools !== true) return false; // Mirrors the gate in `registerDatasetTools` (`!scopes || scopes.includes(data:read)`). const scopes = options.grantedScopes; - return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ) ? DATASET_TOOL_LINES : ''; + return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ); +} + +/** The dataset pair's entries in the tool list, where {@link datasetToolsTaught}. */ +function renderDatasetToolLines(options: RenderSkillOptions): string { + return datasetToolsTaught(options) ? DATASET_TOOL_LINES : ''; +} + +/** + * [#34686] The ask-data skill's data loop under its own heading, where + * {@link datasetToolsTaught}. It renders after every other block of the tool + * list and before the conventions, so a render that does not teach the pair is + * byte-identical to one from before this section existed. + */ +function renderAskSection(options: RenderSkillOptions): string { + return datasetToolsTaught(options) ? `\n${ASK_SECTION_HEADING}\n\n${ASK_SKILL_DATA_LOOP}\n` : ''; } /** The file pair's entries for a host whose bridge carries them, each for the grant that registers it. */ @@ -522,7 +529,7 @@ create/update payload. (the person's confirmation, in your client or in the app, for an action its author declared \`requiresConfirmation\`, the refusal of a call that sends \`confirm\`, and its refusal under an AI service account's own key whatever the call sends). -${renderFileToolLines(options)}${renderDatasetToolLines(options)}${options.federationTools === true && grantsAuthoringTools(options.grantedScopes) ? FEDERATION_TOOL_LINES : ''}${authoringTools ? renderAuthoringSection(authoringTools, describeObjectRegistered) : ''}${dataOnlyBlock} +${renderFileToolLines(options)}${renderDatasetToolLines(options)}${options.federationTools === true && grantsAuthoringTools(options.grantedScopes) ? FEDERATION_TOOL_LINES : ''}${authoringTools ? renderAuthoringSection(authoringTools, describeObjectRegistered) : ''}${dataOnlyBlock}${renderAskSection(options)} ## Conventions & gotchas - **Permissions/RLS apply to every call.** Fewer rows than expected, or a diff --git a/packages/mcp/src/skill-single-source-34686.test.ts b/packages/mcp/src/skill-single-source-34686.test.ts new file mode 100644 index 00000000000..add06151f13 --- /dev/null +++ b/packages/mcp/src/skill-single-source-34686.test.ts @@ -0,0 +1,96 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34686] The data loop `GET /mcp/skill` serves is the published ask-data + * skill's, byte for byte: one source. + * + * The served page renders `ASK_SKILL_DATA_LOOP` (`ask-skill.generated.ts`) + * under `ASK_SECTION_HEADING`; `scripts/gen-mcp-ask-skill.mjs` writes that + * module from `skills/objectstack-ask/SKILL.md`. This file reads the skill + * itself and holds both halves equal to it: the generated module, and the + * section of the page `renderSkillMarkdown` returns (the render the route + * serves). A skill edit without a regeneration, or a hand edit of the module, + * goes red here. + * + * The section rides the dataset tools' gate unchanged: only a host whose bridge + * carries the pair (`datasetTools: true`), and only for a grant that admits + * `data:read` or names no scopes, as `registerDatasetTools` registers them. + */ + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, it, expect } from 'vitest'; +import { + MCP_OAUTH_SCOPE_DATA_READ, + MCP_OAUTH_SCOPE_DATA_WRITE, + MCP_OAUTH_SCOPE_METADATA_WRITE, +} from '@objectstack/spec/ai'; + +import { ASK_SKILL_DATA_LOOP } from './ask-skill.generated.js'; +import { ASK_SECTION_HEADING, renderSkillMarkdown } from './skill-md.js'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const SKILL_PATH = resolve(HERE, '../../../skills/objectstack-ask/SKILL.md'); + +/** + * The skill's body after its one H1 title line, blank lines at either end + * dropped: the same rule `scripts/gen-mcp-ask-skill.mjs` states. + */ +function skillDataLoop(): string { + const lines = readFileSync(SKILL_PATH, 'utf8').replace(/\r\n/g, '\n').split('\n'); + const title = lines.findIndex((line) => line.startsWith('# ')); + expect(title, 'skills/objectstack-ask/SKILL.md has no title line').toBeGreaterThan(0); + return lines.slice(title + 1).join('\n').replace(/^\n+/, '').replace(/\n+$/, ''); +} + +const REGENERATE = 'run `node scripts/gen-mcp-ask-skill.mjs` and commit packages/mcp/src/ask-skill.generated.ts'; +const CONVENTIONS = '\n## Conventions & gotchas'; + +/** The text the page serves under the ask heading, up to the next fixed section. */ +function servedDataLoop(md: string): string | undefined { + const start = md.indexOf(`\n${ASK_SECTION_HEADING}\n`); + if (start === -1) return undefined; + const end = md.indexOf(CONVENTIONS, start); + expect(end, 'the ask section is followed by the conventions section').toBeGreaterThan(start); + return md.slice(start + ASK_SECTION_HEADING.length + 2, end).replace(/^\n+/, '').replace(/\n+$/, ''); +} + +describe('[#34686] /mcp/skill data loop: the published ask-data skill is its one source', () => { + it('the generated module equals the skill\'s data loop', () => { + expect(ASK_SKILL_DATA_LOOP, REGENERATE).toBe(skillDataLoop()); + }); + + it('the served section equals the skill\'s data loop, for every grant that is taught the dataset pair', () => { + const skill = skillDataLoop(); + const renders = [ + renderSkillMarkdown({ datasetTools: true }), + renderSkillMarkdown({ datasetTools: true, mcpUrl: 'https://acme.example/api/v1/mcp', fileTools: true, newRecordUploadLinks: true }), + renderSkillMarkdown({ datasetTools: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }), + renderSkillMarkdown({ + datasetTools: true, + grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_METADATA_WRITE], + authoringTools: [{ name: 'create_object', description: 'Create a draft object.' }], + }), + ]; + for (const md of renders) expect(servedDataLoop(md), REGENERATE).toBe(skill); + }); + + it('the gate still drops it: no section without data:read, and none where the host carries no dataset pair', () => { + const skill = skillDataLoop(); + const firstStep = skill.split('\n').find((line) => line.startsWith('## ')); + expect(firstStep).toBeDefined(); + const dropped = [ + renderSkillMarkdown({ datasetTools: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] }), + renderSkillMarkdown({ datasetTools: true, grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE] }), + renderSkillMarkdown({ datasetTools: true, grantedScopes: [] }), + renderSkillMarkdown({}), + renderSkillMarkdown({ datasetTools: false, grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }), + ]; + for (const md of dropped) { + expect(servedDataLoop(md)).toBeUndefined(); + expect(md).not.toContain(firstStep!); + expect(md).not.toContain('list_datasets'); + } + }); +}); diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index 74f758d5a75..5179b99a628 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -1117,10 +1117,22 @@ export const CROSS_PACKAGE_TEST_INPUTS = { // when Test UI does, which a diff confined to this package never starts; // this half runs on every change to the render's inputs, and a change to // the mirror has to re-run it too. + // + // src/skill-single-source-34686.test.ts reads the published ask-data skill + // and pins the data loop `GET /mcp/skill` serves (the generated + // `ask-skill.generated.ts`, rendered by `renderSkillMarkdown`) byte-equal + // to it: the skill is the one source, so an edit to it alone has to re-run + // this suite, or the served copy drifts with the gate green. One file, not + // `skills/**`: nothing else under the catalog is read. The same test names + // `scripts/gen-mcp-ask-skill.mjs`, the generator that writes the module, in + // its failure text: declared beside the skill, since the module's shape is + // that script's output. globs: [ 'scripts/js-comment-mask.mjs', 'scripts/js-comment-mask.d.mts', 'ui/apps/console/src/pages/developer/objectstack-skill.ts', + 'skills/objectstack-ask/SKILL.md', + 'scripts/gen-mcp-ask-skill.mjs', ], }, '@objectstack/metadata': { diff --git a/scripts/gen-mcp-ask-skill.mjs b/scripts/gen-mcp-ask-skill.mjs new file mode 100644 index 00000000000..ac6fca3ded7 --- /dev/null +++ b/scripts/gen-mcp-ask-skill.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * gen-mcp-ask-skill -- render `packages/mcp/src/ask-skill.generated.ts` from the + * published ask-data skill, `skills/objectstack-ask/SKILL.md`. + * + * node scripts/gen-mcp-ask-skill.mjs # write the module + * node scripts/gen-mcp-ask-skill.mjs --check # exit 1 when the module is stale, write nothing + * + * ## Why a generated module, and not a read of the skill at run time + * + * `GET /mcp/skill` serves the ask-data procedure (the data loop) to every MCP + * client of an open server, and the published skill is its one source. Neither + * of the two cheaper routes survives publishing: + * + * - `@objectstack/mcp` ships `dist`, README and CHANGELOG only, so a read of + * `skills/**` from disk answers nothing in an installed package; and + * `@objectstack/skills` exports only its `package.json`, so a runtime + * dependency on it would mean a filesystem read of another package's build + * output on every host, edge runtimes included. + * - An import the bundler inlines (`skills/...SKILL.md` through an esbuild text + * loader) builds from a path outside the package, and turbo hashes a + * package's build from its own directory (`turbo.json`, `build.inputs`): a + * change to the skill alone would replay a cached `dist` with the old text. + * + * A module committed under the package's own `src/` is hashed with it, ships in + * its `dist`, and is held equal to the skill by + * `packages/mcp/src/skill-single-source-34686.test.ts`, which reads the skill + * and fails when the two differ. Its failure text names this script. + * + * ## What is copied + * + * The skill's body after its title: every line after the first line that + * starts with `# ` (the one H1), with leading and trailing blank lines + * dropped. The frontmatter and the title stay with the skill: the served page + * has its own frontmatter, and gives the text its own heading. The pin test + * applies the same rule to the file it reads, so the rule is stated in two + * places that must agree, and the pin goes red when they do not. + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const REPO = resolve(HERE, '..'); +const SKILL = resolve(REPO, 'skills/objectstack-ask/SKILL.md'); +const MODULE = resolve(REPO, 'packages/mcp/src/ask-skill.generated.ts'); +const SKILL_REL = 'skills/objectstack-ask/SKILL.md'; +const SELF_REL = 'scripts/gen-mcp-ask-skill.mjs'; + +function fail(message) { + process.stderr.write(`gen-mcp-ask-skill: ${message}\n`); + process.exit(2); +} + +/** The skill's body after its one H1 title line, blank lines at either end dropped. */ +function dataLoopText(markdown) { + const lines = markdown.replace(/\r\n/g, '\n').split('\n'); + const title = lines.findIndex((line) => line.startsWith('# ')); + if (title === -1) fail(`${SKILL_REL} has no title line (a line starting with "# "); nothing to copy.`); + return lines.slice(title + 1).join('\n').replace(/^\n+/, '').replace(/\n+$/, ''); +} + +/** One line as a single-quoted TypeScript string literal. */ +function literal(line) { + // A control character would be invisible in the module and in review: refuse it. + if (/[\u0000-\u001f\u007f]/.test(line)) fail(`${SKILL_REL} carries a control character; refusing to copy it.`); + return `'${line.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`; +} + +function renderModule(text) { + const body = text.split('\n').map((line) => ` ${literal(line)},`).join('\n'); + return `// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// GENERATED by ${SELF_REL} from ${SKILL_REL}. +// Do not edit this file: change the skill, then run \`node ${SELF_REL}\`. + +/** + * The ask-data skill's data loop: its body after the title, served under its + * own heading by \`renderSkillMarkdown\` (\`skill-md.ts\`) where the dataset tools + * register for the grant. One source: the published skill. + */ +export const ASK_SKILL_DATA_LOOP: string = [ +${body} +].join('\\n'); +`; +} + +const args = process.argv.slice(2); +const unknown = args.filter((a) => a !== '--check'); +if (unknown.length > 0) fail(`unknown argument(s): ${unknown.join(' ')} (usage: node ${SELF_REL} [--check])`); + +const expected = renderModule(dataLoopText(readFileSync(SKILL, 'utf8'))); +let current; +try { + current = readFileSync(MODULE, 'utf8'); +} catch { + current = undefined; +} + +if (args.includes('--check')) { + if (current === expected) { + process.stdout.write(`gen-mcp-ask-skill: packages/mcp/src/ask-skill.generated.ts is current with ${SKILL_REL}.\n`); + process.exit(0); + } + process.stderr.write( + `gen-mcp-ask-skill: packages/mcp/src/ask-skill.generated.ts is ${current === undefined ? 'missing' : 'stale'} ` + + `against ${SKILL_REL}. Run: node ${SELF_REL}\n`, + ); + process.exit(1); +} + +if (current === expected) { + process.stdout.write('gen-mcp-ask-skill: unchanged.\n'); +} else { + writeFileSync(MODULE, expected); + process.stdout.write(`gen-mcp-ask-skill: wrote packages/mcp/src/ask-skill.generated.ts from ${SKILL_REL}.\n`); +} diff --git a/scripts/pm/dispatch-gates.data.mjs b/scripts/pm/dispatch-gates.data.mjs index c99084ad9b7..d548b277609 100644 --- a/scripts/pm/dispatch-gates.data.mjs +++ b/scripts/pm/dispatch-gates.data.mjs @@ -523,6 +523,18 @@ export const COMPOUND_ANCHOR_LEDGER = [ * one `Thread session:` line against the reader that lists a card thread on * its seat's roster — the same population claim, on a third governed file, * named on the same `self-test-reads` line. + * + * ## The eighth row: a generator whose INPUT is a published skill + * + * `scripts/gen-mcp-ask-skill.mjs` renders the mcp package's committed + * `ask-skill.generated.ts` from the published ask-data skill, so the governed + * file is its input, not a fixture — the fourth row's shape. It spells that + * path in its module body and has no self-test, so `declared` is false: there + * is no `self-test-reads` line for it to carry. No family runs it, so the + * census's DERIVED case has no family to place it under; what holds the + * module equal to the skill is the mcp package's single-source pin test, + * which reads the skill and is re-run by an edit to it through that + * package's cross-package test inputs, not by a gate family. */ export const GOVERNED_READ_FLOOR = Object.freeze([ Object.freeze({ script: 'scripts/check-commit-card-trailers.mjs', file: '.claude/agents/os-dev.md', declared: false }), @@ -531,6 +543,11 @@ export const GOVERNED_READ_FLOOR = Object.freeze([ file: 'skills/objectstack-platform/SKILL.md', declared: false, }), + Object.freeze({ + script: 'scripts/gen-mcp-ask-skill.mjs', + file: 'skills/objectstack-ask/SKILL.md', + declared: false, + }), Object.freeze({ script: 'scripts/pm/check-expected-skips.mjs', file: '.claude/skills/pm-dispatch/SKILL.md', diff --git a/turbo.json b/turbo.json index 484526f010e..33ab50ab6e7 100644 --- a/turbo.json +++ b/turbo.json @@ -439,7 +439,9 @@ "!.turbo/**", "$TURBO_ROOT$/scripts/js-comment-mask.mjs", "$TURBO_ROOT$/scripts/js-comment-mask.d.mts", - "$TURBO_ROOT$/ui/apps/console/src/pages/developer/objectstack-skill.ts" + "$TURBO_ROOT$/ui/apps/console/src/pages/developer/objectstack-skill.ts", + "$TURBO_ROOT$/skills/objectstack-ask/SKILL.md", + "$TURBO_ROOT$/scripts/gen-mcp-ask-skill.mjs" ] }, "@objectstack/runtime#test": {