diff --git a/.changeset/39102-app-skill-text-cap.md b/.changeset/39102-app-skill-text-cap.md new file mode 100644 index 00000000000..430b80588d9 --- /dev/null +++ b/.changeset/39102-app-skill-text-cap.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': minor +'@objectstack/cli': minor +'@objectstack/metadata-protocol': minor +'@object-ui/i18n': minor +--- + +feat!: an app's skills on the ask surface are capped at 8,000 characters, and os validate, the build and the metadata save door refuse an app over it; Studio's Skills page shows each app's total + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing at `os validate`, `os build` and the metadata save door (`@objectstack/cli`, `@objectstack/metadata-protocol`), for an app (package) whose skills with `surface` `ask` or `both` (or unset) add up to more than 8,000 characters: FROM the app building and its skill saves being stored TO `os validate` / `os build` failing it, and a skill save that raises its total refused `422 INVALID_METADATA`, each naming the total and the cap. The one-line fix: trim the app's ask skill text to 8,000 characters or fewer (shorten `description` / `instructions`, drop unneeded `tools`, or set `surface: 'build'` on a skill the ask agent does not need). No key is removed and no stored skill is rewritten. + +The hosted `ask` agent puts every skill an app (package) binds on the `ask` surface into its system prompt and caps that text per app. The cap and its one measure are now declared in the spec, and every door counts with them: + +- `@objectstack/spec/ai` exports `PACKAGE_SKILL_TEXT_CAP` (8,000), `composeSkillSection` (the section the runtime composes for one skill: `### {label} ({name})`, `description`, `instructions`, `Tools: …`), `packageSkillTextLength`, `packageSkillTextTotal`, `countsTowardPackageSkillText` (a skill with `surface` `ask`, `both` or unset counts; `build` never does), `formatPackageSkillTextCount` and `packageSkillTextCapMessage`. +- `os validate` and `os build` fail an app whose total is over the cap, naming the app, its total and the cap (`8,520 / 8,000`); `--json` carries one `errors[]` row per app (`packageId`, `total`, `cap`, `message`), and `os build` writes no artifact. +- The metadata save door (Studio, `PUT /api/v1/meta/skill/:name`, an MCP draft save) refuses a `skill` save after which the app it lands in is over the cap and higher than before, `422 INVALID_METADATA`, naming the app's total and the cap. A save that lowers an over-cap app is accepted, so an app can be trimmed one skill at a time. +- Studio → AI → Skills shows each app's total against the cap, in red when over. + +**What an author changes.** An app that built and saved before and is over the cap now fails `os validate` / `os build`, and a save that adds skill text to it is refused. Shorten the skills' `description` or `instructions`, drop tools a skill does not need, or set `surface: 'build'` on a skill the `ask` agent does not need, until the total is within 8,000. diff --git a/content/docs/ai/agents.mdx b/content/docs/ai/agents.mdx index 4669735debe..571759e7808 100644 --- a/content/docs/ai/agents.mdx +++ b/content/docs/ai/agents.mdx @@ -295,6 +295,32 @@ does not exist is an authoring error in either distribution. So a skill written against the open framework keeps its full meaning when the app runs on ObjectOS; nothing is authored twice. +### An app's `ask` skills share an 8,000-character cap + +On ObjectOS the `ask` agent puts every skill an app binds on the `ask` +surface into its system prompt, so the text one app (package) adds there is +capped at **8,000 characters** (`PACKAGE_SKILL_TEXT_CAP`, +`@objectstack/spec/ai`). One skill counts as the section the runtime composes +for it — its heading `### {label} ({name})`, its `description`, its +`instructions` and its `Tools: …` line — and the app's total sums every skill +whose `surface` is `'ask'` or `'both'`, or unset (the default is `'ask'`). +A `'build'` skill counts nothing. + +The cap is held at every door, with one measure (`packageSkillTextTotal`): + +- `os validate` and `os build` fail an app over it, naming the app, its total + and the cap (`8,520 / 8,000`). +- Saving a skill — in Studio, through the REST metadata API or as an MCP + draft — that would put its app over the cap is refused `422 + INVALID_METADATA` with the same numbers. A save that brings an over-cap app + down is accepted, so an app can be trimmed one skill at a time. +- Studio → AI → Skills shows each app's total against the cap, in red when + over. + +To get back under it, shorten the skills' `description` or `instructions`, +drop tools a skill does not need, or set `surface: 'build'` on a skill the +`ask` agent does not need. + ## The shape of an agent An agent is typed metadata validated by `AgentSchema` — exported, together with the diff --git a/packages/cli/src/commands/compile.ts b/packages/cli/src/commands/compile.ts index 955f472ef3d..03dc36bb399 100644 --- a/packages/cli/src/commands/compile.ts +++ b/packages/cli/src/commands/compile.ts @@ -83,6 +83,8 @@ import { findViewContainerNameRefusals } from '../utils/view-container-names.js' // [ADR-0150 D2, child N] The package door's namespace name refusal — the same // call `os validate` makes at its step 2c-bis. import { findNamespaceNameRefusals } from '../utils/namespace-co-owner-names.js'; +// cloud ADR-0118 D5: the app skill text cap — the walk; the measure is the spec's. +import { findAppSkillTextCapRefusals } from '../utils/app-skill-text-cap.js'; // [ADR-0150 D6, child K] A namespace never equals an object name, both directions, // and no object is short-named `custom` — the spec's predicate over one artifact. import { findNamespaceObjectNameRefusals } from '../utils/namespace-object-names.js'; @@ -588,6 +590,25 @@ export default class Compile extends Command { this.exit(1); } + // 2c-bis'. [cloud ADR-0118 D5] An app whose skills on the `ask` surface + // add up to more than the cap the hosted `ask` runtime holds them + // to. The cap, the measure and the sentence are the spec's, the ones + // the metadata save door refuses the same app with. + const skillTextCapRefusals = findAppSkillTextCapRefusals(result.data as Record); + if (skillTextCapRefusals.length > 0) { + if (flags.json) { + await emitJson({ success: false, errors: skillTextCapRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true }); + this.exit(1); + } + console.log(''); + printError(`App skill text over the cap (${skillTextCapRefusals.length} app${skillTextCapRefusals.length > 1 ? 's' : ''})`); + printBulletList( + skillTextCapRefusals.map((r) => r.message), + { noun: 'skill text cap refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3a-quater. [ADR-0150 D6, child K] A namespace of this artifact equal // to one of its object names, or an object short-named `custom`, is // REFUSED, naming both spellings — the SAME call `os validate` makes diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 51756486180..46d7f72639a 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -84,6 +84,8 @@ import { findViewContainerNameRefusals } from '../utils/view-container-names.js' // bucket 2/3 types has one package holder: the package door's predicate and // sentence, walked over the artifact's packages in boot order. import { findNamespaceNameRefusals } from '../utils/namespace-co-owner-names.js'; +// cloud ADR-0118 D5: the app skill text cap — the walk; the measure is the spec's. +import { findAppSkillTextCapRefusals } from '../utils/app-skill-text-cap.js'; // [ADR-0150 D6, child K] A namespace never equals an object name, both directions, // and no object is short-named `custom` — the spec's predicate over one artifact. import { findNamespaceObjectNameRefusals } from '../utils/namespace-object-names.js'; @@ -597,6 +599,31 @@ export default class Validate extends Command { this.exit(1); } + // 2c-bis'. [cloud ADR-0118 D5] An app whose skills on the `ask` surface + // add up to more than the cap the hosted `ask` runtime holds them + // to. The cap, the measure and the sentence are the spec's, the ones + // the metadata save door refuses the same app with. + const skillTextCapRefusals = findAppSkillTextCapRefusals(result.data as Record); + if (skillTextCapRefusals.length > 0) { + if (flags.json) { + await emitJson({ + valid: false, + errors: skillTextCapRefusals, + warnings: warningsSoFar(), + conversions: conversionNotices, + duration: timer.elapsed(), + }); + this.exit(1); + } + console.log(''); + printError(`App skill text over the cap (${skillTextCapRefusals.length} app${skillTextCapRefusals.length > 1 ? 's' : ''})`); + printBulletList( + skillTextCapRefusals.map((r) => r.message), + { noun: 'skill text cap refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 2c-ter. [ADR-0150 D6, child K] A namespace of this artifact equal to // one of its object names (either direction), or an object // short-named `custom` (`NS_custom`, the ADR-0146 pair's namespace), diff --git a/packages/cli/src/utils/app-skill-text-cap.test.ts b/packages/cli/src/utils/app-skill-text-cap.test.ts new file mode 100644 index 00000000000..04b6a722f1f --- /dev/null +++ b/packages/cli/src/utils/app-skill-text-cap.test.ts @@ -0,0 +1,49 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { PACKAGE_SKILL_TEXT_CAP, packageSkillTextCapMessage, packageSkillTextLength } from '@objectstack/spec/ai'; +import { findAppSkillTextCapRefusals } from './app-skill-text-cap.js'; + +/** A skill whose composed section is `size` characters long. */ +function skillOf(name: string, size: number, surface?: 'ask' | 'build' | 'both') { + const base = { name, label: 'S', tools: [] as string[], ...(surface ? { surface } : {}) }; + const head = packageSkillTextLength({ ...base, surface: 'ask' }); + return { ...base, instructions: 'x'.repeat(size - head - 1) }; +} + +describe('findAppSkillTextCapRefusals (cloud ADR-0118 D5)', () => { + it('the fixture measures what it says', () => { + expect(packageSkillTextLength(skillOf('a', 5000))).toBe(5000); + }); + + it('refuses a one-app stack over the cap, naming the app, its total and the cap', () => { + const rows = findAppSkillTextCapRefusals({ + manifest: { id: 'com.acme.crm' }, + skills: [skillOf('a', 5000), skillOf('b', 3520, 'both')], + }); + expect(rows).toEqual([{ + packageId: 'com.acme.crm', + total: 8520, + cap: PACKAGE_SKILL_TEXT_CAP, + message: packageSkillTextCapMessage('com.acme.crm', 8520), + }]); + }); + + it('accepts exactly the cap, and never counts a build skill', () => { + expect(findAppSkillTextCapRefusals({ manifest: { id: 'p' }, skills: [skillOf('a', 8000)] })).toEqual([]); + expect(findAppSkillTextCapRefusals({ + manifest: { id: 'p' }, + skills: [skillOf('a', 5000), skillOf('b', 5000, 'build')], + })).toEqual([]); + }); + + it('judges each package of an artifact as its own app', () => { + const rows = findAppSkillTextCapRefusals({ + packages: [ + { manifest: { id: 'com.acme.one', skills: [skillOf('a', 5000)] } }, + { manifest: { id: 'com.acme.two', skills: [skillOf('b', 5000), skillOf('c', 5000)] } }, + ], + }); + expect(rows.map((r) => [r.packageId, r.total])).toEqual([['com.acme.two', 10000]]); + }); +}); diff --git a/packages/cli/src/utils/app-skill-text-cap.ts b/packages/cli/src/utils/app-skill-text-cap.ts new file mode 100644 index 00000000000..a3bcd9289ef --- /dev/null +++ b/packages/cli/src/utils/app-skill-text-cap.ts @@ -0,0 +1,76 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os validate`'s and `os build`'s half of the app skill text cap (cloud + * ADR-0118 D5): an app (package) whose skills on the `ask` surface add up to + * more than `PACKAGE_SKILL_TEXT_CAP` characters fails the command, and the + * message names the app, its total and the cap. + * + * ## One measure, not a second rule + * + * The cap, the measure of one skill and the sentence are `@objectstack/spec`'s + * (`PACKAGE_SKILL_TEXT_CAP`, `packageSkillTextTotal`, + * `packageSkillTextCapMessage`) — the same exports the metadata save door and + * Studio's Skills page read, and the measure the hosted `ask` runtime counts. + * What this module owns is the WALK: which skills belong to which app. + * + * ## The walk + * + * An artifact's `packages[]` bodies are one app each, under the id the + * registry installs them by (`artifactPackages`). The stack's own top-level + * `skills` are the stack's app, under its `manifest.id`. A stack with no + * `packages[]` is that one app. + */ + +import { + PACKAGE_SKILL_TEXT_CAP, + packageSkillTextCapMessage, + packageSkillTextTotal, + type PackageSkillTextSource, +} from '@objectstack/spec/ai'; +import { artifactPackages } from './artifact-packages.js'; + +/** One app over the cap, located. */ +export interface AppSkillTextCapRefusalRow { + /** The app's package id, as the registry installs it. */ + packageId: string; + /** The app's total, in characters (`packageSkillTextTotal`). */ + total: number; + /** The cap (`PACKAGE_SKILL_TEXT_CAP`). */ + cap: number; + /** The refusal, in the shared sentence. */ + message: string; +} + +const skillsOf = (body: Record): PackageSkillTextSource[] => + Array.isArray(body.skills) ? (body.skills as PackageSkillTextSource[]) : []; + +const stackAppId = (parsed: Record): string => { + const manifest = parsed.manifest as { id?: unknown; name?: unknown } | undefined; + if (typeof manifest?.id === 'string' && manifest.id !== '') return manifest.id; + if (typeof manifest?.name === 'string' && manifest.name !== '') return manifest.name; + return 'this stack'; +}; + +/** + * Every app of this stack whose `ask` skill text exceeds the cap. `[]` for a + * stack every app of which is within it. + */ +export function findAppSkillTextCapRefusals(parsed: Record): AppSkillTextCapRefusalRow[] { + const apps: Array<{ packageId: string; skills: PackageSkillTextSource[] }> = [ + { packageId: stackAppId(parsed), skills: skillsOf(parsed) }, + ...artifactPackages(parsed).map(({ id, body }) => ({ packageId: id, skills: skillsOf(body) })), + ]; + const rows: AppSkillTextCapRefusalRow[] = []; + for (const { packageId, skills } of apps) { + const total = packageSkillTextTotal(skills); + if (total <= PACKAGE_SKILL_TEXT_CAP) continue; + rows.push({ + packageId, + total, + cap: PACKAGE_SKILL_TEXT_CAP, + message: packageSkillTextCapMessage(packageId, total), + }); + } + return rows; +} diff --git a/packages/cli/test/validate-app-skill-text-cap.test.ts b/packages/cli/test/validate-app-skill-text-cap.test.ts new file mode 100644 index 00000000000..3c24463ef49 --- /dev/null +++ b/packages/cli/test/validate-app-skill-text-cap.test.ts @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [cloud ADR-0118 D5] `os validate` and `os build` refuse an app whose skills + * on the `ask` surface add up to more than `PACKAGE_SKILL_TEXT_CAP`, and the + * row names the app's total and the cap; `os build` writes nothing. A stack + * at the cap validates. + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { execFile } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { PACKAGE_SKILL_TEXT_CAP, packageSkillTextLength } from '@objectstack/spec/ai'; +import { childEnv } from './helpers/serve-process.js'; +import { defineStackSource, linkSpec } from './helpers/define-stack-fixture.js'; + +const HERE = resolve(fileURLToPath(import.meta.url), '..'); +const CLI = resolve(HERE, '../bin/run-dev.js'); +/** A cold spawn of the CLI source entry runs well past vitest's 5 s default. */ +const SPAWN_TIMEOUT_MS = 120_000; +const ARTIFACT = join('dist', 'objectstack.json'); +const APP = 'com.example.skill-cap'; + +interface Run { code: number; stdout: string; stderr: string } + +function runCli(args: string[], cwd: string): Promise { + return new Promise((done) => { + execFile(process.execPath, [CLI, ...args], { cwd, maxBuffer: 16 * 1024 * 1024, env: childEnv({ NO_COLOR: '1' }) }, + (err, stdout, stderr) => done({ + code: err ? (typeof (err as { code?: unknown }).code === 'number' ? (err as unknown as { code: number }).code : 1) : 0, + stdout: String(stdout), + stderr: String(stderr), + })); + }); +} + +function payloadOf(run: Run, label: string): Record { + try { + return JSON.parse(run.stdout) as Record; + } catch { + throw new Error(`${label}: stdout was not one JSON document (exit ${run.code})\n${run.stdout}\n${run.stderr}`); + } +} + +/** A skill whose composed section is `size` characters long. */ +function skillOf(name: string, size: number) { + const base = { name, label: 'Skill', tools: [] as string[] }; + return { ...base, instructions: 'x'.repeat(size - packageSkillTextLength(base) - 1) }; +} + +const stackOf = (sizes: number[]) => ({ + manifest: { id: APP, name: 'skill_cap', version: '1.0.0', type: 'app' }, + skills: sizes.map((size, i) => skillOf(`cap_skill_${i}`, size)), +}); + +const dirs: Record = {}; +let root = ''; + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'os-validate-skill-text-cap-')); + const make = (label: string, s: Record) => { + const dir = join(root, label); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'objectstack.config.ts'), defineStackSource(s)); + linkSpec(dir); + dirs[label] = dir; + }; + make('over-validate', stackOf([5000, 3520])); + make('over-build', stackOf([5000, 3520])); + make('at-cap', stackOf([5000, 3000])); +}); + +afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); +}); + +describe('app skill text cap — os validate and os build', () => { + it('os validate --json exits 1 with one row naming the app, its total and the cap', async () => { + const run = await runCli(['validate', '--json'], dirs['over-validate']); + const payload = payloadOf(run, 'validate --json'); + expect(run.code).toBe(1); + expect(payload.valid).toBe(false); + expect(payload.errors.map((r: any) => [r.packageId, r.total, r.cap])) + .toEqual([[APP, 8520, PACKAGE_SKILL_TEXT_CAP]]); + expect(payload.errors[0].message).toContain('(8,520 / 8,000)'); + }, SPAWN_TIMEOUT_MS); + + it('os validate (text) names the total and the cap', async () => { + const run = await runCli(['validate'], dirs['over-validate']); + expect(run.code).toBe(1); + expect(`${run.stdout}${run.stderr}`).toContain('binds 8,520 characters of skill text on the ask surface; the cap is 8,000'); + }, SPAWN_TIMEOUT_MS); + + it('os build --json exits 1 with the same row and writes no artifact', async () => { + const dir = dirs['over-build']; + const run = await runCli(['build', '--json'], dir); + const payload = payloadOf(run, 'build --json'); + expect(run.code).toBe(1); + expect(payload.success).toBe(false); + expect(payload.errors.map((r: any) => [r.packageId, r.total])).toEqual([[APP, 8520]]); + expect(existsSync(join(dir, ARTIFACT)), 'os build wrote an artifact over the cap').toBe(false); + }, SPAWN_TIMEOUT_MS); + + it('CONTROL — an app exactly at the cap validates', async () => { + const run = await runCli(['validate', '--json'], dirs['at-cap']); + const payload = payloadOf(run, 'at-cap --json'); + expect(payload.valid, JSON.stringify(payload.errors)).toBe(true); + expect(run.code).toBe(0); + }, SPAWN_TIMEOUT_MS); +}); diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index ff970cb1e52..200ef563177 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -100,6 +100,8 @@ import { packageScopedRefusalOf } from './protocol-meta-item-reads.js'; import { pairsOf } from '@objectstack/metadata-core'; import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; +// [cloud ADR-0118 D5] The app skill text cap's save-door read; the measure is the spec's. +import { packageSkillTextCapRefusal } from './protocol-skill-text-cap.js'; export class ProtocolSaveFacet { /** @@ -1504,7 +1506,12 @@ export class ProtocolSaveFacet { // [#35157] …and a `capability` the same way: one name, one // holder, and never a platform capability's name — the same // predicate, judged against the same landing binding. - if (singularType === 'permission' || singularType === 'capability') { + // [cloud ADR-0118 D5] …and a `skill` the same landing binding is + // judged against: a save that would put the app (package) it lands + // in over the skill text cap is refused `422 INVALID_METADATA`, + // naming the app's total and the cap. See + // {@link packageSkillTextCapRefusal}. + if (singularType === 'permission' || singularType === 'capability' || singularType === 'skill') { let landsIn: string | null = null; if (typeof request.packageId === 'string' && request.packageId !== '') { landsIn = request.packageId; @@ -1517,11 +1524,16 @@ export class ProtocolSaveFacet { } landsIn = address.into; } - permissionLandsIn = landsIn; - const nameCollision = await host.permissionSetNameCollisionRefusal( - singularType, request.name, landsIn, 'save', - ); - if (nameCollision) throw nameCollision; + if (singularType === 'skill') { + const capRefusal = await packageSkillTextCapRefusal(host, request.item, request.name, landsIn, mode); + if (capRefusal) throw capRefusal; + } else { + permissionLandsIn = landsIn; + const nameCollision = await host.permissionSetNameCollisionRefusal( + singularType, request.name, landsIn, 'save', + ); + if (nameCollision) throw nameCollision; + } } // [#21639] …and a view container whose save name, or any name its // expansion produces, is a name already served from elsewhere — diff --git a/packages/metadata-protocol/src/protocol-skill-text-cap.ts b/packages/metadata-protocol/src/protocol-skill-text-cap.ts new file mode 100644 index 00000000000..a4ab280707e --- /dev/null +++ b/packages/metadata-protocol/src/protocol-skill-text-cap.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [cloud ADR-0118 D5] The metadata save door's half of the app skill text cap: + * a `skill` save that would put the app (package) it lands in over + * `PACKAGE_SKILL_TEXT_CAP` characters of `ask` skill text is refused + * `422 INVALID_METADATA`, and the refusal names the app, its total after the + * save and the cap. Every writer reaches it — Studio, the REST metadata API, + * an MCP draft save — because they all write through `saveMetaItem`. + * + * ## One measure, not a second rule + * + * The cap, the measure and the sentence are `@objectstack/spec`'s — the exports + * `os validate` / `os build` and Studio's Skills page read, and the measure the + * hosted `ask` runtime counts. What this module owns is the READ: which skills + * the app holds beside the one being saved. + * + * ## The read + * + * The app is the package the save LANDS IN (the save door's landing binding, + * the one the permission-set name refusal judges against). Its skills are the + * served list of that package (`getMetaItems`), with pending drafts shown for a + * draft save (`previewDrafts`) — the set the draft is reviewed and published + * into. The saved body replaces the skill of its name, or joins the set. + * + * ## What is refused + * + * A save after which the app's total is over the cap AND higher than before. + * An app already over the cap (shipped that way, or stored before this door + * judged it) can still be brought down one skill at a time: a save that lowers + * the total is accepted even while the total stays over. A package-less skill + * belongs to no app and is not judged. + */ + +import { + PACKAGE_SKILL_TEXT_CAP, + packageSkillTextCapMessage, + packageSkillTextTotal, + type PackageSkillTextSource, +} from '@objectstack/spec/ai'; +import type { MetadataIssueEntry } from './protocol-metadata-issues.js'; +import type { ProtocolHost } from './protocol-host.js'; + +export type PackageSkillTextCapRefusal = Error & { + code: 'INVALID_METADATA'; + status: 422; + issues: MetadataIssueEntry[]; +}; + +/** + * The refusal of a `skill` save that would put the app it lands in over the + * skill text cap, or `undefined` when the save is within it (or not a skill + * save, or lands in no package). + */ +export async function packageSkillTextCapRefusal( + host: Pick, + item: unknown, + name: string, + landsIn: string | null, + mode: string | undefined, +): Promise { + if (landsIn === null || landsIn === '') return undefined; + if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined; + const listed = ((await host.getMetaItems({ type: 'skill', packageId: landsIn, previewDrafts: mode === 'draft' }))?.items + ?? []) as Array; + const held = listed.filter((s) => s && (s._packageId === undefined || s._packageId === landsIn)); + const others = held.filter((s) => s.name !== name); + const before = packageSkillTextTotal(held); + const total = packageSkillTextTotal([...others, item as PackageSkillTextSource]); + if (total <= PACKAGE_SKILL_TEXT_CAP || total <= before) return undefined; + const sentence = packageSkillTextCapMessage(landsIn, total); + const err = new Error(`skill/${name}: ${sentence} Nothing was saved.`) as PackageSkillTextCapRefusal; + err.code = 'INVALID_METADATA'; + err.status = 422; + err.issues = [{ path: '', message: sentence, code: 'custom' }]; + return err; +} diff --git a/packages/metadata-protocol/src/protocol.skill-text-cap-save-door.test.ts b/packages/metadata-protocol/src/protocol.skill-text-cap-save-door.test.ts new file mode 100644 index 00000000000..7ce5e254450 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.skill-text-cap-save-door.test.ts @@ -0,0 +1,305 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [cloud ADR-0118 D5] The metadata save door refuses a `skill` save that would + * put the app (package) it lands in over the skill text cap — draft and publish + * mode alike, so Studio, the REST metadata API and an MCP draft save all meet + * it — with `422 INVALID_METADATA`, and the refusal names the app's total + * after the save and the cap. Nothing is stored. + * + * Each refusal is paired with a CONTROL through the same door (a save within + * the cap, a `build` skill, a save that lowers an over-cap app), so a door that + * refused everything could not pass. + * + * The engine double is `protocol.permission-set-name-cross-package.test.ts`'s + * — a store of rows plus a registry keyed by name — copied, not imported, so + * each pin can fail on its own. + */ + +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + assertEngineDeleteDispatch, + assertEngineUpdateDispatch, + assertEngineFindOnePredicate, +} from '@objectstack/metadata-core'; +import { PACKAGE_SKILL_TEXT_CAP, packageSkillTextLength } from '@objectstack/spec/ai'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +const APP = 'app.skill_cap'; +const OTHER_APP = 'app.skill_cap_other'; +const INSTALLED_PACKAGES: ReadonlySet = new Set([APP, OTHER_APP]); +const installedPackage = (id: string) => (INSTALLED_PACKAGES.has(id) ? { manifest: { id } } : undefined); + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + metadata: string; + checksum?: string; + version?: number; +} + +interface HistoryRow { + id: string; + type: string; + name: string; + version: number; + organization_id: string | null; + operation_type: string; + metadata?: string | null; +} + +/** ADR-0048 overlay key — (type, name, org, state, package_id). */ +const keyOf = (w: Record) => + `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; + +function matchesWhere(r: Row, where: Record): boolean { + for (const [k, v] of Object.entries(where)) { + if (k === '$or') { + const clauses = v as Array>; + if (!clauses.some((c) => matchesWhere(r, c))) return false; + continue; + } + if (v === undefined) continue; + if ((r as unknown as Record)[k] !== v) return false; + } + return true; +} + +function makeStubEngine() { + const rows = new Map(); + const historyRows: HistoryRow[] = []; + const registered = new Map>(); + let nextId = 0; + let commit: unknown = null; + + const findRow = (w: Record): { key: string; row: Row } | null => { + if (w.id !== undefined) { + for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; + return null; + } + if (w.package_id !== undefined) { + const k = keyOf(w); + const r = rows.get(k); + if (r) return { key: k, row: r }; + } + for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r }; + return null; + }; + + const matchesHistory = (h: HistoryRow, w: Record): boolean => { + if (w.organization_id !== undefined && h.organization_id !== w.organization_id) return false; + if (w.type !== undefined && h.type !== w.type) return false; + if (w.name !== undefined && h.name !== w.name) return false; + if (w.version !== undefined && h.version !== w.version) return false; + if (w.operation_type !== undefined && h.operation_type !== w.operation_type) return false; + return true; + }; + + const engine: any = { + async findOne(table: string, opts: { where: Record }) { + assertEngineFindOnePredicate(table, opts); + if (table === 'sys_metadata_commit') return commit; + if (table === 'sys_metadata_history') { + return historyRows.find((h) => matchesHistory(h, opts.where)) ?? null; + } + if (table !== 'sys_metadata') return null; + return findRow(opts.where)?.row ?? null; + }, + async find(table: string, opts?: { where?: Record; limit?: number }) { + const bound = (all: T[]): T[] => + typeof opts?.limit === 'number' ? all.slice(0, opts.limit) : all; + if (table === 'sys_metadata_history') { + return bound(historyRows.filter((h) => matchesHistory(h, opts?.where ?? {}))); + } + if (table !== 'sys_metadata') return []; + return bound(Array.from(rows.values()).filter((r) => matchesWhere(r, opts?.where ?? {}))); + }, + async insert(table: string, data: Record) { + if (table === 'sys_metadata_history') { + nextId += 1; + const h = { ...(data as unknown as HistoryRow), id: `h_${nextId}` }; + historyRows.push(h); + return { id: h.id }; + } + if (table !== 'sys_metadata') return { id: 'side_effect_skip' }; + nextId += 1; + const row = { ...(data as unknown as Row), id: `r_${nextId}` }; + rows.set(keyOf(data), row); + return { id: row.id }; + }, + async update(_t: string, data: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(data, opts); + const found = findRow(opts.where); + if (!found) return { id: null }; + const merged = { ...found.row, ...(data as unknown as Row) }; + rows.delete(found.key); + rows.set(keyOf(merged), merged); + return { id: found.row.id }; + }, + async delete(_t: string, opts: { where: Record }) { + assertEngineDeleteDispatch(opts); + const found = findRow(opts.where); + if (!found) return { deleted: 0 }; + rows.delete(found.key); + return { deleted: 1 }; + }, + async count() { return 0; }, + async transaction(cb: (ctx: unknown, info: { owned: boolean }) => Promise): Promise { + const rowsAtBegin = new Map(rows); + const historyAtBegin = historyRows.slice(); + try { + return await cb(undefined, { owned: true }); + } catch (error) { + rows.clear(); + for (const [k, r] of rowsAtBegin) rows.set(k, r); + historyRows.splice(0, historyRows.length, ...historyAtBegin); + throw error; + } + }, + async syncObjectSchema() { return true; }, + async dropObjectSchema() { return true; }, + registry: { + registerItem: (type: string, item: any) => { + if (!registered.has(type)) registered.set(type, new Map()); + registered.get(type)!.set(item?.name, item); + }, + unregisterItem: (type: string, name: string) => { registered.get(type)?.delete(name); }, + registerObject: () => {}, + unregisterObject: () => true, + removeObjectOverlay: () => {}, + removeRuntimeShadow: () => false, + removeOverlayEntry: () => true, + listItems: (type: string) => Array.from(registered.get(type)?.values() ?? []), + getItem: (type: string, name: string) => registered.get(type)?.get(name), + getObject: () => undefined, + getPackage: installedPackage, + getArtifactItem: () => undefined, + isPackageDisabled: () => false, + }, + }; + return { + engine, + rows, + historyRows, + registered, + serveCommit: (c: unknown) => { commit = c; }, + }; +} + +function makeProtocol() { + const h = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(h.engine, () => new Map(), undefined) as any; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + return { protocol, ...h }; +} + +type Harness = ReturnType; + +afterEach(() => vi.restoreAllMocks()); + +/** A skill whose composed section is `size` characters long. */ +function skillOf(name: string, size: number, surface?: 'ask' | 'build' | 'both') { + const base = { name, label: 'Skill', tools: [] as string[], ...(surface ? { surface } : {}) }; + return { ...base, instructions: 'x'.repeat(size - packageSkillTextLength({ ...base, surface: 'ask' }) - 1) }; +} + +async function attempt(run: () => Promise): Promise<{ result: T | null; error: any }> { + try { + return { result: await run(), error: null }; + } catch (error) { + return { result: null, error }; + } +} + +const storedSkills = (h: Harness) => Array.from(h.rows.values()) + .filter((r) => r.type === 'skill') + .map((r) => `${r.package_id ?? '-'}/${r.name}/${r.state}`) + .sort(); + +const save = (h: Harness, name: string, size: number, opts: { mode?: 'draft' | 'publish'; packageId?: string; surface?: 'ask' | 'build' | 'both' } = {}) => + h.protocol.saveMetaItem({ + type: 'skill', name, item: skillOf(name, size, opts.surface), + packageId: opts.packageId ?? APP, ...(opts.mode ? { mode: opts.mode } : {}), + }); + +describe('the save door refuses a skill save that puts its app over the skill text cap', () => { + it('premise: the fixture measures what it says', () => { + expect(packageSkillTextLength(skillOf('a', 5000))).toBe(5000); + expect(PACKAGE_SKILL_TEXT_CAP).toBe(8000); + }); + + it.each(['publish', 'draft'] as const)('%s mode: 5,000 held + 3,520 saved is refused 422 INVALID_METADATA naming 8,520 / 8,000; nothing stored', async (mode) => { + const h = makeProtocol(); + await save(h, 'skill_a', 5000); + const before = storedSkills(h); + + const { error } = await attempt(() => save(h, 'skill_b', 3520, { mode })); + + expect(error).toBeInstanceOf(Error); + expect(error.code).toBe('INVALID_METADATA'); + expect(error.status).toBe(422); + expect(error.message).toContain(`App "${APP}" binds 8,520 characters of skill text on the ask surface; the cap is 8,000`); + expect(error.issues.map((i: any) => i.message)).toEqual([expect.stringContaining('(8,520 / 8,000)')]); + expect(storedSkills(h)).toEqual(before); + }); + + it.each(['publish', 'draft'] as const)('CONTROL %s mode: 5,000 held + 3,000 saved (exactly the cap) is accepted', async (mode) => { + const h = makeProtocol(); + await save(h, 'skill_a', 5000); + const { error } = await attempt(() => save(h, 'skill_b', 3000, { mode })); + expect(error).toBeNull(); + expect(storedSkills(h)).toContain(`${APP}/skill_b/${mode === 'draft' ? 'draft' : 'active'}`); + }); + + it('editing a held skill counts its new body, not the old one beside it', async () => { + const h = makeProtocol(); + await save(h, 'skill_a', 5000); + await save(h, 'skill_b', 2000); + // 5,000 + 2,000 → 5,000 + 3,000: within the cap, accepted. + expect((await attempt(() => save(h, 'skill_b', 3000))).error).toBeNull(); + // 5,000 + 3,000 → 5,000 + 3,001: over, refused. + const { error } = await attempt(() => save(h, 'skill_b', 3001)); + expect([error?.code, error?.status]).toEqual(['INVALID_METADATA', 422]); + expect(error.message).toContain('8,001 characters'); + }); + + it('CONTROL: a build skill counts nothing, and another app\'s skills are not this app\'s', async () => { + const h = makeProtocol(); + await save(h, 'skill_a', 5000); + await save(h, 'skill_other', 5000, { packageId: OTHER_APP }); + expect((await attempt(() => save(h, 'skill_build', 5000, { surface: 'build' }))).error).toBeNull(); + expect((await attempt(() => save(h, 'skill_b', 3000))).error).toBeNull(); + }); + + it('a surface switch from build to ask that tips the app over is refused', async () => { + const h = makeProtocol(); + await save(h, 'skill_a', 5000); + await save(h, 'skill_b', 5000, { surface: 'build' }); + const { error } = await attempt(() => save(h, 'skill_b', 5000, { surface: 'both' })); + expect([error?.code, error?.status]).toEqual(['INVALID_METADATA', 422]); + expect(error.message).toContain('10,000 characters'); + }); + + it('CONTROL: an app already over the cap may be brought down one save at a time', async () => { + const h = makeProtocol(); + await save(h, 'skill_a', 5000); + await save(h, 'skill_b', 5000, { surface: 'build' }); + // Stage an over-cap app the way a deployment can hold one from before + // this door judged it: the surface switch, with the refusal off. + const off = vi.spyOn(await import('./protocol-skill-text-cap.js'), 'packageSkillTextCapRefusal'); + off.mockResolvedValue(undefined); + await save(h, 'skill_b', 5000, { surface: 'ask' }); + off.mockRestore(); + // 10,000 → 9,000: still over, but lower — accepted. + expect((await attempt(() => save(h, 'skill_b', 4000))).error).toBeNull(); + // 9,000 → 9,500: higher and over — refused. + const { error } = await attempt(() => save(h, 'skill_b', 4500)); + expect([error?.code, error?.status]).toEqual(['INVALID_METADATA', 422]); + }); +}); diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index c9ffbb4d6d6..b987d10ea18 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -235,6 +235,9 @@ "ObjectKnowledgeSourceSchema (const)", "ObjectQuerySource (type)", "ObjectQuerySourceSchema (const)", + "PACKAGE_SKILL_TEXT_CAP (const)", + "PACKAGE_SKILL_TEXT_SURFACES (const)", + "PackageSkillTextSource (interface)", "PromptTemplate (type)", "PromptTemplateParsed (type)", "PromptTemplateSchema (const)", @@ -322,15 +325,21 @@ "agentForm (const)", "aiContextForm (const)", "aiContextWhereFields (function)", + "composeSkillSection (function)", + "countsTowardPackageSkillText (function)", "defineAgent (function)", "defineSkill (function)", "defineSolutionBlueprint (function)", "defineTool (function)", "deriveAiFaceName (function)", + "formatPackageSkillTextCount (function)", "getDatasetToolJsonSchemas (function)", "getRecordContextToolJsonSchemas (function)", "headingsOf (function)", "knowledgeSourceForm (const)", + "packageSkillTextCapMessage (function)", + "packageSkillTextLength (function)", + "packageSkillTextTotal (function)", "parseAskQuestionEnvelope (function)", "scopesToAgentPermissionSets (function)", "skillBindsRecordContextTool (function)", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 610779dc917..0bd5b80c2d4 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -233,6 +233,9 @@ "ObjectKnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#ObjectKnowledgeSourceSchema (const)", "ObjectQuerySource": "src/ai/object-query-source.zod.ts#ObjectQuerySource (type)", "ObjectQuerySourceSchema": "src/ai/object-query-source.zod.ts#ObjectQuerySourceSchema (const)", + "PACKAGE_SKILL_TEXT_CAP": "src/ai/package-skill-text.ts#PACKAGE_SKILL_TEXT_CAP (const)", + "PACKAGE_SKILL_TEXT_SURFACES": "src/ai/package-skill-text.ts#PACKAGE_SKILL_TEXT_SURFACES (const)", + "PackageSkillTextSource": "src/ai/package-skill-text.ts#PackageSkillTextSource (interface)", "PromptTemplate": "src/ai/model-registry.zod.ts#PromptTemplate (type)", "PromptTemplateParsed": "src/ai/model-registry.zod.ts#PromptTemplateParsed (type)", "PromptTemplateSchema": "src/ai/model-registry.zod.ts#PromptTemplateSchema (const)", @@ -319,15 +322,21 @@ "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", + "composeSkillSection": "src/ai/package-skill-text.ts#composeSkillSection (function)", + "countsTowardPackageSkillText": "src/ai/package-skill-text.ts#countsTowardPackageSkillText (function)", "defineAgent": "src/ai/agent.zod.ts#defineAgent (function)", "defineSkill": "src/ai/skill.zod.ts#defineSkill (function)", "defineSolutionBlueprint": "src/ai/solution-blueprint.zod.ts#defineSolutionBlueprint (function)", "defineTool": "src/ai/tool.zod.ts#defineTool (function)", "deriveAiFaceName": "src/ai/face-name.ts#deriveAiFaceName (function)", + "formatPackageSkillTextCount": "src/ai/package-skill-text.ts#formatPackageSkillTextCount (function)", "getDatasetToolJsonSchemas": "src/ai/dataset-tools.zod.ts#getDatasetToolJsonSchemas (function)", "getRecordContextToolJsonSchemas": "src/ai/record-context-tools.zod.ts#getRecordContextToolJsonSchemas (function)", "headingsOf": "src/ai/record-body-anchor.ts#headingsOf (function)", "knowledgeSourceForm": "src/ai/knowledge-source.metadata-form.ts#knowledgeSourceForm (const)", + "packageSkillTextCapMessage": "src/ai/package-skill-text.ts#packageSkillTextCapMessage (function)", + "packageSkillTextLength": "src/ai/package-skill-text.ts#packageSkillTextLength (function)", + "packageSkillTextTotal": "src/ai/package-skill-text.ts#packageSkillTextTotal (function)", "parseAskQuestionEnvelope": "src/ai/ask-question.zod.ts#parseAskQuestionEnvelope (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", "skillBindsRecordContextTool": "src/ai/skill.zod.ts#skillBindsRecordContextTool (function)", diff --git a/packages/spec/src/ai/index.ts b/packages/spec/src/ai/index.ts index b85f0318d4e..1f5b84a1472 100644 --- a/packages/spec/src/ai/index.ts +++ b/packages/spec/src/ai/index.ts @@ -19,6 +19,7 @@ * - Knowledge source — the `knowledge_source` kind the knowledge service indexes from (ADR-0161 K4) * - Usage — token accounting + per-call cost * - MCP — references and bindings to external MCP servers + * - App skill text — the cap on one app's `ask` skill text and the one measure of it (cloud ADR-0118 D5) * - AI face name — the derived flat name an item is listed under (ADR-0150 D6) * - Dataset tools — `list_datasets` / `query_dataset` inputs and outputs (ADR-0149 D2) * - Context pack — the `ai_context` kind and the `get_record_context` tool's input and output (ADR-0160) @@ -42,6 +43,7 @@ export * from './model-registry.zod'; export * from './usage.zod'; export * from './mcp.zod'; export * from './face-name'; +export * from './package-skill-text'; export * from './dataset-tools.zod'; export * from './ai-context.zod'; export * from './record-context-tools.zod'; diff --git a/packages/spec/src/ai/package-skill-text.test.ts b/packages/spec/src/ai/package-skill-text.test.ts new file mode 100644 index 00000000000..2b4be3b46fb --- /dev/null +++ b/packages/spec/src/ai/package-skill-text.test.ts @@ -0,0 +1,66 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { SkillSchema } from './skill.zod'; +import { + PACKAGE_SKILL_TEXT_CAP, + composeSkillSection, + countsTowardPackageSkillText, + packageSkillTextCapMessage, + packageSkillTextLength, + packageSkillTextTotal, +} from './package-skill-text'; + +const caseSkill = { + name: 'case_management', + label: 'Case Management', + description: 'Handles support case lifecycle', + instructions: 'Use these tools to resolve cases.', + tools: ['create_case', 'resolve_case'], +}; + +describe('app skill text cap (cloud ADR-0118 D5)', () => { + it('declares the cap the hosted ask runtime enforces', () => { + expect(PACKAGE_SKILL_TEXT_CAP).toBe(8_000); + }); + + // The exact string pinned, so a drift against cloud's + // `SkillRegistry.composeSkillSection` shows up as a diff of this literal. + it('composes the section cloud composes: heading, description, instructions, Tools line', () => { + expect(composeSkillSection(caseSkill)).toBe( + '\n### Case Management (case_management)\n' + + 'Handles support case lifecycle\n' + + 'Use these tools to resolve cases.\n' + + 'Tools: create_case, resolve_case', + ); + expect(packageSkillTextLength(caseSkill)).toBe(composeSkillSection(caseSkill).length); + }); + + it('leaves an absent or empty line out', () => { + expect(composeSkillSection({ name: 'bare', label: 'Bare', description: '', tools: [] })) + .toBe('\n### Bare (bare)'); + expect(composeSkillSection({ name: 'only_rules', label: 'Only', instructions: 'Do X.', tools: [] })) + .toBe('\n### Only (only_rules)\nDo X.'); + }); + + it('counts ask and both, and a skill with no surface (the schema default is ask); never build', () => { + expect(SkillSchema.parse({ ...caseSkill }).surface).toBe('ask'); + expect(countsTowardPackageSkillText(caseSkill)).toBe(true); + expect(countsTowardPackageSkillText({ ...caseSkill, surface: 'ask' })).toBe(true); + expect(countsTowardPackageSkillText({ ...caseSkill, surface: 'both' })).toBe(true); + expect(countsTowardPackageSkillText({ ...caseSkill, surface: 'build' })).toBe(false); + expect(packageSkillTextLength({ ...caseSkill, surface: 'build' })).toBe(0); + }); + + it('sums one app', () => { + const one = packageSkillTextLength(caseSkill); + expect(packageSkillTextTotal([caseSkill, { ...caseSkill, surface: 'build' }, caseSkill])).toBe(2 * one); + }); + + it('words the refusal with the app, its total and the cap', () => { + const message = packageSkillTextCapMessage('com.acme.crm', 8520); + expect(message.startsWith('App "com.acme.crm" binds 8,520 characters of skill text on the ask surface; the cap is 8,000')) + .toBe(true); + expect(message).toContain('(8,520 / 8,000)'); + }); +}); diff --git a/packages/spec/src/ai/package-skill-text.ts b/packages/spec/src/ai/package-skill-text.ts new file mode 100644 index 00000000000..a18ef5280c2 --- /dev/null +++ b/packages/spec/src/ai/package-skill-text.ts @@ -0,0 +1,121 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The app skill text cap: how much skill text one app (package) may put in + * front of the `ask` agent, and the one measure every reader counts it with. + * + * The hosted `ask` runtime composes every skill an app binds on the `ask` + * surface into its system prompt, one section per skill, and caps the sum per + * app (cloud ADR-0118 D5; the value is cloud's `PACKAGE_SKILL_TEXT_CAP`). Four + * readers judge the same sum — `os validate` / `os build`, the metadata save + * door, Studio's Skills page and the cloud runtime — so the cap and the + * measure are declared HERE, once, and each reader calls them. A second copy + * of the measure is how an app passes `os validate` and still reads over in + * Studio. + * + * ## The measure + * + * One skill counts as the length of its composed prompt section, the string + * cloud's `SkillRegistry.composeSkillSection` builds: the lines + * + * ```text + * \n### {label} ({name}) + * {description} + * {instructions} + * Tools: {tools joined by ", "} + * ``` + * + * joined with `\n`, an absent or empty line left out. It is a pure function of + * `SkillSchema` fields, so build time, save time and Studio count exactly the + * characters the runtime counts. + * + * ⚠️ One bound, stated rather than hidden: the runtime measures a skill after + * narrowing its `tools` to the `ask` allow-set, while build and save time see + * the DECLARED `tools`. The `Tools:` line here is therefore never shorter than + * the runtime's, so a total these doors accept is one the runtime accepts too. + * + * ## What counts + * + * A skill whose `surface` is `ask` or `both` — and a skill with no `surface`, + * which `SkillSchema` defaults to `ask`. A `build` skill never reaches the + * `ask` agent and counts nothing. Skills bound to no package belong to no app + * and are not summed. + * + * This module measures; it refuses nothing. The refusals are the doors'. + */ + +/** The most skill text, in characters, one app may bind on the `ask` surface. */ +export const PACKAGE_SKILL_TEXT_CAP = 8_000; + +/** The skill `surface` values whose text the `ask` agent reads. */ +export const PACKAGE_SKILL_TEXT_SURFACES = ['ask', 'both'] as const; + +/** + * The fields of a skill the measure reads. Loose on purpose: a door measures + * a stored row or an authored body before or without a parse, so every field + * is read defensively and a non-string value counts as absent. + */ +export interface PackageSkillTextSource { + readonly name?: unknown; + readonly label?: unknown; + readonly description?: unknown; + readonly instructions?: unknown; + readonly tools?: unknown; + readonly surface?: unknown; +} + +const text = (value: unknown): string => (typeof value === 'string' ? value : ''); + +/** + * The prompt section the `ask` runtime composes for one skill — the string + * whose length is the skill's share of its app's total. + */ +export function composeSkillSection(skill: PackageSkillTextSource): string { + const lines = [`\n### ${text(skill.label)} (${text(skill.name)})`]; + const description = text(skill.description); + if (description !== '') lines.push(description); + const instructions = text(skill.instructions); + if (instructions !== '') lines.push(instructions); + const tools = Array.isArray(skill.tools) ? skill.tools.filter((t): t is string => typeof t === 'string') : []; + if (tools.length > 0) lines.push(`Tools: ${tools.join(', ')}`); + return lines.join('\n'); +} + +/** + * Whether a skill's text counts toward its app's total: its `surface` is + * `ask` or `both`, or it has none (the schema default is `ask`). + */ +export function countsTowardPackageSkillText(skill: PackageSkillTextSource): boolean { + const surface = skill.surface ?? 'ask'; + return (PACKAGE_SKILL_TEXT_SURFACES as readonly unknown[]).includes(surface); +} + +/** One skill's share of its app's total: 0 for a skill that does not count. */ +export function packageSkillTextLength(skill: PackageSkillTextSource): number { + return countsTowardPackageSkillText(skill) ? composeSkillSection(skill).length : 0; +} + +/** The total of one app's skills: the sum of {@link packageSkillTextLength}. */ +export function packageSkillTextTotal(skills: Iterable): number { + let total = 0; + for (const skill of skills) total += packageSkillTextLength(skill); + return total; +} + +/** A count as every door prints it: `8,520`. */ +export function formatPackageSkillTextCount(count: number): string { + return count.toLocaleString('en-US'); +} + +/** + * The sentence every door refuses an over-cap app with, so the build, the + * save door and their tests word the same fact the same way: the app, its + * total, the cap, and the ways out. + */ +export function packageSkillTextCapMessage(packageId: string, total: number): string { + return `App "${packageId}" binds ${formatPackageSkillTextCount(total)} characters of skill text on the ask surface; ` + + `the cap is ${formatPackageSkillTextCount(PACKAGE_SKILL_TEXT_CAP)} (${formatPackageSkillTextCount(total)} / ` + + `${formatPackageSkillTextCount(PACKAGE_SKILL_TEXT_CAP)}). Each skill whose surface is 'ask' or 'both' (or unset) ` + + 'counts its heading, description, instructions and Tools line. Shorten those skills\' description or ' + + 'instructions, drop tools they do not need, or set surface: \'build\' on a skill the ask agent does not need.'; +} diff --git a/packages/spec/src/migrations/entries/semantic/19.app-skill-text-over-cap-refused.ts b/packages/spec/src/migrations/entries/semantic/19.app-skill-text-over-cap-refused.ts new file mode 100644 index 00000000000..de01233f1a5 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.app-skill-text-over-cap-refused.ts @@ -0,0 +1,38 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// [cloud ADR-0118 D5] A narrowing of three doors, not of any key: an app +// (package) whose skills on the `ask` surface add up to more than +// PACKAGE_SKILL_TEXT_CAP characters fails `os validate` / `os build`, and a +// skill save that adds text to such an app is refused. No key is added, +// removed or re-shaped and no stored row changes, so no tombstone and no D2 +// conversion: which skill text to cut is the author's judgement. The question +// is whether the stack declares skills at all. +export const entry: SemanticMigration = { + id: 'app-skill-text-over-cap-refused', + surface: + 'An app (package) whose skills with surface ask or both (or no surface, which defaults to ask) add up to more ' + + 'than 8,000 characters of skill text (PACKAGE_SKILL_TEXT_CAP in @objectstack/spec/ai). One skill counts as ' + + 'the section the ask agent composes for it: the heading line with its label and name, its description, its ' + + 'instructions and its Tools line (composeSkillSection). os validate and os build fail such an app; the ' + + 'metadata save door (Studio, PUT /api/v1/meta/skill/NAME, an MCP draft save) refuses a skill save after which ' + + 'the app it lands in is over the cap and higher than before', + replacement: + 'Bring the app within 8,000 characters: shorten its skills\' description or instructions, drop tools a skill ' + + 'does not need from its tools list, or set surface: \'build\' on a skill the ask agent does not need. A save ' + + 'that lowers an app already over the cap is accepted, so a stored app can be trimmed one skill at a time.', + reason: + 'The hosted ask agent puts every skill an app binds on the ask surface into its system prompt and caps that ' + + 'text per app. An app over the cap built and saved without a word, and its rules then did not all reach the ' + + 'agent. The cap and its one measure are now declared in the spec, so os validate, the build, the save door, ' + + 'Studio and the runtime count the same characters. Skills already stored are not rewritten: there is no ' + + 'mechanical answer to which text an author would cut.', + acceptanceCriteria: + 'os validate --json on a stack whose one app binds 8,520 characters of ask skill text exits 1 with one errors ' + + 'row naming the app, total 8520 and cap 8000, and os build writes no artifact; the same ' + + 'stack at 8,000 characters validates. A skill save that would bring a package from 5,000 to 8,520 characters ' + + 'answers 422 INVALID_METADATA naming 8,520 / 8,000 and stores nothing; the same save at 3,000 characters is ' + + 'stored. Studio\'s Skills page shows each app\'s total against the cap, in red when over.', + relevantWhen: { kind: 'stack-declares', keys: ['skills'] }, +}; diff --git a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts index 95cc269f8a1..ed857d95f0b 100644 --- a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts +++ b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts @@ -429,6 +429,7 @@ const SITES: ReadonlyArray<{ site: string; stack: Record; entri entries: ['knowledge-service-held-without-embedder-or-store', 'knowledge-source-publish-refuses-missing-references-and-gated-objects'], }, { site: 'agents[]', stack: { agents: [{ name: 'a' }] }, entries: ['agent-model-provider-retired'] }, + { site: 'skills[]', stack: { skills: [{ name: 's', label: 'S', tools: [] }] }, entries: ['app-skill-text-over-cap-refused'] }, ]; const BY_KEY = new Map(COVERED.map(({ key, entry }) => [key, entry])); diff --git a/packages/spec/src/migrations/semantic-relevance.test.ts b/packages/spec/src/migrations/semantic-relevance.test.ts index d98f7c09cd2..1e9c764c25d 100644 --- a/packages/spec/src/migrations/semantic-relevance.test.ts +++ b/packages/spec/src/migrations/semantic-relevance.test.ts @@ -75,6 +75,7 @@ const EXPECTED_RELEVANCE: Readonly> = { '19:action-body-regexp-literal-token-refused': ['actions', 'objects'], '19:action-locations-page-parts-retired': ['actions', 'objects', 'pages'], '19:agent-model-provider-retired': ['agents'], + '19:app-skill-text-over-cap-refused': ['skills'], '19:body-regexp-pattern-refused': ['actions', 'objects', 'hooks', 'jobs'], '19:book-audience-two-gates-and-catch-all-claim-refused': ['books'], '19:cel-list-equality-refused': diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index e3d69e06362..f6655b77337 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -2316,6 +2316,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.skill-text-cap-save-door.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.skill-text-cap-save-door.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.skill-text-cap-save-door.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.stored-action-gate-lowering.test.ts", "verb": "delete", diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index b9245768dc7..bcb8cf66453 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -142,6 +142,8 @@ import { formatChangedAt, useListChangedAt } from './listChangedAt.js'; import { useListDraftMarks } from './listDraftMarks.js'; import { ListChangedCell } from './ListChangedCell.js'; import { StudioListHeader } from './StudioListHeader.js'; +// [cloud ADR-0118 D5] Each app's ask skill text against the cap, on the Skills list. +import { SkillTextCapTotals } from './SkillTextCapTotals.js'; import { STUDIO_MENU_TYPE_ICONS } from '../studio-design/StudioMenu.js'; import { STUDIO_SOURCE_KEY, @@ -1653,6 +1655,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string /> )} {packageAskDialog} + {type === 'skill' && row.item)} locale={locale} />} {/* Filter row */} {!studioList && (
diff --git a/ui/packages/app-shell/src/views/metadata-admin/SkillTextCapTotals.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SkillTextCapTotals.test.tsx new file mode 100644 index 00000000000..328c380850f --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/SkillTextCapTotals.test.tsx @@ -0,0 +1,66 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [cloud ADR-0118 D5] Studio → AI → Skills shows each app's ask skill text + * against the cap (`8,520 / 8,000`), red when over — counted with the spec's + * measure, the one `os validate` and the save door refuse with. + */ +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, cleanup, screen } from '@testing-library/react'; +import { packageSkillTextLength } from '@objectstack/spec/ai'; +import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; +import { SkillTextCapTotals, appSkillTextTotals } from './SkillTextCapTotals.js'; + +// The zh studio namespace loads lazily in the app; load it once, at collection. +await loadStudioCatalogue('zh'); + +afterEach(cleanup); + +/** A skill row of `size` characters, as the list serves it. */ +function row(name: string, size: number, packageId?: string, surface?: 'ask' | 'build' | 'both') { + const base = { name, label: 'Skill', tools: [] as string[], ...(surface ? { surface } : {}) }; + return { + ...base, + instructions: 'x'.repeat(size - packageSkillTextLength({ ...base, surface: 'ask' }) - 1), + ...(packageId ? { _packageId: packageId } : {}), + }; +} + +const ROWS = [ + row('a', 5000, 'com.acme.crm'), + row('b', 3520, 'com.acme.crm', 'both'), + row('c', 4000, 'com.acme.help'), + row('d', 9000, 'com.acme.help', 'build'), + row('loose', 9000), +]; + +describe('SkillTextCapTotals', () => { + it('sums each app with the spec measure; a build skill and a package-less skill count nothing', () => { + expect(appSkillTextTotals(ROWS)).toEqual([ + { packageId: 'com.acme.crm', total: 8520 }, + { packageId: 'com.acme.help', total: 4000 }, + ]); + }); + + it('shows "total / cap" per app, red (marked over) only when over', () => { + render(); + const [crm, help] = screen.getAllByTestId('skill-text-cap-total'); + expect(crm).toHaveTextContent('com.acme.crm — ask skill text 8,520 / 8,000'); + expect(crm).toHaveAttribute('data-over', 'true'); + expect(crm).toHaveClass('text-destructive'); + expect(help).toHaveTextContent('com.acme.help — ask skill text 4,000 / 8,000'); + expect(help).toHaveAttribute('data-over', 'false'); + expect(help).not.toHaveClass('text-destructive'); + }); + + it('speaks Chinese in the Chinese locale', () => { + render(); + expect(screen.getByTestId('skill-text-cap-total')).toHaveTextContent('com.acme.crm — 问数技能合计 8,520 / 8,000 字'); + }); + + it('draws nothing when no listed skill belongs to an app', () => { + render(); + expect(screen.queryByTestId('skill-text-cap-totals')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SkillTextCapTotals.tsx b/ui/packages/app-shell/src/views/metadata-admin/SkillTextCapTotals.tsx new file mode 100644 index 00000000000..5b77ea641db --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/SkillTextCapTotals.tsx @@ -0,0 +1,65 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [cloud ADR-0118 D5] Studio → AI → Skills: each app's (package's) skill text + * on the `ask` surface against the cap, for example `8,520 / 8,000`, in red + * when over. + * + * The cap and the measure are `@objectstack/spec`'s (`PACKAGE_SKILL_TEXT_CAP`, + * `packageSkillTextTotal`) — the ones `os validate` / `os build` and the save + * door refuse with, and the measure the hosted `ask` runtime counts — so the + * number here is the number those doors judge. It is computed from the rows + * the list already read; a skill bound to no package belongs to no app and is + * not summed. + */ + +import * as React from 'react'; +import { + PACKAGE_SKILL_TEXT_CAP, + formatPackageSkillTextCount, + packageSkillTextTotal, + type PackageSkillTextSource, +} from '@objectstack/spec/ai'; +import { t, tFormat } from './i18n.js'; + +/** Each app's total, in the order its first skill is listed. */ +export function appSkillTextTotals(items: readonly Record[]): Array<{ packageId: string; total: number }> { + const byApp = new Map(); + for (const item of items) { + const packageId = item._packageId; + if (typeof packageId !== 'string' || packageId === '') continue; + const held = byApp.get(packageId) ?? []; + held.push(item as PackageSkillTextSource); + byApp.set(packageId, held); + } + return Array.from(byApp, ([packageId, skills]) => ({ packageId, total: packageSkillTextTotal(skills) })); +} + +export function SkillTextCapTotals({ items, locale }: { items: readonly Record[]; locale: string }) { + const totals = React.useMemo(() => appSkillTextTotals(items), [items]); + if (totals.length === 0) return null; + const cap = formatPackageSkillTextCount(PACKAGE_SKILL_TEXT_CAP); + return ( +
    + {totals.map(({ packageId, total }) => { + const over = total > PACKAGE_SKILL_TEXT_CAP; + return ( +
  • + {tFormat('engine.skillTextCap.total', locale, { + app: packageId, + total: formatPackageSkillTextCount(total), + cap, + })} +
  • + ); + })} +
