@thomasminh1995/depverdict 0.6.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +518 -0
  3. package/bin/depverdict.js +7 -0
  4. package/bin/upgradelens.js +7 -0
  5. package/docs/GR-01-Semantic-Grounding-Failure-Analysis.md +309 -0
  6. package/docs/GR-02-Versioned-Action-Evaluation-Criteria.md +187 -0
  7. package/docs/GR-03-Extractive-Contract-Safety-Experiment.md +242 -0
  8. package/docs/GR-04-Versioned-Production-Extractive-Contract.md +154 -0
  9. package/docs/IA-01-Repository-Usage-Discovery.md +122 -0
  10. package/docs/IA-02-Repository-Impact-Analysis.md +118 -0
  11. package/docs/IA-03-Repository-Impact-Evidence.md +160 -0
  12. package/docs/IA-04-CLI-Orchestration.md +235 -0
  13. package/docs/IA-05-Real-Provider-Validation.md +235 -0
  14. package/docs/IA-05-VinGrade-Validation.md +339 -0
  15. package/docs/MVP-01.md +48 -0
  16. package/docs/MVP-02-Architecture.md +536 -0
  17. package/docs/MVP-02-CLI-HTTP-Runtime.md +50 -0
  18. package/docs/MVP-02-HTTP-Lifecycle.md +37 -0
  19. package/docs/MVP-02-Knowledge-Manifest-Generation.md +75 -0
  20. package/docs/MVP-02-Knowledge-Manifest.md +279 -0
  21. package/docs/MVP-02-Knowledge-Research-Orchestration.md +62 -0
  22. package/docs/MVP-02-Knowledge-Store.md +87 -0
  23. package/docs/MVP-02-PyPI-Registry-Adapter.md +97 -0
  24. package/docs/MVP-02-Research-Planning.md +196 -0
  25. package/docs/MVP-02-Source-Provenance.md +81 -0
  26. package/docs/MVP-02-npm-Registry-Adapter.md +99 -0
  27. package/docs/RR-01-End-to-End-and-Real-Provider-Validation.md +393 -0
  28. package/docs/RR-01-RERUN-Extractive-Contract-Validation.md +566 -0
  29. package/docs/RR-02-Full-Product-Workflow-and-Developer-CLI-UX-Review.md +35 -0
  30. package/docs/RR02-FIX-01-Persistent-Qualification-Resolution.md +32 -0
  31. package/docs/RR02-FIX-02-Stage-aware-CLI-Progress-and-Heartbeat.md +28 -0
  32. package/docs/RR02-FIX-03-npm-Capture-Evidence-Exclusion.md +33 -0
  33. package/docs/RR02-FIX-03A-Complete-Package-Exclusion-and-Evidence-Commit.md +223 -0
  34. package/docs/RR02-FIX-04-Event-loop-safe-Heartbeat.md +393 -0
  35. package/docs/RR02-FIX-05-Materialize-Persisted-Qualification.md +207 -0
  36. package/docs/RR02-RERUN-CLI-Qualification-Progress-UX-and-Package-Validation.md +342 -0
  37. package/docs/VinGrade-MVP-02-Validation.md +480 -0
  38. package/docs/VinGrade-RC02-Live-Validation.md +273 -0
  39. package/docs/ai-capability-discovery.md +573 -0
  40. package/docs/ai-engineering-production-readiness.md +390 -0
  41. package/docs/ai-engineering-review.md +251 -0
  42. package/docs/ai-runtime-governance-discovery.md +754 -0
  43. package/docs/architecture-overview.md +78 -0
  44. package/docs/cli-progress.md +111 -0
  45. package/docs/decisions/diff-01-brand-distribution-identity.md +450 -0
  46. package/docs/decisions/diff-02-identity-compatibility-contract.md +274 -0
  47. package/docs/decisions/diff-03-repository-docs-community-migration.md +165 -0
  48. package/docs/decisions/diff-04-release-evidence-gap-acceptance.md +110 -0
  49. package/docs/discovery/mvp-05-ai-migration-planning-discovery.md +350 -0
  50. package/docs/gateway-runtime-discovery.md +614 -0
  51. package/docs/live-ai-validation.md +299 -0
  52. package/docs/migration-planning-qualification-resolution.md +99 -0
  53. package/docs/migrations/upgradelens-to-depverdict.md +97 -0
  54. package/docs/mp-r03-deterministic-upgrade-decision-architecture.md +135 -0
  55. package/docs/mp-r04-evidence-bounded-migration-handoff-architecture.md +116 -0
  56. package/docs/mp-r05-product-completion-and-decision-first-cli-architecture.md +162 -0
  57. package/docs/mvp-05-deterministic-context-runtime.md +127 -0
  58. package/docs/mvp-05-migration-checklist-contract.md +166 -0
  59. package/docs/mvp-05-migration-checklist-orchestration.md +105 -0
  60. package/docs/mvp-05-migration-evaluation-and-qualification.md +135 -0
  61. package/docs/mvp-05-provider-neutral-generator.md +79 -0
  62. package/docs/ollama-local-smoke-validation.md +156 -0
  63. package/docs/openai-compatible-runtime-discovery.md +789 -0
  64. package/docs/openrouter-one-dependency-validation.md +205 -0
  65. package/docs/oss-02-package-guard-hardening-architecture.md +131 -0
  66. package/docs/oss-04-public-ci-package-metadata-architecture.md +142 -0
  67. package/docs/package-content-policy.md +98 -0
  68. package/docs/releases/v0.5.0-technical-preview.md +114 -0
  69. package/docs/releases/v0.6.0-alpha.1-depverdict-preview.md +101 -0
  70. package/docs/reviews/diff-02-identity-contract-compatibility.md +413 -0
  71. package/docs/reviews/diff-03-repository-docs-community-migration.md +364 -0
  72. package/docs/reviews/diff-04-depverdict-distribution-identity-readiness-rereview.md +453 -0
  73. package/docs/reviews/diff-04-fix-post-rename-identity-release-remediation.md +310 -0
  74. package/docs/reviews/diff-05-final-preview-distribution-qualification.md +561 -0
  75. package/docs/reviews/mvp-05-final-product-value-workflow-rereview.md +471 -0
  76. package/docs/reviews/mvp-05-product-workflow-review.md +605 -0
  77. package/docs/reviews/oss-01-duplicate-artifact-investigation-cleanup.md +411 -0
  78. package/docs/reviews/oss-02-package-guard-hardening.md +303 -0
  79. package/docs/reviews/oss-03-community-scaffolding.md +378 -0
  80. package/docs/reviews/oss-04-public-ci-package-metadata.md +439 -0
  81. package/docs/reviews/oss-05-technical-preview-qualification.md +482 -0
  82. package/docs/reviews/upgradelens-vs-upgradedepdetective-source-comparison.md +355 -0
  83. package/docs/reviews/v0.5.0-pre-release-smoke.md +263 -0
  84. package/docs/reviews/v0.5.0-version-bump-release-verification.md +306 -0
  85. package/docs/runtime-contract-discovery.md +521 -0
  86. package/docs/structured-output-compatibility-report.md +100 -0
  87. package/docs/ts-fix-01-exact-duplicate-occurrence-target-selection-architecture.md +111 -0
  88. package/docs/version-analysis-architecture.md +827 -0
  89. package/eval/README.md +86 -0
  90. package/eval/datasets/generic/declared-constraint.json +59 -0
  91. package/eval/datasets/generic/evidence-conflict.json +73 -0
  92. package/eval/datasets/generic/major-breaking-release.json +66 -0
  93. package/eval/datasets/generic/missing-evidence.json +46 -0
  94. package/eval/datasets/generic/patch-release-low.json +59 -0
  95. package/eval/datasets/node/axios-patch-low.json +59 -0
  96. package/eval/datasets/node/react-major-breaking.json +66 -0
  97. package/eval/datasets/node/react-minor-compatibility.json +66 -0
  98. package/eval/datasets/python/fastapi-deprecation.json +66 -0
  99. package/eval/datasets/python/pydantic-major-breaking.json +66 -0
  100. package/eval/migration-planning/golden-dataset-v2.json +306 -0
  101. package/eval/migration-planning/golden-dataset.json +214 -0
  102. package/eval/schemas/expected-result.schema.json +88 -0
  103. package/eval/schemas/golden-case.schema.json +181 -0
  104. package/package.json +57 -0
  105. package/schemas/ai-scorecard.schema.json +132 -0
  106. package/schemas/benchmark-report.schema.json +189 -0
  107. package/schemas/benchmark.schema.json +55 -0
  108. package/schemas/capability-profile.schema.json +44 -0
  109. package/schemas/conformance-report.schema.json +150 -0
  110. package/schemas/deployment-profile.schema.json +64 -0
  111. package/schemas/evaluation-report.schema.json +158 -0
  112. package/schemas/knowledge-evidence-bundle.schema.json +150 -0
  113. package/schemas/knowledge-manifest.schema.json +548 -0
  114. package/schemas/metrics.schema.json +178 -0
  115. package/schemas/migration-checklist-extractive-candidate.schema.json +42 -0
  116. package/schemas/migration-checklist.schema.json +706 -0
  117. package/schemas/migration-evaluation-dataset-v2.schema.json +208 -0
  118. package/schemas/migration-evaluation-dataset.schema.json +204 -0
  119. package/schemas/migration-planning-qualification-record.schema.json +234 -0
  120. package/schemas/project-manifest.schema.json +308 -0
  121. package/schemas/qualification-record.schema.json +56 -0
  122. package/schemas/repository-impact-evidence.schema.json +232 -0
  123. package/schemas/repository-impact.schema.json +202 -0
  124. package/schemas/upgrade-decision.schema.json +273 -0
  125. package/schemas/usage-index.schema.json +179 -0
  126. package/schemas/version-analysis.schema.json +449 -0
  127. package/src/ai-runtime-debug.js +325 -0
  128. package/src/ai-runtime-error.js +42 -0
  129. package/src/ai-runtime.js +174 -0
  130. package/src/ai-scorecard.js +204 -0
  131. package/src/ai-version-analysis.js +484 -0
  132. package/src/artifact-root-compatibility.js +91 -0
  133. package/src/benchmark-report.js +111 -0
  134. package/src/benchmark-runner.js +191 -0
  135. package/src/canonical-json.js +69 -0
  136. package/src/cli.js +1299 -0
  137. package/src/conformance-report.js +158 -0
  138. package/src/conformance-runner.js +253 -0
  139. package/src/constants.js +73 -0
  140. package/src/cooperative-scheduler.js +79 -0
  141. package/src/dependencies.js +44 -0
  142. package/src/dependency-ai-context.js +625 -0
  143. package/src/detectors.js +253 -0
  144. package/src/discovery.js +234 -0
  145. package/src/ecosystem-version-adapter.js +294 -0
  146. package/src/environment-compatibility.js +77 -0
  147. package/src/evaluation-comparator.js +158 -0
  148. package/src/evaluation-report.js +76 -0
  149. package/src/evaluation-runner.js +248 -0
  150. package/src/evidence-source-adapter.js +472 -0
  151. package/src/files.js +89 -0
  152. package/src/governance-diagnostics.js +64 -0
  153. package/src/governance-loader.js +63 -0
  154. package/src/governance-metadata.js +346 -0
  155. package/src/governance-validator.js +360 -0
  156. package/src/http/bounded-fetch.js +278 -0
  157. package/src/http/cli-http-runtime.js +44 -0
  158. package/src/impact/input-loader.js +157 -0
  159. package/src/impact/matcher.js +40 -0
  160. package/src/impact/repository-impact.js +199 -0
  161. package/src/impact/runtime.js +24 -0
  162. package/src/impact/status.js +62 -0
  163. package/src/impact/writer.js +30 -0
  164. package/src/impact-evidence/input-loader.js +202 -0
  165. package/src/impact-evidence/repository-impact-evidence.js +234 -0
  166. package/src/impact-evidence/runtime.js +16 -0
  167. package/src/impact-evidence/writer.js +30 -0
  168. package/src/index.js +563 -0
  169. package/src/installed-version-baseline.js +196 -0
  170. package/src/knowledge-cache.js +324 -0
  171. package/src/knowledge-evidence-bundle.js +101 -0
  172. package/src/knowledge-evidence-producer.js +233 -0
  173. package/src/knowledge-manifest-builder.js +188 -0
  174. package/src/knowledge-manifest-writer.js +32 -0
  175. package/src/knowledge-manifest.js +255 -0
  176. package/src/knowledge-research.js +615 -0
  177. package/src/metrics-engine.js +205 -0
  178. package/src/migration-checklist/ai-candidate.js +320 -0
  179. package/src/migration-checklist/assembler.js +37 -0
  180. package/src/migration-checklist/context-runtime.js +828 -0
  181. package/src/migration-checklist/evaluation/action-criteria.js +244 -0
  182. package/src/migration-checklist/evaluation/comparator-v2.js +332 -0
  183. package/src/migration-checklist/evaluation/comparator.js +279 -0
  184. package/src/migration-checklist/evaluation/dataset-v2.js +227 -0
  185. package/src/migration-checklist/evaluation/dataset.js +336 -0
  186. package/src/migration-checklist/evaluation/extractive-fixtures-v2.js +148 -0
  187. package/src/migration-checklist/evaluation/metrics-v2.js +226 -0
  188. package/src/migration-checklist/evaluation/metrics.js +158 -0
  189. package/src/migration-checklist/evaluation/qualification-v2.js +321 -0
  190. package/src/migration-checklist/evaluation/qualification.js +239 -0
  191. package/src/migration-checklist/evaluation/runner-v2.js +294 -0
  192. package/src/migration-checklist/evaluation/runner.js +194 -0
  193. package/src/migration-checklist/evaluation/scorecard-v2.js +106 -0
  194. package/src/migration-checklist/evaluation/scorecard.js +86 -0
  195. package/src/migration-checklist/extractive-candidate.js +166 -0
  196. package/src/migration-checklist/extractive-prompt.js +62 -0
  197. package/src/migration-checklist/generator.js +702 -0
  198. package/src/migration-checklist/grounding-policy.js +117 -0
  199. package/src/migration-checklist/input-loader.js +613 -0
  200. package/src/migration-checklist/migration-checklist.js +635 -0
  201. package/src/migration-checklist/presentation.js +292 -0
  202. package/src/migration-checklist/progress.js +96 -0
  203. package/src/migration-checklist/prompt.js +83 -0
  204. package/src/migration-checklist/qualification-guard.js +462 -0
  205. package/src/migration-checklist/qualification-resolution.js +122 -0
  206. package/src/migration-checklist/qualification-store.js +225 -0
  207. package/src/migration-checklist/runtime.js +205 -0
  208. package/src/migration-checklist/verification.js +134 -0
  209. package/src/migration-checklist/writer.js +35 -0
  210. package/src/openai-compatible-provider.js +451 -0
  211. package/src/orchestration/failure-log.js +32 -0
  212. package/src/orchestration/pipeline.js +200 -0
  213. package/src/orchestration/progress-events.js +337 -0
  214. package/src/orchestration/progress-reporter.js +131 -0
  215. package/src/orchestration/text-writer.js +22 -0
  216. package/src/portable.js +13 -0
  217. package/src/product-completion.js +249 -0
  218. package/src/project-manifest-input.js +90 -0
  219. package/src/project-manifest.js +141 -0
  220. package/src/python-requirements.js +137 -0
  221. package/src/registry/npm-packument.js +256 -0
  222. package/src/registry/npm-registry-adapter.js +262 -0
  223. package/src/registry/pypi-project.js +300 -0
  224. package/src/registry/pypi-registry-adapter.js +235 -0
  225. package/src/registry/sanitize-registry-body.js +51 -0
  226. package/src/renderers/console.js +160 -0
  227. package/src/renderers/impact-presentation.js +278 -0
  228. package/src/renderers/markdown.js +172 -0
  229. package/src/research-plan.js +455 -0
  230. package/src/runtime-conformance.js +275 -0
  231. package/src/source-provenance.js +393 -0
  232. package/src/source-url.js +62 -0
  233. package/src/structured-output-schema.js +66 -0
  234. package/src/target-selector.js +306 -0
  235. package/src/upgrade-decision/input-loader.js +107 -0
  236. package/src/upgrade-decision/presentation.js +43 -0
  237. package/src/upgrade-decision/runtime.js +21 -0
  238. package/src/upgrade-decision/upgrade-decision.js +626 -0
  239. package/src/upgrade-decision/writer.js +30 -0
  240. package/src/usage/analyzer-registry.js +63 -0
  241. package/src/usage/coverage.js +116 -0
  242. package/src/usage/input-loader.js +139 -0
  243. package/src/usage/js/analyzer.js +240 -0
  244. package/src/usage/js/parser.js +21 -0
  245. package/src/usage/runtime.js +187 -0
  246. package/src/usage/scope.js +44 -0
  247. package/src/usage/source-files.js +50 -0
  248. package/src/usage/usage-index.js +217 -0
  249. package/src/usage/writer.js +31 -0
  250. package/src/version-analysis-loader.js +203 -0
  251. package/src/version-analysis-manifest.js +314 -0
  252. package/src/version-analysis-writer.js +30 -0
