{"record":{"id":"5bb64bd81331da3b","repo":"JuliusBrussee/caveman","slug":"unknown-capability","errorCode":"unknown_capability","errorMessage":"unknown_capability","messagePattern":"unknown_capability","errorType":"error_code","errorClass":"MiddlewareError","httpStatus":null,"severity":"error","filePath":"packages/sdk/typescript/src/middleware/validate.ts","lineNumber":27,"sourceCode":"export const isToken = (s: unknown): s is string => typeof s === 'string' && /^[a-zA-Z0-9._:/-]{1,256}$/.test(s);\nconst integer = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;\nexport function scopeKey(scope: Scope): string {\n  if (![scope.namespace, scope.session_id, scope.branch_id, scope.cache_epoch].every(isToken)) throw new MiddlewareError('invalid_scope');\n  return JSON.stringify([scope.namespace, scope.session_id, scope.branch_id, scope.cache_epoch]);\n}\nexport class MiddlewareError extends Error {\n  constructor(readonly code: string) { super(`Caveman middleware: ${code}`); this.name = 'MiddlewareError'; }\n}\nexport function validateCapabilities(value: unknown): Capabilities {\n  const c = value as Capabilities;\n  if (!c || c.schema_version !== 1 || !isToken(c.policy_revision) || typeof c.runtime_build !== 'string' ||\n    !['record', 'compress'].includes(c.mode) || !Array.isArray(c.transforms) || c.transforms.length > 128 ||\n    !c.limits || !Object.values(c.limits).every(n => integer(n) && n > 0) ||\n    !integer(c.retention_seconds) || typeof c.recovery !== 'boolean' || typeof c.persistent !== 'boolean') throw new MiddlewareError('unsupported_version');\n  const ids = new Set<string>();\n  for (const t of c.transforms) {\n    if (!isToken(t.transform_id) || ids.has(t.transform_id) || !isToken(t.implementation_version) || !Array.isArray(t.eligible_segment_kinds) ||\n      !['exact_ccr', 'none'].includes(t.recovery) || t.deterministic !== true) throw new MiddlewareError('unknown_capability');\n    ids.add(t.transform_id);\n  }\n  return c;\n}\n\n/** Validate every leaf before an adapter is allowed to apply any of them. */\nexport async function validatePlan(value: unknown, request: OptimizeRequest, inputDigest: string, caps: Capabilities): Promise<Plan> {\n  const p = value as Plan;\n  const invalid = () => { throw new MiddlewareError('invalid_plan'); };\n  if (!p || p.schema_version !== 1 || p.request_id !== request.request_id || p.input_digest !== inputDigest ||\n    p.policy_revision !== request.policy.revision || !isHash(p.replacement_set_id) || !['optimized','bypassed','record'].includes(p.status) ||\n    !isToken(p.reason) || !Array.isArray(p.replacements) || !Array.isArray(p.skipped) || !p.measurement || !p.stability || !p.recovery) invalid();\n  const m = p.measurement;\n  if (m.basis !== 'inferred' || m.scope !== 'segment' || m.verified_saved_usd !== 0 || typeof m.tokenizer !== 'string' ||\n    ![m.tokens_before,m.tokens_after,m.unique_tokens_reduced,m.recovery_overhead_tokens].every(integer) || m.tokens_after > m.tokens_before ||\n    p.stability.provider_bytes !== 'unobserved' || p.stability.provider_cache_hits !== 'unobserved' || !['persistent_choices','unavailable'].includes(p.stability.native) ||\n    typeof p.recovery.available !== 'boolean' || typeof p.recovery.persistent !== 'boolean' || !integer(p.recovery.expires_at)) invalid();\n  const seen = new Set<string>();","sourceCodeStart":9,"sourceCodeEnd":45,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/sdk/typescript/src/middleware/validate.ts#L9-L45","documentation":"MiddlewareError with code 'unknown_capability' is thrown by validateCapabilities when a transform entry in a Capabilities object fails leaf validation. The library validates every declared transform before an adapter is allowed to apply any of them, so a single malformed transform invalidates the whole capability set. Checks include token-shaped transform_id (unique), token-shaped implementation_version, an array eligible_segment_kinds, recovery of 'exact_ccr' or 'none', and deterministic === true.","triggerScenarios":"Calling validateCapabilities with a Capabilities object whose transforms array contains: a transform_id that is not a valid token, a duplicate transform_id, an implementation_version that is not a token, eligible_segment_kinds missing or not an array, a recovery value other than 'exact_ccr'/'none', or deterministic not strictly true.","commonSituations":"Hand-written capability manifests with typos in recovery ('exact', 'ccr'), deterministic omitted or set to 1 instead of true, the same transform listed twice after copy-paste, kebab/underscored transform ids failing isToken, or an upgrade that renamed recovery enum values.","solutions":["Fix the offending transform entry: make transform_id and implementation_version valid tokens and ensure each transform_id is unique in the array","Set recovery to exactly 'exact_ccr' or 'none'","Set deterministic to the boolean true (not 1, not a string)","Ensure eligible_segment_kinds is a non-null array of segment kinds","Log/inspect the capabilities object before validation to find which transform fails"],"exampleFix":"// before\n{ transform_id: 'compress json', recovery: 'exact', deterministic: 1 }\n// after\n{ transform_id: 'compress-json', implementation_version: '1.0.0', eligible_segment_kinds: ['json'], recovery: 'exact_ccr', deterministic: true }","handlingStrategy":"validation","validationCode":"function validTransform(t) {\n  return t && isToken(t.transform_id) && isToken(t.implementation_version) &&\n    Array.isArray(t.eligible_segment_kinds) &&\n    ['exact_ccr','none'].includes(t.recovery) && t.deterministic === true;\n}\nconst seen = new Set();\nif (!c.transforms.every(t => validTransform(t) && !seen.has(t.transform_id) && seen.add(t.transform_id)))\n  throw new Error('capability transform invalid before calling validateCapabilities');","typeGuard":"const isCapabilities = (c) => !!c && c.schema_version === 1 && Array.isArray(c.transforms) &&\n  c.transforms.every(t => typeof t?.transform_id === 'string' && typeof t?.deterministic === 'boolean' &&\n    (t.recovery === 'exact_ccr' || t.recovery === 'none'));","tryCatchPattern":"try { await validateCapabilities(value); } catch (e) {\n  if (e.code === 'unknown_capability') {\n    const bad = value.transforms.findIndex(t => !isCapabilities({ transforms: [t] }));\n    console.error(`invalid transform at index ${bad}:`, value.transforms[bad]);\n  } else throw e;\n}","preventionTips":["Generate capability manifests from a schema-validated source rather than hand-writing them","Keep transform_id values unique and token-shaped (no spaces/special chars)","Always use boolean true for deterministic, never 1","Add a unit test that runs every shipped capability set through validateCapabilities"],"tags":["validation","schema","middleware","capabilities"],"backgroundTag":"schema-validation-failed","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}