+ ); +} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index eb43937127f..9ae467eeff9 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4196,6 +4196,8 @@ const STUDIO_EN: Record = { 'engine.looseItems.bannerHint': 'Open a type to select its loose items and move them into a package.', 'engine.looseItems.typeCount': '{type} ({count})', 'engine.looseItems.unread': 'These types could not be counted: {types}', + 'engine.skillTextCap.total': '{app} — ask skill text {total} / {cap}', + 'engine.skillTextCap.over': 'Over the cap: os validate, the build and saving a skill that adds text refuse this app until it is back within the cap.', 'engine.list.refresh': 'Refresh', 'engine.list.search': 'Search name, label, description…', 'engine.list.empty': 'No items yet.', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 9015bce5545..8a090788ed5 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3722,6 +3722,8 @@ const STUDIO_ZH: Record = { 'engine.looseItems.bannerHint': '打开一种类型,勾选它的散落项,再移入软件包。', 'engine.looseItems.typeCount': '{type}({count})', 'engine.looseItems.unread': '以下类型没能计数:{types}', + 'engine.skillTextCap.total': '{app} — 问数技能合计 {total} / {cap} 字', + 'engine.skillTextCap.over': '超过上限:在降回上限之内前,os validate、构建和会增加文字的技能保存都会拒绝这个应用。', 'engine.list.refresh': '刷新', 'engine.list.search': '搜索名称、显示名或描述…', 'engine.list.empty': '暂无数据。',