@@ -0,0 +1,521 @@
1
+ # LR-00D — AI Runtime Contract Discovery
2
+
3
+ **Status:** Architecture discovery and proposed runtime contract freeze
4
+
5
+ **Ngày:** 2026-07-15
6
+
7
+ **Phạm vi:** Contract chung giữa UpgradeLens AI Core và mọi local, cloud hoặc gateway-backed AI runtime. Tài liệu không triển khai contract hoặc adapter.
8
+
9
+ ## 1. Executive Summary
10
+
11
+ UpgradeLens hiện có một `AiRuntime` nhỏ trong [`src/ai-runtime.js`](../src/ai-runtime.js), nhưng contract hiện tại mới đủ cho MVP-03 foundation: request chứa `context` và `outputSchema`, runtime composition helper dựng prompt, response cho phép `output` là unknown, còn transport errors cuối cùng có thể bị biểu diễn như output schema failure trong [`src/ai-version-analysis.js`](../src/ai-version-analysis.js). Nếu triển khai OpenAI-compatible adapter ngay trên shape này, task semantics, prompt construction, provider errors và execution metadata sẽ tiếp tục trộn ở runtime boundary.
12
+
13
+ Runtime Contract cần tồn tại để đóng băng một ranh giới duy nhất trước LR-01:
14
+
15
+ | Layer | Sở hữu | Không được sở hữu |
16
+ | --- | --- | --- |
17
+ | AI Core | Task semantics, deterministic context, prompt construction, exact output schema, local parsing/schema validation, trust handoff | Provider/model/endpoint/auth/routing/wire quirks |
18
+ | Runtime | Capability enforcement, Deployment Profile, execution policy, security bounds, adapter invocation, normalized response/error/telemetry | Dependency/version facts, evidence selection, risk/trust semantics |
19
+ | Provider Adapter | Provider/gateway protocol mapping, headers, response envelope, provider error mapping | Prompt meaning, schema modification, fallback policy tự phát, trust |
20
+ | Gateway | Forwarding/routing only theo locked deployment policy | Target version, evidence, quality gate, hidden transforms/fallback |
21
+ | Model | Sinh candidate content | Deterministic facts hoặc publication authority |
22
+
23
+ Contract v1 được đề xuất là một **unary, non-streaming, structured-generation operation**. Nó nhận prompt đã render cùng exact schema và correlation IDs; nó trả một normalized successful response hoặc một typed runtime error. Model/provider/endpoint/generation settings không nằm trong AI Core request mà đến từ immutable Deployment Profile.
24
+
25
+ Mục tiêu đồng thời là:
26
+
27
+ - protocol-first: contract không chứa Chat Completions, Responses, Anthropic Messages hay Gemini field names;
28
+ - capability-first: runtime phải chứng minh effective capability trước request;
29
+ - provider-neutral: AI Core không biết OpenAI, Anthropic, Gemini, Ollama, gateways hoặc local engines;
30
+ - task-neutral: runtime chỉ thấy task identity/correlation và rendered prompt, không hiểu Version/Impact/Migration semantics;
31
+ - runtime-neutral: local weights, direct API và gateway đều có cùng success/error boundary.
32
+
33
+ Quyết định tối thiểu:
34
+
35
+ 1. Giữ một operation có semantics tương đương `generateStructured`; không cần plugin/API framework.
36
+ 2. Di chuyển Prompt Builder lên AI Core boundary trước khi gọi runtime; runtime không nhận raw task context để tự dựng prompt.
37
+ 3. Canonical successful `output` là text; AI Core parse JSON và validate exact schema.
38
+ 4. Model/provider configuration thuộc Deployment Profile, không thuộc request do AI Core tạo.
39
+ 5. Structured-output downgrade, model/provider fallback và prompt/response transform bị cấm nếu không có profile/qualification riêng.
40
+ 6. Telemetry bắt đầu tại runtime invocation và kết thúc ở runtime response/error; telemetry không đi vào Version Analysis Manifest.
41
+ 7. Trust Layer bắt đầu sau local JSON parse + exact schema validation; runtime không đưa ra trust decision.
42
+
43
+ Với các quyết định trong 12 section này, Runtime Contract **đủ ổn định để architecture freeze và bắt đầu LR-01**. Future tools, streaming, realtime và agents phải mở extension contract mới thay vì làm phình v1.
44
+
45
+ ## 2. Runtime Architecture
46
+
47
+ ### Standard layers
48
+
49
+ Luồng chuẩn gồm sáu layer theo thứ tự: AI Core → Runtime Contract → Runtime Execution → Provider Adapter → HTTP/local transport → model endpoint. Optional gateway nằm giữa transport và model endpoint nhưng không tạo contract mới với AI Core.
50
+
51
+ | Layer | Responsibility | Được phép biết | Không được phép biết/thay đổi |
52
+ | --- | --- | --- | --- |
53
+ | AI Core | Build deterministic task context, render prompts, select schema, call runtime, validate candidate, invoke trust | Task ID/version, context ID, prompt version/content, schema, task budgets | Provider/model ID, endpoint, auth, gateway routing, wire response |
54
+ | Runtime Contract | Stable request/success/error vocabulary | Generic prompts, structured-output requirement, safe correlation, normalized execution result | Provider request field names và task business logic |
55
+ | Runtime Execution | Bind Deployment Profile, check capability, enforce bounds/policy, measure telemetry | Effective model/runtime configuration, caller requirements, adapter result | Rewriting task input/schema, choosing evidence or interpreting claims |
56
+ | Provider Adapter | Map generic request to one protocol/provider family and normalize response/error | Endpoint wire contract, provider headers/parameters, response/error envelope | Risk taxonomy, evidence semantics, local Ajv/trust rules |
57
+ | Transport | Connect, bound, cancel, authenticate, read response | URL, TLS, headers, byte/time limits | Prompt semantics, retries that switch route/model |
58
+ | Gateway/model | Execute configured route/inference | Translated request allowed by profile | Hidden fallback/transform or authority over final artifact |
59
+
60
+ ### Knowledge boundaries
61
+
62
+ AI Core may know:
63
+
64
+ - which task contract is running;
65
+ - deterministic context and its digest;
66
+ - prompt version and rendered system/user prompt;
67
+ - exact expected output schema/digest;
68
+ - whether the task requires strict structured output;
69
+ - local validation/trust result.
70
+
71
+ AI Core must not know:
72
+
73
+ - provider/gateway brand;
74
+ - model, revision, quantization or inference engine;
75
+ - endpoint URL, credentials, provider headers or request extras;
76
+ - reasoning/thinking/temperature quirks;
77
+ - retry, fallback, provider route or billing logic.
78
+
79
+ Provider Adapter may know all wire-level facts needed to call its endpoint, including how a provider represents messages, schema, reasoning mode, usage, finish reason and errors. It may not inspect the task ID to choose vendor behavior, modify prompt meaning, project a weaker schema silently, or run business validation.
80
+
81
+ ### Relationship to existing code
82
+
83
+ The operation can retain the current `generateStructured` name to minimize LR-01 impact. The architectural change is request ownership:
84
+
85
+ - today `createProviderAiRuntime` invokes a `promptBuilder` inside runtime composition;
86
+ - frozen contract requires Prompt Builder to execute above the runtime boundary;
87
+ - current `context` becomes AI Core input only; runtime receives rendered prompts and `contextId` correlation, not a task-specific context object;
88
+ - current `outputSchema` becomes an explicit structured-output requirement;
89
+ - current provider/model/latency/usage result becomes the normalized response described below.
90
+
91
+ This is a bounded contract refinement, not a new framework or runtime service.
92
+
93
+ ## 3. Runtime Request Contract
94
+
95
+ ### Minimal mandatory fields
96
+
97
+ | Field | Mandatory | Owner | Semantics | Mutation policy |
98
+ | --- | --- | --- | --- | --- |
99
+ | `contractVersion` | Yes | AI Core/runtime interface | Selects Runtime Contract semantics, initially version 1 | Runtime validates; no mutation |
100
+ | `runId` | Yes | Invocation orchestrator | Operational correlation for one invocation/attempt group | Echo only; never sent as prompt content unless provider correlation supports a safe header |
101
+ | `contextId` | Yes | AI Core | Digest/identity of deterministic task input | Echo only; provider cannot alter |
102
+ | `task` | Yes | AI Core | Stable task contract ID such as `version-analysis.v1` | Used for trace/requirement matching, never vendor branching |
103
+ | `promptVersion` | Yes | AI Core | Version of already-rendered prompt semantics | Echo/audit only |
104
+ | `systemPrompt` | Yes | AI Core Prompt Builder | Exact system instruction text | Adapter may serialize roles but not rewrite/inject/compress |
105
+ | `userPrompt` | Yes | AI Core Prompt Builder | Exact user/task input text, including bounded context as designed by the task | Same immutability rule |
106
+ | `structuredOutput` | Yes for v1 operation | AI Core | Required output mode, schema name, exact schema and schema digest | Runtime/adapter must preserve or fail |
107
+ | `budget` | Yes | AI Core + Deployment Profile validation | Task-required input/output envelope | Runtime may enforce a stricter deployment ceiling only if it still satisfies task minimum; otherwise configuration/capability failure |
108
+
109
+ `structuredOutput` conceptually contains:
110
+
111
+ - required semantic mode (`jsonSchema` for production MVP-03 profile);
112
+ - stable schema name for provider APIs that require one;
113
+ - exact JSON Schema object;
114
+ - schema digest for trace/qualification;
115
+ - whether any weaker mode is acceptable. For Version Analysis production this value is false.
116
+
117
+ `budget` conceptually contains:
118
+
119
+ - maximum/required input operating envelope when token counting is available;
120
+ - maximum output tokens required by the task;
121
+ - optional absolute execution deadline supplied by orchestration;
122
+ - no evidence-selection policy. Evidence/context bounding remains AI Core responsibility.
123
+
124
+ ### Optional caller fields
125
+
126
+ | Field | Owner | Use | Constraint |
127
+ | --- | --- | --- | --- |
128
+ | Safe correlation metadata | Evaluation/benchmark/orchestrator | Dataset case, repeat/sample ID, parent trace ID | Small allowlist of strings/numbers; no prompt/evidence/provider extras |
129
+ | Cancellation control | Invocation orchestrator | Abort an in-process request | Execution control, not portable/serialized task metadata |
130
+ | Privacy classification | AI Core/orchestrator | Inform runtime whether remote transmission is allowed | Runtime may reject; cannot downgrade classification |
131
+
132
+ ### Fields intentionally excluded from AI Core request
133
+
134
+ | Excluded field | Correct owner | Reason |
135
+ | --- | --- | --- |
136
+ | Provider, model, revision | Deployment Profile/runtime | Putting them in task request leaks provider selection into AI Core and weakens reproducibility. |
137
+ | Endpoint and auth | Deployment Profile/transport | Secrets/config never belong to semantic request. |
138
+ | Quantization, runtime version, chat template | Deployment Profile | Exact deployment identity, not task semantics. |
139
+ | Temperature, top-p, seed | Deployment Profile | Support/default constraints differ by model; benchmark identity must pin effective values without task code knowing provider rules. |
140
+ | Reasoning/thinking mode and effort | Deployment Profile/capability mapping | Provider-specific controls; task may require a capability class but not a vendor parameter. |
141
+ | Retry/fallback/routing | Deployment Profile/runtime policy | Execution and availability policy; cannot be model-generated or task-selected. |
142
+ | Provider-specific metadata/extras | Adapter/profile allowlist | Generic metadata must not become an escape hatch for vendor logic. |
143
+
144
+ ### Ownership and mutation rules
145
+
146
+ - Runtime must reject missing/unsupported contract version, task requirement, budget or schema mode before transport.
147
+ - Adapter may transform representation only: role/message encoding, schema wrapper, provider parameter names and safe correlation headers.
148
+ - Adapter may not change prompt text semantics, schema keywords, model selected by profile or structured-output mode.
149
+ - Gateway/request extras cannot override prompts, schema, model, streaming, routing/fallback locks or security bounds.
150
+ - Effective deployment/generation settings must be recorded in execution telemetry; they are never inferred from a task request.
151
+
152
+ ## 4. Runtime Response Contract
153
+
154
+ Runtime returns a successful response only when transport/provider envelope is valid and a usable final output exists. All other outcomes use Runtime Error Contract, not a success object with ambiguous warnings.
155
+
156
+ ### Normalized success fields
157
+
158
+ | Field | Required | Semantics | Consumer |
159
+ | --- | --- | --- | --- |
160
+ | `contractVersion` | Yes | Version used for response normalization | Runtime/AI Core guard |
161
+ | `runId`, `contextId` | Yes | Exact correlation echo | Core, evaluation, trace |
162
+ | `output` | Yes | Final assistant/model content as text; for structured operation this text should represent one JSON value | AI Core parser only |
163
+ | `finishReason` | Yes | Normalized terminal reason; success requires an accepted complete state | Core guard + telemetry |
164
+ | Requested identity | Yes | Deployment profile ID/digest and requested provider/model route | Benchmark/trace |
165
+ | Actual identity | Required for benchmark/production | Actual provider, model and revision/digest when observable | Qualification/identity policy |
166
+ | `usage` | Optional values, present container | Normalized token/cache/reasoning usage with unknown represented as null | Benchmark/observability |
167
+ | `timings` | Total latency required; subfields optional | Total wall time, optional queue/provider/network timing | Benchmark/observability |
168
+ | Execution summary | Yes | Attempt/retry count, fallback flag, transform list, effective schema mode | Governance/trace |
169
+ | Warnings | Optional | Non-fatal normalized execution limitations such as usage unavailable | Observability; never semantic claims |
170
+ | Provider correlation | Optional | Bounded request/generation ID or safe route correlation | Operator trace only |
171
+
172
+ ### Identity semantics
173
+
174
+ - `provider` identifies configured adapter/provider boundary; `actualProvider` identifies the upstream provider that executed when a gateway is present.
175
+ - `model` is requested model from Deployment Profile; `actualModel` is provider/gateway response identity.
176
+ - `revision` is exact snapshot/digest when the platform exposes it. Unknown revision can be acceptable for development but not silently accepted for reproducible benchmark/production qualification.
177
+ - Identity mismatch is an error under locked profiles, not a warning.
178
+
179
+ ### Finish reason semantics
180
+
181
+ Normalized vocabulary should distinguish at least:
182
+
183
+ - complete/stop;
184
+ - output length/truncation;
185
+ - content refusal/filter;
186
+ - tool/function call instead of final content;
187
+ - cancellation;
188
+ - unknown provider terminal state.
189
+
190
+ Only complete final content returns success in Runtime Contract v1. Every other state maps to a typed error even if provider HTTP status is 200.
191
+
192
+ ### Portable vs execution-only
193
+
194
+ | Data | Portable task artifact? | Rule |
195
+ | --- | --- | --- |
196
+ | Runtime `output` | Not directly | It becomes candidate input to local parse/schema/trust; raw output is not publishable. |
197
+ | Trusted summary/risk/findings | Yes, through Version Analysis Manifest | Only after existing local validation/trust/manifest invariants. |
198
+ | Runtime/provider/model/revision | No in current Version Analysis artifact | Keep in separate execution/qualification trace. |
199
+ | Usage, latency, cost, attempts | No | Benchmark/observability only. |
200
+ | Stable mapped failure/limitation | May be represented by task failure result | Publish only local stable code/sanitized message, never raw provider detail. |
201
+ | Prompt, evidence, raw response/error | No | Sensitive execution data; default trace excludes it. |
202
+
203
+ Portable artifact boundary remains [`version-analysis-manifest.js`](../src/version-analysis-manifest.js) for MVP-03. Runtime response is execution data, not a portable semantic artifact.
204
+
205
+ ## 5. Runtime Error Contract
206
+
207
+ Runtime errors need a stable provider-neutral code, sanitized message, retryability decision, optional bounded HTTP status/provider code, run/context correlation and execution summary. Raw headers/body/prompt/evidence are never fields.
208
+
209
+ ### Taxonomy
210
+
211
+ | Code | Meaning | Default action | Retry policy |
212
+ | --- | --- | --- | --- |
213
+ | `CONFIGURATION_ERROR` | Missing/invalid Deployment Profile, endpoint, model, auth mode or bounds | Fail fast | Never |
214
+ | `CAPABILITY_MISMATCH` | Task requirement exceeds effective runtime capability | Fail fast before call | Never; choose another qualified profile explicitly |
215
+ | `AUTH_ERROR` | Authentication/authorization rejected | Fail fast | Never |
216
+ | `MODEL_NOT_FOUND` | Requested model/revision unavailable | Fail fast | Never |
217
+ | `NETWORK_ERROR` | DNS/connect/reset/transport failure | Fail or bounded retry | At most profile-declared retry on same tuple |
218
+ | `TIMEOUT` | Configured deadline exceeded | Fail | No default retry; optional same-tuple retry only when explicitly qualified |
219
+ | `CANCELLED` | Caller/operator cancellation | Fail without retry | Never |
220
+ | `RATE_LIMITED` | Provider returns rate/quota signal | Fail or bounded wait | Same tuple only, bounded attempts and `Retry-After` |
221
+ | `PROVIDER_UNAVAILABLE` | Transient upstream 502/503-class failure | Fail or bounded retry | Same tuple only |
222
+ | `SCHEMA_REJECTED` | Endpoint rejects exact schema/keyword combination | Fail conformance | Never downgrade/retry weaker schema |
223
+ | `STRUCTURED_OUTPUT_UNSUPPORTED` | Deployment cannot provide required mode | Fail capability/conformance | Never |
224
+ | `INVALID_RESPONSE` | Invalid envelope, missing/empty content, malformed provider success response | Fail | Never |
225
+ | `OUTPUT_TRUNCATED` | Finish reason/response indicates incomplete output | Fail | Never retry with changed budget/model silently |
226
+ | `CONTENT_REFUSED` | Refusal/content filter prevented final output | Fail | Never automatic retry |
227
+ | `RESPONSE_TOO_LARGE` | Bounded response/error body limit exceeded | Fail | Never |
228
+ | `IDENTITY_MISMATCH` | Actual provider/model/revision violates locked profile | Fail and invalidate sample | Never |
229
+ | `ROUTING_POLICY_VIOLATION` | Unexpected fallback, attempts, account/model route or transform | Fail and invalidate sample | Never |
230
+ | `PROVIDER_ERROR` | Sanitized non-transient provider failure not classified above | Fail | Default never |
231
+ | `UNKNOWN` | No safe classification possible | Fail closed | Never |
232
+
233
+ ### Retry rules
234
+
235
+ Retry is Runtime Execution responsibility, not Provider Adapter improvisation. It must satisfy all conditions:
236
+
237
+ - Deployment Profile explicitly allows it;
238
+ - same provider, model, revision, quantization, reasoning mode and schema mode;
239
+ - bounded attempt count and total deadline;
240
+ - every attempt recorded;
241
+ - no retry for schema/output/trust/identity/routing/config/auth/model errors;
242
+ - no retry can change certification tuple.
243
+
244
+ ### Publication and logging
245
+
246
+ - AI Core may map stable runtime code to a task-local failed result and limitation, as current analysis already does for invalid output classes.
247
+ - Portable artifact may include only stable local code and sanitized user-safe message needed to explain failure/human review.
248
+ - HTTP status, provider error code, attempts and correlation IDs stay execution-only.
249
+ - Raw provider message/body is excluded from portable artifact and default logs because it may echo prompt, evidence or credential material.
250
+ - An error marked retryable does not authorize retry; Deployment Profile policy is final.
251
+
252
+ ## 6. Structured Output Contract
253
+
254
+ ### Required abstraction
255
+
256
+ Runtime Contract expresses the **semantic output guarantee required by the task**, not the provider mechanism. The effective mechanism is recorded by runtime capability/deployment telemetry.
257
+
258
+ | Semantic mode | Guarantee before local validation | Qualification role |
259
+ | --- | --- | --- |
260
+ | Native/runtime JSON Schema | Generation constrained to supplied schema or documented supported subset | Required baseline for MVP-03 production benchmark |
261
+ | JSON mode | One syntactically valid JSON value, no exact schema guarantee | Explicit weaker profile only; separate conformance/qualification |
262
+ | Prompt-only JSON | No transport/decoder guarantee | Experimental compatibility only |
263
+ | Function/tool arguments | Schema may constrain tool arguments, not final task response | Outside Runtime Contract v1 final-output path |
264
+
265
+ Grammar/constrained decoding are implementation mechanisms that can satisfy JSON Schema mode only when exact task schema conformance passes. AI Core does not need to know whether enforcement came from provider-native schema, vLLM/Ollama grammar or another decoder.
266
+
267
+ ### Boundary responsibilities
268
+
269
+ | Layer | Responsibility |
270
+ | --- | --- |
271
+ | AI Core | Supply exact schema/name/digest and required mode; parse returned text; validate exact schema with local Ajv. |
272
+ | Runtime | Confirm effective capability/profile; prohibit downgrade; pass exact requirement to adapter; reject invalid terminal state. |
273
+ | Provider Adapter | Map schema/mode to provider fields without semantic projection; normalize final content. |
274
+ | Local schema validation | Authority for candidate structure regardless of provider “strict” claim. |
275
+ | Trust validation | Authority for evidence refs/URLs, risk downgrade, claim filtering and human review after schema pass. |
276
+
277
+ ### Fallback policy
278
+
279
+ - No silent `jsonSchema → jsonMode → promptOnly` fallback.
280
+ - No retry through function/tool calling because final JSON Schema failed.
281
+ - A weaker mode requires a different Deployment Profile, conformance report and qualification record.
282
+ - Provider-facing schema projection is forbidden in v1 unless a future discovery defines a lossless, audited mapping; exact internal schema still remains authority.
283
+ - Schema rejection is a capability/conformance failure, not a prompt problem.
284
+
285
+ ### Validation order
286
+
287
+ The mandatory order is: valid runtime success envelope → complete output text → JSON parse → exact Ajv candidate validation → trust validation → task result/manifest validation. Invalid output never reaches trust as a valid candidate and raw model claims never bypass this sequence.
288
+
289
+ ## 7. Streaming Contract
290
+
291
+ ### Recommendation
292
+
293
+ Streaming is **not part of Runtime Contract v1**. The frozen operation is unary and non-streaming.
294
+
295
+ Version Analysis does not benefit from streaming because:
296
+
297
+ - the only consumable result is a complete JSON candidate;
298
+ - partial JSON cannot pass Ajv or trust validation;
299
+ - early chunks cannot be published or consumed by MVP-04;
300
+ - streaming complicates timeout, retry, backpressure, gateway fallback and usage/error normalization without improving analysis quality.
301
+
302
+ MVP-04 and MVP-05 should initially use the same non-streaming structured artifact model. They may have larger contexts/outputs, but downstream consumers still need a complete schema-valid and trust-valid artifact. Large output is solved with bounded task schemas/retrieval/chunked task orchestration above runtime, not by exposing untrusted token chunks.
303
+
304
+ ### Partial output rules
305
+
306
+ - Partial JSON is never a successful runtime response.
307
+ - A connection closing before accepted finish state maps to `OUTPUT_TRUNCATED` or `INVALID_RESPONSE`.
308
+ - Runtime may buffer provider streaming internally only if an adapter is forced to consume such an endpoint, but the Runtime Contract still returns one final response and enforces response/deadline bounds. That deployment requires separate conformance.
309
+ - Usage/final identity unavailable until stream end means no success before terminal metadata.
310
+
311
+ ### Cancellation and backpressure
312
+
313
+ - Cancellation remains a runtime invocation control for connect/read/inference, even though streaming is absent.
314
+ - Runtime must release transport resources and return `CANCELLED`; partial content is discarded.
315
+ - Backpressure is an internal transport concern while reading a bounded response, not an AI Core API.
316
+
317
+ If realtime UX or token streaming becomes a real requirement, add a separate versioned streaming operation/contract. Do not make v1 success response polymorphic between object, async iterator and event stream.
318
+
319
+ ## 8. Usage & Telemetry Contract
320
+
321
+ ### Normalized fields
322
+
323
+ | Category | Fields | Requirement |
324
+ | --- | --- | --- |
325
+ | Token usage | input, output, total | Nullable; total may be derived only when input/output are authoritative and derivation is labeled |
326
+ | Extended usage | cached input, reasoning/thinking, tool tokens | Optional and source-labeled; never force into base totals without provider definition |
327
+ | Timings | total latency | Required from runtime wall clock |
328
+ | Provider timings | queue, time-to-first-token, provider latency, network | Optional; preserve null rather than fabricate |
329
+ | Terminal state | normalized finish reason + raw bounded provider code | Normalized required; raw code execution-only |
330
+ | Attempts | attempt count, retry count, fallback occurrence | Required execution summary |
331
+ | Identity | requested/actual provider/model/revision, runtime/gateway profile digest | Required for qualified benchmark/production |
332
+ | Cost | amount, currency, source, authoritative/estimated | Optional; no value when not reliably available |
333
+ | Cache | hit/miss/unknown and provider cache token fields | Optional; semantics/source recorded |
334
+ | Policy | effective schema mode, generation settings digest, transform list | Required for reproducibility trace |
335
+
336
+ ### Telemetry boundaries
337
+
338
+ Telemetry begins immediately when Runtime Contract invocation is accepted, before capability/preflight/transport, and ends after normalized success/error. This allows latency and failure category to include runtime overhead rather than only provider inference.
339
+
340
+ Provider Adapter contributes provider-reported usage/timings/correlation. Runtime contributes wall-clock timing, effective profile identity, retry/fallback/transform observations and normalized error. Benchmark Runner consumes a normalized subset; operational observability may consume the larger execution trace.
341
+
342
+ ### Three data classes
343
+
344
+ | Class | Examples | Storage |
345
+ | --- | --- | --- |
346
+ | Portable semantic artifact | Trusted summary/risk/findings/evidence refs | Version/Impact/Migration manifest only |
347
+ | Benchmark artifact | Dataset/prompt/schema/profile digests, quality metrics, aggregate latency/usage/cost | Versioned evaluation/benchmark outputs |
348
+ | Execution trace | Run/context IDs, requested/actual identity, attempts, timings, finish/error, privacy mode | Separate redacted trace with retention policy |
349
+
350
+ No telemetry is added to `version-analysis.json`. That artifact remains provider-neutral and deterministic in its semantic fields. Benchmark/trace link by run/context/profile digests rather than embedding raw prompts or evidence.
351
+
352
+ ### Cost and missing data
353
+
354
+ - Provider-reported authoritative cost is preferred.
355
+ - Gateway estimate must be labeled estimated and cannot be compared as billing truth.
356
+ - Local runtime per-request cost is null unless operator supplies a separately defined accounting model.
357
+ - Missing usage/cost is null/unknown, never zero.
358
+ - Telemetry warnings must not change risk/trust outcome; they can invalidate qualification/benchmark completeness.
359
+
360
+ ## 9. Security Contract
361
+
362
+ ### Runtime security responsibilities
363
+
364
+ | Risk | Required runtime/adapter behavior |
365
+ | --- | --- |
366
+ | Secrets | Inject from external secret source at runtime construction; never include in request contract, profile artifact, error, trace or portable output. |
367
+ | Authorization | Adapter/transport owns correct header; errors redact header/value and do not echo config. |
368
+ | HTTPS | Require HTTPS for non-loopback remote endpoints; allow plain HTTP only for explicit loopback/local profile by default. |
369
+ | Endpoint validation/SSRF | Accept only expected HTTP(S) forms; reject URL credentials; repo-provided/untrusted remote endpoints require separate trust/confirmation policy. |
370
+ | Redirect | Disable/fail redirects so prompt/auth are not forwarded to an unexpected origin. |
371
+ | Timeout/cancellation | Enforce bounded connect/read/total deadline and release resources on abort. |
372
+ | Response size | Bound success and error bodies; reject oversized content before full buffering/persistence. |
373
+ | Logging | Default to IDs, sizes, status, latency and sanitized categories; no full prompt/evidence/raw body. |
374
+ | Prompt/evidence leakage | Remote transmission requires explicit Deployment Profile/privacy policy; gateway locality does not imply inference locality. |
375
+ | Gateway transforms | Require transforms disabled/empty for baseline; unexpected transform is routing policy violation. |
376
+ | Model identity spoofing/drift | Compare actual identity/route metadata with locked profile; unknown/mismatch invalidates qualified run. |
377
+ | Provider errors | Parse bounded/sanitized fields only; raw body may echo sensitive data and is not logged. |
378
+
379
+ ### Responsibility split
380
+
381
+ - AI Core classifies input privacy and bounds deterministic context/evidence before prompt rendering.
382
+ - Runtime enforces deployment privacy/security policy and refuses unsafe transmission.
383
+ - Adapter implements provider-specific auth/URL/error handling.
384
+ - Operator chooses/approves endpoint, secret source, retention and cloud provider policy.
385
+ - Trust Layer handles model claims and evidence relationships, not network security.
386
+
387
+ ### Prompt and evidence immutability
388
+
389
+ Runtime/adapter may serialize or escape content for the wire but cannot inject vendor prompt text, compress context, heal response, remove evidence or reorder semantic content unless a separate Deployment Profile explicitly describes and qualifies the transform. Version Analysis benchmark/production baseline requires no transforms.
390
+
391
+ ### Identity and gateway rules
392
+
393
+ - Direct endpoint identity comes from locked provider/model configuration plus provider response when available.
394
+ - Gateway-backed deployment must expose requested and actual model/provider, attempt count and transforms through stable metadata or it cannot be qualified.
395
+ - Hidden provider/account failover is prohibited for benchmark/production.
396
+ - A successful HTTP/schema response with unknown route is a governance failure, not a trustworthy success.
397
+
398
+ ## 10. Runtime Capability Contract
399
+
400
+ ### Capability snapshot
401
+
402
+ Each runtime instance must expose an immutable **effective capability snapshot** derived from its Capability Profile + Deployment Profile. This is construction/preflight metadata, not per-request dynamic negotiation and not a model-selection API.
403
+
404
+ | Capability | Minimum declaration |
405
+ | --- | --- |
406
+ | Structured output | Supported semantic modes; JSON Schema dialect/subset/known keywords; enforcement mechanism class |
407
+ | Context | Configured input and output token limits, not only model maximum |
408
+ | Streaming | Supported by endpoint and enabled/disabled in this runtime contract; v1 effective value is disabled |
409
+ | Tool/function calling | Availability only; not part of v1 final structured operation |
410
+ | Reasoning/thinking | Supported modes, configured effective mode and provider constraints |
411
+ | Generation controls | Whether temperature/top-p/seed are supported, fixed, ignored or forbidden; effective settings digest |
412
+ | Usage | Which normalized token/cache/reasoning fields can be reported |
413
+ | Finish reason | Whether reliable terminal reason is available and mapping coverage |
414
+ | Identity | Requested/actual model/provider/revision observability |
415
+ | Routing | Gateway presence, provider pinning, fallback/attempt/transform observability |
416
+ | Citations/grounding | Native provider feature availability; not evidence-ref quality proof |
417
+ | Modalities | Text input/output for v1; future image/audio declarations must not imply v1 support |
418
+ | Security/privacy | Local/remote class, TLS requirement and declared retention/privacy profile reference |
419
+
420
+ ### Three capability layers
421
+
422
+ | Layer | Meaning | Authority |
423
+ | --- | --- | --- |
424
+ | Capability Registry | Official documentation says offering can support capability | Discovery metadata only |
425
+ | Runtime capability snapshot | Exact configured deployment claims it will provide capability | Preflight/config authority |
426
+ | Conformance Report | Exact deployment demonstrated required behavior | Admission authority for benchmark |
427
+
428
+ Only Qualification Record authorizes production. Registry support alone cannot.
429
+
430
+ ### AI Core interaction
431
+
432
+ AI Core expresses task requirements in the request—strict schema and task budget—but does not inspect provider names or select capability fallbacks. Runtime compares requirements with its effective snapshot and either executes exactly or returns `CAPABILITY_MISMATCH`/`STRUCTURED_OUTPUT_UNSUPPORTED` before call.
433
+
434
+ Runtime must not:
435
+
436
+ - probe several modes/models during a production request;
437
+ - change profile based on task name;
438
+ - report configured capability as observed/certified capability;
439
+ - call a weaker mode and merely add a warning;
440
+ - let gateway response override effective capability without invalidating the run.
441
+
442
+ ### Relationship to governance discovery
443
+
444
+ [`ai-runtime-governance-discovery.md`](./ai-runtime-governance-discovery.md) owns registry, conformance and certification lifecycle. Runtime Contract consumes a pinned Deployment Profile/capability snapshot and emits evidence needed by Conformance/Qualification. It does not implement a registry service or certification engine.
445
+
446
+ ## 11. Future Runtime Extensions
447
+
448
+ Runtime Contract v1 intentionally solves one task-neutral capability: unary text-in, structured-text-out generation. Provider API shape is an adapter concern.
449
+
450
+ | Future capability | v1 treatment | Extension rule |
451
+ | --- | --- | --- |
452
+ | OpenAI Responses API | Adapter may use it only if it preserves unary v1 semantics | Stateful conversation/tools require a new operation contract |
453
+ | Anthropic Messages / Gemini generateContent | Provider Adapter mapping | No AI Core provider branches |
454
+ | Function/tool calling | Outside v1 final response | Add a separate tool-call contract only when a task requirement exists |
455
+ | MCP | Outside model runtime | Tool/resource integration layer above runtime; never hidden provider capability |
456
+ | Tool execution | Outside runtime adapter | Host-controlled sandbox/tool runtime with its own security/trust contract |
457
+ | Agent runtime | Outside v1 | New agent orchestration boundary; do not turn `generateStructured` into an event loop |
458
+ | Task orchestration | AI Core/workflow layer | Splitting/chaining Version/Impact/Migration calls is not provider runtime work |
459
+ | Streaming | Outside v1 | Separate streaming operation/version if a complete use case appears |
460
+ | Realtime | Outside v1 | Separate session/event contract |
461
+ | Multimodal image/audio | Not accepted by v1 text prompts | Add versioned typed content blocks only with task/schema requirements |
462
+ | Batch API | Outside request contract | Qualification/benchmark scheduler can batch independent unary calls and normalize results |
463
+ | Native citations/search | Disabled/outside evidence collection boundary | Knowledge Research remains source authority; no model web retrieval in analysis runtime |
464
+ | Reasoning models | Supported through Deployment Profile/capability mapping | Reasoning traces are not portable output and should not be logged by default |
465
+ | Fine-tuning/model training | Outside runtime | Produces another model/deployment profile requiring full qualification |
466
+
467
+ ### Compatibility rule
468
+
469
+ An adapter for OpenAI, Anthropic, Gemini, Ollama, OpenRouter, 9Router, LiteLLM, vLLM, LM Studio or a future provider is conformant if it can preserve v1 semantics and normalized error/identity/telemetry. If a provider feature changes semantics—stateful threads, tool loops, multimodal events—it belongs to a separate extension contract, not provider-specific optional fields in the v1 request.
470
+
471
+ ### Stability rule
472
+
473
+ Future contract versions may add optional response telemetry or capability declarations without changing task semantics. Changes to input content type, execution cardinality, streaming, tools or state require a new major contract/operation. V1 callers never need to know which external API implements the operation.
474
+
475
+ ## 12. Validation
476
+
477
+ ### Discovery validation
478
+
479
+ - Chỉ thêm `docs/runtime-contract-discovery.md`.
480
+ - Không sửa các discovery LR-00, Gateway Runtime, AI Capability hoặc Runtime Governance.
481
+ - Không sửa production code.
482
+ - Không sửa runtime hoặc runtime behavior.
483
+ - Không sửa CLI.
484
+ - Không sửa schema.
485
+ - Không sửa prompt.
486
+ - Không sửa Trust Layer.
487
+ - Không sửa Evaluation, Metrics, Scorecard hoặc Benchmark.
488
+ - Không thêm dependency hoặc cài SDK.
489
+ - Không gọi model và không dùng API key.
490
+ - Không có secret.
491
+ - Không chạy test suite vì không có executable change.
492
+ - `git diff --check` phải pass trước handoff.
493
+
494
+ ### Answers to architecture-freeze questions
495
+
496
+ | # | Question | Frozen answer |
497
+ | ---: | --- | --- |
498
+ | 1 | Runtime Contract tối thiểu là gì? | Một versioned unary non-streaming structured-generation request, normalized success response, typed error contract, effective capability snapshot và execution telemetry boundary. |
499
+ | 2 | AI Core được phép biết gì? | Task/context identity, rendered prompts, exact schema/task budget và local validation/trust result; không provider/model/endpoint. |
500
+ | 3 | Provider Adapter được phép biết gì? | Wire protocol, auth/header/body mapping, provider schema/reasoning parameters, response/error/usage envelope; không task semantics/trust. |
501
+ | 4 | Runtime chịu trách nhiệm đến đâu? | Bind/verify Deployment Profile, enforce capability/security/bounds/routing/retry, call adapter, normalize success/error/identity/telemetry; không interpret claims. |
502
+ | 5 | Trust Layer bắt đầu ở đâu? | Sau successful runtime response, local JSON parse và exact Ajv schema validation; trust then validates refs/URLs/claims/risk/review. |
503
+ | 6 | Evaluation bắt đầu ở đâu? | Trên AI Core analysis/trust path với versioned dataset/prompt/schema/deployment, không ở adapter/transport. |
504
+ | 7 | Telemetry bắt đầu ở đâu? | Tại runtime invocation acceptance và kết thúc sau normalized success/error; lưu ngoài portable semantic artifact. |
505
+ | 8 | Provider-specific logic nằm ở đâu? | Provider Adapter và pinned Deployment Profile only. |
506
+ | 9 | Portable artifact kết thúc ở đâu? | Tại schema/invariant-validated task manifest sau trust; runtime response/telemetry không phải portable semantic artifact. |
507
+ | 10 | Contract đủ ổn định để freeze trước LR-01 chưa? | **YES**, nếu LR-01 giữ unary non-streaming semantics, moves rendered prompt above runtime boundary, implements exact schema/no-downgrade, typed errors, identity and telemetry normalization as specified. |
508
+
509
+ ### Architecture freeze decision
510
+
511
+ Runtime Contract v1 được đề xuất **FROZEN FOR LR-01 IMPLEMENTATION** với các non-negotiable invariants:
512
+
513
+ - AI Core renders prompt and owns schema/trust;
514
+ - runtime request contains no provider/model/auth/routing logic;
515
+ - Deployment Profile owns effective model/generation/security policy;
516
+ - adapter preserves prompt/schema semantics or fails;
517
+ - success requires complete final text and accepted finish reason;
518
+ - local Ajv and trust validation remain mandatory;
519
+ - no silent structured-output downgrade, fallback or transform;
520
+ - streaming/tools/agents remain outside v1;
521
+ - telemetry and secrets never enter portable Version Analysis artifact.
@@ -0,0 +1,100 @@
1
+ # Structured Output Compatibility Report
2
+
3
+ Execution status: EXECUTED
4
+
5
+ ## Configuration
6
+
7
+ - Generated: 2026-07-15T17:36:38.582Z
8
+ - Provider: openai-compatible
9
+ - Model: openai/gpt-5.5
10
+ - Endpoint: https://openrouter.ai/api/v1/chat/completions
11
+ - Prompt: fixed minimal isolation prompt; content intentionally omitted.
12
+ - Retry/fallback: disabled (one request per executed probe).
13
+
14
+ ## Documentation Findings
15
+
16
+ - OpenRouter errors use an `error` envelope; canonical `error.metadata.error_type` takes precedence over HTTP status, and `error.metadata.provider_code` may retain the upstream code.
17
+ - `debug.echo_upstream_body = true` returns the transformed upstream request only on a streaming request. The echoed body is privacy-sensitive and is summarized structurally here, never stored raw.
18
+ - Routing context was requested only in this isolation path with the current `X-OpenRouter-Metadata: enabled` header.
19
+ - Official references: https://openrouter.ai/docs/api/reference/errors-and-debugging and https://openrouter.ai/docs/guides/features/router-metadata
20
+
21
+ ## Independent Keyword Probes
22
+
23
+ | Probe | Isolated feature | Schema digest | HTTP | error_type | Provider code | Result |
24
+ |---|---|---|---:|---|---|---|
25
+ | baseline | minimal json_schema | sha256:4528a3c79c4aaee242a31e586366657f8e9a3f11cc8d2cb040d9bf61ab1bbb63 | 200 | — | — | PASS |
26
+ | probe-a | array + items | sha256:df782155601ed20f5438b2e86340f8142b4765153d0eb25cfdce811137546d39 | 200 | — | — | PASS |
27
+ | probe-b | uniqueItems | sha256:591d86d172b2e9f93c3802f1205003356e84fb8901cf838c1fd005da0f6e4b0e | 400 | — | — | FAIL |
28
+ | probe-f | minItems | sha256:4ff1491b983e8191f04df88d33d53c33bd817e726d0fda1bf216d97827b701bb | 200 | — | — | PASS |
29
+ | probe-c | pattern | sha256:2f8a77dcda994253630e0973a604b3a1fd5f0f7736a0bf51be09ab4d9e8f01d5 | 200 | — | — | PASS |
30
+ | probe-d | nested object | sha256:e4d470b91273f1c4e6ff08da25d0fe1a6200ccf6dbe72f0433afb97ef86dd5d8 | 200 | — | — | PASS |
31
+ | probe-e | array + items + nested object | sha256:994c5342dd2a6fc6a8c8034274bee6a4f4fc033e9b9dba254b974d6fab550f2e | 200 | — | — | PASS |
32
+ | probe-g | remove uniqueItems | sha256:b1939f9b6c06c65670b60388b3160412f714bd3996bc60a9c31f7075ad3b49a7 | 200 | — | — | PASS |
33
+ | probe-h | remove pattern | sha256:ee6016eff1cf98dffb26d8f5f1038396c5b141a39afa519acfc4c320d633c4ec | — | — | — | SKIPPED_POLICY |
34
+ | probe-i | remove uniqueItems + pattern | sha256:9bde9b6c0364cac6b4b355879e1e59c9d5d53606a41400c8c8d085b0413bb89f | — | — | — | SKIPPED_POLICY |
35
+ | probe-j | remove generation-time constraints | sha256:9bde9b6c0364cac6b4b355879e1e59c9d5d53606a41400c8c8d085b0413bb89f | — | — | — | SKIPPED_DUPLICATE |
36
+
37
+ ## Canonical Error Diagnostics
38
+
39
+ | Probe | HTTP | error_type | Provider code | Allowlisted message | Routing summary |
40
+ |---|---:|---|---|---|---|
41
+ | probe-b | 400 | — | — | Provider returned error | {"requestedModel":"openai/gpt-5.5","strategy":"direct","attempt":2,"endpointCount":3,"availableEndpointCount":2} |
42
+
43
+ ## OpenRouter Upstream Debug
44
+
45
+ | Probe | HTTP | Echo observed | Origin assessment | error_type | Provider code | Notes |
46
+ |---|---:|---|---|---|---|---|
47
+ | baseline | 200 | YES | CONFIRMED_UPSTREAM_BODY_OBSERVED | — | — | Echo observed and top-level Responses-style input/text transform captured; nested input and text.format were not decoded in the first safe summary, so semantic preservation is INCONCLUSIVE for this capture. |
48
+ | exact-schema | 400 | NO | LIKELY_UPSTREAM_REJECTION | — | — | No echo body was exposed. Routing attempt=2 makes upstream rejection LIKELY, but missing error_type/provider_code prevents confirmation. |
49
+
50
+ | Field | Original | Upstream transformed |
51
+ |---|---|---|
52
+ | baseline / Structural digest | sha256:bcd97ef54fb72f1337366b3d1c04282ee443550c85cdf630c1a7c66b7f5ba5d0 | sha256:41d1982e3c31f7d9d1d992216e5afa457465b81a2fae5f489c42ca6dca1076b2 |
53
+ | baseline / Model | openai/gpt-5.5 | gpt-5.5-2026-04-23 |
54
+ | baseline / Top-level keys | debug, messages, model, response_format, stream | include, input, model, reasoning, safety_identifier, store, stream, text, truncation, user |
55
+ | baseline / Nested input and text.format | Present in transformed top-level shape | INCONCLUSIVE — not decoded in the first safe summary |
56
+ | exact-schema / Structural digest | sha256:113446ef13992aa9cb56ab219a296301ac1405403b1c79fdf7b20d5a8af6880e | — |
57
+ | exact-schema / Model | openai/gpt-5.5 | — |
58
+ | exact-schema / Stream | true | — |
59
+ | exact-schema / Message count | 2 | — |
60
+ | exact-schema / Message roles | system, user | — |
61
+ | exact-schema / Message character counts | 72, 24 | — |
62
+ | exact-schema / Message digests | sha256:08705068fd2c562b509ec13682b498b0334e6e72d54fe89b9e51b5f79a307d6b, sha256:657c5bdc9e94221ebdceb1ed8243dba0b3d76d30feb8e585d4ac8f0aeff07c91 | — |
63
+ | exact-schema / Response format type | json_schema | — |
64
+ | exact-schema / Schema name | upgradelens_debug_exact_schema | — |
65
+ | exact-schema / Strict | true | — |
66
+ | exact-schema / Schema digest | sha256:c69fee2c69c7bdb79d582f9c2afde8e777093f03f82cd3a705be7dd67df51469 | — |
67
+ | exact-schema / Schema bytes | 1067 | — |
68
+ | exact-schema / Schema keyword counts | {"$schema":1,"type":14,"properties":2,"required":2,"additionalProperties":2,"enum":2,"items":5,"minItems":1,"maxItems":0,"uniqueItems":4,"pattern":3,"minLength":4,"maxLength":0} | — |
69
+ | exact-schema / Top-level keys | debug, messages, model, response_format, stream | — |
70
+
71
+ ## Transformation Comparison
72
+
73
+ - baseline: Echo observed and top-level Responses-style input/text transform captured; nested input and text.format were not decoded in the first safe summary, so semantic preservation is INCONCLUSIVE for this capture.
74
+ - exact-schema: No echo body was exposed. Routing attempt=2 makes upstream rejection LIKELY, but missing error_type/provider_code prevents confirmation.
75
+
76
+ ## Causal Conclusion
77
+
78
+ - arrayWithItems: CONFIRMED — array with items is supported.
79
+ - uniqueItems: CONFIRMED — uniqueItems is incompatible because Probe A passed and otherwise-identical Probe B failed.
80
+ - pattern: CONFIRMED — pattern is supported.
81
+ - nestedObject: CONFIRMED — nested strict objects are supported.
82
+ - arrayOfObjects: CONFIRMED — arrays of strict nested objects are supported.
83
+ - minItems: CONFIRMED — minItems is supported.
84
+ - exactSchema: CONFIRMED — the unchanged exact schema was rejected while the exact clone with only uniqueItems removed passed.
85
+
86
+ ## Recommended Production Fix
87
+
88
+ Create a separately reviewed provider-facing generation schema projection that recursively removes only `uniqueItems`. Keep `pattern`, `minItems`, the unchanged candidate schema, and local Ajv validation; local validation remains authoritative for uniqueness and the full output contract. Do not implement that production change in RT-02D.
89
+
90
+ ## Request Count and Cost Boundary
91
+
92
+ - Independent probe requests: 8/10.
93
+ - Upstream debug requests: 2/2.
94
+ - Total OpenRouter requests: 10/12.
95
+ - Retry count: 0.
96
+ - Fallback requests initiated by this script: 0. OpenRouter-internal routing attempts, if any, are only represented by sanitized routing metadata.
97
+
98
+ ## Security
99
+
100
+ The artifact excludes credentials, prompt content, full schemas, raw provider responses, raw SSE events, raw upstream bodies, generation/request IDs, account data, billing data, and repository context.