@techis/ai-contracts 0.0.0-stage → 0.3.0-rc.15

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 (171) hide show
  1. package/LICENSE +122 -0
  2. package/README.md +28 -3
  3. package/THIRD_PARTY_NOTICES +34 -0
  4. package/dist/availability.d.ts +21 -0
  5. package/dist/availability.d.ts.map +1 -0
  6. package/dist/availability.js +2 -0
  7. package/dist/availability.js.map +1 -0
  8. package/dist/catalog-adoption.d.ts +20 -0
  9. package/dist/catalog-adoption.d.ts.map +1 -0
  10. package/dist/catalog-adoption.js +76 -0
  11. package/dist/catalog-adoption.js.map +1 -0
  12. package/dist/catalog-composition.d.ts +10 -0
  13. package/dist/catalog-composition.d.ts.map +1 -0
  14. package/dist/catalog-composition.js +58 -0
  15. package/dist/catalog-composition.js.map +1 -0
  16. package/dist/catalog-delivery.d.ts +47 -0
  17. package/dist/catalog-delivery.d.ts.map +1 -0
  18. package/dist/catalog-delivery.js +83 -0
  19. package/dist/catalog-delivery.js.map +1 -0
  20. package/dist/catalog-package-data.d.ts +8 -0
  21. package/dist/catalog-package-data.d.ts.map +1 -0
  22. package/dist/catalog-package-data.js +2640 -0
  23. package/dist/catalog-package-data.js.map +1 -0
  24. package/dist/compatibility.d.ts +68 -0
  25. package/dist/compatibility.d.ts.map +1 -0
  26. package/dist/compatibility.js +207 -0
  27. package/dist/compatibility.js.map +1 -0
  28. package/dist/configuration-bundle.d.ts +201 -0
  29. package/dist/configuration-bundle.d.ts.map +1 -0
  30. package/dist/configuration-bundle.js +619 -0
  31. package/dist/configuration-bundle.js.map +1 -0
  32. package/dist/entities.d.ts +619 -0
  33. package/dist/entities.d.ts.map +1 -0
  34. package/dist/entities.js +2 -0
  35. package/dist/entities.js.map +1 -0
  36. package/dist/fixtures.d.ts +25 -0
  37. package/dist/fixtures.d.ts.map +1 -0
  38. package/dist/fixtures.js +546 -0
  39. package/dist/fixtures.js.map +1 -0
  40. package/dist/hash.d.ts +8 -0
  41. package/dist/hash.d.ts.map +1 -0
  42. package/dist/hash.js +13 -0
  43. package/dist/hash.js.map +1 -0
  44. package/dist/host-qualification.d.ts +90 -0
  45. package/dist/host-qualification.d.ts.map +1 -0
  46. package/dist/host-qualification.js +65 -0
  47. package/dist/host-qualification.js.map +1 -0
  48. package/dist/icc-catalog.d.ts +31 -0
  49. package/dist/icc-catalog.d.ts.map +1 -0
  50. package/dist/icc-catalog.js +321 -0
  51. package/dist/icc-catalog.js.map +1 -0
  52. package/dist/icc-csf-profiles.d.ts +28 -0
  53. package/dist/icc-csf-profiles.d.ts.map +1 -0
  54. package/dist/icc-csf-profiles.js +394 -0
  55. package/dist/icc-csf-profiles.js.map +1 -0
  56. package/dist/index.d.ts +24 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +24 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/model-maintenance.d.ts +216 -0
  61. package/dist/model-maintenance.d.ts.map +1 -0
  62. package/dist/model-maintenance.js +387 -0
  63. package/dist/model-maintenance.js.map +1 -0
  64. package/dist/model-package-data.d.ts +3 -0
  65. package/dist/model-package-data.d.ts.map +1 -0
  66. package/dist/model-package-data.js +867 -0
  67. package/dist/model-package-data.js.map +1 -0
  68. package/dist/persona-inventory.d.ts +143 -0
  69. package/dist/persona-inventory.d.ts.map +1 -0
  70. package/dist/persona-inventory.js +56 -0
  71. package/dist/persona-inventory.js.map +1 -0
  72. package/dist/profile-identity.d.ts +27 -0
  73. package/dist/profile-identity.d.ts.map +1 -0
  74. package/dist/profile-identity.js +30 -0
  75. package/dist/profile-identity.js.map +1 -0
  76. package/dist/reasoning-validation.d.ts +9 -0
  77. package/dist/reasoning-validation.d.ts.map +1 -0
  78. package/dist/reasoning-validation.js +79 -0
  79. package/dist/reasoning-validation.js.map +1 -0
  80. package/dist/reasoning.d.ts +55 -0
  81. package/dist/reasoning.d.ts.map +1 -0
  82. package/dist/reasoning.js +13 -0
  83. package/dist/reasoning.js.map +1 -0
  84. package/dist/receipt.d.ts +16 -0
  85. package/dist/receipt.d.ts.map +1 -0
  86. package/dist/receipt.js +18 -0
  87. package/dist/receipt.js.map +1 -0
  88. package/dist/schemas/adoption-change-set.schema.json +91 -0
  89. package/dist/schemas/bundle.d.ts +124 -0
  90. package/dist/schemas/bundle.d.ts.map +1 -0
  91. package/dist/schemas/bundle.js +84 -0
  92. package/dist/schemas/bundle.js.map +1 -0
  93. package/dist/schemas/catalog-release.schema.json +110 -0
  94. package/dist/schemas/catalog-review-input.schema.json +179 -0
  95. package/dist/schemas/catalog-review-output.schema.json +259 -0
  96. package/dist/schemas/catalog-review-output.v2.schema.json +251 -0
  97. package/dist/schemas/catalog-review-record.schema.json +391 -0
  98. package/dist/schemas/client-persona-inventory.schema.json +107 -0
  99. package/dist/schemas/common.schema.json +324 -0
  100. package/dist/schemas/config.d.ts +1106 -0
  101. package/dist/schemas/config.d.ts.map +1 -0
  102. package/dist/schemas/config.js +496 -0
  103. package/dist/schemas/config.js.map +1 -0
  104. package/dist/schemas/configuration-bundle-manifest.schema.json +143 -0
  105. package/dist/schemas/configuration-manifest.schema.json +109 -0
  106. package/dist/schemas/connection.schema.json +49 -0
  107. package/dist/schemas/core.d.ts +1333 -0
  108. package/dist/schemas/core.d.ts.map +1 -0
  109. package/dist/schemas/core.js +341 -0
  110. package/dist/schemas/core.js.map +1 -0
  111. package/dist/schemas/desktop-configuration-revision.schema.json +146 -0
  112. package/dist/schemas/execution-profile-revision.schema.json +235 -0
  113. package/dist/schemas/execution-receipt.schema.json +431 -0
  114. package/dist/schemas/host-adapter-qualification.schema.json +161 -0
  115. package/dist/schemas/host-qualification-policy.schema.json +50 -0
  116. package/dist/schemas/index.d.ts +11 -0
  117. package/dist/schemas/index.d.ts.map +1 -0
  118. package/dist/schemas/index.js +34 -0
  119. package/dist/schemas/index.js.map +1 -0
  120. package/dist/schemas/inventory.d.ts +170 -0
  121. package/dist/schemas/inventory.d.ts.map +1 -0
  122. package/dist/schemas/inventory.js +87 -0
  123. package/dist/schemas/inventory.js.map +1 -0
  124. package/dist/schemas/model-definition.schema.json +429 -0
  125. package/dist/schemas/model-package-release.schema.json +594 -0
  126. package/dist/schemas/model-upgrade-advisory.schema.json +191 -0
  127. package/dist/schemas/operation-contract-document.schema.json +153 -0
  128. package/dist/schemas/persona-assignments.schema.json +125 -0
  129. package/dist/schemas/persona-registry-overlay.schema.json +93 -0
  130. package/dist/schemas/persona-source-document.schema.json +86 -0
  131. package/dist/schemas/persona-specification.schema.json +122 -0
  132. package/dist/schemas/price-revision.schema.json +299 -0
  133. package/dist/schemas/profile-assessment.schema.json +288 -0
  134. package/dist/schemas/scoped.d.ts +424 -0
  135. package/dist/schemas/scoped.d.ts.map +1 -0
  136. package/dist/schemas/scoped.js +203 -0
  137. package/dist/schemas/scoped.js.map +1 -0
  138. package/dist/schemas/usage-aggregate-query.schema.json +86 -0
  139. package/dist/schemas/usage-page.schema.json +22 -0
  140. package/dist/schemas/usage-query.schema.json +77 -0
  141. package/dist/schemas/usage-summary.schema.json +468 -0
  142. package/dist/schemas/usage.d.ts +527 -0
  143. package/dist/schemas/usage.d.ts.map +1 -0
  144. package/dist/schemas/usage.js +142 -0
  145. package/dist/schemas/usage.js.map +1 -0
  146. package/dist/scoped-configuration.d.ts +208 -0
  147. package/dist/scoped-configuration.d.ts.map +1 -0
  148. package/dist/scoped-configuration.js +425 -0
  149. package/dist/scoped-configuration.js.map +1 -0
  150. package/dist/scripts/emit-schemas.d.ts +2 -0
  151. package/dist/scripts/emit-schemas.d.ts.map +1 -0
  152. package/dist/scripts/emit-schemas.js +24 -0
  153. package/dist/scripts/emit-schemas.js.map +1 -0
  154. package/dist/scripts/verify-bundle.d.ts +3 -0
  155. package/dist/scripts/verify-bundle.d.ts.map +1 -0
  156. package/dist/scripts/verify-bundle.js +59 -0
  157. package/dist/scripts/verify-bundle.js.map +1 -0
  158. package/dist/validation.d.ts +11 -0
  159. package/dist/validation.d.ts.map +1 -0
  160. package/dist/validation.js +41 -0
  161. package/dist/validation.js.map +1 -0
  162. package/package.json +33 -6
  163. package/third-party-licenses/ajv-formats@3.0.1/LICENSE +21 -0
  164. package/third-party-licenses/ajv@8.20.0/LICENSE +22 -0
  165. package/third-party-licenses/fast-deep-equal@3.1.3/LICENSE +21 -0
  166. package/third-party-licenses/fast-uri@3.1.7/LICENSE +30 -0
  167. package/third-party-licenses/json-schema-traverse@1.0.0/LICENSE +21 -0
  168. package/third-party-licenses/require-from-string@2.0.2/license +21 -0
  169. package/third-party-licenses/typescript@5.9.3/LICENSE.txt +55 -0
  170. package/third-party-licenses/typescript@5.9.3/ThirdPartyNoticeText.txt +193 -0
  171. package/third-party-licenses.json +102 -0
@@ -0,0 +1,216 @@
1
+ import type { CatalogRelease, ExecutionReceipt, ModelDefinition } from "./entities.js";
2
+ import type { ScopedConfigurationSnapshotV2 } from "./scoped-configuration.js";
3
+ import { type HostQualificationPolicy } from "./host-qualification.js";
4
+ export type ReviewOutcome = "accepted" | "needs-evidence" | "rejected";
5
+ export type AdvisoryVerdict = "yes" | "no" | "mixed" | "unknown";
6
+ export type MigrationClass = "compatible-upgrade" | "adaptation-required" | "incompatible" | "unverified";
7
+ export interface EvidenceClaim {
8
+ key: string;
9
+ value: unknown;
10
+ /** Literal excerpt from the supplied evidence, not a model-authored citation. */
11
+ quote: string;
12
+ taskDefinition?: string;
13
+ successCriterion?: string;
14
+ }
15
+ export interface CatalogEvidence {
16
+ evidenceId: string;
17
+ kind: "provider-documentation" | "provider-discovery" | "provider-advisory" | "evaluation" | "host-qualification";
18
+ uri: string;
19
+ collectedAt: string;
20
+ content: string;
21
+ sha256: string;
22
+ claims: EvidenceClaim[];
23
+ }
24
+ export interface CatalogReviewPolicy {
25
+ schemaVersion?: 2;
26
+ revision: string;
27
+ /** Evidence collection is external to review; the trusted host chooses allowed public sources. */
28
+ allowedSourceOrigins: string[];
29
+ maxEvidenceAgeDays: number | null;
30
+ hostQualification?: HostQualificationPolicy;
31
+ }
32
+ export interface CatalogReviewInput {
33
+ base: CatalogRelease;
34
+ catalog: CatalogRelease;
35
+ evidence: CatalogEvidence[];
36
+ policy: CatalogReviewPolicy;
37
+ }
38
+ export interface CatalogFactChange {
39
+ key: string;
40
+ before: unknown;
41
+ after: unknown;
42
+ }
43
+ export interface AdvisoryComparison {
44
+ verdict: AdvisoryVerdict;
45
+ scope: "model-quality" | "comparable-tasks" | "cost-per-successful-task";
46
+ basis: "provider-reported" | "independently-measured" | "insufficient-evidence";
47
+ reason: string;
48
+ evidenceIds: string[];
49
+ }
50
+ export interface ModelUpgradeAdvisory {
51
+ fromModel: string;
52
+ toModel: string;
53
+ relationship: "successor" | "alternative" | "unknown";
54
+ migrationClass: MigrationClass;
55
+ better: AdvisoryComparison;
56
+ cheaper: AdvisoryComparison;
57
+ /** Additional claims require citations too; text is never a substitute for a supported verdict. */
58
+ highlights: Array<{
59
+ text: string;
60
+ claimKey: string;
61
+ evidenceIds: string[];
62
+ }>;
63
+ caveats: string[];
64
+ migrationSteps: string[];
65
+ evidenceIds: string[];
66
+ }
67
+ export interface CatalogReviewOutput {
68
+ outcome: ReviewOutcome;
69
+ findings: Array<{
70
+ factKey: string;
71
+ status: "supported" | "insufficient" | "contradicted";
72
+ evidenceIds: string[];
73
+ reason: string;
74
+ }>;
75
+ advisories: ModelUpgradeAdvisory[];
76
+ issues: string[];
77
+ }
78
+ export interface CatalogEvidenceReference {
79
+ referenceId: string;
80
+ evidenceId: string;
81
+ sourceUri: string;
82
+ sourceSha256: string;
83
+ claimKey: string;
84
+ value: unknown;
85
+ quote: string;
86
+ }
87
+ /** V2 wire output selects immutable claim references; the host renders canonical legacy highlights after validation. */
88
+ export interface CatalogReviewOutputV2 extends Omit<CatalogReviewOutput, "advisories"> {
89
+ schemaVersion: 2;
90
+ advisories: Array<Omit<ModelUpgradeAdvisory, "highlights"> & {
91
+ highlights: Array<{
92
+ referenceId: string;
93
+ }>;
94
+ }>;
95
+ }
96
+ export interface CatalogReviewRecord {
97
+ schemaVersion: 1;
98
+ kind: "catalog-model-review";
99
+ recordId: string;
100
+ baseCatalogHash: string;
101
+ candidateCatalogHash: string;
102
+ evidenceHash: string;
103
+ policyHash: string;
104
+ instructionsHash: string;
105
+ reviewer: {
106
+ provider: string;
107
+ providerModelId: string;
108
+ profileId: string;
109
+ profileRevision: string;
110
+ spendingCap: {
111
+ currency: string;
112
+ amount: number;
113
+ } | null;
114
+ };
115
+ outcome: ReviewOutcome;
116
+ modelOutput: CatalogReviewOutput | null;
117
+ gateErrors: string[];
118
+ receipt: ExecutionReceipt;
119
+ reviewedAt: string;
120
+ }
121
+ export interface ModelPackageRelease {
122
+ schemaVersion: 1;
123
+ kind: "techis-model-package-release";
124
+ packageVersion: string;
125
+ builtAt: string;
126
+ baseCatalog: CatalogRelease;
127
+ catalog: CatalogRelease;
128
+ evidence: CatalogEvidence[];
129
+ policy: CatalogReviewPolicy;
130
+ review: CatalogReviewRecord;
131
+ payloadHash: string;
132
+ }
133
+ export declare const MODEL_UPGRADE_ADVISORY_SCHEMA: {
134
+ type: string;
135
+ additionalProperties: boolean;
136
+ required: string[];
137
+ properties: Record<string, unknown>;
138
+ };
139
+ export declare const CATALOG_REVIEW_OUTPUT_SCHEMA: {
140
+ type: string;
141
+ additionalProperties: boolean;
142
+ required: string[];
143
+ properties: Record<string, unknown>;
144
+ };
145
+ export declare const CATALOG_REVIEW_OUTPUT_V2_SCHEMA: {
146
+ required: string[];
147
+ properties: {
148
+ schemaVersion: {
149
+ type: string;
150
+ const: number;
151
+ };
152
+ advisories: {
153
+ type: string;
154
+ items: {
155
+ properties: {
156
+ highlights: {
157
+ type: string;
158
+ items: {
159
+ type: string;
160
+ additionalProperties: boolean;
161
+ required: string[];
162
+ properties: Record<string, unknown>;
163
+ };
164
+ };
165
+ };
166
+ type: string;
167
+ additionalProperties: boolean;
168
+ required: string[];
169
+ };
170
+ };
171
+ };
172
+ type: string;
173
+ additionalProperties: boolean;
174
+ };
175
+ export declare const CATALOG_REVIEW_INPUT_SCHEMA: {
176
+ type: string;
177
+ additionalProperties: boolean;
178
+ required: string[];
179
+ properties: Record<string, unknown>;
180
+ };
181
+ export declare const CATALOG_REVIEW_RECORD_SCHEMA: {
182
+ type: string;
183
+ additionalProperties: boolean;
184
+ required: string[];
185
+ properties: Record<string, unknown>;
186
+ };
187
+ export declare const MODEL_PACKAGE_RELEASE_SCHEMA: {
188
+ type: string;
189
+ additionalProperties: boolean;
190
+ required: string[];
191
+ properties: Record<string, unknown>;
192
+ };
193
+ export declare class CatalogMaintenanceValidationError extends Error {
194
+ }
195
+ export declare const catalogFactKey: (kind: "model" | "price", id: string, field: string) => string;
196
+ export declare const advisoryClaimKey: (kind: "better" | "cheaper" | "relationship", from: string, to: string, scope: string) => string;
197
+ /** Only attributed typed quotes are selectable. The digest binds source identity, claim key/value and complete literal quote. */
198
+ export declare function catalogEvidenceReferences(input: Pick<CatalogReviewInput, "evidence">): CatalogEvidenceReference[];
199
+ /** Compare factual leaves. IDs/provenance are validated separately; arrays are complete facts, never implicitly set-equal. */
200
+ export declare function catalogFactChanges(base: CatalogRelease, next: CatalogRelease): CatalogFactChange[];
201
+ /** Public evidence gates are shared by discovery and independent review before either executes. */
202
+ export declare function validateCatalogEvidence(input: Pick<CatalogReviewInput, "evidence" | "policy">, now?: Date): void;
203
+ /** Structural gates precede model execution. Supplied documents are public evidence, not retrieval instructions. */
204
+ export declare function validateCatalogReviewInput(input: CatalogReviewInput, now?: Date): CatalogFactChange[];
205
+ /** Contract-level substitution assessment; actual consumer profiles/operations still require the adoption evaluator. */
206
+ export declare function classifyModelSubstitution(before: ModelDefinition, after: ModelDefinition): MigrationClass;
207
+ /** Model acceptance never bypasses evidence coverage, identity or technical checks. */
208
+ export declare function validateCatalogReviewOutput(input: CatalogReviewInput, value: unknown, now?: Date): CatalogReviewOutput;
209
+ export declare function catalogReviewRecordIdentity(record: Omit<CatalogReviewRecord, "recordId"> | CatalogReviewRecord): string;
210
+ export declare function createModelPackageRelease(input: Omit<ModelPackageRelease, "schemaVersion" | "kind" | "payloadHash">): ModelPackageRelease;
211
+ export declare function modelPackageReleaseIdentity(release: ModelPackageRelease): string;
212
+ export declare function verifyModelPackageRelease(value: unknown): ModelPackageRelease;
213
+ /** Read-only advisory projection. This never updates the consumer's bindings, catalog, instructions or receipts. */
214
+ export declare function modelUpgradeAdvisoriesForSnapshot(release: ModelPackageRelease, snapshot: Pick<ScopedConfigurationSnapshotV2, "catalog" | "profiles">): ModelUpgradeAdvisory[];
215
+ export declare function formatModelUpgradeAdvisory(advisory: ModelUpgradeAdvisory): string;
216
+ //# sourceMappingURL=model-maintenance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-maintenance.d.ts","sourceRoot":"","sources":["../src/model-maintenance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACvF,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAI/E,OAAO,EAAsE,KAAK,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3I,MAAM,MAAM,aAAa,GAAG,UAAU,GAAG,gBAAgB,GAAG,UAAU,CAAC;AACvE,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,CAAC;AACjE,MAAM,MAAM,cAAc,GAAG,oBAAoB,GAAG,qBAAqB,GAAG,cAAc,GAAG,YAAY,CAAC;AAC1G,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,OAAO,CAAC;IACf,iFAAiF;IACjF,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AACD,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,wBAAwB,GAAG,oBAAoB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MAAM,GAAG,aAAa,CAAC,GAAG,mBAAmB,CAIzI;AACD,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,mBAAmB,GAAG,MAAM,CAGhF;AACD,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,mBAAmB,CA+B7E;AAED,oHAAoH;AACpH,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,mBAAmB,EAC5E,QAAQ,EAAE,IAAI,CAAC,6BAA6B,EAAE,SAAS,GAAG,UAAU,CAAC,0BAMtE;AACD,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,CAKjF"}
@@ -0,0 +1,387 @@
1
+ import { assertValidEntity, compileSchema } from "./validation.js";
2
+ import { canonicalJsonV2, hashDocumentV2, sha256HexV2 } from "./scoped-configuration.js";
3
+ import { containsSecretShapedMaterial } from "./configuration-bundle.js";
4
+ import { HOST_QUALIFICATION_POLICY_SCHEMA, validateHostAdapterQualification } from "./host-qualification.js";
5
+ const string = { type: "string", minLength: 1 };
6
+ const strings = { type: "array", items: string };
7
+ const object = (properties) => ({ type: "object", additionalProperties: false,
8
+ required: Object.keys(properties), properties });
9
+ const comparison = object({ verdict: { type: "string", enum: ["yes", "no", "mixed", "unknown"] },
10
+ scope: { type: "string", enum: ["model-quality", "comparable-tasks", "cost-per-successful-task"] },
11
+ basis: { type: "string", enum: ["provider-reported", "independently-measured", "insufficient-evidence"] }, reason: string, evidenceIds: strings });
12
+ export const MODEL_UPGRADE_ADVISORY_SCHEMA = object({ fromModel: string, toModel: string,
13
+ relationship: { type: "string", enum: ["successor", "alternative", "unknown"] },
14
+ migrationClass: { type: "string", enum: ["compatible-upgrade", "adaptation-required", "incompatible", "unverified"] },
15
+ better: comparison, cheaper: comparison,
16
+ highlights: { type: "array", items: object({ text: string, claimKey: string, evidenceIds: strings }) },
17
+ caveats: strings, migrationSteps: strings, evidenceIds: strings });
18
+ export const CATALOG_REVIEW_OUTPUT_SCHEMA = object({ outcome: { type: "string", enum: ["accepted", "needs-evidence", "rejected"] },
19
+ findings: { type: "array", items: object({ factKey: string, status: { type: "string", enum: ["supported", "insufficient", "contradicted"] },
20
+ evidenceIds: strings, reason: string }) }, advisories: { type: "array", items: MODEL_UPGRADE_ADVISORY_SCHEMA }, issues: strings });
21
+ const validateOutput = compileSchema(CATALOG_REVIEW_OUTPUT_SCHEMA);
22
+ export const CATALOG_REVIEW_OUTPUT_V2_SCHEMA = { ...CATALOG_REVIEW_OUTPUT_SCHEMA,
23
+ required: [...CATALOG_REVIEW_OUTPUT_SCHEMA.required, "schemaVersion"], properties: {
24
+ ...CATALOG_REVIEW_OUTPUT_SCHEMA.properties, schemaVersion: { type: "integer", const: 2 }, advisories: { type: "array", items: {
25
+ ...MODEL_UPGRADE_ADVISORY_SCHEMA, properties: { ...MODEL_UPGRADE_ADVISORY_SCHEMA.properties,
26
+ highlights: { type: "array", items: object({ referenceId: { type: "string", pattern: "^[a-f0-9]{64}$" } }) }
27
+ }
28
+ } }
29
+ } };
30
+ const validateOutputV2 = compileSchema(CATALOG_REVIEW_OUTPUT_V2_SCHEMA);
31
+ const hash = { type: "string", pattern: "^[a-f0-9]{64}$" };
32
+ const money = object({ currency: string, amount: { type: "number", minimum: 0 } });
33
+ const policySchema = { ...object({ schemaVersion: { const: 2 }, revision: string, allowedSourceOrigins: { ...strings, minItems: 1 },
34
+ maxEvidenceAgeDays: { anyOf: [{ type: "number", minimum: 0 }, { type: "null" }] }, hostQualification: HOST_QUALIFICATION_POLICY_SCHEMA }),
35
+ required: ["revision", "allowedSourceOrigins", "maxEvidenceAgeDays"] };
36
+ const claimSchema = { ...object({ key: string, value: {}, quote: string, taskDefinition: string, successCriterion: string }),
37
+ required: ["key", "value", "quote"] };
38
+ const evidenceSchema = object({ evidenceId: string,
39
+ kind: { enum: ["provider-documentation", "provider-discovery", "provider-advisory", "evaluation", "host-qualification"] }, uri: string,
40
+ collectedAt: string, content: string, sha256: hash, claims: { type: "array", items: claimSchema } });
41
+ export const CATALOG_REVIEW_INPUT_SCHEMA = object({ base: {}, catalog: {},
42
+ evidence: { type: "array", items: evidenceSchema }, policy: policySchema });
43
+ export const CATALOG_REVIEW_RECORD_SCHEMA = object({ schemaVersion: { const: 1 }, kind: { const: "catalog-model-review" },
44
+ recordId: hash, baseCatalogHash: hash, candidateCatalogHash: hash, evidenceHash: hash, policyHash: hash, instructionsHash: hash,
45
+ reviewer: object({ provider: string, providerModelId: string, profileId: string, profileRevision: string,
46
+ spendingCap: { anyOf: [money, { type: "null" }] } }), outcome: { enum: ["accepted", "needs-evidence", "rejected"] },
47
+ modelOutput: { anyOf: [CATALOG_REVIEW_OUTPUT_SCHEMA, { type: "null" }] }, gateErrors: strings, receipt: {}, reviewedAt: string });
48
+ export const MODEL_PACKAGE_RELEASE_SCHEMA = object({ schemaVersion: { const: 1 }, kind: { const: "techis-model-package-release" },
49
+ packageVersion: string, builtAt: string, baseCatalog: {}, catalog: {}, evidence: { type: "array", items: evidenceSchema },
50
+ policy: policySchema, review: CATALOG_REVIEW_RECORD_SCHEMA, payloadHash: hash });
51
+ const validateInputShape = compileSchema(CATALOG_REVIEW_INPUT_SCHEMA);
52
+ const validateEvidenceShape = compileSchema(object({ evidence: { type: "array", items: evidenceSchema }, policy: policySchema }));
53
+ const validateReleaseShape = compileSchema(MODEL_PACKAGE_RELEASE_SCHEMA);
54
+ export class CatalogMaintenanceValidationError extends Error {
55
+ }
56
+ function requireCondition(condition, message) {
57
+ if (!condition)
58
+ throw new CatalogMaintenanceValidationError(message);
59
+ }
60
+ const same = (a, b) => canonicalJsonV2(a) === canonicalJsonV2(b);
61
+ export const catalogFactKey = (kind, id, field) => `${kind}/${encodeURIComponent(id)}/${field}`;
62
+ export const advisoryClaimKey = (kind, from, to, scope) => `${kind}/${encodeURIComponent(from)}/${encodeURIComponent(to)}/${scope}`;
63
+ /** Only attributed typed quotes are selectable. The digest binds source identity, claim key/value and complete literal quote. */
64
+ export function catalogEvidenceReferences(input) {
65
+ return input.evidence.filter(source => source.kind !== "provider-discovery").flatMap(source => source.claims.map(claim => {
66
+ const reference = { evidenceId: source.evidenceId, sourceUri: source.uri, sourceSha256: source.sha256,
67
+ claimKey: claim.key, value: structuredClone(claim.value), quote: claim.quote };
68
+ return { referenceId: hashDocumentV2(reference), ...reference };
69
+ }));
70
+ }
71
+ /** Compare factual leaves. IDs/provenance are validated separately; arrays are complete facts, never implicitly set-equal. */
72
+ export function catalogFactChanges(base, next) {
73
+ const changes = [];
74
+ function walk(key, before, after) {
75
+ // Observation provenance is validated against the supplied evidence, not claimed as a provider fact.
76
+ if (key.endsWith("/availability/source"))
77
+ return;
78
+ // A newly explicit null is a real uncertainty fact; absent and unknown must not collapse.
79
+ if (same(before ?? null, after ?? null) && !(before === undefined && after === null))
80
+ return;
81
+ if (after && typeof after === "object" && !Array.isArray(after)) {
82
+ const previous = (before && typeof before === "object" ? before : {});
83
+ for (const field of new Set([...Object.keys(previous), ...Object.keys(after)])) {
84
+ walk(key + "/" + field, previous[field], after[field]);
85
+ }
86
+ }
87
+ else
88
+ changes.push({ key, before: before ?? null, after: after ?? null });
89
+ }
90
+ for (const [kind, before, after, idKey] of [
91
+ ["model", base.models, next.models, "catalogId"], ["price", base.prices, next.prices, "priceRevisionId"]
92
+ ]) {
93
+ for (const item of after) {
94
+ const value = item;
95
+ const id = String(value[idKey]);
96
+ const previous = before.find(entry => entry[idKey] === id);
97
+ for (const field of new Set([...Object.keys(previous ?? {}), ...Object.keys(value)])) {
98
+ if ([idKey, "schemaVersion", "source", "notes", "activePriceRevisionId", "observedAt"].includes(field))
99
+ continue;
100
+ walk(catalogFactKey(kind, id, field), previous?.[field], value[field]);
101
+ }
102
+ }
103
+ }
104
+ return changes.sort((a, b) => a.key.localeCompare(b.key));
105
+ }
106
+ /** Public evidence gates are shared by discovery and independent review before either executes. */
107
+ export function validateCatalogEvidence(input, now = new Date()) {
108
+ const shape = validateEvidenceShape(input);
109
+ requireCondition(shape.valid, "Invalid catalog evidence: " + shape.errors.join("; "));
110
+ requireCondition(!containsSecretShapedMaterial(input), "Catalog evidence must be public and secrets-excluded.");
111
+ const evidenceIds = new Set();
112
+ for (const evidence of input.evidence) {
113
+ requireCondition(evidence.evidenceId && !evidenceIds.has(evidence.evidenceId), "Evidence IDs must be unique.");
114
+ evidenceIds.add(evidence.evidenceId);
115
+ requireCondition(["provider-documentation", "provider-discovery", "provider-advisory", "evaluation", "host-qualification"].includes(evidence.kind), "Unsupported evidence kind.");
116
+ if (evidence.kind === "host-qualification") {
117
+ requireCondition(input.policy.schemaVersion === 2, "Artifact-bound host evidence requires review policy v2.");
118
+ requireCondition(evidence.uri === `urn:techis:host-qualification:sha256:${evidence.sha256}`, "Host evidence URI must identify its immutable content.");
119
+ const report = validateHostAdapterQualification(evidence.content, input.policy.hostQualification);
120
+ requireCondition(Date.parse(report.receipt.completedAt) <= Date.parse(evidence.collectedAt), "Host receipt cannot postdate qualification.");
121
+ const key = catalogFactKey("model", report.mapping.catalogId, "adapterId");
122
+ requireCondition(evidence.claims.length === 1 && evidence.claims[0].key === key &&
123
+ evidence.claims[0].value === report.mapping.adapterId, "Host qualification supports only its exact adapter mapping.");
124
+ }
125
+ else {
126
+ const url = new URL(evidence.uri);
127
+ requireCondition(url.protocol === "https:" && !url.username && !url.password &&
128
+ input.policy.allowedSourceOrigins.includes(url.origin), "Evidence source is outside the allowed public origins.");
129
+ }
130
+ requireCondition(sha256HexV2(evidence.content) === evidence.sha256, "Evidence content hash mismatch.");
131
+ const age = now.getTime() - Date.parse(evidence.collectedAt);
132
+ requireCondition(Number.isFinite(age) && age >= 0 && (input.policy.maxEvidenceAgeDays === null ||
133
+ age <= input.policy.maxEvidenceAgeDays * 86_400_000), "Evidence date is invalid, future or stale.");
134
+ requireCondition(Array.isArray(evidence.claims), "Evidence claims must be supplied explicitly.");
135
+ const claimKeys = new Set();
136
+ for (const claim of evidence.claims) {
137
+ requireCondition(!claimKeys.has(claim.key), "Duplicate evidence claim key.");
138
+ claimKeys.add(claim.key);
139
+ requireCondition(claim.quote.trim() && evidence.content.includes(claim.quote), "Evidence claim excerpt is missing from its source.");
140
+ }
141
+ }
142
+ }
143
+ /** Structural gates precede model execution. Supplied documents are public evidence, not retrieval instructions. */
144
+ export function validateCatalogReviewInput(input, now = new Date()) {
145
+ const shape = validateInputShape(input);
146
+ requireCondition(shape.valid, "Invalid review input: " + shape.errors.join("; "));
147
+ requireCondition(!containsSecretShapedMaterial(input), "Catalog review accepts public, secrets-excluded material only.");
148
+ assertValidEntity("catalog-release", input.base);
149
+ assertValidEntity("catalog-release", input.catalog);
150
+ requireCondition(input.base.catalogRevision !== input.catalog.catalogRevision, "A new immutable catalog revision is required.");
151
+ requireCondition(input.policy.revision && Array.isArray(input.policy.allowedSourceOrigins) && input.policy.allowedSourceOrigins.length, "An explicit evidence policy and allowed source origins are required.");
152
+ requireCondition(input.policy.maxEvidenceAgeDays === null || (Number.isFinite(input.policy.maxEvidenceAgeDays) &&
153
+ input.policy.maxEvidenceAgeDays >= 0), "Invalid evidence age policy.");
154
+ const models = new Map(input.catalog.models.map(model => [model.catalogId, model]));
155
+ const prices = new Map(input.catalog.prices.map(price => [price.priceRevisionId, price]));
156
+ requireCondition(models.size === input.catalog.models.length && prices.size === input.catalog.prices.length, "Duplicate model or price ID.");
157
+ for (const previous of input.base.models) {
158
+ const model = models.get(previous.catalogId);
159
+ requireCondition(model && model.provider === previous.provider && model.providerModelId === previous.providerModelId, "Historical stable model identity must be retained: " + previous.catalogId);
160
+ }
161
+ for (const previous of input.base.prices)
162
+ requireCondition(same(prices.get(previous.priceRevisionId), previous), "Historical immutable price must be retained: " + previous.priceRevisionId);
163
+ if (input.base.releaseSequence !== undefined)
164
+ requireCondition(input.catalog.releaseSequence !== undefined &&
165
+ input.catalog.releaseSequence > input.base.releaseSequence, "Catalog sequence must advance.");
166
+ for (const model of models.values()) {
167
+ requireCondition(model.capabilities.maxInputTokens <= model.capabilities.contextWindowTokens &&
168
+ model.capabilities.maxOutputTokens <= model.capabilities.contextWindowTokens, "Model token limits exceed context.");
169
+ if (model.activePriceRevisionId) {
170
+ const price = prices.get(model.activePriceRevisionId);
171
+ requireCondition(price && (!price.scope.catalogId || price.scope.catalogId === model.catalogId) &&
172
+ (!price.scope.provider || price.scope.provider === model.provider), "Active price has missing or mismatched scope.");
173
+ }
174
+ const seen = new Set([model.catalogId]);
175
+ let successor = model.lifecycle.replacementCatalogId;
176
+ while (successor) {
177
+ requireCondition(models.has(successor) && !seen.has(successor), "Missing or cyclic replacement relationship.");
178
+ seen.add(successor);
179
+ successor = models.get(successor).lifecycle.replacementCatalogId;
180
+ }
181
+ }
182
+ validateCatalogEvidence({ evidence: input.evidence, policy: input.policy }, now);
183
+ for (const source of input.evidence.filter(source => source.kind === "host-qualification")) {
184
+ const report = validateHostAdapterQualification(source.content, input.policy.hostQualification);
185
+ const model = models.get(report.mapping.catalogId);
186
+ requireCondition(model && model.provider === report.mapping.provider && model.providerModelId === report.mapping.providerModelId &&
187
+ model.adapterId === report.mapping.adapterId, "Host mapping does not cover the exact candidate model.");
188
+ }
189
+ for (const price of input.catalog.prices.filter(price => price.schemaVersion === 2)) {
190
+ const previous = input.base.prices.find(previous => previous.priceRevisionId === price.priceRevisionId);
191
+ if (previous)
192
+ continue; // Immutable historical observation was already verified at its original review.
193
+ requireCondition(price.observedAt === price.source.verifiedAt && input.evidence.some(evidence => evidence.kind === "provider-documentation" && evidence.uri === price.source.uri && evidence.collectedAt === price.observedAt &&
194
+ evidence.claims.some(claim => claim.key.startsWith(`price/${encodeURIComponent(price.priceRevisionId)}/`))), "Price observation must match its exact public rate evidence.");
195
+ }
196
+ if (input.catalog.schemaVersion === 2) {
197
+ for (const model of input.catalog.models) {
198
+ const previous = input.base.models.find(previous => previous.catalogId === model.catalogId);
199
+ if (!previous || !same(previous.availability, model.availability)) {
200
+ requireCondition(model.schemaVersion === 2, "New v2 catalog entries require a verified model-v2 availability observation.");
201
+ assertVerifiedModelAvailability(input, model);
202
+ }
203
+ }
204
+ }
205
+ return catalogFactChanges(input.base, input.catalog);
206
+ }
207
+ /** Availability admits catalog entries; it does not assert GA, task fitness or consumer access. */
208
+ function assertVerifiedModelAvailability(input, model) {
209
+ const observation = model.availability;
210
+ const key = catalogFactKey("model", model.catalogId, "availability/status");
211
+ requireCondition(model.schemaVersion === 2 && observation?.status === "available", "Verified model availability is required: " + model.catalogId);
212
+ requireCondition(input.evidence.some(evidence => evidence.uri === observation.source.uri &&
213
+ evidence.collectedAt === observation.source.verifiedAt &&
214
+ evidence.claims.some(claim => claim.key === key && claim.value === "available")), "No matching verified availability evidence: " + model.catalogId);
215
+ requireCondition(!input.evidence.some(evidence => evidence.claims.some(claim => claim.key === key && claim.value !== "available")), "Conflicting evidence claim: " + key);
216
+ }
217
+ /** Contract-level substitution assessment; actual consumer profiles/operations still require the adoption evaluator. */
218
+ export function classifyModelSubstitution(before, after) {
219
+ if (after.lifecycle.status === "retired" || after.lifecycle.status === "deprecated")
220
+ return "incompatible";
221
+ const subset = (a, b) => a.every(value => b.includes(value));
222
+ if (before.provider !== after.provider || before.adapterId !== after.adapterId || after.lifecycle.status !== "ga" ||
223
+ !subset(before.capabilities.inputModalities, after.capabilities.inputModalities) ||
224
+ !subset(before.capabilities.outputModalities, after.capabilities.outputModalities) ||
225
+ !subset(before.capabilities.providerTools, after.capabilities.providerTools) ||
226
+ (before.capabilities.structuredOutput && !after.capabilities.structuredOutput) ||
227
+ after.capabilities.contextWindowTokens < before.capabilities.contextWindowTokens ||
228
+ after.capabilities.maxInputTokens < before.capabilities.maxInputTokens ||
229
+ after.capabilities.maxOutputTokens < before.capabilities.maxOutputTokens ||
230
+ !subset(before.nativeReasoning.supportedControls, after.nativeReasoning.supportedControls) ||
231
+ !subset(before.nativeReasoning.supportedEffortLevels ?? [], after.nativeReasoning.supportedEffortLevels ?? []) ||
232
+ (before.nativeReasoning.disableSupported && !after.nativeReasoning.disableSupported) ||
233
+ before.nativeReasoning.defaultEffort !== after.nativeReasoning.defaultEffort ||
234
+ before.nativeReasoning.defaultThinkingEnabled !== after.nativeReasoning.defaultThinkingEnabled ||
235
+ !same(before.nativeReasoning.budgetTokensRange ?? null, after.nativeReasoning.budgetTokensRange ?? null))
236
+ return "adaptation-required";
237
+ return "compatible-upgrade";
238
+ }
239
+ /** Model acceptance never bypasses evidence coverage, identity or technical checks. */
240
+ export function validateCatalogReviewOutput(input, value, now = new Date()) {
241
+ if (value && typeof value === "object" && value.schemaVersion === 2) {
242
+ const wire = validateOutputV2(value);
243
+ requireCondition(wire.valid, "Invalid review output v2: " + wire.errors.join("; "));
244
+ const raw = value;
245
+ const references = new Map(catalogEvidenceReferences(input).map(reference => [reference.referenceId, reference]));
246
+ value = { outcome: raw.outcome, findings: structuredClone(raw.findings), issues: structuredClone(raw.issues),
247
+ advisories: raw.advisories.map(advisory => ({ ...structuredClone(advisory), highlights: advisory.highlights.map(highlight => {
248
+ const reference = references.get(highlight.referenceId);
249
+ requireCondition(reference, "Unknown or mismatched typed evidence reference: " + highlight.referenceId);
250
+ return { text: reference.quote, claimKey: reference.claimKey, evidenceIds: [reference.evidenceId] };
251
+ }) })) };
252
+ }
253
+ const result = validateOutput(value);
254
+ requireCondition(result.valid, "Invalid review output: " + result.errors.join("; "));
255
+ const output = value;
256
+ const changes = validateCatalogReviewInput(input, now);
257
+ const evidenceById = new Map(input.evidence.map(evidence => [evidence.evidenceId, evidence]));
258
+ const cite = (ids) => ids.map(id => {
259
+ const evidence = evidenceById.get(id);
260
+ requireCondition(evidence, "Unknown evidence ID: " + id);
261
+ return evidence;
262
+ });
263
+ const support = (ids, key, expected, comparisonKind, basis) => {
264
+ const sources = cite(ids);
265
+ const availabilityFact = key.endsWith("/availability/status");
266
+ requireCondition(sources.some(source => (source.kind !== "provider-discovery" || availabilityFact) &&
267
+ (input.policy.schemaVersion !== 2 || !key.endsWith("/adapterId") || source.kind === "host-qualification") &&
268
+ (basis !== "independently-measured" || source.kind === "evaluation") &&
269
+ (basis !== "provider-reported" || source.kind === "provider-advisory" || source.kind === "provider-documentation") &&
270
+ source.claims.some(claim => claim.key === key && same(claim.value, expected) &&
271
+ (comparisonKind !== "cheaper" || Boolean(claim.taskDefinition?.trim() && claim.successCriterion?.trim())))), "No matching supported evidence claim: " + key);
272
+ requireCondition(!sources.some(source => source.claims.some(claim => claim.key === key && !same(claim.value, expected))), "Conflicting evidence claim: " + key);
273
+ };
274
+ const findings = new Map(output.findings.map(finding => [finding.factKey, finding]));
275
+ requireCondition(findings.size === output.findings.length, "Duplicate fact findings.");
276
+ for (const finding of output.findings) {
277
+ requireCondition(changes.some(change => change.key === finding.factKey), "Finding names no changed fact.");
278
+ cite(finding.evidenceIds);
279
+ }
280
+ if (output.outcome === "accepted") {
281
+ for (const change of changes) {
282
+ const finding = findings.get(change.key);
283
+ requireCondition(finding?.status === "supported", "Missing or unsupported changed fact: " + change.key);
284
+ const model = input.catalog.models.find(model => change.key === catalogFactKey("model", model.catalogId, "lifecycle/status"));
285
+ const price = input.catalog.prices.find(price => change.key === catalogFactKey("price", price.priceRevisionId, "effectiveDate"));
286
+ if (model?.schemaVersion === 2 && model.lifecycle.status === "unknown") {
287
+ // Unknown is explicit uncertainty, not a fabricated provider lifecycle assertion.
288
+ assertVerifiedModelAvailability(input, model);
289
+ support(finding.evidenceIds, catalogFactKey("model", model.catalogId, "availability/status"), "available");
290
+ requireCondition(!input.evidence.some(evidence => evidence.claims.some(claim => claim.key === change.key && claim.value !== "unknown")), "Known lifecycle evidence cannot be relabeled unknown: " + model.catalogId);
291
+ }
292
+ else if (price?.schemaVersion === 2 && price.effectiveDate === null) {
293
+ requireCondition(cite(finding.evidenceIds).some(source => source.kind === "provider-documentation" &&
294
+ source.uri === price.source.uri && source.collectedAt === price.observedAt && source.claims.some(claim => claim.key.startsWith(`price/${encodeURIComponent(price.priceRevisionId)}/`) && !claim.key.endsWith("/effectiveDate"))), "Unknown provider effective date needs attributed observed rates.");
295
+ requireCondition(!input.evidence.some(source => source.claims.some(claim => claim.key === change.key && claim.value !== null)), "Known price-effective-date evidence cannot be erased.");
296
+ }
297
+ else
298
+ support(finding.evidenceIds, change.key, change.after);
299
+ }
300
+ }
301
+ const pairs = new Set();
302
+ for (const advisory of output.advisories) {
303
+ const before = input.base.models.find(model => model.catalogId === advisory.fromModel);
304
+ const after = input.catalog.models.find(model => model.catalogId === advisory.toModel);
305
+ requireCondition(before && after && advisory.fromModel !== advisory.toModel, "Advisory needs distinct existing old/new models.");
306
+ const pair = canonicalJsonV2([advisory.fromModel, advisory.toModel]);
307
+ requireCondition(!pairs.has(pair), "Duplicate advisory pair.");
308
+ pairs.add(pair);
309
+ cite(advisory.evidenceIds);
310
+ if (advisory.relationship !== "unknown")
311
+ support(advisory.evidenceIds, advisoryClaimKey("relationship", advisory.fromModel, advisory.toModel, "lineage"), advisory.relationship);
312
+ if (advisory.migrationClass === "compatible-upgrade")
313
+ requireCondition(advisory.relationship === "successor" &&
314
+ classifyModelSubstitution(before, after) === "compatible-upgrade", "Direct upgrade cannot preserve the prior contract.");
315
+ requireCondition(advisory.better.scope !== "cost-per-successful-task" && advisory.cheaper.scope === "cost-per-successful-task", "Advisory must distinguish quality from cost per successful comparable task.");
316
+ for (const kind of ["better", "cheaper"]) {
317
+ const comparison = advisory[kind];
318
+ cite(comparison.evidenceIds);
319
+ if (comparison.verdict === "unknown")
320
+ requireCondition(comparison.basis === "insufficient-evidence", "Unknown requires explicit insufficient evidence.");
321
+ else {
322
+ requireCondition(comparison.basis !== "insufficient-evidence", "A positive/negative verdict needs attributed evidence.");
323
+ support(comparison.evidenceIds, advisoryClaimKey(kind, advisory.fromModel, advisory.toModel, comparison.scope), comparison.verdict, kind, comparison.basis);
324
+ }
325
+ }
326
+ for (const highlight of advisory.highlights) {
327
+ const sources = cite(highlight.evidenceIds);
328
+ requireCondition(sources.some(source => source.kind !== "provider-discovery" && source.claims.some(claim => claim.key === highlight.claimKey && claim.quote === highlight.text)), "Highlight must be an exact cited source statement.");
329
+ }
330
+ }
331
+ return structuredClone(output);
332
+ }
333
+ export function catalogReviewRecordIdentity(record) {
334
+ const { recordId: _ignored, ...body } = record;
335
+ return hashDocumentV2(body);
336
+ }
337
+ export function createModelPackageRelease(input) {
338
+ const release = { schemaVersion: 1, kind: "techis-model-package-release", ...structuredClone(input), payloadHash: "" };
339
+ release.payloadHash = modelPackageReleaseIdentity(release);
340
+ return verifyModelPackageRelease(release);
341
+ }
342
+ export function modelPackageReleaseIdentity(release) {
343
+ const { payloadHash: _ignored, ...body } = release;
344
+ return hashDocumentV2(body);
345
+ }
346
+ export function verifyModelPackageRelease(value) {
347
+ const shape = validateReleaseShape(value);
348
+ requireCondition(shape.valid, "Invalid package release: " + shape.errors.join("; "));
349
+ requireCondition(!containsSecretShapedMaterial(value), "Model package payload must exclude secrets.");
350
+ const release = value;
351
+ requireCondition(release.schemaVersion === 1 && release.kind === "techis-model-package-release" &&
352
+ /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(release.packageVersion) && Number.isFinite(Date.parse(release.builtAt)), "Invalid model package identity.");
353
+ requireCondition(release.payloadHash === modelPackageReleaseIdentity(release), "Package payload hash mismatch.");
354
+ const review = release.review;
355
+ assertValidEntity("execution-receipt", review.receipt);
356
+ requireCondition(Number.isFinite(Date.parse(review.reviewedAt)) && Date.parse(review.reviewedAt) <= Date.parse(release.builtAt), "Invalid review/publication chronology.");
357
+ requireCondition(review.schemaVersion === 1 && review.kind === "catalog-model-review" &&
358
+ review.recordId === catalogReviewRecordIdentity(review), "Review record hash or kind mismatch.");
359
+ requireCondition(review.outcome === "accepted" && review.modelOutput?.outcome === "accepted" && !review.gateErrors.length, "Only model-reviewed accepted catalogs can be packaged.");
360
+ requireCondition(review.baseCatalogHash === hashDocumentV2(release.baseCatalog) &&
361
+ review.candidateCatalogHash === hashDocumentV2(release.catalog) && review.evidenceHash === hashDocumentV2(release.evidence) &&
362
+ review.policyHash === hashDocumentV2(release.policy), "Review does not cover this exact catalog/evidence/policy.");
363
+ requireCondition(review.receipt.status === "succeeded" && review.receipt.providerModelId === review.reviewer.providerModelId &&
364
+ review.receipt.provider === review.reviewer.provider && review.receipt.profileId === review.reviewer.profileId &&
365
+ review.receipt.profileRevision === review.reviewer.profileRevision && review.receipt.instructionHash === review.instructionsHash &&
366
+ (!review.receipt.effectiveInstructionHash || review.receipt.effectiveInstructionHash === review.instructionsHash) &&
367
+ review.receipt.requested.outputSchemaPresent && review.receipt.attempts.length > 0 &&
368
+ review.receipt.attempts.some(attempt => attempt.outcome === "succeeded" && attempt.role === "primary" &&
369
+ attempt.providerRequestStarted && attempt.providerModelId === review.reviewer.providerModelId) &&
370
+ review.receipt.operationId === "catalog-maintenance.review" && !review.receipt.fallbackUsed, "Receipt does not prove the configured reviewer executed.");
371
+ validateCatalogReviewOutput({ base: release.baseCatalog, catalog: release.catalog, evidence: release.evidence, policy: release.policy }, review.modelOutput, new Date(review.reviewedAt));
372
+ return structuredClone(release);
373
+ }
374
+ /** Read-only advisory projection. This never updates the consumer's bindings, catalog, instructions or receipts. */
375
+ export function modelUpgradeAdvisoriesForSnapshot(release, snapshot) {
376
+ const verified = verifyModelPackageRelease(release);
377
+ const used = new Set(Object.values(snapshot.profiles).flatMap(profile => [profile.primary, ...profile.fallbacks].map(slot => slot.catalogId)));
378
+ return verified.review.modelOutput.advisories.filter(advisory => used.has(advisory.fromModel) &&
379
+ snapshot.catalog.models.some(model => model.catalogId === advisory.fromModel &&
380
+ same(model, verified.baseCatalog.models.find(previous => previous.catalogId === model.catalogId))));
381
+ }
382
+ export function formatModelUpgradeAdvisory(advisory) {
383
+ const line = (label, comparison) => `${label}: ${comparison.verdict}. ${comparison.reason} (${comparison.basis}; ${comparison.scope})`;
384
+ return [line("Better for comparable models/tasks?", advisory.better), line("Cheaper for comparable tasks?", advisory.cheaper),
385
+ ...advisory.caveats, ...advisory.migrationSteps].join("\n");
386
+ }
387
+ //# sourceMappingURL=model-maintenance.js.map