@aiquants/enrichment-governance-core 0.4.0 → 0.5.0
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.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +7 -4
- package/dist/index.d.ts +7 -4
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var je=Object.defineProperty;var Fo=Object.getOwnPropertyDescriptor;var Lo=Object.getOwnPropertyNames;var Mo=Object.prototype.hasOwnProperty;var zo=(e,t)=>{for(var o in t)je(e,o,{get:t[o],enumerable:!0})},ko=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Lo(t))!Mo.call(e,a)&&a!==o&&je(e,a,{get:()=>t[a],enumerable:!(n=Fo(t,a))||n.enumerable});return e};var Go=e=>ko(je({},"__esModule",{value:!0}),e);var Wn={};zo(Wn,{AUTHORITY_CANDIDATE_PAGE_LIMIT_MAX:()=>ct,AUTHORITY_SEARCH_QUERY_MAX_LENGTH:()=>Qt,AUTHORITY_SEARCH_QUERY_MIN_LENGTH:()=>ot,ApprovalStatusSchema:()=>b,AuthoritativeSourceSchema:()=>He,AuthorityCandidatePageSchema:()=>nn,AuthorityCandidateQuerySchema:()=>cn,AuthorityCandidateSchema:()=>Zo,AuthoritySearchTextSchema:()=>lt,AuthorityTierSchema:()=>D,BaseGovernanceClient:()=>K,CLOUD_CAPABLE_CAPABILITIES:()=>Hn,CitationProofLeafSchema:()=>zt,CitationProofSchema:()=>kt,ConfidentialityCapabilityPolicyDtoSchema:()=>Yn,ConfidentialityLevelSchema:()=>Re.ConfidentialityLevelSchema,DOCUMENT_AUTHORITY_COMMAND_RULES:()=>$,DOCUMENT_AUTHORITY_PAGE_LIMIT_MAX:()=>it,DeletedDocumentAuthorityEventImageSchema:()=>vo,DocumentAuthorityCommandBlockerSchema:()=>ln,DocumentAuthorityCommandFieldErrorSchema:()=>ut,DocumentAuthorityCommandFieldReasonSchema:()=>J,DocumentAuthorityCommandFieldSchema:()=>F,DocumentAuthorityCommandKindSchema:()=>I,DocumentAuthorityCommandRejectionCodeSchema:()=>Y,DocumentAuthorityCommandRejectionSchema:()=>pn,DocumentAuthorityCommandResultSchema:()=>Tn,DocumentAuthorityCommandSchema:()=>Wt,DocumentAuthorityEventImageSchema:()=>xt,DocumentAuthorityPageQuerySchema:()=>an,DocumentAuthorityPageSchema:()=>Zt,DocumentAuthorityPageWithCategoriesSchema:()=>on,DocumentAuthorityRowSchema:()=>O,DocumentRefSchema:()=>L,FailedTieGroupReasonSchema:()=>uo,FailedTieGroupSchema:()=>Ne,FeatureFlagKeySchema:()=>Tt,FileUriSchema:()=>P.FileUriSchema,GovernanceAdminClient:()=>yt,GovernanceAnswerRequestSchema:()=>Ze,GovernanceAnswerResponseSchema:()=>Xe,GovernanceClient:()=>ft,GovernanceClientError:()=>q,GovernanceSearchHitSchema:()=>Ft,GovernanceSearchMetadataSchema:()=>Ee,GovernanceSearchRequestSchema:()=>$e,GovernanceSearchResponseSchema:()=>Qe,GovernanceSearchSnippetSchema:()=>_t,GovernanceSimulateCaseDiffSchema:()=>Ye,GovernanceSimulateCaseScoresSchema:()=>Se,GovernanceSimulateRequestSchema:()=>We,GovernanceSimulateResponseSchema:()=>Je,GovernanceSimulateScoresSchema:()=>Ce,GovernedCapabilitySchema:()=>Po,JsonPrimitiveSchema:()=>Oo,JsonValueSchema:()=>vt,KnowledgeGovernanceEventRecordSchema:()=>qn,KnowledgeGovernanceEventSchema:()=>Fe,NormalizedPolicyCategorySchema:()=>v,NormalizedScoreSchema:()=>Ae,OPERATOR_IDENTIFIER_MAX_LENGTH:()=>Ke,OffsetIsoInstantSchema:()=>S,POLICY_CATEGORY_MAX_LENGTH:()=>Pe,POLICY_CATEGORY_UNICODE_VERSION:()=>Jo,POLICY_CATEGORY_WHITESPACE_CODE_POINTS:()=>Yt,POLICY_CONFLICT_DECISION_REASON_BLANK_CODE_POINTS:()=>co,POLICY_CONFLICT_DECISION_REASON_MAX_LENGTH:()=>gt,POLICY_CONFLICT_PAGE_LIMIT_MAX:()=>Rt,POLICY_CONFLICT_SUMMARY_MAX_LENGTH:()=>lo,PolicyCategoryRejectionSchema:()=>rt,PolicyCategorySchema:()=>Kt,PolicyConflictCountsSchema:()=>mo,PolicyConflictDecisionEventImageSchema:()=>bt,PolicyConflictDecisionFieldErrorSchema:()=>It,PolicyConflictDecisionFieldReasonSchema:()=>ht,PolicyConflictDecisionFieldSchema:()=>B,PolicyConflictDecisionKindSchema:()=>At,PolicyConflictDecisionRejectionCodeSchema:()=>pe,PolicyConflictDecisionRejectionSchema:()=>wn,PolicyConflictDecisionSchema:()=>Eo,PolicyConflictDetailSchema:()=>So,PolicyConflictDetectedEventImageSchema:()=>wo,PolicyConflictDetectedFailedGroupSchema:()=>To,PolicyConflictDetectionFailureReasonSchema:()=>Ro,PolicyConflictDetectionOutcomeSchema:()=>go,PolicyConflictDetectionRequestRejectionCodeSchema:()=>Do,PolicyConflictDetectionRequestRejectionSchema:()=>_n,PolicyConflictDetectionRequestSchema:()=>Un,PolicyConflictDetectionStateSchema:()=>fo,PolicyConflictFactsSchema:()=>oe,PolicyConflictPageQuerySchema:()=>Dn,PolicyConflictPageSchema:()=>gn,PolicyConflictRefSchema:()=>Lt,PolicyConflictResolutionStatusSchema:()=>Z,PolicyConflictRowSchema:()=>Dt,PolicyConflictSeveritySchema:()=>ie,PolicyConflictStateSchema:()=>Et,PolicyConflictSummarySchema:()=>ho,PolicyConflictUnmeasuredReasonSchema:()=>po,PolicyConflictViewerSchema:()=>yo,PromptTemplateDtoSchema:()=>Kn,REPLACEABLE_AUTHORITY_PAGE_LIMIT_MAX:()=>st,RecordedPolicyConflictDecisionSchema:()=>Co,RelatedDecisionSchema:()=>Nt,ReplaceableAuthorityPageSchema:()=>rn,ReplaceableAuthorityQuerySchema:()=>sn,ReplacedAuthorityChangeSchema:()=>xo,RowVersionSchema:()=>te,SEVERITY_BY_TIER:()=>nt,Sha256HexSchema:()=>z,StoredDecisionReasonSchema:()=>fe,SystemFeatureFlagDtoSchema:()=>Bn,SystemParameterDtoSchema:()=>$n,TenantIdSchema:()=>P.TenantIdSchema,UpdateFeatureFlagRequestSchema:()=>Qn,UpdateParameterRequestSchema:()=>Zn,UpdatePromptTemplateRequestSchema:()=>Xn,UtcInstantSchema:()=>x,VerifiedCitationSchema:()=>Mt,bytesToHex:()=>Ue,canonicalPolicyConflictFactsJson:()=>Sn,checkDocumentAuthorityCommand:()=>fn,checkPolicyConflictDecision:()=>On,computeCitationLeafHash:()=>eo,computeCitationMerkleRoot:()=>to,constantTimeCompare:()=>Jt,documentAuthorityCommandBlocker:()=>dt,equalRankGroups:()=>Xo,isDocumentAuthorityCommandAvailable:()=>dn,isEligibleAuthority:()=>Bt,normalizePolicyCategory:()=>at,offsetIsoOfUtcInstant:()=>Qo,parseUtcInstant:()=>qt,policyConflictFactsHash:()=>En,policyConflictFactsOf:()=>Rn,sha256:()=>ue,tiePairs:()=>Wo,utcInstantOfOffsetIso:()=>Ko,verifyCitationProof:()=>mt});module.exports=Go(Wn);var ee=require("@aiquants/enrichment-core"),l=require("zod");var Ot=require("zod"),jo=/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.\d{7}$/,Ve=1,Ut=9999,Pt=7,qe=60,Vo=14*qe,qo=Ot.z.string().datetime({offset:!0}),Bo=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|([+-])(\d{2}):(\d{2}))$/,Ho=(e,t,o)=>{let n=new Date(0);return n.setUTCFullYear(e,t-1,o),e>=Ve&&e<=Ut&&n.getUTCMonth()===t-1&&n.getUTCDate()===o},Be=e=>{let t=jo.exec(e);if(t===null)return null;let[o,n,a,s,u,m]=t.slice(1,7).map(Number);return Ho(o,n,a)&&s<=23&&u<=59&&m<=59?e:null},Q=(e,t)=>String(e).padStart(t,"0"),ae=e=>{let t=qo.safeParse(e).success?Bo.exec(e):null;if(t===null)return null;let[,o,n,a,s,u,m,f="",R="+",T="00",w="00"]=t,h=(R==="-"?-1:1)*(Number(T)*qe+Number(w));if(Number(o)<Ve||f.length>Pt||Number(w)>=qe||Math.abs(h)>Vo)return null;let y=new Date(0);y.setUTCFullYear(Number(o),Number(n)-1,Number(a)),y.setUTCHours(Number(s),Number(u)-h,Number(m),0);let C=y.getUTCFullYear();if(C<Ve||C>Ut)return null;let G=`${Q(C,4)}-${Q(y.getUTCMonth()+1,2)}-${Q(y.getUTCDate(),2)}`,U=`${Q(y.getUTCHours(),2)}:${Q(y.getUTCMinutes(),2)}:${Q(y.getUTCSeconds(),2)}`;return`${G} ${U}.${f.padEnd(Pt,"0")}`},_=(e,t)=>{let o=ae(e),n=ae(t);return o===null||n===null?null:o<n?-1:o>n?1:0};var et=require("@aiquants/enrichment-core"),N=require("zod");var P=require("@aiquants/enrichment-core"),r=require("zod"),Re=require("@aiquants/enrichment-core");var $e=r.z.object({query:r.z.string().min(1,"Search query must not be empty"),policyCategory:r.z.string().optional(),includeHistoricalRevisions:r.z.boolean().optional(),maxAuthorityTier:r.z.union([r.z.literal(1),r.z.literal(2),r.z.literal(3),r.z.literal(4),r.z.literal(5)]).optional(),limit:r.z.number().int().positive().optional()}),_t=r.z.object({text:r.z.string(),citationText:r.z.string(),chunkHash:r.z.string(),chunkIndex:r.z.number().int().nonnegative(),parentChunkUid:r.z.string().optional(),clauseIdentifier:r.z.string().optional(),breadcrumbPath:r.z.array(r.z.string()).optional(),page:r.z.number().int().optional(),sheetName:r.z.string().optional(),slideIndex:r.z.number().int().optional(),timestampSec:r.z.number().optional(),score:r.z.number()}),Nt=r.z.object({decisionId:r.z.string(),title:r.z.string(),approvedBy:r.z.string()}),D=r.z.union([r.z.literal(1),r.z.literal(2),r.z.literal(3),r.z.literal(4),r.z.literal(5)]),b=r.z.enum(["DRAFT","APPROVED","DEPRECATED"]),ie=r.z.enum(["LOW","MEDIUM","HIGH","CRITICAL"]),Z=r.z.enum(["UNRESOLVED","RESOLVED","IGNORED"]),Ke=100,Ft=r.z.object({metadataId:r.z.number().int(),fileUri:P.FileUriSchema,fileName:r.z.string(),documentTitle:r.z.string(),authorityTier:D.nullable(),validFrom:r.z.string().nullable(),validUntil:r.z.string().nullable(),isCurrentlyAuthoritative:r.z.boolean(),confidentialityLevel:P.ConfidentialityLevelSchema,snippets:r.z.array(_t),relatedDecisions:r.z.array(Nt).optional(),policyWarning:r.z.string().optional()}),Ee=r.z.object({searchMode:r.z.enum(["tri_store","sql_vector","sql_keyword_degraded"]),qualityTier:r.z.enum(["HIGH_TRI_STORE","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),isDegraded:r.z.boolean(),degradationReason:r.z.string().nullable(),circuitBreakerStatus:r.z.record(r.z.enum(["CLOSED","OPEN","HALF_OPEN","HEALTHY"])),executionTimeMs:r.z.number().nonnegative()}),Qe=r.z.object({hits:r.z.array(Ft),tiers:r.z.object({sql:r.z.boolean(),vector:r.z.boolean(),graph:r.z.boolean()}),masked:r.z.boolean(),searchMetadata:Ee}),Ze=r.z.object({question:r.z.string().min(1,"Question must not be empty"),asOf:r.z.string().optional(),asOfTx:r.z.string().optional()}),He=r.z.object({metadataId:r.z.number().int(),documentTitle:r.z.string(),authorityTier:D,approvalStatus:b,validFrom:r.z.string(),validUntil:r.z.string().nullable(),isCurrentlyAuthoritative:r.z.boolean()}),Lt=r.z.object({conflictId:r.z.number().int(),sourceMetadataId:r.z.number().int(),targetMetadataId:r.z.number().int(),conflictSummary:r.z.string(),severity:ie,resolutionStatus:Z}),Mt=r.z.object({chunkUid:r.z.string().uuid("chunkUid must be a valid UUID"),metadataId:r.z.number().int(),documentTitle:r.z.string(),clauseIdentifier:r.z.string(),breadcrumbPath:r.z.array(r.z.string()),exactQuotedText:r.z.string(),chunkHash:r.z.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),authorityTier:D,isVerified:r.z.boolean()}),z=r.z.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),zt=r.z.object({chunkUid:r.z.string().uuid("chunkUid must be a valid UUID"),chunkHash:z}),kt=r.z.object({algorithm:r.z.literal("SHA-256"),merkleRoot:z,leafCount:r.z.number().int().positive(),leaves:r.z.array(zt).min(1),tenantId:P.TenantIdSchema,scopeDigest:z,asOf:r.z.string().datetime(),asOfTx:r.z.string().datetime(),generatedAt:r.z.string().datetime(),signature:r.z.string().min(1,"Signature must not be empty")}),Xe=r.z.object({answer:r.z.string(),authoritative:r.z.array(He),superseded:r.z.array(He),conflicts:r.z.array(Lt),verifiedCitations:r.z.array(Mt),citationProof:kt.nullable(),isFullyGrounded:r.z.boolean(),requiresHumanArbitration:r.z.boolean(),tiers:r.z.object({sql:r.z.boolean(),vector:r.z.boolean(),graph:r.z.boolean()}),searchMetadata:Ee}),We=r.z.object({promptOverrides:r.z.record(r.z.string()).optional(),parameterOverrides:r.z.record(r.z.union([r.z.string(),r.z.number(),r.z.boolean()])).optional(),strategyOverrides:r.z.record(r.z.record(r.z.union([r.z.string(),r.z.number(),r.z.boolean()]))).optional(),intentTypes:r.z.array(r.z.enum(["SET","DIFF","PATH","NEGATION","COUNT"])).optional()}),Ae=r.z.number().min(0).max(1),Se=r.z.object({contextRelevance:Ae,groundedness:Ae,answerRelevance:Ae}),Ce=Se.extend({meanAnswerChars:r.z.number().nonnegative(),meanLatencyMs:r.z.number().nonnegative()}),Ye=r.z.object({caseId:r.z.string(),intentType:r.z.enum(["SET","DIFF","PATH","NEGATION","COUNT"]),beforeScores:Se,afterScores:Se}),Je=r.z.object({simulationId:r.z.string(),evaluatedCount:r.z.number().int().nonnegative(),before:Ce,after:Ce,delta:Ce,regressions:r.z.array(Ye),improvements:r.z.array(Ye),searchMetadata:Ee});var i=(e,t,o,n)=>{e.addIssue(n===void 0?{code:N.z.ZodIssueCode.custom,path:[...t],message:o}:{code:N.z.ZodIssueCode.custom,path:[...t],message:o,params:{reason:n}})},ge=e=>e==null||e==="",Gt=e=>{let t=N.z.unknown().superRefine((o,n)=>e(n)).safeParse(void 0);return t.success?[]:t.error.issues},De=(e,t)=>{let o=t.schema.safeParse(e);if(o.success)return{ok:!0,value:o.data};let n={ok:!1,rejection:{code:"BODY_INVALID"}},a=f=>f.path.length===0?void 0:t.fieldOfKey.get(f.path[0]);if(!o.error.issues.every(f=>a(f)!==void 0))return n;let s=e,u=[];for(let f of[...o.error.issues,...t.skippedIssues(s)]){let R=a(f);if(R===void 0)return n;let T=f.code===N.z.ZodIssueCode.custom?f.params?.reason:void 0,w=T??(ge(s[f.path[0]])?"REQUIRED":"MALFORMED"),h=t.fieldError.safeParse({path:R,reason:w});if(!h.success){if(T!==void 0)throw new RangeError(`A rule reported ${JSON.stringify(T)} at ${JSON.stringify(R)}, which the form does not pair`);return n}u.push(h.data)}return{ok:!1,rejection:{code:"FIELD_INVALID",fieldErrors:t.fields.flatMap(f=>{let R=u.find(T=>T.path===f);return R===void 0?[]:[R]})}}},Ie=(e,t,o)=>{e.forEach((n,a)=>{a>0&&t.indexOf(n)<=t.indexOf(e[a-1])&&i(o,["fieldErrors",a],"Each field appears once, in the form's order")})},xe=()=>e=>e,p=N.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),g=N.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),be=N.z.number().int().min(et.SYSTEM_PARAMETER_RANGES.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min).max(et.SYSTEM_PARAMETER_RANGES.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.max),X=e=>N.z.number().int().min(1).max(e),k=N.z.string().min(1).max(Ke),Yo=/\p{Cs}/u,ce=e=>!Yo.test(e),ve=(e,t)=>{let o=0,n=e.length;for(;o<n&&t.has(e.charCodeAt(o));)o+=1;for(;n>o&&t.has(e.charCodeAt(n-1));)n-=1;return e.slice(o,n)},W=(e,t,o)=>{e.forEach((n,a)=>{a>0&&n>=e[a-1]&&i(o,["rows",a],"Rows are in strictly descending order of their key")}),t!==null&&t!==e.at(-1)&&i(o,["nextAfter"],"nextAfter is absent or the key of the last row")},se=(e,t,o,n)=>{e>=t&&i(n,o,"The source governs the smaller document version (source < target)")},Te=(e,t,o,n,a,s)=>{(e?!(t===o||t===n):t!==null)&&i(s,a,"A resolution records one document of the pair as prevailing, and only a resolution does")},$o=(e,t)=>{let o=t===null?null:_(t,e);return o!==null&&o<=0},le=(e,t,o,n)=>{$o(e,t)&&i(n,o,"validUntil must be after validFrom","NOT_AFTER_VALID_FROM")},we=(e,t,o,n,a)=>{e!=="DRAFT"&&!t&&i(a,n.approval,"An APPROVED or DEPRECATED row carries its approval"),o&&!t&&i(a,n.withdrawal,"Only an approval once given can be withdrawn"),e==="DRAFT"&&t&&!o&&i(a,n.withdrawal,"A DRAFT row that was approved carries its withdrawal")};function qt(e){let t=Be(e);if(t===null)throw new RangeError(`Not a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff: ${JSON.stringify(e)}`);return t}var x=l.z.string().transform((e,t)=>{let o=Be(e);return o===null?(t.addIssue({code:l.z.ZodIssueCode.custom,message:"Must be a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff"}),l.z.NEVER):o});function Ko(e){let t=ae(e);if(t===null)throw new RangeError(`Not an ISO 8601 instant with a UTC offset that datetimeoffset(7) can hold: ${JSON.stringify(e)}`);return t}var S=l.z.string().refine(e=>ae(e)!==null,{message:"Must be an ISO 8601 instant yyyy-mm-ddThh:mi:ss[.f] with Z or a \xB1hh:mi offset within \xB114:00, at most seven fractional digits and a year between 0001 and 9999 both as written and in UTC"});function Qo(e){let t=qt(e);return`${t.slice(0,10)}T${t.slice(11)}Z`}var Zo=l.z.object({metadataId:p,authorityTier:D,approvalStatus:b,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict();function Bt(e,t,o){return e.approvalStatus===b.enum.APPROVED&&e.validFromUtc<=t&&(e.validUntilUtc===null||e.validUntilUtc>t)&&e.txCreatedAtUtc<=o&&(e.txSupersededAtUtc===null||e.txSupersededAtUtc>o)}var Ht=(e,t)=>e.metadataId-t.metadataId,tt=e=>`${e.authorityTier} ${e.validFromUtc}`;function Xo(e,t,o){let n=new Set,a=new Map;for(let s of e){if(n.has(s.metadataId))throw new RangeError(`Two authority rows govern the same document version: metadataId ${s.metadataId}`);if(n.add(s.metadataId),!Bt(s,t,o))continue;let u=tt(s),m=a.get(u);m===void 0?a.set(u,[s]):m.push(s)}return[...a.values()].filter(s=>s.length>=2).map(s=>[...s].sort(Ht)).sort((s,u)=>s[0].metadataId-u[0].metadataId)}function Wo(e){let t=[...e].sort(Ht);return t.forEach((o,n)=>{if(tt(o)!==tt(t[0]))throw new RangeError(`An equal-rank group mixes ranks: metadataId ${t[0].metadataId} and ${o.metadataId}`);if(n>0&&o.metadataId===t[n-1].metadataId)throw new RangeError(`An equal-rank group repeats a document version: metadataId ${o.metadataId}`)}),t.flatMap((o,n)=>t.slice(n+1).map(a=>[o,a]))}var nt=Object.freeze({1:"CRITICAL",2:"HIGH",3:"MEDIUM",4:"LOW",5:"LOW"}),Pe=50,Jo="17.0",rt=l.z.enum(["MALFORMED","EMPTY","TOO_LONG"]),Yt=Object.freeze([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]),$t=new Set(Yt),en=e=>{let t=[],o=0;for(let n=0;n<=e.length;n+=1)(n===e.length||$t.has(e.charCodeAt(n)))&&(n>o&&t.push(e.slice(o,n)),o=n+1);return t.join(" ")};function at(e){if(!ce(e))return{ok:!1,reason:"MALFORMED"};let t=en(e.normalize("NFKC"));return t.length===0?{ok:!1,reason:"EMPTY"}:t.length>Pe?{ok:!1,reason:"TOO_LONG"}:{ok:!0,value:t}}var Kt=l.z.string().transform((e,t)=>{let o=at(e);return o.ok?o.value:(i(t,[],`A policy category must be well-formed text of 1 to ${Pe} UTF-16 code units after normalization`,o.reason),l.z.NEVER)}),v=l.z.string().refine(e=>{let t=at(e);return t.ok&&t.value===e},{message:`A stored policy category must be well-formed, normalized (NFKC, single spaces, trimmed) and 1 to ${Pe} UTF-16 code units`}),it=50,ct=50,st=50,ot=2,Qt=200,tn=e=>[...e].length,lt=l.z.string().transform(e=>ve(e,$t)).pipe(l.z.string().max(Qt).refine(ce,{message:"A search text is well-formed text without an unpaired surrogate"}).refine(e=>tn(e)>=ot,{message:`A search text has at least ${ot} characters (code points) once trimmed`})),te=l.z.string().regex(/^[0-9a-f]{16}$/,"Must be a rowversion as 16 lowercase hexadecimal digits"),L=l.z.object({metadataId:p,fileName:l.z.string().min(1),fileUri:ee.FileUriSchema,revision:l.z.number().int().min(1),isCurrent:l.z.boolean(),isDeleted:l.z.boolean(),confidentialityLevel:ee.ConfidentialityLevelSchema.exclude([ee.QUARANTINED_CONFIDENTIALITY_LEVEL])}).strict(),O=l.z.object({authorityId:p,document:L,authorityTier:D,policyCategory:v,validFrom:S,validUntil:S.nullable(),txCreatedAt:S,txSupersededAt:S.nullable(),approvalStatus:b,approvedBy:k.nullable(),approvedAt:S.nullable(),withdrawnBy:k.nullable(),withdrawnAt:S.nullable(),replaces:L.nullable(),supersededBy:L.nullable(),replacesAnother:l.z.boolean(),isSuperseded:l.z.boolean(),rowVersion:te,updatedBy:k,updatedAt:S}).strict().superRefine((e,t)=>{le(e.validFrom,e.validUntil,["validUntil"],t),e.approvedBy===null!=(e.approvedAt===null)&&i(t,["approvedAt"],"approvedBy and approvedAt are present together or absent together"),e.withdrawnBy===null!=(e.withdrawnAt===null)&&i(t,["withdrawnAt"],"withdrawnBy and withdrawnAt are present together or absent together"),we(e.approvalStatus,e.approvedAt!==null,e.withdrawnAt!==null,{approval:["approvedAt"],withdrawal:["withdrawnAt"]},t);let o=e.approvedAt===null||e.withdrawnAt===null?null:_(e.withdrawnAt,e.approvedAt);e.approvalStatus==="DRAFT"&&o!==null&&o<0&&i(t,["withdrawnAt"],"A DRAFT row's withdrawal is no earlier than its approval");let n=e.txSupersededAt!==null;(e.approvalStatus==="DEPRECATED"?!n:n)&&i(t,["txSupersededAt"],"txSupersededAt is recorded exactly when the row is DEPRECATED"),e.replaces!==null&&!e.replacesAnother&&i(t,["replacesAnother"],"A row that names the document it replaces replaces another"),e.supersededBy!==null&&!e.isSuperseded&&i(t,["isSuperseded"],"A row that names its successor is superseded"),e.replaces?.metadataId===e.document.metadataId&&i(t,["replaces"],"A row does not replace its own document version"),e.supersededBy?.metadataId===e.document.metadataId&&i(t,["supersededBy"],"A row is not superseded by its own document version")}),Zt=l.z.object({rows:l.z.array(O).max(it),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{W(e.rows.map(o=>o.authorityId),e.nextAfter,t)}),on=l.z.object({page:Zt,categories:l.z.array(v).nullable()}).strict().superRefine((e,t)=>{e.categories!==null&&new Set(e.categories).size!==e.categories.length&&i(t,["categories"],"Each category appears once")}),nn=l.z.object({rows:l.z.array(L).max(ct),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{W(e.rows.map(o=>o.metadataId),e.nextAfter,t),e.rows.forEach((o,n)=>{(!o.isCurrent||o.isDeleted)&&i(t,["rows",n],"A candidate is a current, undeleted document version")})}),rn=l.z.object({rows:l.z.array(O).max(st),nextAfter:p.nullable(),totalCount:g}).strict().superRefine((e,t)=>{W(e.rows.map(o=>o.authorityId),e.nextAfter,t),e.totalCount<e.rows.length&&i(t,["totalCount"],"totalCount counts at least the rows of the page"),e.rows.forEach((o,n)=>{(o.approvalStatus!=="APPROVED"||o.isSuperseded)&&i(t,["rows",n],"A row a replacement may name is approved and not yet superseded"),o.policyCategory!==e.rows[0].policyCategory&&i(t,["rows",n,"policyCategory"],"The rows a replacement may name share one category")})}),an=l.z.object({status:b.optional(),category:v.optional(),after:p.optional(),limit:X(it)}).strict(),cn=l.z.object({q:lt,after:p.optional(),limit:X(ct)}).strict(),sn=l.z.object({category:v,q:lt.optional(),after:p.optional(),limit:X(st)}).strict(),I=l.z.enum(["create","update","approve","withdraw","deprecate","delete"]),F=l.z.enum(["authorityTier","policyCategory","validFrom","validUntil","replacesMetadataId"]),jt={authorityTier:D,policyCategory:Kt,validFrom:S,validUntil:S.nullable(),replacesMetadataId:p.nullable()},Vt=Object.freeze([...F.options]),$=Object.freeze({create:Object.freeze({before:null,after:"DRAFT",changes:Vt,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!1}),update:Object.freeze({before:"DRAFT",after:"DRAFT",changes:Vt,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1}),approve:Object.freeze({before:"DRAFT",after:"APPROVED",changes:Object.freeze(["approvedBy"]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!0}),withdraw:Object.freeze({before:"APPROVED",after:"DRAFT",changes:Object.freeze(["withdrawnBy"]),requiresNeverApproved:!1,requiresNoReplacement:!0,requiresCurrentDocument:!1,runsDetection:!0}),deprecate:Object.freeze({before:"APPROVED",after:"DEPRECATED",changes:Object.freeze([]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!0}),delete:Object.freeze({before:"DRAFT",after:null,changes:Object.freeze([]),requiresNeverApproved:!0,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1})}),ln=l.z.enum(["STATUS","APPROVED_ONCE","REPLACES_ANOTHER","DOCUMENT_NOT_CURRENT"]);function dt(e,t){let o=$[e];return t.approvalStatus!==o.before?"STATUS":o.requiresNeverApproved&&t.approvedAt!==null?"APPROVED_ONCE":o.requiresNoReplacement&&t.replacesAnother?"REPLACES_ANOTHER":o.requiresCurrentDocument&&(!t.document.isCurrent||t.document.isDeleted)?"DOCUMENT_NOT_CURRENT":null}function dn(e,t){return dt(e,t)===null}var de={authorityId:p,expectedRowVersion:te},un=e=>e.kind===I.enum.create&&e.replacesMetadataId===e.metadataId&&p.safeParse(e.replacesMetadataId).success,Xt=(e,t)=>{let{validFrom:o,validUntil:n}=e;typeof o=="string"&&(n===null||typeof n=="string")&&le(o,n,["validUntil"],t),un(e)&&i(t,["replacesMetadataId"],"A document version does not replace itself","SELF_REPLACEMENT")},Wt=l.z.discriminatedUnion("kind",[l.z.object({kind:l.z.literal(I.enum.create),metadataId:p,...jt}).strict(),l.z.object({kind:l.z.literal(I.enum.update),...de,...jt}).strict(),l.z.object({kind:l.z.literal(I.enum.approve),...de}).strict(),l.z.object({kind:l.z.literal(I.enum.withdraw),...de}).strict(),l.z.object({kind:l.z.literal(I.enum.deprecate),...de}).strict(),l.z.object({kind:l.z.literal(I.enum.delete),...de}).strict()]).superRefine(Xt),J=l.z.enum(["REQUIRED",...rt.options,"NOT_AFTER_VALID_FROM","SELF_REPLACEMENT"]),ut=l.z.discriminatedUnion("path",[l.z.object({path:l.z.literal(F.enum.authorityTier),reason:J.extract(["REQUIRED","MALFORMED"])}).strict(),l.z.object({path:l.z.literal(F.enum.policyCategory),reason:J.extract(["REQUIRED",...rt.options])}).strict(),l.z.object({path:l.z.literal(F.enum.validFrom),reason:J.extract(["REQUIRED","MALFORMED"])}).strict(),l.z.object({path:l.z.literal(F.enum.validUntil),reason:J.extract(["REQUIRED","MALFORMED","NOT_AFTER_VALID_FROM"])}).strict(),l.z.object({path:l.z.literal(F.enum.replacesMetadataId),reason:J.extract(["REQUIRED","MALFORMED","SELF_REPLACEMENT"])}).strict()]),Y=l.z.enum(["BODY_INVALID","FIELD_INVALID","NOT_FOUND","REPLACEMENT_NOT_FOUND","STALE","ALREADY_REGISTERED","RANK_LIMIT_REACHED","NOT_AFTER_REPLACED","DOCUMENT_NOT_CURRENT","DEADLOCK","DEPLOYMENT_DISABLED"]),pn=xe()(l.z.discriminatedUnion("code",[l.z.object({code:Y.extract(["FIELD_INVALID"]),fieldErrors:l.z.array(ut).min(1)}).strict(),l.z.object({code:Y.extract(["STALE"]),row:O}).strict(),l.z.object({code:Y.extract(["ALREADY_REGISTERED"]),row:O}).strict(),l.z.object({code:Y.extract(["DOCUMENT_NOT_CURRENT"]),row:O}).strict(),l.z.object({code:Y.extract(["RANK_LIMIT_REACHED"]),rowScopeApplied:l.z.boolean(),limit:be.nullable()}).strict(),l.z.object({code:Y.exclude(["FIELD_INVALID","STALE","ALREADY_REGISTERED","DOCUMENT_NOT_CURRENT","RANK_LIMIT_REACHED"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&Ie(e.fieldErrors.map(o=>o.path),F.options,t),e.code==="ALREADY_REGISTERED"&&(!e.row.document.isCurrent||e.row.document.isDeleted)&&i(t,["row","document"],"The registered row's document version is current and not deleted, as the create requires"),e.code==="DOCUMENT_NOT_CURRENT"&&dt("approve",e.row)!=="DOCUMENT_NOT_CURRENT"&&i(t,["row"],"The row is a DRAFT whose document version is no longer current or has been deleted"),e.code==="RANK_LIMIT_REACHED"&&e.limit===null!==e.rowScopeApplied&&i(t,["limit"],"The limit is shown exactly to an operator whose row scope is unrestricted")})),mn={schema:Wt,fieldOfKey:new Map(F.options.map(e=>[e,e])),fields:F.options,fieldError:ut,skippedIssues:e=>Gt(t=>Xt(e,t))};function fn(e){return De(e,mn)}var q=class extends Error{statusCode;responseBody;parsedBody;constructor(t,o,n,a){super(t),this.name="GovernanceClientError",this.statusCode=o,this.responseBody=n,this.parsedBody=a}},K=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for GovernanceClient.");let o=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey){let n;try{n=new URL(o)}catch{throw new Error(`Invalid baseUrl format: ${t.baseUrl}`)}if(n.protocol==="http:"){let a=n.hostname.toLowerCase();if(!(a==="localhost"||a==="127.0.0.1"||a==="[::1]"||a==="::1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.")}}this.baseUrl=o,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,o,n,a,s){let u=new URL(t.startsWith("/")?t.slice(1):t,`${this.baseUrl}/`);if(a)for(let[h,y]of Object.entries(a))y!=null&&y.trim().length>0&&u.searchParams.append(h,y);let m=u.toString(),f={Accept:"application/json"};this.apiKey&&(f.Authorization=`Bearer ${this.apiKey}`),n!==void 0&&(f["Content-Type"]="application/json");let R=new AbortController,T=setTimeout(()=>R.abort(),this.timeoutMs),w=R.signal;s&&(w=AbortSignal.any([R.signal,s]));try{let h=await this.fetchFn(m,{method:o,headers:f,body:n!==void 0?JSON.stringify(n):void 0,signal:w}),y=await h.text();if(!h.ok){let C;try{C=JSON.parse(y)}catch{}throw new q(`API request failed with status ${h.status}: ${y}`,h.status,y,C)}if(y.trim().length===0)return;try{return JSON.parse(y)}catch(C){let G=C.message;throw new q(`Failed to parse response JSON from ${m}: ${G}`,h.status,y)}}catch(h){if(h instanceof q)throw h;let y=h instanceof Error?h.message:String(h);throw new q(`Network request failed for ${o} ${m}: ${y}`,0,"")}finally{clearTimeout(T)}}};var pt=new Uint8Array([0]),Oe=new Uint8Array([1]),yn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function M(e,t){return e>>>t|e<<32-t}function ue(e){let t=1779033703,o=3144134277,n=1013904242,a=2773480762,s=1359893119,u=2600822924,m=528734635,f=1541459225,R=e.length,T=R*8,w=(R+8>>6)+1<<6,h=new Uint8Array(w);h.set(e),h[R]=128;let y=new DataView(h.buffer,h.byteOffset,h.byteLength);y.setUint32(w-4,T>>>0,!1),y.setUint32(w-8,Math.floor(T/4294967296),!1);let C=new Uint32Array(64);for(let Le=0;Le<w;Le+=64){for(let A=0;A<16;A++)C[A]=y.getUint32(Le+A*4,!1);for(let A=16;A<64;A++){let ke=M(C[A-15],7)^M(C[A-15],18)^C[A-15]>>>3,Ge=M(C[A-2],17)^M(C[A-2],19)^C[A-2]>>>10;C[A]=C[A-16]+ke+C[A-7]+Ge>>>0}let j=t,ne=o,re=n,Me=a,V=s,ye=u,he=m,ze=f;for(let A=0;A<64;A++){let ke=M(V,6)^M(V,11)^M(V,25),Ge=V&ye^~V&he,wt=ze+ke+Ge+yn[A]+C[A]>>>0,Uo=M(j,2)^M(j,13)^M(j,22),_o=j&ne^j&re^ne&re,No=Uo+_o>>>0;ze=he,he=ye,ye=V,V=Me+wt>>>0,Me=re,re=ne,ne=j,j=wt+No>>>0}t=t+j>>>0,o=o+ne>>>0,n=n+re>>>0,a=a+Me>>>0,s=s+V>>>0,u=u+ye>>>0,m=m+he>>>0,f=f+ze>>>0}let G=new Uint8Array(32),U=new DataView(G.buffer,G.byteOffset,G.byteLength);return U.setUint32(0,t,!1),U.setUint32(4,o,!1),U.setUint32(8,n,!1),U.setUint32(12,a,!1),U.setUint32(16,s,!1),U.setUint32(20,u,!1),U.setUint32(24,m,!1),U.setUint32(28,f,!1),G}function Ue(e){let t="";for(let o=0;o<e.length;o++)t+=e[o].toString(16).padStart(2,"0");return t}function Jt(e,t){if(e.length!==t.length)return!1;let o=0;for(let n=0;n<e.length;n++)o|=e.charCodeAt(n)^t.charCodeAt(n);return o===0}function eo(e,t,o){if(!(e?.trim()&&t?.trim()&&o?.trim()))throw new Error("tenantId, chunkUid, and chunkHash must be non-empty strings.");if(e.includes("")||t.includes("")||o.includes(""))throw new Error("Parameters must not contain delimiter control characters.");let a=new TextEncoder().encode(`${e}${t}${o}`),s=new Uint8Array(pt.length+a.length);return s.set(pt,0),s.set(a,pt.length),ue(s)}function to(e){if(!e||e.length===0)return null;for(let o=0;o<e.length;o++)if(!(e[o]instanceof Uint8Array)||e[o].length!==32)throw new Error(`Leaf at index ${o} must be a 32-byte Uint8Array.`);let t=[...e];for(;t.length>1;){let o=[];for(let n=0;n<t.length-1;n+=2){let a=t[n],s=t[n+1],u=new Uint8Array(Oe.length+a.length+s.length);u.set(Oe,0),u.set(a,Oe.length),u.set(s,Oe.length+a.length),o.push(ue(u))}t.length%2===1&&o.push(t[t.length-1]),t=o}return Ue(t[0])}function mt(e,t){try{if(!e||typeof e!="object"||e.algorithm!=="SHA-256"||t?.expectedTenantId&&e.tenantId!==t.expectedTenantId||!Array.isArray(e.leaves)||e.leafCount!==e.leaves.length||e.leafCount===0)return!1;if(t?.expectedCitations){if(t.expectedCitations.length!==e.leaves.length)return!1;for(let a=0;a<e.leaves.length;a++)if(t.expectedCitations[a].chunkUid!==e.leaves[a].chunkUid||t.expectedCitations[a].chunkHash!==e.leaves[a].chunkHash)return!1}for(let a=0;a<e.leaves.length;a++){let s=e.leaves[a];if(!s||typeof s!="object"||!s.chunkUid||!s.chunkHash||a>0&&e.leaves[a].chunkUid<=e.leaves[a-1].chunkUid)return!1}let o=[];for(let a of e.leaves)o.push(eo(e.tenantId,a.chunkUid,a.chunkHash));let n=to(o);return!n||typeof e.merkleRoot!="string"?!1:Jt(n,e.merkleRoot)}catch{return!1}}var ft=class extends K{async search(t,o){let n=$e.parse(t),a=o?{tenant_id:P.TenantIdSchema.parse(o)}:void 0,s=await this.request("/ai/governance/search","POST",n,a);return Qe.parse(s)}async answer(t,o){let n=Ze.parse(t),a=o?{tenant_id:P.TenantIdSchema.parse(o)}:void 0,s=await this.request("/ai/governance/answer","POST",n,a);return Xe.parse(s)}verifyCitationProof(t,o){return mt(t,o)}};var oo=require("@aiquants/enrichment-core");var yt=class extends K{async simulate(t,o){let n=We.parse(t),a=o?{tenant_id:oo.TenantIdSchema.parse(o)}:void 0,s=await this.request("/ai/governance/simulate","POST",n,a);return Je.parse(s)}};var E=require("zod");var me=require("@aiquants/enrichment-core"),c=require("zod");var Et=c.z.enum(["UNRESOLVED_ACTIVE","UNRESOLVED_CLEARED","RESOLVED","IGNORED"]),Rt=50,gt=2e3,co=Object.freeze([9,10,13,32,12288]),hn=new Set(co),so=e=>ve(e,hn),lo=1e3,An=g.min(me.SYSTEM_PARAMETER_RANGES.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min+1),uo=c.z.enum(["TIE_GROUP_OVER_LIMIT"]),Ne=c.z.object({policyCategory:v,authorityTier:D,validFromUtc:x,reason:uo,tieGroupSize:An}).strict(),po=c.z.enum(["NEVER_DETECTED","DETECTION_INCOMPLETE_FOR_READABLE"]),Cn={UNRESOLVED_ACTIVE:g,UNRESOLVED_CLEARED:g,RESOLVED:g,IGNORED:g},mo=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("measured"),values:c.z.object(Cn).strict(),partial:c.z.boolean()}).strict(),c.z.object({kind:c.z.literal("unmeasured"),reason:po}).strict()]),fo=c.z.object({lastDetectedAt:S,nextTransitionAt:S.nullable(),isStale:c.z.boolean(),failedGroups:c.z.array(Ne).nullable(),tieGroupLimit:be.nullable()}).strict().superRefine((e,t)=>{e.failedGroups===null!=(e.tieGroupLimit===null)&&i(t,["tieGroupLimit"],"failedGroups and tieGroupLimit are present together or absent together")}),yo=c.z.object({canDecide:c.z.boolean(),rowScopeApplied:c.z.boolean()}).strict(),ho=c.z.object({counts:mo,detection:fo.nullable(),viewer:yo}).strict().superRefine((e,t)=>{let{counts:o,detection:n,viewer:a}=e,s=o.kind==="unmeasured"&&o.reason==="NEVER_DETECTED";n===null!==s&&i(t,["detection"],"The detection is absent exactly when the counts were never detected"),n!==null&&a.rowScopeApplied!==(n.failedGroups===null)&&i(t,["detection","failedGroups"],"Only an operator whose row scope is unrestricted sees the failed groups"),o.kind==="unmeasured"&&o.reason==="DETECTION_INCOMPLETE_FOR_READABLE"&&!a.rowScopeApplied&&i(t,["counts","reason"],"Only an operator with a row scope has counts left unmeasured by a failed group");let u=n===null?null:n.failedGroups,m=u!==null&&u.length>0;o.kind==="measured"&&o.partial!==m&&i(t,["counts","partial"],"The counts are partial exactly when failed groups are shown")}),no=c.z.object({metadataId:p,approvalStatus:b,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict(),oe=c.z.object({policyCategory:v,authorityTier:D,validFromUtc:x,source:no,target:no}).strict().superRefine((e,t)=>{se(e.source.metadataId,e.target.metadataId,["target","metadataId"],t);for(let o of["source","target"])e[o].validFromUtc!==e.validFromUtc&&i(t,[o,"validFromUtc"],"Both documents share the effective date of the rank"),e[o].approvalStatus!==b.enum.APPROVED&&i(t,[o,"approvalStatus"],"Both documents were approved when the pair was detected")}),Ao=e=>Ue(ue(new TextEncoder().encode((0,me.canonicalJson)(e))));function Sn(e){return(0,me.canonicalJson)(oe.parse(e))}function En(e){return Ao(oe.parse(e))}var ro=e=>({metadataId:e.metadataId,approvalStatus:e.approvalStatus,validFromUtc:e.validFromUtc,validUntilUtc:e.validUntilUtc,txCreatedAtUtc:e.txCreatedAtUtc,txSupersededAtUtc:e.txSupersededAtUtc});function Rn(e,t,o){if(t.authorityTier!==o.authorityTier)throw new RangeError(`A pair shares one rank: metadataId ${t.metadataId} has tier ${t.authorityTier} and ${o.metadataId} tier ${o.authorityTier}`);return oe.parse({policyCategory:e,authorityTier:t.authorityTier,validFromUtc:t.validFromUtc,source:ro(t),target:ro(o)})}var Dt=c.z.object({conflictId:p,state:Et,severity:ie,policyCategory:v,authorityTier:D,source:L,target:L,lastDetectedAt:S,clearedAt:S.nullable()}).strict().superRefine((e,t)=>{se(e.source.metadataId,e.target.metadataId,["target","metadataId"],t),e.severity!==nt[e.authorityTier]&&i(t,["severity"],"The severity is the one the tier derives"),e.state==="UNRESOLVED_ACTIVE"&&e.clearedAt!==null&&i(t,["clearedAt"],"A pair still detected has not been cleared"),e.state==="UNRESOLVED_CLEARED"&&e.clearedAt===null&&i(t,["clearedAt"],"A pair no longer detected carries when it was cleared")}),gn=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("unmeasured")}).strict(),c.z.object({kind:c.z.literal("page"),rows:c.z.array(Dt).max(Rt),nextAfter:p.nullable()}).strict()]).superRefine((e,t)=>{e.kind==="page"&&W(e.rows.map(o=>o.conflictId),e.nextAfter,t)}),Dn=c.z.object({state:Et,severity:ie.optional(),after:p.optional(),limit:X(Rt)}).strict(),B=c.z.enum(["verdict","reason"]),ht=c.z.enum(["REQUIRED","MALFORMED","EMPTY","TOO_LONG"]),In=e=>ce(e)?e.length===0?"EMPTY":e.length>gt?"TOO_LONG":null:"MALFORMED",fe=c.z.string().superRefine((e,t)=>{e!==so(e)&&i(t,[],"A stored reason has no blank character at either end");let o=In(e);o!==null&&i(t,[],`A reason is well-formed text of 1 to ${gt} UTF-16 code units`,o)}),Co=c.z.object({status:Z.exclude(["UNRESOLVED"]),prevailingMetadataId:p.nullable(),reason:fe,decidedBy:k,decidedAt:S,factsChangedSinceDecision:c.z.boolean()}).strict(),ao=c.z.object({document:L,authority:O}).strict(),xn=Object.keys(L.shape),_e=(e,t,o,n,a)=>{for(let s of xn)e[s]!==t[s]&&i(a,[...o,s],n)},So=c.z.object({conflict:Dt,conflictSummary:c.z.string().min(1).max(lo),facts:oe,factsHash:z,relatedReadablePairs:g,source:ao,target:ao,decision:Co.nullable()}).strict().superRefine((e,t)=>{let{conflict:o,facts:n,decision:a}=e;for(let m of["source","target"])n[m].metadataId!==o[m].metadataId&&i(t,["facts",m,"metadataId"],"The facts name the documents of the pair"),_e(e[m].document,o[m],[m,"document"],"The detail shows the pair's document as the pair's row does",t),_e(e[m].authority.document,o[m],[m,"authority","document"],"The authority row shows the pair's document as the pair's row does",t);(n.policyCategory!==o.policyCategory||n.authorityTier!==o.authorityTier)&&i(t,["facts"],"The facts carry the subject and the tier of the pair");let s=oe.safeParse(n);s.success&&e.factsHash!==Ao(s.data)&&i(t,["factsHash"],"The facts hash is the SHA-256 of the canonical text of the facts shown");let u=o.state==="UNRESOLVED_ACTIVE"||o.state==="UNRESOLVED_CLEARED";if(a===null){u||i(t,["decision"],"A resolved or ignored pair carries its decision");return}a.status!==o.state&&i(t,["decision","status"],"An unresolved pair carries no decision, and a decided pair's state is its verdict"),Te(a.status==="RESOLVED",a.prevailingMetadataId,o.source.metadataId,o.target.metadataId,["decision","prevailingMetadataId"],t)}),At=c.z.enum(["RESOLVE","IGNORE"]),Ct=c.z.string().transform(so).pipe(fe),St={conflictId:p,expectedFactsHash:z},Eo=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal(At.enum.RESOLVE),...St,prevailingMetadataId:p,reason:Ct}).strict(),c.z.object({kind:c.z.literal(At.enum.IGNORE),...St,reason:Ct}).strict()]),io=c.z.custom(ge),bn=c.z.object({kind:io,...St,prevailingMetadataId:io,reason:Ct}).strict(),Ro=c.z.enum(["SUBJECT_WRITE_FAILED","DETECTION_FAILED"]),go=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("detected"),summary:ho}).strict(),c.z.object({kind:c.z.literal("busy")}).strict(),c.z.object({kind:c.z.literal("failed"),reason:Ro,failedCategory:v.nullable(),rowScopeApplied:c.z.boolean()}).strict()]).superRefine((e,t)=>{e.kind==="detected"&&e.summary.detection===null&&i(t,["summary","detection"],"A completed detection leaves its state"),e.kind==="failed"&&e.failedCategory!==null!=(e.reason==="SUBJECT_WRITE_FAILED"&&!e.rowScopeApplied)&&i(t,["failedCategory"],"The failed category is shown exactly for a subject that failed, to an operator whose row scope is unrestricted")}),vn=(e,t,o)=>{e.replaces===null?i(o,["row","replaces"],"An approved row that replaces a row the operator reads names it"):_e(t.document,e.replaces,["replaced","document"],"The replaced row is the one the approved row names",o),t.supersededBy===null?i(o,["replaced","supersededBy"],"The replaced row names the approved document version as its successor"):_e(t.supersededBy,e.document,["replaced","supersededBy"],"The replaced row names the approved document version as its successor",o),t.approvalStatus!==b.enum.APPROVED&&i(o,["replaced","approvalStatus"],"The replaced row stays approved"),t.policyCategory!==e.policyCategory&&i(o,["replaced","policyCategory"],"The replaced row shares the approved row's category");let n=t.validUntil===null?null:_(t.validUntil,e.validFrom);(t.validUntil===null||n!==null&&n>0)&&i(o,["replaced","validUntil"],"The replaced row ends no later than the approved row takes effect")},Tn=c.z.discriminatedUnion("kind",[c.z.object({kind:I.extract(["create","update"]),row:O,detection:c.z.null()}).strict(),c.z.object({kind:I.extract(["approve","withdraw","deprecate"]),row:O,detection:go,replaced:O.nullable()}).strict(),c.z.object({kind:I.extract(["delete"]),row:c.z.null(),detection:c.z.null()}).strict()]).superRefine((e,t)=>{e.row!==null&&(e.row.approvalStatus!==$[e.kind].after&&i(t,["row","approvalStatus"],"The row has the approval status the command leaves"),"replaced"in e&&(e.replaced!==null!==(e.kind==="approve"&&e.row.replacesAnother)?i(t,["replaced"],"An approval of a row that replaces another carries that row, and no other result does"):e.replaced!==null&&vn(e.row,e.replaced,t)))}),It=c.z.discriminatedUnion("path",[c.z.object({path:c.z.literal(B.enum.verdict),reason:ht.extract(["REQUIRED"])}).strict(),c.z.object({path:c.z.literal(B.enum.reason),reason:ht}).strict()]),pe=c.z.enum(["BODY_INVALID","FIELD_INVALID","ID_MISMATCH","PREVAILING_NOT_IN_PAIR","NOT_FOUND","STALE","DEADLOCK","DEPLOYMENT_DISABLED"]),wn=xe()(c.z.discriminatedUnion("code",[c.z.object({code:pe.extract(["FIELD_INVALID"]),fieldErrors:c.z.array(It).min(1)}).strict(),c.z.object({code:pe.extract(["STALE"]),detail:So}).strict(),c.z.object({code:pe.exclude(["FIELD_INVALID","STALE"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&Ie(e.fieldErrors.map(o=>o.path),B.options,t)})),Pn={schema:Eo,fieldOfKey:new Map([["kind",B.enum.verdict],["prevailingMetadataId",B.enum.verdict],["reason",B.enum.reason]]),fields:B.options,fieldError:It,skippedIssues:e=>{if(!ge(e.kind))return[];let t=bn.safeParse(e);return t.success?[]:t.error.issues}};function On(e){return De(e,Pn)}var Un=c.z.object({intent:c.z.literal("detect")}).strict(),Do=pe.extract(["BODY_INVALID","DEPLOYMENT_DISABLED"]),_n=c.z.object({code:Do}).strict();var Fe=E.z.enum(["document_authority.command","policy_conflict.decided","policy_conflict.detected","governance.maintenance"]),Io=E.z.object({validUntil:S.nullable(),supersededByMetadataId:p.nullable()}).strict(),xo=E.z.object({metadataId:p,before:Io,after:Io}).strict(),bo={authorityTier:D,policyCategory:v,validFrom:S,validUntil:S.nullable(),approvedBy:k.nullable(),withdrawnBy:k.nullable(),replacesMetadataId:p.nullable(),supersededByMetadataId:p.nullable()},Nn=Object.keys(bo),xt=E.z.object({approvalStatus:b,...bo,replaced:xo.optional()}).strict().superRefine((e,t)=>{le(e.validFrom,e.validUntil,["validUntil"],t),we(e.approvalStatus,e.approvedBy!==null,e.withdrawnBy!==null,{approval:["approvedBy"],withdrawal:["withdrawnBy"]},t)}),vo=E.z.object({deleted:E.z.literal(!0)}).strict(),bt=E.z.object({resolutionStatus:Z,sourceMetadataId:p,targetMetadataId:p,prevailingMetadataId:p.nullable(),arbitrationDecision:fe.nullable(),factsHash:z}).strict().superRefine((e,t)=>{se(e.sourceMetadataId,e.targetMetadataId,["targetMetadataId"],t),Te(e.resolutionStatus==="RESOLVED",e.prevailingMetadataId,e.sourceMetadataId,e.targetMetadataId,["prevailingMetadataId"],t),e.resolutionStatus==="UNRESOLVED"!=(e.arbitrationDecision===null)&&i(t,["arbitrationDecision"],"A decided pair carries its reason, and an unresolved pair none")}),To=Ne.omit({reason:!0}),wo=E.z.object({policyCategory:v,asOf:x,inserted:g,factsChanged:g,reopened:g,cleared:g,activePairs:g,failedGroups:E.z.array(To)}).strict().superRefine((e,t)=>{e.inserted+e.factsChanged+e.reopened+e.cleared===0&&e.failedGroups.length===0&&i(t,[],"A detection is recorded only for a subject it changed"),e.inserted+e.factsChanged>e.activePairs&&i(t,["factsChanged"],"The pairs whose facts changed are among the standing pairs the detection did not insert"),e.inserted+e.reopened>e.activePairs&&i(t,["reopened"],"The pairs that reappeared are among the standing pairs the detection did not insert"),e.failedGroups.forEach((o,n)=>{o.policyCategory!==e.policyCategory&&i(t,["failedGroups",n,"policyCategory"],"A subject records its own failed groups")})}),Fn=E.z.object({event:E.z.literal(Fe.enum["document_authority.command"]),command:I,authorityId:p,metadataId:p,before:xt.nullable(),after:E.z.union([xt,vo]),rowVersionBefore:te.nullable(),rowVersionAfter:te.nullable()}).strict(),Ln=E.z.object({event:E.z.literal(Fe.enum["policy_conflict.decided"]),conflictId:p,before:bt,after:bt}).strict(),Mn=E.z.object({event:E.z.literal(Fe.enum["policy_conflict.detected"]),before:E.z.null(),after:wo}).strict(),zn=(e,t,o)=>{if((e.command==="approve"&&t.replacesMetadataId!==null)!==(t.replaced!==void 0)&&i(o,["after","replaced"],"An approval that replaces another row records that row's change, and nothing else does"),t.replaced===void 0)return;let{replaced:a}=t;a.metadataId!==t.replacesMetadataId&&i(o,["after","replaced","metadataId"],"The replaced row is the one the approved row names"),a.before.supersededByMetadataId!==null&&i(o,["after","replaced","before","supersededByMetadataId"],"The replaced row was not yet superseded"),a.after.supersededByMetadataId!==e.metadataId&&i(o,["after","replaced","after","supersededByMetadataId"],"The replaced row is superseded by the approved document version");let s=a.before.validUntil,u=s===null?null:_(s,t.validFrom),m=s===null?t.validFrom:u===null?null:u===1?t.validFrom:s,f=a.after.validUntil===null||m===null?null:_(a.after.validUntil,m);(a.after.validUntil===null||f!==null&&f!==0)&&i(o,["after","replaced","after","validUntil"],"The replaced row ends when the approved row takes effect, unless it had already ended")},kn=(e,t,o)=>{let n=t[e],a=o[e];if(n===a)return!0;if(e!=="validFrom"&&e!=="validUntil"||typeof n!="string"||typeof a!="string")return!1;let s=_(n,a);return s===null||s===0},Gn=(e,t,o,n)=>{let a=$[e.command],s=Nn.filter(u=>!a.changes.includes(u));for(let u of s)a.before===null?o!==null&&o[u]!==null&&i(n,["after",u],`The ${e.command} command leaves ${u} empty`):t!==null&&o!==null&&!kn(u,t,o)&&i(n,["after",u],`The ${e.command} command keeps ${u}`)},jn=(e,t)=>{let o=$[e.command],{before:n}=e,a="deleted"in e.after?null:e.after;o.before===null!=(n===null)?i(t,["before"],"Only a create records no image before the command"):n!==null&&n.approvalStatus!==o.before&&i(t,["before","approvalStatus"],`The ${e.command} command finds a row whose status is ${o.before}`),o.after===null!=(a===null)?i(t,["after"],"Only a delete records the deleted marker after the command"):a!==null&&a.approvalStatus!==o.after&&i(t,["after","approvalStatus"],`The ${e.command} command leaves a row whose status is ${o.after}`),o.before===null!=(e.rowVersionBefore===null)&&i(t,["rowVersionBefore"],"The row version before is recorded exactly when a row existed before the command"),o.after===null!=(e.rowVersionAfter===null)&&i(t,["rowVersionAfter"],"The row version after is recorded exactly when a row exists after the command"),n?.replaced!==void 0&&i(t,["before","replaced"],"Only the image after an approval records the replaced row's change"),o.requiresNeverApproved&&n!==null&&n.approvedBy!==null&&i(t,["before","approvedBy"],`The ${e.command} command applies only to a row never approved`),o.requiresNoReplacement&&n!==null&&n.replacesMetadataId!==null&&i(t,["before","replacesMetadataId"],`The ${e.command} command applies only to a row that replaces no other; a replacing approval ends by deprecation`);for(let[s,u]of[["before",n],["after",a]])u!==null&&u.replacesMetadataId===e.metadataId&&i(t,[s,"replacesMetadataId"],"A row does not replace its own document version");Gn(e,n,a,t),a!==null&&zn(e,a,t)},Vn=(e,t)=>{let{before:o,after:n}=e;o.resolutionStatus!=="UNRESOLVED"&&i(t,["before","resolutionStatus"],"A decision is taken on an unresolved pair"),n.resolutionStatus==="UNRESOLVED"&&i(t,["after","resolutionStatus"],"A decision resolves or ignores the pair"),(n.sourceMetadataId!==o.sourceMetadataId||n.targetMetadataId!==o.targetMetadataId)&&i(t,["after"],"A decision keeps the pair"),n.factsHash!==o.factsHash&&i(t,["after","factsHash"],"A decision records the facts it was taken on")},qn=E.z.discriminatedUnion("event",[Fn,Ln,Mn]).superRefine((e,t)=>{e.event==="document_authority.command"?jn(e,t):e.event==="policy_conflict.decided"&&Vn(e,t)});var H=require("@aiquants/enrichment-core"),d=require("zod");var Tt=d.z.enum(["ENABLE_VECTOR_SEARCH","ENABLE_VECTOR_INDEXING","ENABLE_GRAPH_SEARCH","ENABLE_GRAPH_INDEXING","ENABLE_ASSET_EXTRACTION","ENABLE_MEDIA_ANALYSIS","ENABLE_DYNAMIC_CLASSIFIER_RULES","ENABLE_SEMANTIC_CACHE","ENABLE_CONTEXT_COMPRESSION","ENABLE_MULTI_AGENT_SWARM","ENABLE_AUTONOMOUS_ONTOLOGY","ENABLE_MERKLE_CITATION_PROOF","ENABLE_REALTIME_CDC_INGESTION","ENABLE_COLPALI_IMAGE_INDEXING"]),Bn=d.z.object({tenantId:H.TenantIdSchema,flagKey:Tt,isEnabled:d.z.boolean(),description:d.z.string(),updatedBy:d.z.string(),updatedAt:d.z.string()}),Po=d.z.enum(["ocr","enrichment","transcription","asset_extraction","vector_indexing","graph_indexing","governance_answer"]),Hn=["ocr","enrichment","transcription","governance_answer"],Yn=d.z.object({tenantId:H.TenantIdSchema,confidentialityLevel:Re.ConfidentialityLevelSchema,capability:Po,isEnabled:d.z.boolean(),allowCloudProvider:d.z.boolean(),promptKey:d.z.string().min(1).nullable(),description:d.z.string().nullable(),updatedBy:d.z.string(),updatedAt:d.z.string()}),$n=d.z.object({tenantId:H.TenantIdSchema,parameterKey:d.z.string().min(1),parameterValue:d.z.string(),dataType:d.z.enum(["string","int","float","bool","json"]),description:d.z.string(),isSecret:d.z.boolean(),updatedBy:d.z.string(),updatedAt:d.z.string()}),Kn=d.z.object({tenantId:H.TenantIdSchema,promptKey:d.z.string().min(1),promptVersion:d.z.number().int(),promptTemplate:d.z.string(),provider:d.z.string(),modelName:d.z.string(),temperature:d.z.number(),maxTokens:d.z.number().int(),isSystemPrompt:d.z.boolean(),description:d.z.string(),updatedBy:d.z.string(),updatedAt:d.z.string()}),Qn=d.z.object({tenantId:H.TenantIdSchema,flagKey:Tt,isEnabled:d.z.boolean(),updatedBy:d.z.string().min(1)}),Zn=d.z.object({tenantId:H.TenantIdSchema,parameterKey:d.z.string().min(1),parameterValue:d.z.string(),updatedBy:d.z.string().min(1)}),Xn=d.z.object({tenantId:H.TenantIdSchema,promptKey:d.z.string().min(1),promptTemplate:d.z.string().min(1,"promptTemplate must not be empty"),provider:d.z.string().min(1),modelName:d.z.string().min(1),temperature:d.z.number().min(0).max(2).optional(),maxTokens:d.z.number().int().positive().optional(),updatedBy:d.z.string().min(1)}),Oo=d.z.union([d.z.string(),d.z.number(),d.z.boolean(),d.z.null()]),vt=d.z.lazy(()=>d.z.union([Oo,d.z.array(vt),d.z.record(vt)]));0&&(module.exports={AUTHORITY_CANDIDATE_PAGE_LIMIT_MAX,AUTHORITY_SEARCH_QUERY_MAX_LENGTH,AUTHORITY_SEARCH_QUERY_MIN_LENGTH,ApprovalStatusSchema,AuthoritativeSourceSchema,AuthorityCandidatePageSchema,AuthorityCandidateQuerySchema,AuthorityCandidateSchema,AuthoritySearchTextSchema,AuthorityTierSchema,BaseGovernanceClient,CLOUD_CAPABLE_CAPABILITIES,CitationProofLeafSchema,CitationProofSchema,ConfidentialityCapabilityPolicyDtoSchema,ConfidentialityLevelSchema,DOCUMENT_AUTHORITY_COMMAND_RULES,DOCUMENT_AUTHORITY_PAGE_LIMIT_MAX,DeletedDocumentAuthorityEventImageSchema,DocumentAuthorityCommandBlockerSchema,DocumentAuthorityCommandFieldErrorSchema,DocumentAuthorityCommandFieldReasonSchema,DocumentAuthorityCommandFieldSchema,DocumentAuthorityCommandKindSchema,DocumentAuthorityCommandRejectionCodeSchema,DocumentAuthorityCommandRejectionSchema,DocumentAuthorityCommandResultSchema,DocumentAuthorityCommandSchema,DocumentAuthorityEventImageSchema,DocumentAuthorityPageQuerySchema,DocumentAuthorityPageSchema,DocumentAuthorityPageWithCategoriesSchema,DocumentAuthorityRowSchema,DocumentRefSchema,FailedTieGroupReasonSchema,FailedTieGroupSchema,FeatureFlagKeySchema,FileUriSchema,GovernanceAdminClient,GovernanceAnswerRequestSchema,GovernanceAnswerResponseSchema,GovernanceClient,GovernanceClientError,GovernanceSearchHitSchema,GovernanceSearchMetadataSchema,GovernanceSearchRequestSchema,GovernanceSearchResponseSchema,GovernanceSearchSnippetSchema,GovernanceSimulateCaseDiffSchema,GovernanceSimulateCaseScoresSchema,GovernanceSimulateRequestSchema,GovernanceSimulateResponseSchema,GovernanceSimulateScoresSchema,GovernedCapabilitySchema,JsonPrimitiveSchema,JsonValueSchema,KnowledgeGovernanceEventRecordSchema,KnowledgeGovernanceEventSchema,NormalizedPolicyCategorySchema,NormalizedScoreSchema,OPERATOR_IDENTIFIER_MAX_LENGTH,OffsetIsoInstantSchema,POLICY_CATEGORY_MAX_LENGTH,POLICY_CATEGORY_UNICODE_VERSION,POLICY_CATEGORY_WHITESPACE_CODE_POINTS,POLICY_CONFLICT_DECISION_REASON_BLANK_CODE_POINTS,POLICY_CONFLICT_DECISION_REASON_MAX_LENGTH,POLICY_CONFLICT_PAGE_LIMIT_MAX,POLICY_CONFLICT_SUMMARY_MAX_LENGTH,PolicyCategoryRejectionSchema,PolicyCategorySchema,PolicyConflictCountsSchema,PolicyConflictDecisionEventImageSchema,PolicyConflictDecisionFieldErrorSchema,PolicyConflictDecisionFieldReasonSchema,PolicyConflictDecisionFieldSchema,PolicyConflictDecisionKindSchema,PolicyConflictDecisionRejectionCodeSchema,PolicyConflictDecisionRejectionSchema,PolicyConflictDecisionSchema,PolicyConflictDetailSchema,PolicyConflictDetectedEventImageSchema,PolicyConflictDetectedFailedGroupSchema,PolicyConflictDetectionFailureReasonSchema,PolicyConflictDetectionOutcomeSchema,PolicyConflictDetectionRequestRejectionCodeSchema,PolicyConflictDetectionRequestRejectionSchema,PolicyConflictDetectionRequestSchema,PolicyConflictDetectionStateSchema,PolicyConflictFactsSchema,PolicyConflictPageQuerySchema,PolicyConflictPageSchema,PolicyConflictRefSchema,PolicyConflictResolutionStatusSchema,PolicyConflictRowSchema,PolicyConflictSeveritySchema,PolicyConflictStateSchema,PolicyConflictSummarySchema,PolicyConflictUnmeasuredReasonSchema,PolicyConflictViewerSchema,PromptTemplateDtoSchema,REPLACEABLE_AUTHORITY_PAGE_LIMIT_MAX,RecordedPolicyConflictDecisionSchema,RelatedDecisionSchema,ReplaceableAuthorityPageSchema,ReplaceableAuthorityQuerySchema,ReplacedAuthorityChangeSchema,RowVersionSchema,SEVERITY_BY_TIER,Sha256HexSchema,StoredDecisionReasonSchema,SystemFeatureFlagDtoSchema,SystemParameterDtoSchema,TenantIdSchema,UpdateFeatureFlagRequestSchema,UpdateParameterRequestSchema,UpdatePromptTemplateRequestSchema,UtcInstantSchema,VerifiedCitationSchema,bytesToHex,canonicalPolicyConflictFactsJson,checkDocumentAuthorityCommand,checkPolicyConflictDecision,computeCitationLeafHash,computeCitationMerkleRoot,constantTimeCompare,documentAuthorityCommandBlocker,equalRankGroups,isDocumentAuthorityCommandAvailable,isEligibleAuthority,normalizePolicyCategory,offsetIsoOfUtcInstant,parseUtcInstant,policyConflictFactsHash,policyConflictFactsOf,sha256,tiePairs,utcInstantOfOffsetIso,verifyCitationProof});
|
|
1
|
+
"use strict";var je=Object.defineProperty;var Fo=Object.getOwnPropertyDescriptor;var Lo=Object.getOwnPropertyNames;var Mo=Object.prototype.hasOwnProperty;var zo=(e,t)=>{for(var o in t)je(e,o,{get:t[o],enumerable:!0})},ko=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Lo(t))!Mo.call(e,a)&&a!==o&&je(e,a,{get:()=>t[a],enumerable:!(n=Fo(t,a))||n.enumerable});return e};var Go=e=>ko(je({},"__esModule",{value:!0}),e);var Wn={};zo(Wn,{AUTHORITY_CANDIDATE_PAGE_LIMIT_MAX:()=>ct,AUTHORITY_SEARCH_QUERY_MAX_LENGTH:()=>Qt,AUTHORITY_SEARCH_QUERY_MIN_LENGTH:()=>ot,ApprovalStatusSchema:()=>b,AuthoritativeSourceSchema:()=>He,AuthorityCandidatePageSchema:()=>nn,AuthorityCandidateQuerySchema:()=>cn,AuthorityCandidateSchema:()=>Zo,AuthoritySearchTextSchema:()=>lt,AuthorityTierSchema:()=>D,BaseGovernanceClient:()=>K,CLOUD_CAPABLE_CAPABILITIES:()=>Hn,CitationProofLeafSchema:()=>zt,CitationProofSchema:()=>kt,ConfidentialityCapabilityPolicyDtoSchema:()=>Yn,ConfidentialityLevelSchema:()=>Re.ConfidentialityLevelSchema,DOCUMENT_AUTHORITY_COMMAND_RULES:()=>$,DOCUMENT_AUTHORITY_PAGE_LIMIT_MAX:()=>it,DeletedDocumentAuthorityEventImageSchema:()=>vo,DocumentAuthorityCommandBlockerSchema:()=>ln,DocumentAuthorityCommandFieldErrorSchema:()=>ut,DocumentAuthorityCommandFieldReasonSchema:()=>J,DocumentAuthorityCommandFieldSchema:()=>F,DocumentAuthorityCommandKindSchema:()=>I,DocumentAuthorityCommandRejectionCodeSchema:()=>Y,DocumentAuthorityCommandRejectionSchema:()=>pn,DocumentAuthorityCommandResultSchema:()=>Tn,DocumentAuthorityCommandSchema:()=>Wt,DocumentAuthorityEventImageSchema:()=>xt,DocumentAuthorityPageQuerySchema:()=>an,DocumentAuthorityPageSchema:()=>Zt,DocumentAuthorityPageWithCategoriesSchema:()=>on,DocumentAuthorityRowSchema:()=>O,DocumentRefSchema:()=>L,FailedTieGroupReasonSchema:()=>uo,FailedTieGroupSchema:()=>Ne,FeatureFlagKeySchema:()=>Tt,FileUriSchema:()=>P.FileUriSchema,GovernanceAdminClient:()=>yt,GovernanceAnswerRequestSchema:()=>Ze,GovernanceAnswerResponseSchema:()=>Xe,GovernanceClient:()=>ft,GovernanceClientError:()=>q,GovernanceSearchHitSchema:()=>Ft,GovernanceSearchMetadataSchema:()=>Ee,GovernanceSearchRequestSchema:()=>$e,GovernanceSearchResponseSchema:()=>Qe,GovernanceSearchSnippetSchema:()=>Ut,GovernanceSimulateCaseDiffSchema:()=>Ye,GovernanceSimulateCaseScoresSchema:()=>Se,GovernanceSimulateRequestSchema:()=>We,GovernanceSimulateResponseSchema:()=>Je,GovernanceSimulateScoresSchema:()=>Ce,GovernedCapabilitySchema:()=>Po,JsonPrimitiveSchema:()=>Oo,JsonValueSchema:()=>vt,KnowledgeGovernanceEventRecordSchema:()=>qn,KnowledgeGovernanceEventSchema:()=>Fe,NormalizedPolicyCategorySchema:()=>v,NormalizedScoreSchema:()=>Ae,OPERATOR_IDENTIFIER_MAX_LENGTH:()=>Ke,OffsetIsoInstantSchema:()=>S,POLICY_CATEGORY_MAX_LENGTH:()=>Pe,POLICY_CATEGORY_UNICODE_VERSION:()=>Jo,POLICY_CATEGORY_WHITESPACE_CODE_POINTS:()=>Yt,POLICY_CONFLICT_DECISION_REASON_BLANK_CODE_POINTS:()=>co,POLICY_CONFLICT_DECISION_REASON_MAX_LENGTH:()=>gt,POLICY_CONFLICT_PAGE_LIMIT_MAX:()=>Rt,POLICY_CONFLICT_SUMMARY_MAX_LENGTH:()=>lo,PolicyCategoryRejectionSchema:()=>rt,PolicyCategorySchema:()=>Kt,PolicyConflictCountsSchema:()=>mo,PolicyConflictDecisionEventImageSchema:()=>bt,PolicyConflictDecisionFieldErrorSchema:()=>It,PolicyConflictDecisionFieldReasonSchema:()=>ht,PolicyConflictDecisionFieldSchema:()=>B,PolicyConflictDecisionKindSchema:()=>At,PolicyConflictDecisionRejectionCodeSchema:()=>pe,PolicyConflictDecisionRejectionSchema:()=>wn,PolicyConflictDecisionSchema:()=>Eo,PolicyConflictDetailSchema:()=>So,PolicyConflictDetectedEventImageSchema:()=>wo,PolicyConflictDetectedFailedGroupSchema:()=>To,PolicyConflictDetectionFailureReasonSchema:()=>Ro,PolicyConflictDetectionOutcomeSchema:()=>go,PolicyConflictDetectionRequestRejectionCodeSchema:()=>Do,PolicyConflictDetectionRequestRejectionSchema:()=>Un,PolicyConflictDetectionRequestSchema:()=>_n,PolicyConflictDetectionStateSchema:()=>fo,PolicyConflictFactsSchema:()=>oe,PolicyConflictPageQuerySchema:()=>Dn,PolicyConflictPageSchema:()=>gn,PolicyConflictRefSchema:()=>Lt,PolicyConflictResolutionStatusSchema:()=>Z,PolicyConflictRowSchema:()=>Dt,PolicyConflictSeveritySchema:()=>ie,PolicyConflictStateSchema:()=>Et,PolicyConflictSummarySchema:()=>ho,PolicyConflictUnmeasuredReasonSchema:()=>po,PolicyConflictViewerSchema:()=>yo,PromptTemplateDtoSchema:()=>Kn,REPLACEABLE_AUTHORITY_PAGE_LIMIT_MAX:()=>st,RecordedPolicyConflictDecisionSchema:()=>Co,RelatedDecisionSchema:()=>Nt,ReplaceableAuthorityPageSchema:()=>rn,ReplaceableAuthorityQuerySchema:()=>sn,ReplacedAuthorityChangeSchema:()=>xo,RowVersionSchema:()=>te,SEVERITY_BY_TIER:()=>nt,Sha256HexSchema:()=>z,StoredDecisionReasonSchema:()=>fe,SystemFeatureFlagDtoSchema:()=>Bn,SystemParameterDtoSchema:()=>$n,TenantIdSchema:()=>P.TenantIdSchema,UpdateFeatureFlagRequestSchema:()=>Qn,UpdateParameterRequestSchema:()=>Zn,UpdatePromptTemplateRequestSchema:()=>Xn,UtcInstantSchema:()=>x,VerifiedCitationSchema:()=>Mt,bytesToHex:()=>_e,canonicalPolicyConflictFactsJson:()=>Sn,checkDocumentAuthorityCommand:()=>fn,checkPolicyConflictDecision:()=>On,computeCitationLeafHash:()=>eo,computeCitationMerkleRoot:()=>to,constantTimeCompare:()=>Jt,documentAuthorityCommandBlocker:()=>dt,equalRankGroups:()=>Xo,isDocumentAuthorityCommandAvailable:()=>dn,isEligibleAuthority:()=>Bt,normalizePolicyCategory:()=>at,offsetIsoOfUtcInstant:()=>Qo,parseUtcInstant:()=>qt,policyConflictFactsHash:()=>En,policyConflictFactsOf:()=>Rn,sha256:()=>ue,tiePairs:()=>Wo,utcInstantOfOffsetIso:()=>Ko,verifyCitationProof:()=>mt});module.exports=Go(Wn);var ee=require("@aiquants/enrichment-core"),l=require("zod");var Ot=require("zod"),jo=/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.\d{7}$/,Ve=1,_t=9999,Pt=7,qe=60,Vo=14*qe,qo=Ot.z.string().datetime({offset:!0}),Bo=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|([+-])(\d{2}):(\d{2}))$/,Ho=(e,t,o)=>{let n=new Date(0);return n.setUTCFullYear(e,t-1,o),e>=Ve&&e<=_t&&n.getUTCMonth()===t-1&&n.getUTCDate()===o},Be=e=>{let t=jo.exec(e);if(t===null)return null;let[o,n,a,s,u,m]=t.slice(1,7).map(Number);return Ho(o,n,a)&&s<=23&&u<=59&&m<=59?e:null},Q=(e,t)=>String(e).padStart(t,"0"),ae=e=>{let t=qo.safeParse(e).success?Bo.exec(e):null;if(t===null)return null;let[,o,n,a,s,u,m,f="",R="+",T="00",w="00"]=t,h=(R==="-"?-1:1)*(Number(T)*qe+Number(w));if(Number(o)<Ve||f.length>Pt||Number(w)>=qe||Math.abs(h)>Vo)return null;let y=new Date(0);y.setUTCFullYear(Number(o),Number(n)-1,Number(a)),y.setUTCHours(Number(s),Number(u)-h,Number(m),0);let C=y.getUTCFullYear();if(C<Ve||C>_t)return null;let G=`${Q(C,4)}-${Q(y.getUTCMonth()+1,2)}-${Q(y.getUTCDate(),2)}`,_=`${Q(y.getUTCHours(),2)}:${Q(y.getUTCMinutes(),2)}:${Q(y.getUTCSeconds(),2)}`;return`${G} ${_}.${f.padEnd(Pt,"0")}`},U=(e,t)=>{let o=ae(e),n=ae(t);return o===null||n===null?null:o<n?-1:o>n?1:0};var et=require("@aiquants/enrichment-core"),N=require("zod");var P=require("@aiquants/enrichment-core"),r=require("zod"),Re=require("@aiquants/enrichment-core");var $e=r.z.object({query:r.z.string().min(1,"Search query must not be empty"),policyCategory:r.z.string().optional(),includeHistoricalRevisions:r.z.boolean().optional(),maxAuthorityTier:r.z.union([r.z.literal(1),r.z.literal(2),r.z.literal(3),r.z.literal(4),r.z.literal(5)]).optional(),limit:r.z.number().int().positive().optional()}),Ut=r.z.object({text:r.z.string(),citationText:r.z.string(),chunkHash:r.z.string(),chunkIndex:r.z.number().int().nonnegative(),parentChunkUid:r.z.string().optional(),clauseIdentifier:r.z.string().optional(),breadcrumbPath:r.z.array(r.z.string()).optional(),page:r.z.number().int().optional(),sheetName:r.z.string().optional(),slideIndex:r.z.number().int().optional(),timestampSec:r.z.number().optional(),score:r.z.number()}),Nt=r.z.object({decisionId:r.z.string(),title:r.z.string(),approvedBy:r.z.string()}),D=r.z.union([r.z.literal(1),r.z.literal(2),r.z.literal(3),r.z.literal(4),r.z.literal(5)]),b=r.z.enum(["DRAFT","APPROVED","DEPRECATED"]),ie=r.z.enum(["LOW","MEDIUM","HIGH","CRITICAL"]),Z=r.z.enum(["UNRESOLVED","RESOLVED","IGNORED"]),Ke=100,Ft=r.z.object({metadataId:r.z.number().int(),fileUri:P.FileUriSchema,fileName:r.z.string(),documentTitle:r.z.string(),authorityTier:D.nullable(),validFrom:r.z.string().nullable(),validUntil:r.z.string().nullable(),isCurrentlyAuthoritative:r.z.boolean(),confidentialityLevel:P.ConfidentialityLevelSchema,snippets:r.z.array(Ut),relatedDecisions:r.z.array(Nt).optional(),policyWarning:r.z.string().optional()}),Ee=r.z.object({searchMode:r.z.enum(["tri_store","sql_vector","sql_keyword_degraded"]),qualityTier:r.z.enum(["HIGH_TRI_STORE","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),isDegraded:r.z.boolean(),degradationReason:r.z.string().nullable(),circuitBreakerStatus:r.z.record(r.z.enum(["CLOSED","OPEN","HALF_OPEN","HEALTHY"])),executionTimeMs:r.z.number().nonnegative()}),Qe=r.z.object({hits:r.z.array(Ft),tiers:r.z.object({sql:r.z.boolean(),vector:r.z.boolean(),graph:r.z.boolean()}),masked:r.z.boolean(),searchMetadata:Ee}),Ze=r.z.object({question:r.z.string().min(1,"Question must not be empty"),asOf:r.z.string().optional(),asOfTx:r.z.string().optional()}),He=r.z.object({metadataId:r.z.number().int(),documentTitle:r.z.string(),authorityTier:D,approvalStatus:b,validFrom:r.z.string(),validUntil:r.z.string().nullable(),isCurrentlyAuthoritative:r.z.boolean()}),Lt=r.z.object({conflictId:r.z.number().int(),sourceMetadataId:r.z.number().int(),targetMetadataId:r.z.number().int(),conflictSummary:r.z.string(),severity:ie,resolutionStatus:Z}),Mt=r.z.object({chunkUid:r.z.string().uuid("chunkUid must be a valid UUID"),metadataId:r.z.number().int(),documentTitle:r.z.string(),clauseIdentifier:r.z.string(),breadcrumbPath:r.z.array(r.z.string()),exactQuotedText:r.z.string(),chunkHash:r.z.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),authorityTier:D,isVerified:r.z.boolean()}),z=r.z.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),zt=r.z.object({chunkUid:r.z.string().uuid("chunkUid must be a valid UUID"),chunkHash:z}),kt=r.z.object({algorithm:r.z.literal("SHA-256"),merkleRoot:z,leafCount:r.z.number().int().positive(),leaves:r.z.array(zt).min(1),tenantId:P.TenantIdSchema,scopeDigest:z,asOf:r.z.string().datetime(),asOfTx:r.z.string().datetime(),generatedAt:r.z.string().datetime(),signature:r.z.string().min(1,"Signature must not be empty")}),Xe=r.z.object({answer:r.z.string(),authoritative:r.z.array(He),superseded:r.z.array(He),conflicts:r.z.array(Lt),verifiedCitations:r.z.array(Mt),citationProof:kt.nullable(),isFullyGrounded:r.z.boolean(),requiresHumanArbitration:r.z.boolean(),tiers:r.z.object({sql:r.z.boolean(),vector:r.z.boolean(),graph:r.z.boolean()}),searchMetadata:Ee}),We=r.z.object({promptOverrides:r.z.record(r.z.string()).optional(),parameterOverrides:r.z.record(r.z.union([r.z.string(),r.z.number(),r.z.boolean()])).optional(),strategyOverrides:r.z.record(r.z.record(r.z.union([r.z.string(),r.z.number(),r.z.boolean()]))).optional(),intentTypes:r.z.array(r.z.enum(["SET","DIFF","PATH","NEGATION","COUNT"])).optional()}),Ae=r.z.number().min(0).max(1),Se=r.z.object({contextRelevance:Ae,groundedness:Ae,answerRelevance:Ae}),Ce=Se.extend({meanAnswerChars:r.z.number().nonnegative(),meanLatencyMs:r.z.number().nonnegative()}),Ye=r.z.object({caseId:r.z.string(),intentType:r.z.enum(["SET","DIFF","PATH","NEGATION","COUNT"]),beforeScores:Se,afterScores:Se}),Je=r.z.object({simulationId:r.z.string(),evaluatedCount:r.z.number().int().nonnegative(),before:Ce,after:Ce,delta:Ce,regressions:r.z.array(Ye),improvements:r.z.array(Ye),searchMetadata:Ee});var i=(e,t,o,n)=>{e.addIssue(n===void 0?{code:N.z.ZodIssueCode.custom,path:[...t],message:o}:{code:N.z.ZodIssueCode.custom,path:[...t],message:o,params:{reason:n}})},ge=e=>e==null||e==="",Gt=e=>{let t=N.z.unknown().superRefine((o,n)=>e(n)).safeParse(void 0);return t.success?[]:t.error.issues},De=(e,t)=>{let o=t.schema.safeParse(e);if(o.success)return{ok:!0,value:o.data};let n={ok:!1,rejection:{code:"BODY_INVALID"}},a=f=>f.path.length===0?void 0:t.fieldOfKey.get(f.path[0]);if(!o.error.issues.every(f=>a(f)!==void 0))return n;let s=e,u=[];for(let f of[...o.error.issues,...t.skippedIssues(s)]){let R=a(f);if(R===void 0)return n;let T=f.code===N.z.ZodIssueCode.custom?f.params?.reason:void 0,w=T??(ge(s[f.path[0]])?"REQUIRED":"MALFORMED"),h=t.fieldError.safeParse({path:R,reason:w});if(!h.success){if(T!==void 0)throw new RangeError(`A rule reported ${JSON.stringify(T)} at ${JSON.stringify(R)}, which the form does not pair`);return n}u.push(h.data)}return{ok:!1,rejection:{code:"FIELD_INVALID",fieldErrors:t.fields.flatMap(f=>{let R=u.find(T=>T.path===f);return R===void 0?[]:[R]})}}},Ie=(e,t,o)=>{e.forEach((n,a)=>{a>0&&t.indexOf(n)<=t.indexOf(e[a-1])&&i(o,["fieldErrors",a],"Each field appears once, in the form's order")})},xe=()=>e=>e,p=N.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),g=N.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),be=N.z.number().int().min(et.SYSTEM_PARAMETER_RANGES.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min).max(et.SYSTEM_PARAMETER_RANGES.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.max),X=e=>N.z.number().int().min(1).max(e),k=N.z.string().min(1).max(Ke),Yo=/\p{Cs}/u,ce=e=>!Yo.test(e),ve=(e,t)=>{let o=0,n=e.length;for(;o<n&&t.has(e.charCodeAt(o));)o+=1;for(;n>o&&t.has(e.charCodeAt(n-1));)n-=1;return e.slice(o,n)},W=(e,t,o)=>{e.forEach((n,a)=>{a>0&&n>=e[a-1]&&i(o,["rows",a],"Rows are in strictly descending order of their key")}),t!==null&&t!==e.at(-1)&&i(o,["nextAfter"],"nextAfter is absent or the key of the last row")},se=(e,t,o,n)=>{e>=t&&i(n,o,"The source governs the smaller document version (source < target)")},Te=(e,t,o,n,a,s)=>{(e?!(t===o||t===n):t!==null)&&i(s,a,"A resolution records one document of the pair as prevailing, and only a resolution does")},$o=(e,t)=>{let o=t===null?null:U(t,e);return o!==null&&o<=0},le=(e,t,o,n)=>{$o(e,t)&&i(n,o,"validUntil must be after validFrom","NOT_AFTER_VALID_FROM")},we=(e,t,o,n,a)=>{e!=="DRAFT"&&!t&&i(a,n.approval,"An APPROVED or DEPRECATED row carries its approval"),o&&!t&&i(a,n.withdrawal,"Only an approval once given can be withdrawn"),e==="DRAFT"&&t&&!o&&i(a,n.withdrawal,"A DRAFT row that was approved carries its withdrawal")};function qt(e){let t=Be(e);if(t===null)throw new RangeError(`Not a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff: ${JSON.stringify(e)}`);return t}var x=l.z.string().transform((e,t)=>{let o=Be(e);return o===null?(t.addIssue({code:l.z.ZodIssueCode.custom,message:"Must be a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff"}),l.z.NEVER):o});function Ko(e){let t=ae(e);if(t===null)throw new RangeError(`Not an ISO 8601 instant with a UTC offset that datetimeoffset(7) can hold: ${JSON.stringify(e)}`);return t}var S=l.z.string().refine(e=>ae(e)!==null,{message:"Must be an ISO 8601 instant yyyy-mm-ddThh:mi:ss[.f] with Z or a \xB1hh:mi offset within \xB114:00, at most seven fractional digits and a year between 0001 and 9999 both as written and in UTC"});function Qo(e){let t=qt(e);return`${t.slice(0,10)}T${t.slice(11)}Z`}var Zo=l.z.object({metadataId:p,authorityTier:D,approvalStatus:b,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict();function Bt(e,t,o){return e.approvalStatus===b.enum.APPROVED&&e.validFromUtc<=t&&(e.validUntilUtc===null||e.validUntilUtc>t)&&e.txCreatedAtUtc<=o&&(e.txSupersededAtUtc===null||e.txSupersededAtUtc>o)}var Ht=(e,t)=>e.metadataId-t.metadataId,tt=e=>`${e.authorityTier} ${e.validFromUtc}`;function Xo(e,t,o){let n=new Set,a=new Map;for(let s of e){if(n.has(s.metadataId))throw new RangeError(`Two authority rows govern the same document version: metadataId ${s.metadataId}`);if(n.add(s.metadataId),!Bt(s,t,o))continue;let u=tt(s),m=a.get(u);m===void 0?a.set(u,[s]):m.push(s)}return[...a.values()].filter(s=>s.length>=2).map(s=>[...s].sort(Ht)).sort((s,u)=>s[0].metadataId-u[0].metadataId)}function Wo(e){let t=[...e].sort(Ht);return t.forEach((o,n)=>{if(tt(o)!==tt(t[0]))throw new RangeError(`An equal-rank group mixes ranks: metadataId ${t[0].metadataId} and ${o.metadataId}`);if(n>0&&o.metadataId===t[n-1].metadataId)throw new RangeError(`An equal-rank group repeats a document version: metadataId ${o.metadataId}`)}),t.flatMap((o,n)=>t.slice(n+1).map(a=>[o,a]))}var nt=Object.freeze({1:"CRITICAL",2:"HIGH",3:"MEDIUM",4:"LOW",5:"LOW"}),Pe=50,Jo="17.0",rt=l.z.enum(["MALFORMED","EMPTY","TOO_LONG"]),Yt=Object.freeze([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]),$t=new Set(Yt),en=e=>{let t=[],o=0;for(let n=0;n<=e.length;n+=1)(n===e.length||$t.has(e.charCodeAt(n)))&&(n>o&&t.push(e.slice(o,n)),o=n+1);return t.join(" ")};function at(e){if(!ce(e))return{ok:!1,reason:"MALFORMED"};let t=en(e.normalize("NFKC"));return t.length===0?{ok:!1,reason:"EMPTY"}:t.length>Pe?{ok:!1,reason:"TOO_LONG"}:{ok:!0,value:t}}var Kt=l.z.string().transform((e,t)=>{let o=at(e);return o.ok?o.value:(i(t,[],`A policy category must be well-formed text of 1 to ${Pe} UTF-16 code units after normalization`,o.reason),l.z.NEVER)}),v=l.z.string().refine(e=>{let t=at(e);return t.ok&&t.value===e},{message:`A stored policy category must be well-formed, normalized (NFKC, single spaces, trimmed) and 1 to ${Pe} UTF-16 code units`}),it=50,ct=50,st=50,ot=2,Qt=200,tn=e=>[...e].length,lt=l.z.string().transform(e=>ve(e,$t)).pipe(l.z.string().max(Qt).refine(ce,{message:"A search text is well-formed text without an unpaired surrogate"}).refine(e=>tn(e)>=ot,{message:`A search text has at least ${ot} characters (code points) once trimmed`})),te=l.z.string().regex(/^[0-9a-f]{16}$/,"Must be a rowversion as 16 lowercase hexadecimal digits"),L=l.z.object({metadataId:p,fileName:l.z.string().min(1),fileUri:ee.FileUriSchema,revision:l.z.number().int().min(1),isCurrent:l.z.boolean(),isDeleted:l.z.boolean(),confidentialityLevel:ee.ConfidentialityLevelSchema.exclude([ee.QUARANTINED_CONFIDENTIALITY_LEVEL])}).strict(),O=l.z.object({authorityId:p,document:L,authorityTier:D,policyCategory:v,validFrom:S,validUntil:S.nullable(),txCreatedAt:S,txSupersededAt:S.nullable(),approvalStatus:b,approvedBy:k.nullable(),approvedAt:S.nullable(),withdrawnBy:k.nullable(),withdrawnAt:S.nullable(),replaces:L.nullable(),supersededBy:L.nullable(),replacesAnother:l.z.boolean(),isSuperseded:l.z.boolean(),rowVersion:te,updatedBy:k,updatedAt:S}).strict().superRefine((e,t)=>{le(e.validFrom,e.validUntil,["validUntil"],t),e.approvedBy===null!=(e.approvedAt===null)&&i(t,["approvedAt"],"approvedBy and approvedAt are present together or absent together"),e.withdrawnBy===null!=(e.withdrawnAt===null)&&i(t,["withdrawnAt"],"withdrawnBy and withdrawnAt are present together or absent together"),we(e.approvalStatus,e.approvedAt!==null,e.withdrawnAt!==null,{approval:["approvedAt"],withdrawal:["withdrawnAt"]},t);let o=e.approvedAt===null||e.withdrawnAt===null?null:U(e.withdrawnAt,e.approvedAt);e.approvalStatus==="DRAFT"&&o!==null&&o<0&&i(t,["withdrawnAt"],"A DRAFT row's withdrawal is no earlier than its approval");let n=e.txSupersededAt!==null;(e.approvalStatus==="DEPRECATED"?!n:n)&&i(t,["txSupersededAt"],"txSupersededAt is recorded exactly when the row is DEPRECATED"),e.replaces!==null&&!e.replacesAnother&&i(t,["replacesAnother"],"A row that names the document it replaces replaces another"),e.supersededBy!==null&&!e.isSuperseded&&i(t,["isSuperseded"],"A row that names its successor is superseded"),e.replaces?.metadataId===e.document.metadataId&&i(t,["replaces"],"A row does not replace its own document version"),e.supersededBy?.metadataId===e.document.metadataId&&i(t,["supersededBy"],"A row is not superseded by its own document version")}),Zt=l.z.object({rows:l.z.array(O).max(it),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{W(e.rows.map(o=>o.authorityId),e.nextAfter,t)}),on=l.z.object({page:Zt,categories:l.z.array(v).nullable()}).strict().superRefine((e,t)=>{e.categories!==null&&new Set(e.categories).size!==e.categories.length&&i(t,["categories"],"Each category appears once")}),nn=l.z.object({rows:l.z.array(L).max(ct),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{W(e.rows.map(o=>o.metadataId),e.nextAfter,t),e.rows.forEach((o,n)=>{(!o.isCurrent||o.isDeleted)&&i(t,["rows",n],"A candidate is a current, undeleted document version")})}),rn=l.z.object({rows:l.z.array(O).max(st),nextAfter:p.nullable(),totalCount:g}).strict().superRefine((e,t)=>{W(e.rows.map(o=>o.authorityId),e.nextAfter,t),e.totalCount<e.rows.length&&i(t,["totalCount"],"totalCount counts at least the rows of the page"),e.rows.forEach((o,n)=>{(o.approvalStatus!=="APPROVED"||o.isSuperseded)&&i(t,["rows",n],"A row a replacement may name is approved and not yet superseded"),o.policyCategory!==e.rows[0].policyCategory&&i(t,["rows",n,"policyCategory"],"The rows a replacement may name share one category")})}),an=l.z.object({status:b.optional(),category:v.optional(),after:p.optional(),limit:X(it)}).strict(),cn=l.z.object({q:lt,after:p.optional(),limit:X(ct)}).strict(),sn=l.z.object({category:v,q:lt.optional(),after:p.optional(),limit:X(st)}).strict(),I=l.z.enum(["create","update","approve","withdraw","deprecate","delete"]),F=l.z.enum(["authorityTier","policyCategory","validFrom","validUntil","replacesMetadataId"]),jt={authorityTier:D,policyCategory:Kt,validFrom:S,validUntil:S.nullable(),replacesMetadataId:p.nullable()},Vt=Object.freeze([...F.options]),$=Object.freeze({create:Object.freeze({before:null,after:"DRAFT",changes:Vt,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!1}),update:Object.freeze({before:"DRAFT",after:"DRAFT",changes:Vt,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1}),approve:Object.freeze({before:"DRAFT",after:"APPROVED",changes:Object.freeze(["approvedBy"]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!0}),withdraw:Object.freeze({before:"APPROVED",after:"DRAFT",changes:Object.freeze(["withdrawnBy"]),requiresNeverApproved:!1,requiresNoReplacement:!0,requiresCurrentDocument:!1,runsDetection:!0}),deprecate:Object.freeze({before:"APPROVED",after:"DEPRECATED",changes:Object.freeze([]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!0}),delete:Object.freeze({before:"DRAFT",after:null,changes:Object.freeze([]),requiresNeverApproved:!0,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1})}),ln=l.z.enum(["STATUS","APPROVED_ONCE","REPLACES_ANOTHER","DOCUMENT_NOT_CURRENT"]);function dt(e,t){let o=$[e];return t.approvalStatus!==o.before?"STATUS":o.requiresNeverApproved&&t.approvedAt!==null?"APPROVED_ONCE":o.requiresNoReplacement&&t.replacesAnother?"REPLACES_ANOTHER":o.requiresCurrentDocument&&(!t.document.isCurrent||t.document.isDeleted)?"DOCUMENT_NOT_CURRENT":null}function dn(e,t){return dt(e,t)===null}var de={authorityId:p,expectedRowVersion:te},un=e=>e.kind===I.enum.create&&e.replacesMetadataId===e.metadataId&&p.safeParse(e.replacesMetadataId).success,Xt=(e,t)=>{let{validFrom:o,validUntil:n}=e;typeof o=="string"&&(n===null||typeof n=="string")&&le(o,n,["validUntil"],t),un(e)&&i(t,["replacesMetadataId"],"A document version does not replace itself","SELF_REPLACEMENT")},Wt=l.z.discriminatedUnion("kind",[l.z.object({kind:l.z.literal(I.enum.create),metadataId:p,...jt}).strict(),l.z.object({kind:l.z.literal(I.enum.update),...de,...jt}).strict(),l.z.object({kind:l.z.literal(I.enum.approve),...de}).strict(),l.z.object({kind:l.z.literal(I.enum.withdraw),...de}).strict(),l.z.object({kind:l.z.literal(I.enum.deprecate),...de}).strict(),l.z.object({kind:l.z.literal(I.enum.delete),...de}).strict()]).superRefine(Xt),J=l.z.enum(["REQUIRED",...rt.options,"NOT_AFTER_VALID_FROM","SELF_REPLACEMENT"]),ut=l.z.discriminatedUnion("path",[l.z.object({path:l.z.literal(F.enum.authorityTier),reason:J.extract(["REQUIRED","MALFORMED"])}).strict(),l.z.object({path:l.z.literal(F.enum.policyCategory),reason:J.extract(["REQUIRED",...rt.options])}).strict(),l.z.object({path:l.z.literal(F.enum.validFrom),reason:J.extract(["REQUIRED","MALFORMED"])}).strict(),l.z.object({path:l.z.literal(F.enum.validUntil),reason:J.extract(["REQUIRED","MALFORMED","NOT_AFTER_VALID_FROM"])}).strict(),l.z.object({path:l.z.literal(F.enum.replacesMetadataId),reason:J.extract(["REQUIRED","MALFORMED","SELF_REPLACEMENT"])}).strict()]),Y=l.z.enum(["BODY_INVALID","FIELD_INVALID","NOT_FOUND","REPLACEMENT_NOT_FOUND","STALE","ALREADY_REGISTERED","RANK_LIMIT_REACHED","NOT_AFTER_REPLACED","DOCUMENT_NOT_CURRENT","DEADLOCK","DEPLOYMENT_DISABLED"]),pn=xe()(l.z.discriminatedUnion("code",[l.z.object({code:Y.extract(["FIELD_INVALID"]),fieldErrors:l.z.array(ut).min(1)}).strict(),l.z.object({code:Y.extract(["STALE"]),row:O}).strict(),l.z.object({code:Y.extract(["ALREADY_REGISTERED"]),row:O}).strict(),l.z.object({code:Y.extract(["DOCUMENT_NOT_CURRENT"]),row:O}).strict(),l.z.object({code:Y.extract(["RANK_LIMIT_REACHED"]),rowScopeApplied:l.z.boolean(),limit:be.nullable()}).strict(),l.z.object({code:Y.exclude(["FIELD_INVALID","STALE","ALREADY_REGISTERED","DOCUMENT_NOT_CURRENT","RANK_LIMIT_REACHED"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&Ie(e.fieldErrors.map(o=>o.path),F.options,t),e.code==="ALREADY_REGISTERED"&&(!e.row.document.isCurrent||e.row.document.isDeleted)&&i(t,["row","document"],"The registered row's document version is current and not deleted, as the create requires"),e.code==="DOCUMENT_NOT_CURRENT"&&dt("approve",e.row)!=="DOCUMENT_NOT_CURRENT"&&i(t,["row"],"The row is a DRAFT whose document version is no longer current or has been deleted"),e.code==="RANK_LIMIT_REACHED"&&e.limit===null!==e.rowScopeApplied&&i(t,["limit"],"The limit is shown exactly to an operator whose row scope is unrestricted")})),mn={schema:Wt,fieldOfKey:new Map(F.options.map(e=>[e,e])),fields:F.options,fieldError:ut,skippedIssues:e=>Gt(t=>Xt(e,t))};function fn(e){return De(e,mn)}var q=class extends Error{statusCode;responseBody;parsedBody;constructor(t,o,n,a){super(t),this.name="GovernanceClientError",this.statusCode=o,this.responseBody=n,this.parsedBody=a}},K=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for GovernanceClient.");let o=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey){let n;try{n=new URL(o)}catch{throw new Error(`Invalid baseUrl format: ${t.baseUrl}`)}if(n.protocol==="http:"){let a=n.hostname.toLowerCase();if(!(a==="localhost"||a==="127.0.0.1"||a==="[::1]"||a==="::1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.")}}this.baseUrl=o,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,o,n,a,s){let u=new URL(t.startsWith("/")?t.slice(1):t,`${this.baseUrl}/`);if(a)for(let[h,y]of Object.entries(a))y!=null&&y.trim().length>0&&u.searchParams.append(h,y);let m=u.toString(),f={Accept:"application/json"};this.apiKey&&(f.Authorization=`Bearer ${this.apiKey}`),n!==void 0&&(f["Content-Type"]="application/json");let R=new AbortController,T=setTimeout(()=>R.abort(),this.timeoutMs),w=R.signal;s&&(w=AbortSignal.any([R.signal,s]));try{let h=await this.fetchFn(m,{method:o,headers:f,body:n!==void 0?JSON.stringify(n):void 0,signal:w}),y=await h.text();if(!h.ok){let C;try{C=JSON.parse(y)}catch{}throw new q(`API request failed with status ${h.status}: ${y}`,h.status,y,C)}if(y.trim().length===0)return;try{return JSON.parse(y)}catch(C){let G=C.message;throw new q(`Failed to parse response JSON from ${m}: ${G}`,h.status,y)}}catch(h){if(h instanceof q)throw h;let y=h instanceof Error?h.message:String(h);throw new q(`Network request failed for ${o} ${m}: ${y}`,0,"")}finally{clearTimeout(T)}}};var pt=new Uint8Array([0]),Oe=new Uint8Array([1]),yn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function M(e,t){return e>>>t|e<<32-t}function ue(e){let t=1779033703,o=3144134277,n=1013904242,a=2773480762,s=1359893119,u=2600822924,m=528734635,f=1541459225,R=e.length,T=R*8,w=(R+8>>6)+1<<6,h=new Uint8Array(w);h.set(e),h[R]=128;let y=new DataView(h.buffer,h.byteOffset,h.byteLength);y.setUint32(w-4,T>>>0,!1),y.setUint32(w-8,Math.floor(T/4294967296),!1);let C=new Uint32Array(64);for(let Le=0;Le<w;Le+=64){for(let A=0;A<16;A++)C[A]=y.getUint32(Le+A*4,!1);for(let A=16;A<64;A++){let ke=M(C[A-15],7)^M(C[A-15],18)^C[A-15]>>>3,Ge=M(C[A-2],17)^M(C[A-2],19)^C[A-2]>>>10;C[A]=C[A-16]+ke+C[A-7]+Ge>>>0}let j=t,ne=o,re=n,Me=a,V=s,ye=u,he=m,ze=f;for(let A=0;A<64;A++){let ke=M(V,6)^M(V,11)^M(V,25),Ge=V&ye^~V&he,wt=ze+ke+Ge+yn[A]+C[A]>>>0,_o=M(j,2)^M(j,13)^M(j,22),Uo=j&ne^j&re^ne&re,No=_o+Uo>>>0;ze=he,he=ye,ye=V,V=Me+wt>>>0,Me=re,re=ne,ne=j,j=wt+No>>>0}t=t+j>>>0,o=o+ne>>>0,n=n+re>>>0,a=a+Me>>>0,s=s+V>>>0,u=u+ye>>>0,m=m+he>>>0,f=f+ze>>>0}let G=new Uint8Array(32),_=new DataView(G.buffer,G.byteOffset,G.byteLength);return _.setUint32(0,t,!1),_.setUint32(4,o,!1),_.setUint32(8,n,!1),_.setUint32(12,a,!1),_.setUint32(16,s,!1),_.setUint32(20,u,!1),_.setUint32(24,m,!1),_.setUint32(28,f,!1),G}function _e(e){let t="";for(let o=0;o<e.length;o++)t+=e[o].toString(16).padStart(2,"0");return t}function Jt(e,t){if(e.length!==t.length)return!1;let o=0;for(let n=0;n<e.length;n++)o|=e.charCodeAt(n)^t.charCodeAt(n);return o===0}function eo(e,t,o){if(!(e?.trim()&&t?.trim()&&o?.trim()))throw new Error("tenantId, chunkUid, and chunkHash must be non-empty strings.");if(e.includes("")||t.includes("")||o.includes(""))throw new Error("Parameters must not contain delimiter control characters.");let a=new TextEncoder().encode(`${e}${t}${o}`),s=new Uint8Array(pt.length+a.length);return s.set(pt,0),s.set(a,pt.length),ue(s)}function to(e){if(!e||e.length===0)return null;for(let o=0;o<e.length;o++)if(!(e[o]instanceof Uint8Array)||e[o].length!==32)throw new Error(`Leaf at index ${o} must be a 32-byte Uint8Array.`);let t=[...e];for(;t.length>1;){let o=[];for(let n=0;n<t.length-1;n+=2){let a=t[n],s=t[n+1],u=new Uint8Array(Oe.length+a.length+s.length);u.set(Oe,0),u.set(a,Oe.length),u.set(s,Oe.length+a.length),o.push(ue(u))}t.length%2===1&&o.push(t[t.length-1]),t=o}return _e(t[0])}function mt(e,t){try{if(!e||typeof e!="object"||e.algorithm!=="SHA-256"||t?.expectedTenantId&&e.tenantId!==t.expectedTenantId||!Array.isArray(e.leaves)||e.leafCount!==e.leaves.length||e.leafCount===0)return!1;if(t?.expectedCitations){if(t.expectedCitations.length!==e.leaves.length)return!1;for(let a=0;a<e.leaves.length;a++)if(t.expectedCitations[a].chunkUid!==e.leaves[a].chunkUid||t.expectedCitations[a].chunkHash!==e.leaves[a].chunkHash)return!1}for(let a=0;a<e.leaves.length;a++){let s=e.leaves[a];if(!s||typeof s!="object"||!s.chunkUid||!s.chunkHash||a>0&&e.leaves[a].chunkUid<=e.leaves[a-1].chunkUid)return!1}let o=[];for(let a of e.leaves)o.push(eo(e.tenantId,a.chunkUid,a.chunkHash));let n=to(o);return!n||typeof e.merkleRoot!="string"?!1:Jt(n,e.merkleRoot)}catch{return!1}}var ft=class extends K{async search(t,o){let n=$e.parse(t),a=o?{tenant_id:P.TenantIdSchema.parse(o)}:void 0,s=await this.request("/ai/governance/search","POST",n,a);return Qe.parse(s)}async answer(t,o){let n=Ze.parse(t),a=o?{tenant_id:P.TenantIdSchema.parse(o)}:void 0,s=await this.request("/ai/governance/answer","POST",n,a);return Xe.parse(s)}verifyCitationProof(t,o){return mt(t,o)}};var oo=require("@aiquants/enrichment-core");var yt=class extends K{async simulate(t,o){let n=We.parse(t),a=o?{tenant_id:oo.TenantIdSchema.parse(o)}:void 0,s=await this.request("/ai/governance/simulate","POST",n,a);return Je.parse(s)}};var E=require("zod");var me=require("@aiquants/enrichment-core"),c=require("zod");var Et=c.z.enum(["UNRESOLVED_ACTIVE","UNRESOLVED_CLEARED","RESOLVED","IGNORED"]),Rt=50,gt=2e3,co=Object.freeze([9,10,13,32,12288]),hn=new Set(co),so=e=>ve(e,hn),lo=1e3,An=g.min(me.SYSTEM_PARAMETER_RANGES.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min+1),uo=c.z.enum(["TIE_GROUP_OVER_LIMIT"]),Ne=c.z.object({policyCategory:v,authorityTier:D,validFromUtc:x,reason:uo,tieGroupSize:An}).strict(),po=c.z.enum(["NEVER_DETECTED","DETECTION_INCOMPLETE_FOR_READABLE"]),Cn={UNRESOLVED_ACTIVE:g,UNRESOLVED_CLEARED:g,RESOLVED:g,IGNORED:g},mo=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("measured"),values:c.z.object(Cn).strict(),partial:c.z.boolean()}).strict(),c.z.object({kind:c.z.literal("unmeasured"),reason:po}).strict()]),fo=c.z.object({lastDetectedAt:S,nextTransitionAt:S.nullable(),isStale:c.z.boolean(),failedGroups:c.z.array(Ne).nullable(),tieGroupLimit:be.nullable()}).strict().superRefine((e,t)=>{e.failedGroups===null!=(e.tieGroupLimit===null)&&i(t,["tieGroupLimit"],"failedGroups and tieGroupLimit are present together or absent together")}),yo=c.z.object({canDecide:c.z.boolean(),rowScopeApplied:c.z.boolean()}).strict(),ho=c.z.object({counts:mo,detection:fo.nullable(),viewer:yo}).strict().superRefine((e,t)=>{let{counts:o,detection:n,viewer:a}=e,s=o.kind==="unmeasured"&&o.reason==="NEVER_DETECTED";n===null!==s&&i(t,["detection"],"The detection is absent exactly when the counts were never detected"),n!==null&&a.rowScopeApplied!==(n.failedGroups===null)&&i(t,["detection","failedGroups"],"Only an operator whose row scope is unrestricted sees the failed groups"),o.kind==="unmeasured"&&o.reason==="DETECTION_INCOMPLETE_FOR_READABLE"&&!a.rowScopeApplied&&i(t,["counts","reason"],"Only an operator with a row scope has counts left unmeasured by a failed group");let u=n===null?null:n.failedGroups,m=u!==null&&u.length>0;o.kind==="measured"&&o.partial!==m&&i(t,["counts","partial"],"The counts are partial exactly when failed groups are shown")}),no=c.z.object({metadataId:p,approvalStatus:b,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict(),oe=c.z.object({policyCategory:v,authorityTier:D,validFromUtc:x,source:no,target:no}).strict().superRefine((e,t)=>{se(e.source.metadataId,e.target.metadataId,["target","metadataId"],t);for(let o of["source","target"])e[o].validFromUtc!==e.validFromUtc&&i(t,[o,"validFromUtc"],"Both documents share the effective date of the rank"),e[o].approvalStatus!==b.enum.APPROVED&&i(t,[o,"approvalStatus"],"Both documents were approved when the pair was detected")}),Ao=e=>_e(ue(new TextEncoder().encode((0,me.canonicalJson)(e))));function Sn(e){return(0,me.canonicalJson)(oe.parse(e))}function En(e){return Ao(oe.parse(e))}var ro=e=>({metadataId:e.metadataId,approvalStatus:e.approvalStatus,validFromUtc:e.validFromUtc,validUntilUtc:e.validUntilUtc,txCreatedAtUtc:e.txCreatedAtUtc,txSupersededAtUtc:e.txSupersededAtUtc});function Rn(e,t,o){if(t.authorityTier!==o.authorityTier)throw new RangeError(`A pair shares one rank: metadataId ${t.metadataId} has tier ${t.authorityTier} and ${o.metadataId} tier ${o.authorityTier}`);return oe.parse({policyCategory:e,authorityTier:t.authorityTier,validFromUtc:t.validFromUtc,source:ro(t),target:ro(o)})}var Dt=c.z.object({conflictId:p,state:Et,severity:ie,policyCategory:v,authorityTier:D,source:L,target:L,lastDetectedAt:S,clearedAt:S.nullable()}).strict().superRefine((e,t)=>{se(e.source.metadataId,e.target.metadataId,["target","metadataId"],t),e.severity!==nt[e.authorityTier]&&i(t,["severity"],"The severity is the one the tier derives"),e.state==="UNRESOLVED_ACTIVE"&&e.clearedAt!==null&&i(t,["clearedAt"],"A pair still detected has not been cleared"),e.state==="UNRESOLVED_CLEARED"&&e.clearedAt===null&&i(t,["clearedAt"],"A pair no longer detected carries when it was cleared")}),gn=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("unmeasured")}).strict(),c.z.object({kind:c.z.literal("page"),rows:c.z.array(Dt).max(Rt),nextAfter:p.nullable()}).strict()]).superRefine((e,t)=>{e.kind==="page"&&W(e.rows.map(o=>o.conflictId),e.nextAfter,t)}),Dn=c.z.object({state:Et,severity:ie.optional(),after:p.optional(),limit:X(Rt)}).strict(),B=c.z.enum(["verdict","reason"]),ht=c.z.enum(["REQUIRED","MALFORMED","EMPTY","TOO_LONG"]),In=e=>ce(e)?e.length===0?"EMPTY":e.length>gt?"TOO_LONG":null:"MALFORMED",fe=c.z.string().superRefine((e,t)=>{e!==so(e)&&i(t,[],"A stored reason has no blank character at either end");let o=In(e);o!==null&&i(t,[],`A reason is well-formed text of 1 to ${gt} UTF-16 code units`,o)}),Co=c.z.object({status:Z.exclude(["UNRESOLVED"]),prevailingMetadataId:p.nullable(),reason:fe,decidedBy:k,decidedAt:S,factsChangedSinceDecision:c.z.boolean()}).strict(),ao=c.z.object({document:L,authority:O}).strict(),xn=Object.keys(L.shape),Ue=(e,t,o,n,a)=>{for(let s of xn)e[s]!==t[s]&&i(a,[...o,s],n)},So=c.z.object({conflict:Dt,conflictSummary:c.z.string().min(1).max(lo),facts:oe,factsHash:z,relatedReadablePairs:g,source:ao,target:ao,decision:Co.nullable()}).strict().superRefine((e,t)=>{let{conflict:o,facts:n,decision:a}=e;for(let m of["source","target"])n[m].metadataId!==o[m].metadataId&&i(t,["facts",m,"metadataId"],"The facts name the documents of the pair"),Ue(e[m].document,o[m],[m,"document"],"The detail shows the pair's document as the pair's row does",t),Ue(e[m].authority.document,o[m],[m,"authority","document"],"The authority row shows the pair's document as the pair's row does",t);(n.policyCategory!==o.policyCategory||n.authorityTier!==o.authorityTier)&&i(t,["facts"],"The facts carry the subject and the tier of the pair");let s=oe.safeParse(n);s.success&&e.factsHash!==Ao(s.data)&&i(t,["factsHash"],"The facts hash is the SHA-256 of the canonical text of the facts shown");let u=o.state==="UNRESOLVED_ACTIVE"||o.state==="UNRESOLVED_CLEARED";if(a===null){u||i(t,["decision"],"A resolved or ignored pair carries its decision");return}a.status!==o.state&&i(t,["decision","status"],"An unresolved pair carries no decision, and a decided pair's state is its verdict"),Te(a.status==="RESOLVED",a.prevailingMetadataId,o.source.metadataId,o.target.metadataId,["decision","prevailingMetadataId"],t)}),At=c.z.enum(["RESOLVE","IGNORE"]),Ct=c.z.string().transform(so).pipe(fe),St={conflictId:p,expectedFactsHash:z},Eo=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal(At.enum.RESOLVE),...St,prevailingMetadataId:p,reason:Ct}).strict(),c.z.object({kind:c.z.literal(At.enum.IGNORE),...St,reason:Ct}).strict()]),io=c.z.custom(ge),bn=c.z.object({kind:io,...St,prevailingMetadataId:io,reason:Ct}).strict(),Ro=c.z.enum(["SUBJECT_WRITE_FAILED","DETECTION_FAILED"]),go=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("detected"),summary:ho}).strict(),c.z.object({kind:c.z.literal("busy")}).strict(),c.z.object({kind:c.z.literal("failed"),reason:Ro,failedCategory:v.nullable(),rowScopeApplied:c.z.boolean()}).strict()]).superRefine((e,t)=>{e.kind==="detected"&&e.summary.detection===null&&i(t,["summary","detection"],"A completed detection leaves its state"),e.kind==="failed"&&e.failedCategory!==null!=(e.reason==="SUBJECT_WRITE_FAILED"&&!e.rowScopeApplied)&&i(t,["failedCategory"],"The failed category is shown exactly for a subject that failed, to an operator whose row scope is unrestricted")}),vn=(e,t,o)=>{e.replaces===null?i(o,["row","replaces"],"An approved row that replaces a row the operator reads names it"):Ue(t.document,e.replaces,["replaced","document"],"The replaced row is the one the approved row names",o),t.supersededBy===null?i(o,["replaced","supersededBy"],"The replaced row names the approved document version as its successor"):Ue(t.supersededBy,e.document,["replaced","supersededBy"],"The replaced row names the approved document version as its successor",o),t.approvalStatus!==b.enum.APPROVED&&i(o,["replaced","approvalStatus"],"The replaced row stays approved"),t.policyCategory!==e.policyCategory&&i(o,["replaced","policyCategory"],"The replaced row shares the approved row's category");let n=t.validUntil===null?null:U(t.validUntil,e.validFrom);(t.validUntil===null||n!==null&&n>0)&&i(o,["replaced","validUntil"],"The replaced row ends no later than the approved row takes effect")},Tn=c.z.discriminatedUnion("kind",[c.z.object({kind:I.extract(["create","update"]),row:O,detection:c.z.null()}).strict(),c.z.object({kind:I.extract(["approve","withdraw","deprecate"]),row:O,detection:go,replaced:O.nullable()}).strict(),c.z.object({kind:I.extract(["delete"]),row:c.z.null(),detection:c.z.null()}).strict()]).superRefine((e,t)=>{e.row!==null&&(e.row.approvalStatus!==$[e.kind].after&&i(t,["row","approvalStatus"],"The row has the approval status the command leaves"),"replaced"in e&&(e.replaced!==null!==(e.kind==="approve"&&e.row.replacesAnother)?i(t,["replaced"],"An approval of a row that replaces another carries that row, and no other result does"):e.replaced!==null&&vn(e.row,e.replaced,t)))}),It=c.z.discriminatedUnion("path",[c.z.object({path:c.z.literal(B.enum.verdict),reason:ht.extract(["REQUIRED"])}).strict(),c.z.object({path:c.z.literal(B.enum.reason),reason:ht}).strict()]),pe=c.z.enum(["BODY_INVALID","FIELD_INVALID","ID_MISMATCH","PREVAILING_NOT_IN_PAIR","NOT_FOUND","STALE","DEADLOCK","DEPLOYMENT_DISABLED"]),wn=xe()(c.z.discriminatedUnion("code",[c.z.object({code:pe.extract(["FIELD_INVALID"]),fieldErrors:c.z.array(It).min(1)}).strict(),c.z.object({code:pe.extract(["STALE"]),detail:So}).strict(),c.z.object({code:pe.exclude(["FIELD_INVALID","STALE"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&Ie(e.fieldErrors.map(o=>o.path),B.options,t)})),Pn={schema:Eo,fieldOfKey:new Map([["kind",B.enum.verdict],["prevailingMetadataId",B.enum.verdict],["reason",B.enum.reason]]),fields:B.options,fieldError:It,skippedIssues:e=>{if(!ge(e.kind))return[];let t=bn.safeParse(e);return t.success?[]:t.error.issues}};function On(e){return De(e,Pn)}var _n=c.z.object({intent:c.z.literal("detect")}).strict(),Do=pe.extract(["BODY_INVALID","DEPLOYMENT_DISABLED"]),Un=c.z.object({code:Do}).strict();var Fe=E.z.enum(["document_authority.command","policy_conflict.decided","policy_conflict.detected","governance.maintenance"]),Io=E.z.object({validUntil:S.nullable(),supersededByMetadataId:p.nullable()}).strict(),xo=E.z.object({metadataId:p,before:Io,after:Io}).strict(),bo={authorityTier:D,policyCategory:v,validFrom:S,validUntil:S.nullable(),approvedBy:k.nullable(),withdrawnBy:k.nullable(),replacesMetadataId:p.nullable(),supersededByMetadataId:p.nullable()},Nn=Object.keys(bo),xt=E.z.object({approvalStatus:b,...bo,replaced:xo.optional()}).strict().superRefine((e,t)=>{le(e.validFrom,e.validUntil,["validUntil"],t),we(e.approvalStatus,e.approvedBy!==null,e.withdrawnBy!==null,{approval:["approvedBy"],withdrawal:["withdrawnBy"]},t)}),vo=E.z.object({deleted:E.z.literal(!0)}).strict(),bt=E.z.object({resolutionStatus:Z,sourceMetadataId:p,targetMetadataId:p,prevailingMetadataId:p.nullable(),arbitrationDecision:fe.nullable(),factsHash:z}).strict().superRefine((e,t)=>{se(e.sourceMetadataId,e.targetMetadataId,["targetMetadataId"],t),Te(e.resolutionStatus==="RESOLVED",e.prevailingMetadataId,e.sourceMetadataId,e.targetMetadataId,["prevailingMetadataId"],t),e.resolutionStatus==="UNRESOLVED"!=(e.arbitrationDecision===null)&&i(t,["arbitrationDecision"],"A decided pair carries its reason, and an unresolved pair none")}),To=Ne.omit({reason:!0}),wo=E.z.object({policyCategory:v,asOf:x,inserted:g,factsChanged:g,reopened:g,cleared:g,activePairs:g,failedGroups:E.z.array(To)}).strict().superRefine((e,t)=>{e.inserted+e.factsChanged+e.reopened+e.cleared===0&&e.failedGroups.length===0&&i(t,[],"A detection is recorded only for a subject it changed"),e.inserted+e.factsChanged>e.activePairs&&i(t,["factsChanged"],"The pairs whose facts changed are among the standing pairs the detection did not insert"),e.inserted+e.reopened>e.activePairs&&i(t,["reopened"],"The pairs that reappeared are among the standing pairs the detection did not insert"),e.failedGroups.forEach((o,n)=>{o.policyCategory!==e.policyCategory&&i(t,["failedGroups",n,"policyCategory"],"A subject records its own failed groups")})}),Fn=E.z.object({event:E.z.literal(Fe.enum["document_authority.command"]),command:I,authorityId:p,metadataId:p,before:xt.nullable(),after:E.z.union([xt,vo]),rowVersionBefore:te.nullable(),rowVersionAfter:te.nullable()}).strict(),Ln=E.z.object({event:E.z.literal(Fe.enum["policy_conflict.decided"]),conflictId:p,before:bt,after:bt}).strict(),Mn=E.z.object({event:E.z.literal(Fe.enum["policy_conflict.detected"]),before:E.z.null(),after:wo}).strict(),zn=(e,t,o)=>{if((e.command==="approve"&&t.replacesMetadataId!==null)!==(t.replaced!==void 0)&&i(o,["after","replaced"],"An approval that replaces another row records that row's change, and nothing else does"),t.replaced===void 0)return;let{replaced:a}=t;a.metadataId!==t.replacesMetadataId&&i(o,["after","replaced","metadataId"],"The replaced row is the one the approved row names"),a.before.supersededByMetadataId!==null&&i(o,["after","replaced","before","supersededByMetadataId"],"The replaced row was not yet superseded"),a.after.supersededByMetadataId!==e.metadataId&&i(o,["after","replaced","after","supersededByMetadataId"],"The replaced row is superseded by the approved document version");let s=a.before.validUntil,u=s===null?null:U(s,t.validFrom),m=s===null?t.validFrom:u===null?null:u===1?t.validFrom:s,f=a.after.validUntil===null||m===null?null:U(a.after.validUntil,m);(a.after.validUntil===null||f!==null&&f!==0)&&i(o,["after","replaced","after","validUntil"],"The replaced row ends when the approved row takes effect, unless it had already ended")},kn=(e,t,o)=>{let n=t[e],a=o[e];if(n===a)return!0;if(e!=="validFrom"&&e!=="validUntil"||typeof n!="string"||typeof a!="string")return!1;let s=U(n,a);return s===null||s===0},Gn=(e,t,o,n)=>{let a=$[e.command],s=Nn.filter(u=>!a.changes.includes(u));for(let u of s)a.before===null?o!==null&&o[u]!==null&&i(n,["after",u],`The ${e.command} command leaves ${u} empty`):t!==null&&o!==null&&!kn(u,t,o)&&i(n,["after",u],`The ${e.command} command keeps ${u}`)},jn=(e,t)=>{let o=$[e.command],{before:n}=e,a="deleted"in e.after?null:e.after;o.before===null!=(n===null)?i(t,["before"],"Only a create records no image before the command"):n!==null&&n.approvalStatus!==o.before&&i(t,["before","approvalStatus"],`The ${e.command} command finds a row whose status is ${o.before}`),o.after===null!=(a===null)?i(t,["after"],"Only a delete records the deleted marker after the command"):a!==null&&a.approvalStatus!==o.after&&i(t,["after","approvalStatus"],`The ${e.command} command leaves a row whose status is ${o.after}`),o.before===null!=(e.rowVersionBefore===null)&&i(t,["rowVersionBefore"],"The row version before is recorded exactly when a row existed before the command"),o.after===null!=(e.rowVersionAfter===null)&&i(t,["rowVersionAfter"],"The row version after is recorded exactly when a row exists after the command"),n?.replaced!==void 0&&i(t,["before","replaced"],"Only the image after an approval records the replaced row's change"),o.requiresNeverApproved&&n!==null&&n.approvedBy!==null&&i(t,["before","approvedBy"],`The ${e.command} command applies only to a row never approved`),o.requiresNoReplacement&&n!==null&&n.replacesMetadataId!==null&&i(t,["before","replacesMetadataId"],`The ${e.command} command applies only to a row that replaces no other; a replacing approval ends by deprecation`);for(let[s,u]of[["before",n],["after",a]])u!==null&&u.replacesMetadataId===e.metadataId&&i(t,[s,"replacesMetadataId"],"A row does not replace its own document version");Gn(e,n,a,t),a!==null&&zn(e,a,t)},Vn=(e,t)=>{let{before:o,after:n}=e;o.resolutionStatus!=="UNRESOLVED"&&i(t,["before","resolutionStatus"],"A decision is taken on an unresolved pair"),n.resolutionStatus==="UNRESOLVED"&&i(t,["after","resolutionStatus"],"A decision resolves or ignores the pair"),(n.sourceMetadataId!==o.sourceMetadataId||n.targetMetadataId!==o.targetMetadataId)&&i(t,["after"],"A decision keeps the pair"),n.factsHash!==o.factsHash&&i(t,["after","factsHash"],"A decision records the facts it was taken on")},qn=E.z.discriminatedUnion("event",[Fn,Ln,Mn]).superRefine((e,t)=>{e.event==="document_authority.command"?jn(e,t):e.event==="policy_conflict.decided"&&Vn(e,t)});var H=require("@aiquants/enrichment-core"),d=require("zod");var Tt=d.z.enum(["ENABLE_VECTOR_SEARCH","ENABLE_VECTOR_INDEXING","ENABLE_GRAPH_SEARCH","ENABLE_GRAPH_INDEXING","ENABLE_ASSET_EXTRACTION","ENABLE_MEDIA_ANALYSIS","ENABLE_OCR","ENABLE_DYNAMIC_CLASSIFIER_RULES","ENABLE_SEMANTIC_CACHE","ENABLE_CONTEXT_COMPRESSION","ENABLE_MULTI_AGENT_SWARM","ENABLE_AUTONOMOUS_ONTOLOGY","ENABLE_MERKLE_CITATION_PROOF","ENABLE_REALTIME_CDC_INGESTION","ENABLE_COLPALI_IMAGE_INDEXING"]),Bn=d.z.object({tenantId:H.TenantIdSchema,flagKey:Tt,isEnabled:d.z.boolean(),description:d.z.string(),updatedBy:d.z.string(),updatedAt:d.z.string()}),Po=d.z.enum(["ocr","enrichment","transcription","asset_extraction","vector_indexing","graph_indexing","governance_answer"]),Hn=["ocr","enrichment","transcription","governance_answer"],Yn=d.z.object({tenantId:H.TenantIdSchema,confidentialityLevel:Re.ConfidentialityLevelSchema,capability:Po,isEnabled:d.z.boolean(),allowCloudProvider:d.z.boolean(),promptKey:d.z.string().min(1).nullable(),description:d.z.string().nullable(),updatedBy:d.z.string(),updatedAt:d.z.string()}),$n=d.z.object({tenantId:H.TenantIdSchema,parameterKey:d.z.string().min(1),parameterValue:d.z.string(),dataType:d.z.enum(["string","int","float","bool","json"]),description:d.z.string(),isSecret:d.z.boolean(),updatedBy:d.z.string(),updatedAt:d.z.string()}),Kn=d.z.object({tenantId:H.TenantIdSchema,promptKey:d.z.string().min(1),promptVersion:d.z.number().int(),promptTemplate:d.z.string(),provider:d.z.string(),modelName:d.z.string(),temperature:d.z.number(),maxTokens:d.z.number().int(),isSystemPrompt:d.z.boolean(),description:d.z.string(),updatedBy:d.z.string(),updatedAt:d.z.string()}),Qn=d.z.object({tenantId:H.TenantIdSchema,flagKey:Tt,isEnabled:d.z.boolean(),updatedBy:d.z.string().min(1)}),Zn=d.z.object({tenantId:H.TenantIdSchema,parameterKey:d.z.string().min(1),parameterValue:d.z.string(),updatedBy:d.z.string().min(1)}),Xn=d.z.object({tenantId:H.TenantIdSchema,promptKey:d.z.string().min(1),promptTemplate:d.z.string().min(1,"promptTemplate must not be empty"),provider:d.z.string().min(1),modelName:d.z.string().min(1),temperature:d.z.number().min(0).max(2).optional(),maxTokens:d.z.number().int().positive().optional(),updatedBy:d.z.string().min(1)}),Oo=d.z.union([d.z.string(),d.z.number(),d.z.boolean(),d.z.null()]),vt=d.z.lazy(()=>d.z.union([Oo,d.z.array(vt),d.z.record(vt)]));0&&(module.exports={AUTHORITY_CANDIDATE_PAGE_LIMIT_MAX,AUTHORITY_SEARCH_QUERY_MAX_LENGTH,AUTHORITY_SEARCH_QUERY_MIN_LENGTH,ApprovalStatusSchema,AuthoritativeSourceSchema,AuthorityCandidatePageSchema,AuthorityCandidateQuerySchema,AuthorityCandidateSchema,AuthoritySearchTextSchema,AuthorityTierSchema,BaseGovernanceClient,CLOUD_CAPABLE_CAPABILITIES,CitationProofLeafSchema,CitationProofSchema,ConfidentialityCapabilityPolicyDtoSchema,ConfidentialityLevelSchema,DOCUMENT_AUTHORITY_COMMAND_RULES,DOCUMENT_AUTHORITY_PAGE_LIMIT_MAX,DeletedDocumentAuthorityEventImageSchema,DocumentAuthorityCommandBlockerSchema,DocumentAuthorityCommandFieldErrorSchema,DocumentAuthorityCommandFieldReasonSchema,DocumentAuthorityCommandFieldSchema,DocumentAuthorityCommandKindSchema,DocumentAuthorityCommandRejectionCodeSchema,DocumentAuthorityCommandRejectionSchema,DocumentAuthorityCommandResultSchema,DocumentAuthorityCommandSchema,DocumentAuthorityEventImageSchema,DocumentAuthorityPageQuerySchema,DocumentAuthorityPageSchema,DocumentAuthorityPageWithCategoriesSchema,DocumentAuthorityRowSchema,DocumentRefSchema,FailedTieGroupReasonSchema,FailedTieGroupSchema,FeatureFlagKeySchema,FileUriSchema,GovernanceAdminClient,GovernanceAnswerRequestSchema,GovernanceAnswerResponseSchema,GovernanceClient,GovernanceClientError,GovernanceSearchHitSchema,GovernanceSearchMetadataSchema,GovernanceSearchRequestSchema,GovernanceSearchResponseSchema,GovernanceSearchSnippetSchema,GovernanceSimulateCaseDiffSchema,GovernanceSimulateCaseScoresSchema,GovernanceSimulateRequestSchema,GovernanceSimulateResponseSchema,GovernanceSimulateScoresSchema,GovernedCapabilitySchema,JsonPrimitiveSchema,JsonValueSchema,KnowledgeGovernanceEventRecordSchema,KnowledgeGovernanceEventSchema,NormalizedPolicyCategorySchema,NormalizedScoreSchema,OPERATOR_IDENTIFIER_MAX_LENGTH,OffsetIsoInstantSchema,POLICY_CATEGORY_MAX_LENGTH,POLICY_CATEGORY_UNICODE_VERSION,POLICY_CATEGORY_WHITESPACE_CODE_POINTS,POLICY_CONFLICT_DECISION_REASON_BLANK_CODE_POINTS,POLICY_CONFLICT_DECISION_REASON_MAX_LENGTH,POLICY_CONFLICT_PAGE_LIMIT_MAX,POLICY_CONFLICT_SUMMARY_MAX_LENGTH,PolicyCategoryRejectionSchema,PolicyCategorySchema,PolicyConflictCountsSchema,PolicyConflictDecisionEventImageSchema,PolicyConflictDecisionFieldErrorSchema,PolicyConflictDecisionFieldReasonSchema,PolicyConflictDecisionFieldSchema,PolicyConflictDecisionKindSchema,PolicyConflictDecisionRejectionCodeSchema,PolicyConflictDecisionRejectionSchema,PolicyConflictDecisionSchema,PolicyConflictDetailSchema,PolicyConflictDetectedEventImageSchema,PolicyConflictDetectedFailedGroupSchema,PolicyConflictDetectionFailureReasonSchema,PolicyConflictDetectionOutcomeSchema,PolicyConflictDetectionRequestRejectionCodeSchema,PolicyConflictDetectionRequestRejectionSchema,PolicyConflictDetectionRequestSchema,PolicyConflictDetectionStateSchema,PolicyConflictFactsSchema,PolicyConflictPageQuerySchema,PolicyConflictPageSchema,PolicyConflictRefSchema,PolicyConflictResolutionStatusSchema,PolicyConflictRowSchema,PolicyConflictSeveritySchema,PolicyConflictStateSchema,PolicyConflictSummarySchema,PolicyConflictUnmeasuredReasonSchema,PolicyConflictViewerSchema,PromptTemplateDtoSchema,REPLACEABLE_AUTHORITY_PAGE_LIMIT_MAX,RecordedPolicyConflictDecisionSchema,RelatedDecisionSchema,ReplaceableAuthorityPageSchema,ReplaceableAuthorityQuerySchema,ReplacedAuthorityChangeSchema,RowVersionSchema,SEVERITY_BY_TIER,Sha256HexSchema,StoredDecisionReasonSchema,SystemFeatureFlagDtoSchema,SystemParameterDtoSchema,TenantIdSchema,UpdateFeatureFlagRequestSchema,UpdateParameterRequestSchema,UpdatePromptTemplateRequestSchema,UtcInstantSchema,VerifiedCitationSchema,bytesToHex,canonicalPolicyConflictFactsJson,checkDocumentAuthorityCommand,checkPolicyConflictDecision,computeCitationLeafHash,computeCitationMerkleRoot,constantTimeCompare,documentAuthorityCommandBlocker,equalRankGroups,isDocumentAuthorityCommandAvailable,isEligibleAuthority,normalizePolicyCategory,offsetIsoOfUtcInstant,parseUtcInstant,policyConflictFactsHash,policyConflictFactsOf,sha256,tiePairs,utcInstantOfOffsetIso,verifyCitationProof});
|
package/dist/index.d.cts
CHANGED
|
@@ -11478,6 +11478,7 @@ declare const FeatureFlagKeySchema: z.ZodEnum<[
|
|
|
11478
11478
|
"ENABLE_GRAPH_INDEXING",
|
|
11479
11479
|
"ENABLE_ASSET_EXTRACTION",
|
|
11480
11480
|
"ENABLE_MEDIA_ANALYSIS",
|
|
11481
|
+
"ENABLE_OCR",
|
|
11481
11482
|
"ENABLE_DYNAMIC_CLASSIFIER_RULES",
|
|
11482
11483
|
"ENABLE_SEMANTIC_CACHE",
|
|
11483
11484
|
"ENABLE_CONTEXT_COMPRESSION",
|
|
@@ -11497,6 +11498,7 @@ declare const SystemFeatureFlagDtoSchema: z.ZodObject<{
|
|
|
11497
11498
|
"ENABLE_GRAPH_INDEXING",
|
|
11498
11499
|
"ENABLE_ASSET_EXTRACTION",
|
|
11499
11500
|
"ENABLE_MEDIA_ANALYSIS",
|
|
11501
|
+
"ENABLE_OCR",
|
|
11500
11502
|
"ENABLE_DYNAMIC_CLASSIFIER_RULES",
|
|
11501
11503
|
"ENABLE_SEMANTIC_CACHE",
|
|
11502
11504
|
"ENABLE_CONTEXT_COMPRESSION",
|
|
@@ -11514,14 +11516,14 @@ declare const SystemFeatureFlagDtoSchema: z.ZodObject<{
|
|
|
11514
11516
|
tenantId: string;
|
|
11515
11517
|
updatedBy: string;
|
|
11516
11518
|
updatedAt: string;
|
|
11517
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11519
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11518
11520
|
isEnabled: boolean;
|
|
11519
11521
|
description: string;
|
|
11520
11522
|
}, {
|
|
11521
11523
|
tenantId: string;
|
|
11522
11524
|
updatedBy: string;
|
|
11523
11525
|
updatedAt: string;
|
|
11524
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11526
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11525
11527
|
isEnabled: boolean;
|
|
11526
11528
|
description: string;
|
|
11527
11529
|
}>;
|
|
@@ -11668,6 +11670,7 @@ declare const UpdateFeatureFlagRequestSchema: z.ZodObject<{
|
|
|
11668
11670
|
"ENABLE_GRAPH_INDEXING",
|
|
11669
11671
|
"ENABLE_ASSET_EXTRACTION",
|
|
11670
11672
|
"ENABLE_MEDIA_ANALYSIS",
|
|
11673
|
+
"ENABLE_OCR",
|
|
11671
11674
|
"ENABLE_DYNAMIC_CLASSIFIER_RULES",
|
|
11672
11675
|
"ENABLE_SEMANTIC_CACHE",
|
|
11673
11676
|
"ENABLE_CONTEXT_COMPRESSION",
|
|
@@ -11682,12 +11685,12 @@ declare const UpdateFeatureFlagRequestSchema: z.ZodObject<{
|
|
|
11682
11685
|
}, "strip", z.ZodTypeAny, {
|
|
11683
11686
|
tenantId: string;
|
|
11684
11687
|
updatedBy: string;
|
|
11685
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11688
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11686
11689
|
isEnabled: boolean;
|
|
11687
11690
|
}, {
|
|
11688
11691
|
tenantId: string;
|
|
11689
11692
|
updatedBy: string;
|
|
11690
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11693
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11691
11694
|
isEnabled: boolean;
|
|
11692
11695
|
}>;
|
|
11693
11696
|
type UpdateFeatureFlagRequestInput = z.input<typeof UpdateFeatureFlagRequestSchema>;
|
package/dist/index.d.ts
CHANGED
|
@@ -11478,6 +11478,7 @@ declare const FeatureFlagKeySchema: z.ZodEnum<[
|
|
|
11478
11478
|
"ENABLE_GRAPH_INDEXING",
|
|
11479
11479
|
"ENABLE_ASSET_EXTRACTION",
|
|
11480
11480
|
"ENABLE_MEDIA_ANALYSIS",
|
|
11481
|
+
"ENABLE_OCR",
|
|
11481
11482
|
"ENABLE_DYNAMIC_CLASSIFIER_RULES",
|
|
11482
11483
|
"ENABLE_SEMANTIC_CACHE",
|
|
11483
11484
|
"ENABLE_CONTEXT_COMPRESSION",
|
|
@@ -11497,6 +11498,7 @@ declare const SystemFeatureFlagDtoSchema: z.ZodObject<{
|
|
|
11497
11498
|
"ENABLE_GRAPH_INDEXING",
|
|
11498
11499
|
"ENABLE_ASSET_EXTRACTION",
|
|
11499
11500
|
"ENABLE_MEDIA_ANALYSIS",
|
|
11501
|
+
"ENABLE_OCR",
|
|
11500
11502
|
"ENABLE_DYNAMIC_CLASSIFIER_RULES",
|
|
11501
11503
|
"ENABLE_SEMANTIC_CACHE",
|
|
11502
11504
|
"ENABLE_CONTEXT_COMPRESSION",
|
|
@@ -11514,14 +11516,14 @@ declare const SystemFeatureFlagDtoSchema: z.ZodObject<{
|
|
|
11514
11516
|
tenantId: string;
|
|
11515
11517
|
updatedBy: string;
|
|
11516
11518
|
updatedAt: string;
|
|
11517
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11519
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11518
11520
|
isEnabled: boolean;
|
|
11519
11521
|
description: string;
|
|
11520
11522
|
}, {
|
|
11521
11523
|
tenantId: string;
|
|
11522
11524
|
updatedBy: string;
|
|
11523
11525
|
updatedAt: string;
|
|
11524
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11526
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11525
11527
|
isEnabled: boolean;
|
|
11526
11528
|
description: string;
|
|
11527
11529
|
}>;
|
|
@@ -11668,6 +11670,7 @@ declare const UpdateFeatureFlagRequestSchema: z.ZodObject<{
|
|
|
11668
11670
|
"ENABLE_GRAPH_INDEXING",
|
|
11669
11671
|
"ENABLE_ASSET_EXTRACTION",
|
|
11670
11672
|
"ENABLE_MEDIA_ANALYSIS",
|
|
11673
|
+
"ENABLE_OCR",
|
|
11671
11674
|
"ENABLE_DYNAMIC_CLASSIFIER_RULES",
|
|
11672
11675
|
"ENABLE_SEMANTIC_CACHE",
|
|
11673
11676
|
"ENABLE_CONTEXT_COMPRESSION",
|
|
@@ -11682,12 +11685,12 @@ declare const UpdateFeatureFlagRequestSchema: z.ZodObject<{
|
|
|
11682
11685
|
}, "strip", z.ZodTypeAny, {
|
|
11683
11686
|
tenantId: string;
|
|
11684
11687
|
updatedBy: string;
|
|
11685
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11688
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11686
11689
|
isEnabled: boolean;
|
|
11687
11690
|
}, {
|
|
11688
11691
|
tenantId: string;
|
|
11689
11692
|
updatedBy: string;
|
|
11690
|
-
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11693
|
+
flagKey: "ENABLE_VECTOR_SEARCH" | "ENABLE_VECTOR_INDEXING" | "ENABLE_GRAPH_SEARCH" | "ENABLE_GRAPH_INDEXING" | "ENABLE_ASSET_EXTRACTION" | "ENABLE_MEDIA_ANALYSIS" | "ENABLE_OCR" | "ENABLE_DYNAMIC_CLASSIFIER_RULES" | "ENABLE_SEMANTIC_CACHE" | "ENABLE_CONTEXT_COMPRESSION" | "ENABLE_MULTI_AGENT_SWARM" | "ENABLE_AUTONOMOUS_ONTOLOGY" | "ENABLE_MERKLE_CITATION_PROOF" | "ENABLE_REALTIME_CDC_INGESTION" | "ENABLE_COLPALI_IMAGE_INDEXING";
|
|
11691
11694
|
isEnabled: boolean;
|
|
11692
11695
|
}>;
|
|
11693
11696
|
type UpdateFeatureFlagRequestInput = z.input<typeof UpdateFeatureFlagRequestSchema>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConfidentialityLevelSchema as uo,FileUriSchema as po,QUARANTINED_CONFIDENTIALITY_LEVEL as mo}from"@aiquants/enrichment-core";import{z as l}from"zod";import{z as $t}from"zod";var Kt=/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.\d{7}$/,Pe=1,$e=9999,Ye=7,Oe=60,Qt=14*Oe,Zt=$t.string().datetime({offset:!0}),Xt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|([+-])(\d{2}):(\d{2}))$/,Wt=(e,t,o)=>{let n=new Date(0);return n.setUTCFullYear(e,t-1,o),e>=Pe&&e<=$e&&n.getUTCMonth()===t-1&&n.getUTCDate()===o},Ue=e=>{let t=Kt.exec(e);if(t===null)return null;let[o,n,a,s,u,m]=t.slice(1,7).map(Number);return Wt(o,n,a)&&s<=23&&u<=59&&m<=59?e:null},H=(e,t)=>String(e).padStart(t,"0"),J=e=>{let t=Zt.safeParse(e).success?Xt.exec(e):null;if(t===null)return null;let[,o,n,a,s,u,m,f="",R="+",b="00",v="00"]=t,h=(R==="-"?-1:1)*(Number(b)*Oe+Number(v));if(Number(o)<Pe||f.length>Ye||Number(v)>=Oe||Math.abs(h)>Qt)return null;let y=new Date(0);y.setUTCFullYear(Number(o),Number(n)-1,Number(a)),y.setUTCHours(Number(s),Number(u)-h,Number(m),0);let C=y.getUTCFullYear();if(C<Pe||C>$e)return null;let z=`${H(C,4)}-${H(y.getUTCMonth()+1,2)}-${H(y.getUTCDate(),2)}`,P=`${H(y.getUTCHours(),2)}:${H(y.getUTCMinutes(),2)}:${H(y.getUTCSeconds(),2)}`;return`${z} ${P}.${f.padEnd(Ye,"0")}`},O=(e,t)=>{let o=J(e),n=J(t);return o===null||n===null?null:o<n?-1:o>n?1:0};import{SYSTEM_PARAMETER_RANGES as rt}from"@aiquants/enrichment-core";import{z as N}from"zod";import{ConfidentialityLevelSchema as Jt,FileUriSchema as eo,TenantIdSchema as de}from"@aiquants/enrichment-core";import{z as r}from"zod";import{ConfidentialityLevelSchema as nt}from"@aiquants/enrichment-core";var Ze=r.object({query:r.string().min(1,"Search query must not be empty"),policyCategory:r.string().optional(),includeHistoricalRevisions:r.boolean().optional(),maxAuthorityTier:r.union([r.literal(1),r.literal(2),r.literal(3),r.literal(4),r.literal(5)]).optional(),limit:r.number().int().positive().optional()}),to=r.object({text:r.string(),citationText:r.string(),chunkHash:r.string(),chunkIndex:r.number().int().nonnegative(),parentChunkUid:r.string().optional(),clauseIdentifier:r.string().optional(),breadcrumbPath:r.array(r.string()).optional(),page:r.number().int().optional(),sheetName:r.string().optional(),slideIndex:r.number().int().optional(),timestampSec:r.number().optional(),score:r.number()}),oo=r.object({decisionId:r.string(),title:r.string(),approvedBy:r.string()}),D=r.union([r.literal(1),r.literal(2),r.literal(3),r.literal(4),r.literal(5)]),T=r.enum(["DRAFT","APPROVED","DEPRECATED"]),ue=r.enum(["LOW","MEDIUM","HIGH","CRITICAL"]),ee=r.enum(["UNRESOLVED","RESOLVED","IGNORED"]),Xe=100,no=r.object({metadataId:r.number().int(),fileUri:eo,fileName:r.string(),documentTitle:r.string(),authorityTier:D.nullable(),validFrom:r.string().nullable(),validUntil:r.string().nullable(),isCurrentlyAuthoritative:r.boolean(),confidentialityLevel:Jt,snippets:r.array(to),relatedDecisions:r.array(oo).optional(),policyWarning:r.string().optional()}),Le=r.object({searchMode:r.enum(["tri_store","sql_vector","sql_keyword_degraded"]),qualityTier:r.enum(["HIGH_TRI_STORE","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),isDegraded:r.boolean(),degradationReason:r.string().nullable(),circuitBreakerStatus:r.record(r.enum(["CLOSED","OPEN","HALF_OPEN","HEALTHY"])),executionTimeMs:r.number().nonnegative()}),We=r.object({hits:r.array(no),tiers:r.object({sql:r.boolean(),vector:r.boolean(),graph:r.boolean()}),masked:r.boolean(),searchMetadata:Le}),Je=r.object({question:r.string().min(1,"Question must not be empty"),asOf:r.string().optional(),asOfTx:r.string().optional()}),Ke=r.object({metadataId:r.number().int(),documentTitle:r.string(),authorityTier:D,approvalStatus:T,validFrom:r.string(),validUntil:r.string().nullable(),isCurrentlyAuthoritative:r.boolean()}),ro=r.object({conflictId:r.number().int(),sourceMetadataId:r.number().int(),targetMetadataId:r.number().int(),conflictSummary:r.string(),severity:ue,resolutionStatus:ee}),ao=r.object({chunkUid:r.string().uuid("chunkUid must be a valid UUID"),metadataId:r.number().int(),documentTitle:r.string(),clauseIdentifier:r.string(),breadcrumbPath:r.array(r.string()),exactQuotedText:r.string(),chunkHash:r.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),authorityTier:D,isVerified:r.boolean()}),j=r.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),io=r.object({chunkUid:r.string().uuid("chunkUid must be a valid UUID"),chunkHash:j}),co=r.object({algorithm:r.literal("SHA-256"),merkleRoot:j,leafCount:r.number().int().positive(),leaves:r.array(io).min(1),tenantId:de,scopeDigest:j,asOf:r.string().datetime(),asOfTx:r.string().datetime(),generatedAt:r.string().datetime(),signature:r.string().min(1,"Signature must not be empty")}),et=r.object({answer:r.string(),authoritative:r.array(Ke),superseded:r.array(Ke),conflicts:r.array(ro),verifiedCitations:r.array(ao),citationProof:co.nullable(),isFullyGrounded:r.boolean(),requiresHumanArbitration:r.boolean(),tiers:r.object({sql:r.boolean(),vector:r.boolean(),graph:r.boolean()}),searchMetadata:Le}),tt=r.object({promptOverrides:r.record(r.string()).optional(),parameterOverrides:r.record(r.union([r.string(),r.number(),r.boolean()])).optional(),strategyOverrides:r.record(r.record(r.union([r.string(),r.number(),r.boolean()]))).optional(),intentTypes:r.array(r.enum(["SET","DIFF","PATH","NEGATION","COUNT"])).optional()}),_e=r.number().min(0).max(1),Fe=r.object({contextRelevance:_e,groundedness:_e,answerRelevance:_e}),Ne=Fe.extend({meanAnswerChars:r.number().nonnegative(),meanLatencyMs:r.number().nonnegative()}),Qe=r.object({caseId:r.string(),intentType:r.enum(["SET","DIFF","PATH","NEGATION","COUNT"]),beforeScores:Fe,afterScores:Fe}),ot=r.object({simulationId:r.string(),evaluatedCount:r.number().int().nonnegative(),before:Ne,after:Ne,delta:Ne,regressions:r.array(Qe),improvements:r.array(Qe),searchMetadata:Le});var i=(e,t,o,n)=>{e.addIssue(n===void 0?{code:N.ZodIssueCode.custom,path:[...t],message:o}:{code:N.ZodIssueCode.custom,path:[...t],message:o,params:{reason:n}})},pe=e=>e==null||e==="",at=e=>{let t=N.unknown().superRefine((o,n)=>e(n)).safeParse(void 0);return t.success?[]:t.error.issues},me=(e,t)=>{let o=t.schema.safeParse(e);if(o.success)return{ok:!0,value:o.data};let n={ok:!1,rejection:{code:"BODY_INVALID"}},a=f=>f.path.length===0?void 0:t.fieldOfKey.get(f.path[0]);if(!o.error.issues.every(f=>a(f)!==void 0))return n;let s=e,u=[];for(let f of[...o.error.issues,...t.skippedIssues(s)]){let R=a(f);if(R===void 0)return n;let b=f.code===N.ZodIssueCode.custom?f.params?.reason:void 0,v=b??(pe(s[f.path[0]])?"REQUIRED":"MALFORMED"),h=t.fieldError.safeParse({path:R,reason:v});if(!h.success){if(b!==void 0)throw new RangeError(`A rule reported ${JSON.stringify(b)} at ${JSON.stringify(R)}, which the form does not pair`);return n}u.push(h.data)}return{ok:!1,rejection:{code:"FIELD_INVALID",fieldErrors:t.fields.flatMap(f=>{let R=u.find(b=>b.path===f);return R===void 0?[]:[R]})}}},fe=(e,t,o)=>{e.forEach((n,a)=>{a>0&&t.indexOf(n)<=t.indexOf(e[a-1])&&i(o,["fieldErrors",a],"Each field appears once, in the form's order")})},ye=()=>e=>e,p=N.number().int().positive().max(Number.MAX_SAFE_INTEGER),g=N.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),he=N.number().int().min(rt.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min).max(rt.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.max),Y=e=>N.number().int().min(1).max(e),F=N.string().min(1).max(Xe),so=/\p{Cs}/u,te=e=>!so.test(e),Ae=(e,t)=>{let o=0,n=e.length;for(;o<n&&t.has(e.charCodeAt(o));)o+=1;for(;n>o&&t.has(e.charCodeAt(n-1));)n-=1;return e.slice(o,n)},$=(e,t,o)=>{e.forEach((n,a)=>{a>0&&n>=e[a-1]&&i(o,["rows",a],"Rows are in strictly descending order of their key")}),t!==null&&t!==e.at(-1)&&i(o,["nextAfter"],"nextAfter is absent or the key of the last row")},oe=(e,t,o,n)=>{e>=t&&i(n,o,"The source governs the smaller document version (source < target)")},Ce=(e,t,o,n,a,s)=>{(e?!(t===o||t===n):t!==null)&&i(s,a,"A resolution records one document of the pair as prevailing, and only a resolution does")},lo=(e,t)=>{let o=t===null?null:O(t,e);return o!==null&&o<=0},ne=(e,t,o,n)=>{lo(e,t)&&i(n,o,"validUntil must be after validFrom","NOT_AFTER_VALID_FROM")},Se=(e,t,o,n,a)=>{e!=="DRAFT"&&!t&&i(a,n.approval,"An APPROVED or DEPRECATED row carries its approval"),o&&!t&&i(a,n.withdrawal,"Only an approval once given can be withdrawn"),e==="DRAFT"&&t&&!o&&i(a,n.withdrawal,"A DRAFT row that was approved carries its withdrawal")};function fo(e){let t=Ue(e);if(t===null)throw new RangeError(`Not a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff: ${JSON.stringify(e)}`);return t}var x=l.string().transform((e,t)=>{let o=Ue(e);return o===null?(t.addIssue({code:l.ZodIssueCode.custom,message:"Must be a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff"}),l.NEVER):o});function On(e){let t=J(e);if(t===null)throw new RangeError(`Not an ISO 8601 instant with a UTC offset that datetimeoffset(7) can hold: ${JSON.stringify(e)}`);return t}var S=l.string().refine(e=>J(e)!==null,{message:"Must be an ISO 8601 instant yyyy-mm-ddThh:mi:ss[.f] with Z or a \xB1hh:mi offset within \xB114:00, at most seven fractional digits and a year between 0001 and 9999 both as written and in UTC"});function Un(e){let t=fo(e);return`${t.slice(0,10)}T${t.slice(11)}Z`}var _n=l.object({metadataId:p,authorityTier:D,approvalStatus:T,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict();function yo(e,t,o){return e.approvalStatus===T.enum.APPROVED&&e.validFromUtc<=t&&(e.validUntilUtc===null||e.validUntilUtc>t)&&e.txCreatedAtUtc<=o&&(e.txSupersededAtUtc===null||e.txSupersededAtUtc>o)}var lt=(e,t)=>e.metadataId-t.metadataId,Me=e=>`${e.authorityTier} ${e.validFromUtc}`;function Nn(e,t,o){let n=new Set,a=new Map;for(let s of e){if(n.has(s.metadataId))throw new RangeError(`Two authority rows govern the same document version: metadataId ${s.metadataId}`);if(n.add(s.metadataId),!yo(s,t,o))continue;let u=Me(s),m=a.get(u);m===void 0?a.set(u,[s]):m.push(s)}return[...a.values()].filter(s=>s.length>=2).map(s=>[...s].sort(lt)).sort((s,u)=>s[0].metadataId-u[0].metadataId)}function Fn(e){let t=[...e].sort(lt);return t.forEach((o,n)=>{if(Me(o)!==Me(t[0]))throw new RangeError(`An equal-rank group mixes ranks: metadataId ${t[0].metadataId} and ${o.metadataId}`);if(n>0&&o.metadataId===t[n-1].metadataId)throw new RangeError(`An equal-rank group repeats a document version: metadataId ${o.metadataId}`)}),t.flatMap((o,n)=>t.slice(n+1).map(a=>[o,a]))}var dt=Object.freeze({1:"CRITICAL",2:"HIGH",3:"MEDIUM",4:"LOW",5:"LOW"}),ze=50,Ln="17.0",ut=l.enum(["MALFORMED","EMPTY","TOO_LONG"]),ho=Object.freeze([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]),pt=new Set(ho),Ao=e=>{let t=[],o=0;for(let n=0;n<=e.length;n+=1)(n===e.length||pt.has(e.charCodeAt(n)))&&(n>o&&t.push(e.slice(o,n)),o=n+1);return t.join(" ")};function mt(e){if(!te(e))return{ok:!1,reason:"MALFORMED"};let t=Ao(e.normalize("NFKC"));return t.length===0?{ok:!1,reason:"EMPTY"}:t.length>ze?{ok:!1,reason:"TOO_LONG"}:{ok:!0,value:t}}var Co=l.string().transform((e,t)=>{let o=mt(e);return o.ok?o.value:(i(t,[],`A policy category must be well-formed text of 1 to ${ze} UTF-16 code units after normalization`,o.reason),l.NEVER)}),w=l.string().refine(e=>{let t=mt(e);return t.ok&&t.value===e},{message:`A stored policy category must be well-formed, normalized (NFKC, single spaces, trimmed) and 1 to ${ze} UTF-16 code units`}),ft=50,yt=50,ht=50,it=2,So=200,Eo=e=>[...e].length,At=l.string().transform(e=>Ae(e,pt)).pipe(l.string().max(So).refine(te,{message:"A search text is well-formed text without an unpaired surrogate"}).refine(e=>Eo(e)>=it,{message:`A search text has at least ${it} characters (code points) once trimmed`})),ie=l.string().regex(/^[0-9a-f]{16}$/,"Must be a rowversion as 16 lowercase hexadecimal digits"),M=l.object({metadataId:p,fileName:l.string().min(1),fileUri:po,revision:l.number().int().min(1),isCurrent:l.boolean(),isDeleted:l.boolean(),confidentialityLevel:uo.exclude([mo])}).strict(),U=l.object({authorityId:p,document:M,authorityTier:D,policyCategory:w,validFrom:S,validUntil:S.nullable(),txCreatedAt:S,txSupersededAt:S.nullable(),approvalStatus:T,approvedBy:F.nullable(),approvedAt:S.nullable(),withdrawnBy:F.nullable(),withdrawnAt:S.nullable(),replaces:M.nullable(),supersededBy:M.nullable(),replacesAnother:l.boolean(),isSuperseded:l.boolean(),rowVersion:ie,updatedBy:F,updatedAt:S}).strict().superRefine((e,t)=>{ne(e.validFrom,e.validUntil,["validUntil"],t),e.approvedBy===null!=(e.approvedAt===null)&&i(t,["approvedAt"],"approvedBy and approvedAt are present together or absent together"),e.withdrawnBy===null!=(e.withdrawnAt===null)&&i(t,["withdrawnAt"],"withdrawnBy and withdrawnAt are present together or absent together"),Se(e.approvalStatus,e.approvedAt!==null,e.withdrawnAt!==null,{approval:["approvedAt"],withdrawal:["withdrawnAt"]},t);let o=e.approvedAt===null||e.withdrawnAt===null?null:O(e.withdrawnAt,e.approvedAt);e.approvalStatus==="DRAFT"&&o!==null&&o<0&&i(t,["withdrawnAt"],"A DRAFT row's withdrawal is no earlier than its approval");let n=e.txSupersededAt!==null;(e.approvalStatus==="DEPRECATED"?!n:n)&&i(t,["txSupersededAt"],"txSupersededAt is recorded exactly when the row is DEPRECATED"),e.replaces!==null&&!e.replacesAnother&&i(t,["replacesAnother"],"A row that names the document it replaces replaces another"),e.supersededBy!==null&&!e.isSuperseded&&i(t,["isSuperseded"],"A row that names its successor is superseded"),e.replaces?.metadataId===e.document.metadataId&&i(t,["replaces"],"A row does not replace its own document version"),e.supersededBy?.metadataId===e.document.metadataId&&i(t,["supersededBy"],"A row is not superseded by its own document version")}),Ro=l.object({rows:l.array(U).max(ft),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{$(e.rows.map(o=>o.authorityId),e.nextAfter,t)}),Mn=l.object({page:Ro,categories:l.array(w).nullable()}).strict().superRefine((e,t)=>{e.categories!==null&&new Set(e.categories).size!==e.categories.length&&i(t,["categories"],"Each category appears once")}),zn=l.object({rows:l.array(M).max(yt),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{$(e.rows.map(o=>o.metadataId),e.nextAfter,t),e.rows.forEach((o,n)=>{(!o.isCurrent||o.isDeleted)&&i(t,["rows",n],"A candidate is a current, undeleted document version")})}),kn=l.object({rows:l.array(U).max(ht),nextAfter:p.nullable(),totalCount:g}).strict().superRefine((e,t)=>{$(e.rows.map(o=>o.authorityId),e.nextAfter,t),e.totalCount<e.rows.length&&i(t,["totalCount"],"totalCount counts at least the rows of the page"),e.rows.forEach((o,n)=>{(o.approvalStatus!=="APPROVED"||o.isSuperseded)&&i(t,["rows",n],"A row a replacement may name is approved and not yet superseded"),o.policyCategory!==e.rows[0].policyCategory&&i(t,["rows",n,"policyCategory"],"The rows a replacement may name share one category")})}),Gn=l.object({status:T.optional(),category:w.optional(),after:p.optional(),limit:Y(ft)}).strict(),jn=l.object({q:At,after:p.optional(),limit:Y(yt)}).strict(),Vn=l.object({category:w,q:At.optional(),after:p.optional(),limit:Y(ht)}).strict(),I=l.enum(["create","update","approve","withdraw","deprecate","delete"]),L=l.enum(["authorityTier","policyCategory","validFrom","validUntil","replacesMetadataId"]),ct={authorityTier:D,policyCategory:Co,validFrom:S,validUntil:S.nullable(),replacesMetadataId:p.nullable()},st=Object.freeze([...L.options]),Q=Object.freeze({create:Object.freeze({before:null,after:"DRAFT",changes:st,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!1}),update:Object.freeze({before:"DRAFT",after:"DRAFT",changes:st,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1}),approve:Object.freeze({before:"DRAFT",after:"APPROVED",changes:Object.freeze(["approvedBy"]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!0}),withdraw:Object.freeze({before:"APPROVED",after:"DRAFT",changes:Object.freeze(["withdrawnBy"]),requiresNeverApproved:!1,requiresNoReplacement:!0,requiresCurrentDocument:!1,runsDetection:!0}),deprecate:Object.freeze({before:"APPROVED",after:"DEPRECATED",changes:Object.freeze([]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!0}),delete:Object.freeze({before:"DRAFT",after:null,changes:Object.freeze([]),requiresNeverApproved:!0,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1})}),qn=l.enum(["STATUS","APPROVED_ONCE","REPLACES_ANOTHER","DOCUMENT_NOT_CURRENT"]);function Ct(e,t){let o=Q[e];return t.approvalStatus!==o.before?"STATUS":o.requiresNeverApproved&&t.approvedAt!==null?"APPROVED_ONCE":o.requiresNoReplacement&&t.replacesAnother?"REPLACES_ANOTHER":o.requiresCurrentDocument&&(!t.document.isCurrent||t.document.isDeleted)?"DOCUMENT_NOT_CURRENT":null}function Bn(e,t){return Ct(e,t)===null}var re={authorityId:p,expectedRowVersion:ie},go=e=>e.kind===I.enum.create&&e.replacesMetadataId===e.metadataId&&p.safeParse(e.replacesMetadataId).success,St=(e,t)=>{let{validFrom:o,validUntil:n}=e;typeof o=="string"&&(n===null||typeof n=="string")&&ne(o,n,["validUntil"],t),go(e)&&i(t,["replacesMetadataId"],"A document version does not replace itself","SELF_REPLACEMENT")},Do=l.discriminatedUnion("kind",[l.object({kind:l.literal(I.enum.create),metadataId:p,...ct}).strict(),l.object({kind:l.literal(I.enum.update),...re,...ct}).strict(),l.object({kind:l.literal(I.enum.approve),...re}).strict(),l.object({kind:l.literal(I.enum.withdraw),...re}).strict(),l.object({kind:l.literal(I.enum.deprecate),...re}).strict(),l.object({kind:l.literal(I.enum.delete),...re}).strict()]).superRefine(St),ae=l.enum(["REQUIRED",...ut.options,"NOT_AFTER_VALID_FROM","SELF_REPLACEMENT"]),Et=l.discriminatedUnion("path",[l.object({path:l.literal(L.enum.authorityTier),reason:ae.extract(["REQUIRED","MALFORMED"])}).strict(),l.object({path:l.literal(L.enum.policyCategory),reason:ae.extract(["REQUIRED",...ut.options])}).strict(),l.object({path:l.literal(L.enum.validFrom),reason:ae.extract(["REQUIRED","MALFORMED"])}).strict(),l.object({path:l.literal(L.enum.validUntil),reason:ae.extract(["REQUIRED","MALFORMED","NOT_AFTER_VALID_FROM"])}).strict(),l.object({path:l.literal(L.enum.replacesMetadataId),reason:ae.extract(["REQUIRED","MALFORMED","SELF_REPLACEMENT"])}).strict()]),K=l.enum(["BODY_INVALID","FIELD_INVALID","NOT_FOUND","REPLACEMENT_NOT_FOUND","STALE","ALREADY_REGISTERED","RANK_LIMIT_REACHED","NOT_AFTER_REPLACED","DOCUMENT_NOT_CURRENT","DEADLOCK","DEPLOYMENT_DISABLED"]),Hn=ye()(l.discriminatedUnion("code",[l.object({code:K.extract(["FIELD_INVALID"]),fieldErrors:l.array(Et).min(1)}).strict(),l.object({code:K.extract(["STALE"]),row:U}).strict(),l.object({code:K.extract(["ALREADY_REGISTERED"]),row:U}).strict(),l.object({code:K.extract(["DOCUMENT_NOT_CURRENT"]),row:U}).strict(),l.object({code:K.extract(["RANK_LIMIT_REACHED"]),rowScopeApplied:l.boolean(),limit:he.nullable()}).strict(),l.object({code:K.exclude(["FIELD_INVALID","STALE","ALREADY_REGISTERED","DOCUMENT_NOT_CURRENT","RANK_LIMIT_REACHED"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&fe(e.fieldErrors.map(o=>o.path),L.options,t),e.code==="ALREADY_REGISTERED"&&(!e.row.document.isCurrent||e.row.document.isDeleted)&&i(t,["row","document"],"The registered row's document version is current and not deleted, as the create requires"),e.code==="DOCUMENT_NOT_CURRENT"&&Ct("approve",e.row)!=="DOCUMENT_NOT_CURRENT"&&i(t,["row"],"The row is a DRAFT whose document version is no longer current or has been deleted"),e.code==="RANK_LIMIT_REACHED"&&e.limit===null!==e.rowScopeApplied&&i(t,["limit"],"The limit is shown exactly to an operator whose row scope is unrestricted")})),Io={schema:Do,fieldOfKey:new Map(L.options.map(e=>[e,e])),fields:L.options,fieldError:Et,skippedIssues:e=>at(t=>St(e,t))};function Yn(e){return me(e,Io)}var V=class extends Error{statusCode;responseBody;parsedBody;constructor(t,o,n,a){super(t),this.name="GovernanceClientError",this.statusCode=o,this.responseBody=n,this.parsedBody=a}},Z=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for GovernanceClient.");let o=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey){let n;try{n=new URL(o)}catch{throw new Error(`Invalid baseUrl format: ${t.baseUrl}`)}if(n.protocol==="http:"){let a=n.hostname.toLowerCase();if(!(a==="localhost"||a==="127.0.0.1"||a==="[::1]"||a==="::1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.")}}this.baseUrl=o,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,o,n,a,s){let u=new URL(t.startsWith("/")?t.slice(1):t,`${this.baseUrl}/`);if(a)for(let[h,y]of Object.entries(a))y!=null&&y.trim().length>0&&u.searchParams.append(h,y);let m=u.toString(),f={Accept:"application/json"};this.apiKey&&(f.Authorization=`Bearer ${this.apiKey}`),n!==void 0&&(f["Content-Type"]="application/json");let R=new AbortController,b=setTimeout(()=>R.abort(),this.timeoutMs),v=R.signal;s&&(v=AbortSignal.any([R.signal,s]));try{let h=await this.fetchFn(m,{method:o,headers:f,body:n!==void 0?JSON.stringify(n):void 0,signal:v}),y=await h.text();if(!h.ok){let C;try{C=JSON.parse(y)}catch{}throw new V(`API request failed with status ${h.status}: ${y}`,h.status,y,C)}if(y.trim().length===0)return;try{return JSON.parse(y)}catch(C){let z=C.message;throw new V(`Failed to parse response JSON from ${m}: ${z}`,h.status,y)}}catch(h){if(h instanceof V)throw h;let y=h instanceof Error?h.message:String(h);throw new V(`Network request failed for ${o} ${m}: ${y}`,0,"")}finally{clearTimeout(b)}}};var ke=new Uint8Array([0]),Ee=new Uint8Array([1]),xo=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function _(e,t){return e>>>t|e<<32-t}function Re(e){let t=1779033703,o=3144134277,n=1013904242,a=2773480762,s=1359893119,u=2600822924,m=528734635,f=1541459225,R=e.length,b=R*8,v=(R+8>>6)+1<<6,h=new Uint8Array(v);h.set(e),h[R]=128;let y=new DataView(h.buffer,h.byteOffset,h.byteLength);y.setUint32(v-4,b>>>0,!1),y.setUint32(v-8,Math.floor(b/4294967296),!1);let C=new Uint32Array(64);for(let xe=0;xe<v;xe+=64){for(let A=0;A<16;A++)C[A]=y.getUint32(xe+A*4,!1);for(let A=16;A<64;A++){let Te=_(C[A-15],7)^_(C[A-15],18)^C[A-15]>>>3,we=_(C[A-2],17)^_(C[A-2],19)^C[A-2]>>>10;C[A]=C[A-16]+Te+C[A-7]+we>>>0}let k=t,X=o,W=n,be=a,G=s,se=u,le=m,ve=f;for(let A=0;A<64;A++){let Te=_(G,6)^_(G,11)^_(G,25),we=G&se^~G&le,He=ve+Te+we+xo[A]+C[A]>>>0,Bt=_(k,2)^_(k,13)^_(k,22),Ht=k&X^k&W^X&W,Yt=Bt+Ht>>>0;ve=le,le=se,se=G,G=be+He>>>0,be=W,W=X,X=k,k=He+Yt>>>0}t=t+k>>>0,o=o+X>>>0,n=n+W>>>0,a=a+be>>>0,s=s+G>>>0,u=u+se>>>0,m=m+le>>>0,f=f+ve>>>0}let z=new Uint8Array(32),P=new DataView(z.buffer,z.byteOffset,z.byteLength);return P.setUint32(0,t,!1),P.setUint32(4,o,!1),P.setUint32(8,n,!1),P.setUint32(12,a,!1),P.setUint32(16,s,!1),P.setUint32(20,u,!1),P.setUint32(24,m,!1),P.setUint32(28,f,!1),z}function Ge(e){let t="";for(let o=0;o<e.length;o++)t+=e[o].toString(16).padStart(2,"0");return t}function bo(e,t){if(e.length!==t.length)return!1;let o=0;for(let n=0;n<e.length;n++)o|=e.charCodeAt(n)^t.charCodeAt(n);return o===0}function vo(e,t,o){if(!(e?.trim()&&t?.trim()&&o?.trim()))throw new Error("tenantId, chunkUid, and chunkHash must be non-empty strings.");if(e.includes("")||t.includes("")||o.includes(""))throw new Error("Parameters must not contain delimiter control characters.");let a=new TextEncoder().encode(`${e}${t}${o}`),s=new Uint8Array(ke.length+a.length);return s.set(ke,0),s.set(a,ke.length),Re(s)}function To(e){if(!e||e.length===0)return null;for(let o=0;o<e.length;o++)if(!(e[o]instanceof Uint8Array)||e[o].length!==32)throw new Error(`Leaf at index ${o} must be a 32-byte Uint8Array.`);let t=[...e];for(;t.length>1;){let o=[];for(let n=0;n<t.length-1;n+=2){let a=t[n],s=t[n+1],u=new Uint8Array(Ee.length+a.length+s.length);u.set(Ee,0),u.set(a,Ee.length),u.set(s,Ee.length+a.length),o.push(Re(u))}t.length%2===1&&o.push(t[t.length-1]),t=o}return Ge(t[0])}function Rt(e,t){try{if(!e||typeof e!="object"||e.algorithm!=="SHA-256"||t?.expectedTenantId&&e.tenantId!==t.expectedTenantId||!Array.isArray(e.leaves)||e.leafCount!==e.leaves.length||e.leafCount===0)return!1;if(t?.expectedCitations){if(t.expectedCitations.length!==e.leaves.length)return!1;for(let a=0;a<e.leaves.length;a++)if(t.expectedCitations[a].chunkUid!==e.leaves[a].chunkUid||t.expectedCitations[a].chunkHash!==e.leaves[a].chunkHash)return!1}for(let a=0;a<e.leaves.length;a++){let s=e.leaves[a];if(!s||typeof s!="object"||!s.chunkUid||!s.chunkHash||a>0&&e.leaves[a].chunkUid<=e.leaves[a-1].chunkUid)return!1}let o=[];for(let a of e.leaves)o.push(vo(e.tenantId,a.chunkUid,a.chunkHash));let n=To(o);return!n||typeof e.merkleRoot!="string"?!1:bo(n,e.merkleRoot)}catch{return!1}}var gt=class extends Z{async search(t,o){let n=Ze.parse(t),a=o?{tenant_id:de.parse(o)}:void 0,s=await this.request("/ai/governance/search","POST",n,a);return We.parse(s)}async answer(t,o){let n=Je.parse(t),a=o?{tenant_id:de.parse(o)}:void 0,s=await this.request("/ai/governance/answer","POST",n,a);return et.parse(s)}verifyCitationProof(t,o){return Rt(t,o)}};import{TenantIdSchema as wo}from"@aiquants/enrichment-core";var Dt=class extends Z{async simulate(t,o){let n=tt.parse(t),a=o?{tenant_id:wo.parse(o)}:void 0,s=await this.request("/ai/governance/simulate","POST",n,a);return ot.parse(s)}};import{z as E}from"zod";import{canonicalJson as Pt,SYSTEM_PARAMETER_RANGES as Po}from"@aiquants/enrichment-core";import{z as c}from"zod";var Ot=c.enum(["UNRESOLVED_ACTIVE","UNRESOLVED_CLEARED","RESOLVED","IGNORED"]),Ut=50,_t=2e3,Oo=Object.freeze([9,10,13,32,12288]),Uo=new Set(Oo),Nt=e=>Ae(e,Uo),_o=1e3,No=g.min(Po.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min+1),Fo=c.enum(["TIE_GROUP_OVER_LIMIT"]),qe=c.object({policyCategory:w,authorityTier:D,validFromUtc:x,reason:Fo,tieGroupSize:No}).strict(),Lo=c.enum(["NEVER_DETECTED","DETECTION_INCOMPLETE_FOR_READABLE"]),Mo={UNRESOLVED_ACTIVE:g,UNRESOLVED_CLEARED:g,RESOLVED:g,IGNORED:g},zo=c.discriminatedUnion("kind",[c.object({kind:c.literal("measured"),values:c.object(Mo).strict(),partial:c.boolean()}).strict(),c.object({kind:c.literal("unmeasured"),reason:Lo}).strict()]),ko=c.object({lastDetectedAt:S,nextTransitionAt:S.nullable(),isStale:c.boolean(),failedGroups:c.array(qe).nullable(),tieGroupLimit:he.nullable()}).strict().superRefine((e,t)=>{e.failedGroups===null!=(e.tieGroupLimit===null)&&i(t,["tieGroupLimit"],"failedGroups and tieGroupLimit are present together or absent together")}),Go=c.object({canDecide:c.boolean(),rowScopeApplied:c.boolean()}).strict(),jo=c.object({counts:zo,detection:ko.nullable(),viewer:Go}).strict().superRefine((e,t)=>{let{counts:o,detection:n,viewer:a}=e,s=o.kind==="unmeasured"&&o.reason==="NEVER_DETECTED";n===null!==s&&i(t,["detection"],"The detection is absent exactly when the counts were never detected"),n!==null&&a.rowScopeApplied!==(n.failedGroups===null)&&i(t,["detection","failedGroups"],"Only an operator whose row scope is unrestricted sees the failed groups"),o.kind==="unmeasured"&&o.reason==="DETECTION_INCOMPLETE_FOR_READABLE"&&!a.rowScopeApplied&&i(t,["counts","reason"],"Only an operator with a row scope has counts left unmeasured by a failed group");let u=n===null?null:n.failedGroups,m=u!==null&&u.length>0;o.kind==="measured"&&o.partial!==m&&i(t,["counts","partial"],"The counts are partial exactly when failed groups are shown")}),It=c.object({metadataId:p,approvalStatus:T,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict(),ce=c.object({policyCategory:w,authorityTier:D,validFromUtc:x,source:It,target:It}).strict().superRefine((e,t)=>{oe(e.source.metadataId,e.target.metadataId,["target","metadataId"],t);for(let o of["source","target"])e[o].validFromUtc!==e.validFromUtc&&i(t,[o,"validFromUtc"],"Both documents share the effective date of the rank"),e[o].approvalStatus!==T.enum.APPROVED&&i(t,[o,"approvalStatus"],"Both documents were approved when the pair was detected")}),Ft=e=>Ge(Re(new TextEncoder().encode(Pt(e))));function ur(e){return Pt(ce.parse(e))}function pr(e){return Ft(ce.parse(e))}var xt=e=>({metadataId:e.metadataId,approvalStatus:e.approvalStatus,validFromUtc:e.validFromUtc,validUntilUtc:e.validUntilUtc,txCreatedAtUtc:e.txCreatedAtUtc,txSupersededAtUtc:e.txSupersededAtUtc});function mr(e,t,o){if(t.authorityTier!==o.authorityTier)throw new RangeError(`A pair shares one rank: metadataId ${t.metadataId} has tier ${t.authorityTier} and ${o.metadataId} tier ${o.authorityTier}`);return ce.parse({policyCategory:e,authorityTier:t.authorityTier,validFromUtc:t.validFromUtc,source:xt(t),target:xt(o)})}var Lt=c.object({conflictId:p,state:Ot,severity:ue,policyCategory:w,authorityTier:D,source:M,target:M,lastDetectedAt:S,clearedAt:S.nullable()}).strict().superRefine((e,t)=>{oe(e.source.metadataId,e.target.metadataId,["target","metadataId"],t),e.severity!==dt[e.authorityTier]&&i(t,["severity"],"The severity is the one the tier derives"),e.state==="UNRESOLVED_ACTIVE"&&e.clearedAt!==null&&i(t,["clearedAt"],"A pair still detected has not been cleared"),e.state==="UNRESOLVED_CLEARED"&&e.clearedAt===null&&i(t,["clearedAt"],"A pair no longer detected carries when it was cleared")}),fr=c.discriminatedUnion("kind",[c.object({kind:c.literal("unmeasured")}).strict(),c.object({kind:c.literal("page"),rows:c.array(Lt).max(Ut),nextAfter:p.nullable()}).strict()]).superRefine((e,t)=>{e.kind==="page"&&$(e.rows.map(o=>o.conflictId),e.nextAfter,t)}),yr=c.object({state:Ot,severity:ue.optional(),after:p.optional(),limit:Y(Ut)}).strict(),q=c.enum(["verdict","reason"]),bt=c.enum(["REQUIRED","MALFORMED","EMPTY","TOO_LONG"]),Vo=e=>te(e)?e.length===0?"EMPTY":e.length>_t?"TOO_LONG":null:"MALFORMED",Ie=c.string().superRefine((e,t)=>{e!==Nt(e)&&i(t,[],"A stored reason has no blank character at either end");let o=Vo(e);o!==null&&i(t,[],`A reason is well-formed text of 1 to ${_t} UTF-16 code units`,o)}),qo=c.object({status:ee.exclude(["UNRESOLVED"]),prevailingMetadataId:p.nullable(),reason:Ie,decidedBy:F,decidedAt:S,factsChangedSinceDecision:c.boolean()}).strict(),vt=c.object({document:M,authority:U}).strict(),Bo=Object.keys(M.shape),De=(e,t,o,n,a)=>{for(let s of Bo)e[s]!==t[s]&&i(a,[...o,s],n)},Ho=c.object({conflict:Lt,conflictSummary:c.string().min(1).max(_o),facts:ce,factsHash:j,relatedReadablePairs:g,source:vt,target:vt,decision:qo.nullable()}).strict().superRefine((e,t)=>{let{conflict:o,facts:n,decision:a}=e;for(let m of["source","target"])n[m].metadataId!==o[m].metadataId&&i(t,["facts",m,"metadataId"],"The facts name the documents of the pair"),De(e[m].document,o[m],[m,"document"],"The detail shows the pair's document as the pair's row does",t),De(e[m].authority.document,o[m],[m,"authority","document"],"The authority row shows the pair's document as the pair's row does",t);(n.policyCategory!==o.policyCategory||n.authorityTier!==o.authorityTier)&&i(t,["facts"],"The facts carry the subject and the tier of the pair");let s=ce.safeParse(n);s.success&&e.factsHash!==Ft(s.data)&&i(t,["factsHash"],"The facts hash is the SHA-256 of the canonical text of the facts shown");let u=o.state==="UNRESOLVED_ACTIVE"||o.state==="UNRESOLVED_CLEARED";if(a===null){u||i(t,["decision"],"A resolved or ignored pair carries its decision");return}a.status!==o.state&&i(t,["decision","status"],"An unresolved pair carries no decision, and a decided pair's state is its verdict"),Ce(a.status==="RESOLVED",a.prevailingMetadataId,o.source.metadataId,o.target.metadataId,["decision","prevailingMetadataId"],t)}),Tt=c.enum(["RESOLVE","IGNORE"]),je=c.string().transform(Nt).pipe(Ie),Ve={conflictId:p,expectedFactsHash:j},Yo=c.discriminatedUnion("kind",[c.object({kind:c.literal(Tt.enum.RESOLVE),...Ve,prevailingMetadataId:p,reason:je}).strict(),c.object({kind:c.literal(Tt.enum.IGNORE),...Ve,reason:je}).strict()]),wt=c.custom(pe),$o=c.object({kind:wt,...Ve,prevailingMetadataId:wt,reason:je}).strict(),Ko=c.enum(["SUBJECT_WRITE_FAILED","DETECTION_FAILED"]),Qo=c.discriminatedUnion("kind",[c.object({kind:c.literal("detected"),summary:jo}).strict(),c.object({kind:c.literal("busy")}).strict(),c.object({kind:c.literal("failed"),reason:Ko,failedCategory:w.nullable(),rowScopeApplied:c.boolean()}).strict()]).superRefine((e,t)=>{e.kind==="detected"&&e.summary.detection===null&&i(t,["summary","detection"],"A completed detection leaves its state"),e.kind==="failed"&&e.failedCategory!==null!=(e.reason==="SUBJECT_WRITE_FAILED"&&!e.rowScopeApplied)&&i(t,["failedCategory"],"The failed category is shown exactly for a subject that failed, to an operator whose row scope is unrestricted")}),Zo=(e,t,o)=>{e.replaces===null?i(o,["row","replaces"],"An approved row that replaces a row the operator reads names it"):De(t.document,e.replaces,["replaced","document"],"The replaced row is the one the approved row names",o),t.supersededBy===null?i(o,["replaced","supersededBy"],"The replaced row names the approved document version as its successor"):De(t.supersededBy,e.document,["replaced","supersededBy"],"The replaced row names the approved document version as its successor",o),t.approvalStatus!==T.enum.APPROVED&&i(o,["replaced","approvalStatus"],"The replaced row stays approved"),t.policyCategory!==e.policyCategory&&i(o,["replaced","policyCategory"],"The replaced row shares the approved row's category");let n=t.validUntil===null?null:O(t.validUntil,e.validFrom);(t.validUntil===null||n!==null&&n>0)&&i(o,["replaced","validUntil"],"The replaced row ends no later than the approved row takes effect")},hr=c.discriminatedUnion("kind",[c.object({kind:I.extract(["create","update"]),row:U,detection:c.null()}).strict(),c.object({kind:I.extract(["approve","withdraw","deprecate"]),row:U,detection:Qo,replaced:U.nullable()}).strict(),c.object({kind:I.extract(["delete"]),row:c.null(),detection:c.null()}).strict()]).superRefine((e,t)=>{e.row!==null&&(e.row.approvalStatus!==Q[e.kind].after&&i(t,["row","approvalStatus"],"The row has the approval status the command leaves"),"replaced"in e&&(e.replaced!==null!==(e.kind==="approve"&&e.row.replacesAnother)?i(t,["replaced"],"An approval of a row that replaces another carries that row, and no other result does"):e.replaced!==null&&Zo(e.row,e.replaced,t)))}),Mt=c.discriminatedUnion("path",[c.object({path:c.literal(q.enum.verdict),reason:bt.extract(["REQUIRED"])}).strict(),c.object({path:c.literal(q.enum.reason),reason:bt}).strict()]),ge=c.enum(["BODY_INVALID","FIELD_INVALID","ID_MISMATCH","PREVAILING_NOT_IN_PAIR","NOT_FOUND","STALE","DEADLOCK","DEPLOYMENT_DISABLED"]),Ar=ye()(c.discriminatedUnion("code",[c.object({code:ge.extract(["FIELD_INVALID"]),fieldErrors:c.array(Mt).min(1)}).strict(),c.object({code:ge.extract(["STALE"]),detail:Ho}).strict(),c.object({code:ge.exclude(["FIELD_INVALID","STALE"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&fe(e.fieldErrors.map(o=>o.path),q.options,t)})),Xo={schema:Yo,fieldOfKey:new Map([["kind",q.enum.verdict],["prevailingMetadataId",q.enum.verdict],["reason",q.enum.reason]]),fields:q.options,fieldError:Mt,skippedIssues:e=>{if(!pe(e.kind))return[];let t=$o.safeParse(e);return t.success?[]:t.error.issues}};function Cr(e){return me(e,Xo)}var Sr=c.object({intent:c.literal("detect")}).strict(),Wo=ge.extract(["BODY_INVALID","DEPLOYMENT_DISABLED"]),Er=c.object({code:Wo}).strict();var Be=E.enum(["document_authority.command","policy_conflict.decided","policy_conflict.detected","governance.maintenance"]),zt=E.object({validUntil:S.nullable(),supersededByMetadataId:p.nullable()}).strict(),Jo=E.object({metadataId:p,before:zt,after:zt}).strict(),jt={authorityTier:D,policyCategory:w,validFrom:S,validUntil:S.nullable(),approvedBy:F.nullable(),withdrawnBy:F.nullable(),replacesMetadataId:p.nullable(),supersededByMetadataId:p.nullable()},en=Object.keys(jt),kt=E.object({approvalStatus:T,...jt,replaced:Jo.optional()}).strict().superRefine((e,t)=>{ne(e.validFrom,e.validUntil,["validUntil"],t),Se(e.approvalStatus,e.approvedBy!==null,e.withdrawnBy!==null,{approval:["approvedBy"],withdrawal:["withdrawnBy"]},t)}),tn=E.object({deleted:E.literal(!0)}).strict(),Gt=E.object({resolutionStatus:ee,sourceMetadataId:p,targetMetadataId:p,prevailingMetadataId:p.nullable(),arbitrationDecision:Ie.nullable(),factsHash:j}).strict().superRefine((e,t)=>{oe(e.sourceMetadataId,e.targetMetadataId,["targetMetadataId"],t),Ce(e.resolutionStatus==="RESOLVED",e.prevailingMetadataId,e.sourceMetadataId,e.targetMetadataId,["prevailingMetadataId"],t),e.resolutionStatus==="UNRESOLVED"!=(e.arbitrationDecision===null)&&i(t,["arbitrationDecision"],"A decided pair carries its reason, and an unresolved pair none")}),on=qe.omit({reason:!0}),nn=E.object({policyCategory:w,asOf:x,inserted:g,factsChanged:g,reopened:g,cleared:g,activePairs:g,failedGroups:E.array(on)}).strict().superRefine((e,t)=>{e.inserted+e.factsChanged+e.reopened+e.cleared===0&&e.failedGroups.length===0&&i(t,[],"A detection is recorded only for a subject it changed"),e.inserted+e.factsChanged>e.activePairs&&i(t,["factsChanged"],"The pairs whose facts changed are among the standing pairs the detection did not insert"),e.inserted+e.reopened>e.activePairs&&i(t,["reopened"],"The pairs that reappeared are among the standing pairs the detection did not insert"),e.failedGroups.forEach((o,n)=>{o.policyCategory!==e.policyCategory&&i(t,["failedGroups",n,"policyCategory"],"A subject records its own failed groups")})}),rn=E.object({event:E.literal(Be.enum["document_authority.command"]),command:I,authorityId:p,metadataId:p,before:kt.nullable(),after:E.union([kt,tn]),rowVersionBefore:ie.nullable(),rowVersionAfter:ie.nullable()}).strict(),an=E.object({event:E.literal(Be.enum["policy_conflict.decided"]),conflictId:p,before:Gt,after:Gt}).strict(),cn=E.object({event:E.literal(Be.enum["policy_conflict.detected"]),before:E.null(),after:nn}).strict(),sn=(e,t,o)=>{if((e.command==="approve"&&t.replacesMetadataId!==null)!==(t.replaced!==void 0)&&i(o,["after","replaced"],"An approval that replaces another row records that row's change, and nothing else does"),t.replaced===void 0)return;let{replaced:a}=t;a.metadataId!==t.replacesMetadataId&&i(o,["after","replaced","metadataId"],"The replaced row is the one the approved row names"),a.before.supersededByMetadataId!==null&&i(o,["after","replaced","before","supersededByMetadataId"],"The replaced row was not yet superseded"),a.after.supersededByMetadataId!==e.metadataId&&i(o,["after","replaced","after","supersededByMetadataId"],"The replaced row is superseded by the approved document version");let s=a.before.validUntil,u=s===null?null:O(s,t.validFrom),m=s===null?t.validFrom:u===null?null:u===1?t.validFrom:s,f=a.after.validUntil===null||m===null?null:O(a.after.validUntil,m);(a.after.validUntil===null||f!==null&&f!==0)&&i(o,["after","replaced","after","validUntil"],"The replaced row ends when the approved row takes effect, unless it had already ended")},ln=(e,t,o)=>{let n=t[e],a=o[e];if(n===a)return!0;if(e!=="validFrom"&&e!=="validUntil"||typeof n!="string"||typeof a!="string")return!1;let s=O(n,a);return s===null||s===0},dn=(e,t,o,n)=>{let a=Q[e.command],s=en.filter(u=>!a.changes.includes(u));for(let u of s)a.before===null?o!==null&&o[u]!==null&&i(n,["after",u],`The ${e.command} command leaves ${u} empty`):t!==null&&o!==null&&!ln(u,t,o)&&i(n,["after",u],`The ${e.command} command keeps ${u}`)},un=(e,t)=>{let o=Q[e.command],{before:n}=e,a="deleted"in e.after?null:e.after;o.before===null!=(n===null)?i(t,["before"],"Only a create records no image before the command"):n!==null&&n.approvalStatus!==o.before&&i(t,["before","approvalStatus"],`The ${e.command} command finds a row whose status is ${o.before}`),o.after===null!=(a===null)?i(t,["after"],"Only a delete records the deleted marker after the command"):a!==null&&a.approvalStatus!==o.after&&i(t,["after","approvalStatus"],`The ${e.command} command leaves a row whose status is ${o.after}`),o.before===null!=(e.rowVersionBefore===null)&&i(t,["rowVersionBefore"],"The row version before is recorded exactly when a row existed before the command"),o.after===null!=(e.rowVersionAfter===null)&&i(t,["rowVersionAfter"],"The row version after is recorded exactly when a row exists after the command"),n?.replaced!==void 0&&i(t,["before","replaced"],"Only the image after an approval records the replaced row's change"),o.requiresNeverApproved&&n!==null&&n.approvedBy!==null&&i(t,["before","approvedBy"],`The ${e.command} command applies only to a row never approved`),o.requiresNoReplacement&&n!==null&&n.replacesMetadataId!==null&&i(t,["before","replacesMetadataId"],`The ${e.command} command applies only to a row that replaces no other; a replacing approval ends by deprecation`);for(let[s,u]of[["before",n],["after",a]])u!==null&&u.replacesMetadataId===e.metadataId&&i(t,[s,"replacesMetadataId"],"A row does not replace its own document version");dn(e,n,a,t),a!==null&&sn(e,a,t)},pn=(e,t)=>{let{before:o,after:n}=e;o.resolutionStatus!=="UNRESOLVED"&&i(t,["before","resolutionStatus"],"A decision is taken on an unresolved pair"),n.resolutionStatus==="UNRESOLVED"&&i(t,["after","resolutionStatus"],"A decision resolves or ignores the pair"),(n.sourceMetadataId!==o.sourceMetadataId||n.targetMetadataId!==o.targetMetadataId)&&i(t,["after"],"A decision keeps the pair"),n.factsHash!==o.factsHash&&i(t,["after","factsHash"],"A decision records the facts it was taken on")},Tr=E.discriminatedUnion("event",[rn,an,cn]).superRefine((e,t)=>{e.event==="document_authority.command"?un(e,t):e.event==="policy_conflict.decided"&&pn(e,t)});import{TenantIdSchema as B}from"@aiquants/enrichment-core";import{z as d}from"zod";var qt=d.enum(["ENABLE_VECTOR_SEARCH","ENABLE_VECTOR_INDEXING","ENABLE_GRAPH_SEARCH","ENABLE_GRAPH_INDEXING","ENABLE_ASSET_EXTRACTION","ENABLE_MEDIA_ANALYSIS","ENABLE_DYNAMIC_CLASSIFIER_RULES","ENABLE_SEMANTIC_CACHE","ENABLE_CONTEXT_COMPRESSION","ENABLE_MULTI_AGENT_SWARM","ENABLE_AUTONOMOUS_ONTOLOGY","ENABLE_MERKLE_CITATION_PROOF","ENABLE_REALTIME_CDC_INGESTION","ENABLE_COLPALI_IMAGE_INDEXING"]),_r=d.object({tenantId:B,flagKey:qt,isEnabled:d.boolean(),description:d.string(),updatedBy:d.string(),updatedAt:d.string()}),mn=d.enum(["ocr","enrichment","transcription","asset_extraction","vector_indexing","graph_indexing","governance_answer"]),Nr=["ocr","enrichment","transcription","governance_answer"],Fr=d.object({tenantId:B,confidentialityLevel:nt,capability:mn,isEnabled:d.boolean(),allowCloudProvider:d.boolean(),promptKey:d.string().min(1).nullable(),description:d.string().nullable(),updatedBy:d.string(),updatedAt:d.string()}),Lr=d.object({tenantId:B,parameterKey:d.string().min(1),parameterValue:d.string(),dataType:d.enum(["string","int","float","bool","json"]),description:d.string(),isSecret:d.boolean(),updatedBy:d.string(),updatedAt:d.string()}),Mr=d.object({tenantId:B,promptKey:d.string().min(1),promptVersion:d.number().int(),promptTemplate:d.string(),provider:d.string(),modelName:d.string(),temperature:d.number(),maxTokens:d.number().int(),isSystemPrompt:d.boolean(),description:d.string(),updatedBy:d.string(),updatedAt:d.string()}),zr=d.object({tenantId:B,flagKey:qt,isEnabled:d.boolean(),updatedBy:d.string().min(1)}),kr=d.object({tenantId:B,parameterKey:d.string().min(1),parameterValue:d.string(),updatedBy:d.string().min(1)}),Gr=d.object({tenantId:B,promptKey:d.string().min(1),promptTemplate:d.string().min(1,"promptTemplate must not be empty"),provider:d.string().min(1),modelName:d.string().min(1),temperature:d.number().min(0).max(2).optional(),maxTokens:d.number().int().positive().optional(),updatedBy:d.string().min(1)}),fn=d.union([d.string(),d.number(),d.boolean(),d.null()]),Vt=d.lazy(()=>d.union([fn,d.array(Vt),d.record(Vt)]));export{yt as AUTHORITY_CANDIDATE_PAGE_LIMIT_MAX,So as AUTHORITY_SEARCH_QUERY_MAX_LENGTH,it as AUTHORITY_SEARCH_QUERY_MIN_LENGTH,T as ApprovalStatusSchema,Ke as AuthoritativeSourceSchema,zn as AuthorityCandidatePageSchema,jn as AuthorityCandidateQuerySchema,_n as AuthorityCandidateSchema,At as AuthoritySearchTextSchema,D as AuthorityTierSchema,Z as BaseGovernanceClient,Nr as CLOUD_CAPABLE_CAPABILITIES,io as CitationProofLeafSchema,co as CitationProofSchema,Fr as ConfidentialityCapabilityPolicyDtoSchema,nt as ConfidentialityLevelSchema,Q as DOCUMENT_AUTHORITY_COMMAND_RULES,ft as DOCUMENT_AUTHORITY_PAGE_LIMIT_MAX,tn as DeletedDocumentAuthorityEventImageSchema,qn as DocumentAuthorityCommandBlockerSchema,Et as DocumentAuthorityCommandFieldErrorSchema,ae as DocumentAuthorityCommandFieldReasonSchema,L as DocumentAuthorityCommandFieldSchema,I as DocumentAuthorityCommandKindSchema,K as DocumentAuthorityCommandRejectionCodeSchema,Hn as DocumentAuthorityCommandRejectionSchema,hr as DocumentAuthorityCommandResultSchema,Do as DocumentAuthorityCommandSchema,kt as DocumentAuthorityEventImageSchema,Gn as DocumentAuthorityPageQuerySchema,Ro as DocumentAuthorityPageSchema,Mn as DocumentAuthorityPageWithCategoriesSchema,U as DocumentAuthorityRowSchema,M as DocumentRefSchema,Fo as FailedTieGroupReasonSchema,qe as FailedTieGroupSchema,qt as FeatureFlagKeySchema,eo as FileUriSchema,Dt as GovernanceAdminClient,Je as GovernanceAnswerRequestSchema,et as GovernanceAnswerResponseSchema,gt as GovernanceClient,V as GovernanceClientError,no as GovernanceSearchHitSchema,Le as GovernanceSearchMetadataSchema,Ze as GovernanceSearchRequestSchema,We as GovernanceSearchResponseSchema,to as GovernanceSearchSnippetSchema,Qe as GovernanceSimulateCaseDiffSchema,Fe as GovernanceSimulateCaseScoresSchema,tt as GovernanceSimulateRequestSchema,ot as GovernanceSimulateResponseSchema,Ne as GovernanceSimulateScoresSchema,mn as GovernedCapabilitySchema,fn as JsonPrimitiveSchema,Vt as JsonValueSchema,Tr as KnowledgeGovernanceEventRecordSchema,Be as KnowledgeGovernanceEventSchema,w as NormalizedPolicyCategorySchema,_e as NormalizedScoreSchema,Xe as OPERATOR_IDENTIFIER_MAX_LENGTH,S as OffsetIsoInstantSchema,ze as POLICY_CATEGORY_MAX_LENGTH,Ln as POLICY_CATEGORY_UNICODE_VERSION,ho as POLICY_CATEGORY_WHITESPACE_CODE_POINTS,Oo as POLICY_CONFLICT_DECISION_REASON_BLANK_CODE_POINTS,_t as POLICY_CONFLICT_DECISION_REASON_MAX_LENGTH,Ut as POLICY_CONFLICT_PAGE_LIMIT_MAX,_o as POLICY_CONFLICT_SUMMARY_MAX_LENGTH,ut as PolicyCategoryRejectionSchema,Co as PolicyCategorySchema,zo as PolicyConflictCountsSchema,Gt as PolicyConflictDecisionEventImageSchema,Mt as PolicyConflictDecisionFieldErrorSchema,bt as PolicyConflictDecisionFieldReasonSchema,q as PolicyConflictDecisionFieldSchema,Tt as PolicyConflictDecisionKindSchema,ge as PolicyConflictDecisionRejectionCodeSchema,Ar as PolicyConflictDecisionRejectionSchema,Yo as PolicyConflictDecisionSchema,Ho as PolicyConflictDetailSchema,nn as PolicyConflictDetectedEventImageSchema,on as PolicyConflictDetectedFailedGroupSchema,Ko as PolicyConflictDetectionFailureReasonSchema,Qo as PolicyConflictDetectionOutcomeSchema,Wo as PolicyConflictDetectionRequestRejectionCodeSchema,Er as PolicyConflictDetectionRequestRejectionSchema,Sr as PolicyConflictDetectionRequestSchema,ko as PolicyConflictDetectionStateSchema,ce as PolicyConflictFactsSchema,yr as PolicyConflictPageQuerySchema,fr as PolicyConflictPageSchema,ro as PolicyConflictRefSchema,ee as PolicyConflictResolutionStatusSchema,Lt as PolicyConflictRowSchema,ue as PolicyConflictSeveritySchema,Ot as PolicyConflictStateSchema,jo as PolicyConflictSummarySchema,Lo as PolicyConflictUnmeasuredReasonSchema,Go as PolicyConflictViewerSchema,Mr as PromptTemplateDtoSchema,ht as REPLACEABLE_AUTHORITY_PAGE_LIMIT_MAX,qo as RecordedPolicyConflictDecisionSchema,oo as RelatedDecisionSchema,kn as ReplaceableAuthorityPageSchema,Vn as ReplaceableAuthorityQuerySchema,Jo as ReplacedAuthorityChangeSchema,ie as RowVersionSchema,dt as SEVERITY_BY_TIER,j as Sha256HexSchema,Ie as StoredDecisionReasonSchema,_r as SystemFeatureFlagDtoSchema,Lr as SystemParameterDtoSchema,de as TenantIdSchema,zr as UpdateFeatureFlagRequestSchema,kr as UpdateParameterRequestSchema,Gr as UpdatePromptTemplateRequestSchema,x as UtcInstantSchema,ao as VerifiedCitationSchema,Ge as bytesToHex,ur as canonicalPolicyConflictFactsJson,Yn as checkDocumentAuthorityCommand,Cr as checkPolicyConflictDecision,vo as computeCitationLeafHash,To as computeCitationMerkleRoot,bo as constantTimeCompare,Ct as documentAuthorityCommandBlocker,Nn as equalRankGroups,Bn as isDocumentAuthorityCommandAvailable,yo as isEligibleAuthority,mt as normalizePolicyCategory,Un as offsetIsoOfUtcInstant,fo as parseUtcInstant,pr as policyConflictFactsHash,mr as policyConflictFactsOf,Re as sha256,Fn as tiePairs,On as utcInstantOfOffsetIso,Rt as verifyCitationProof};
|
|
1
|
+
import{ConfidentialityLevelSchema as uo,FileUriSchema as po,QUARANTINED_CONFIDENTIALITY_LEVEL as mo}from"@aiquants/enrichment-core";import{z as l}from"zod";import{z as $t}from"zod";var Kt=/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.\d{7}$/,Pe=1,$e=9999,Ye=7,Oe=60,Qt=14*Oe,Zt=$t.string().datetime({offset:!0}),Xt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|([+-])(\d{2}):(\d{2}))$/,Wt=(e,t,o)=>{let n=new Date(0);return n.setUTCFullYear(e,t-1,o),e>=Pe&&e<=$e&&n.getUTCMonth()===t-1&&n.getUTCDate()===o},_e=e=>{let t=Kt.exec(e);if(t===null)return null;let[o,n,a,s,u,m]=t.slice(1,7).map(Number);return Wt(o,n,a)&&s<=23&&u<=59&&m<=59?e:null},H=(e,t)=>String(e).padStart(t,"0"),J=e=>{let t=Zt.safeParse(e).success?Xt.exec(e):null;if(t===null)return null;let[,o,n,a,s,u,m,f="",R="+",b="00",v="00"]=t,h=(R==="-"?-1:1)*(Number(b)*Oe+Number(v));if(Number(o)<Pe||f.length>Ye||Number(v)>=Oe||Math.abs(h)>Qt)return null;let y=new Date(0);y.setUTCFullYear(Number(o),Number(n)-1,Number(a)),y.setUTCHours(Number(s),Number(u)-h,Number(m),0);let C=y.getUTCFullYear();if(C<Pe||C>$e)return null;let z=`${H(C,4)}-${H(y.getUTCMonth()+1,2)}-${H(y.getUTCDate(),2)}`,P=`${H(y.getUTCHours(),2)}:${H(y.getUTCMinutes(),2)}:${H(y.getUTCSeconds(),2)}`;return`${z} ${P}.${f.padEnd(Ye,"0")}`},O=(e,t)=>{let o=J(e),n=J(t);return o===null||n===null?null:o<n?-1:o>n?1:0};import{SYSTEM_PARAMETER_RANGES as rt}from"@aiquants/enrichment-core";import{z as N}from"zod";import{ConfidentialityLevelSchema as Jt,FileUriSchema as eo,TenantIdSchema as de}from"@aiquants/enrichment-core";import{z as r}from"zod";import{ConfidentialityLevelSchema as nt}from"@aiquants/enrichment-core";var Ze=r.object({query:r.string().min(1,"Search query must not be empty"),policyCategory:r.string().optional(),includeHistoricalRevisions:r.boolean().optional(),maxAuthorityTier:r.union([r.literal(1),r.literal(2),r.literal(3),r.literal(4),r.literal(5)]).optional(),limit:r.number().int().positive().optional()}),to=r.object({text:r.string(),citationText:r.string(),chunkHash:r.string(),chunkIndex:r.number().int().nonnegative(),parentChunkUid:r.string().optional(),clauseIdentifier:r.string().optional(),breadcrumbPath:r.array(r.string()).optional(),page:r.number().int().optional(),sheetName:r.string().optional(),slideIndex:r.number().int().optional(),timestampSec:r.number().optional(),score:r.number()}),oo=r.object({decisionId:r.string(),title:r.string(),approvedBy:r.string()}),D=r.union([r.literal(1),r.literal(2),r.literal(3),r.literal(4),r.literal(5)]),T=r.enum(["DRAFT","APPROVED","DEPRECATED"]),ue=r.enum(["LOW","MEDIUM","HIGH","CRITICAL"]),ee=r.enum(["UNRESOLVED","RESOLVED","IGNORED"]),Xe=100,no=r.object({metadataId:r.number().int(),fileUri:eo,fileName:r.string(),documentTitle:r.string(),authorityTier:D.nullable(),validFrom:r.string().nullable(),validUntil:r.string().nullable(),isCurrentlyAuthoritative:r.boolean(),confidentialityLevel:Jt,snippets:r.array(to),relatedDecisions:r.array(oo).optional(),policyWarning:r.string().optional()}),Le=r.object({searchMode:r.enum(["tri_store","sql_vector","sql_keyword_degraded"]),qualityTier:r.enum(["HIGH_TRI_STORE","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),isDegraded:r.boolean(),degradationReason:r.string().nullable(),circuitBreakerStatus:r.record(r.enum(["CLOSED","OPEN","HALF_OPEN","HEALTHY"])),executionTimeMs:r.number().nonnegative()}),We=r.object({hits:r.array(no),tiers:r.object({sql:r.boolean(),vector:r.boolean(),graph:r.boolean()}),masked:r.boolean(),searchMetadata:Le}),Je=r.object({question:r.string().min(1,"Question must not be empty"),asOf:r.string().optional(),asOfTx:r.string().optional()}),Ke=r.object({metadataId:r.number().int(),documentTitle:r.string(),authorityTier:D,approvalStatus:T,validFrom:r.string(),validUntil:r.string().nullable(),isCurrentlyAuthoritative:r.boolean()}),ro=r.object({conflictId:r.number().int(),sourceMetadataId:r.number().int(),targetMetadataId:r.number().int(),conflictSummary:r.string(),severity:ue,resolutionStatus:ee}),ao=r.object({chunkUid:r.string().uuid("chunkUid must be a valid UUID"),metadataId:r.number().int(),documentTitle:r.string(),clauseIdentifier:r.string(),breadcrumbPath:r.array(r.string()),exactQuotedText:r.string(),chunkHash:r.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),authorityTier:D,isVerified:r.boolean()}),j=r.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),io=r.object({chunkUid:r.string().uuid("chunkUid must be a valid UUID"),chunkHash:j}),co=r.object({algorithm:r.literal("SHA-256"),merkleRoot:j,leafCount:r.number().int().positive(),leaves:r.array(io).min(1),tenantId:de,scopeDigest:j,asOf:r.string().datetime(),asOfTx:r.string().datetime(),generatedAt:r.string().datetime(),signature:r.string().min(1,"Signature must not be empty")}),et=r.object({answer:r.string(),authoritative:r.array(Ke),superseded:r.array(Ke),conflicts:r.array(ro),verifiedCitations:r.array(ao),citationProof:co.nullable(),isFullyGrounded:r.boolean(),requiresHumanArbitration:r.boolean(),tiers:r.object({sql:r.boolean(),vector:r.boolean(),graph:r.boolean()}),searchMetadata:Le}),tt=r.object({promptOverrides:r.record(r.string()).optional(),parameterOverrides:r.record(r.union([r.string(),r.number(),r.boolean()])).optional(),strategyOverrides:r.record(r.record(r.union([r.string(),r.number(),r.boolean()]))).optional(),intentTypes:r.array(r.enum(["SET","DIFF","PATH","NEGATION","COUNT"])).optional()}),Ue=r.number().min(0).max(1),Fe=r.object({contextRelevance:Ue,groundedness:Ue,answerRelevance:Ue}),Ne=Fe.extend({meanAnswerChars:r.number().nonnegative(),meanLatencyMs:r.number().nonnegative()}),Qe=r.object({caseId:r.string(),intentType:r.enum(["SET","DIFF","PATH","NEGATION","COUNT"]),beforeScores:Fe,afterScores:Fe}),ot=r.object({simulationId:r.string(),evaluatedCount:r.number().int().nonnegative(),before:Ne,after:Ne,delta:Ne,regressions:r.array(Qe),improvements:r.array(Qe),searchMetadata:Le});var i=(e,t,o,n)=>{e.addIssue(n===void 0?{code:N.ZodIssueCode.custom,path:[...t],message:o}:{code:N.ZodIssueCode.custom,path:[...t],message:o,params:{reason:n}})},pe=e=>e==null||e==="",at=e=>{let t=N.unknown().superRefine((o,n)=>e(n)).safeParse(void 0);return t.success?[]:t.error.issues},me=(e,t)=>{let o=t.schema.safeParse(e);if(o.success)return{ok:!0,value:o.data};let n={ok:!1,rejection:{code:"BODY_INVALID"}},a=f=>f.path.length===0?void 0:t.fieldOfKey.get(f.path[0]);if(!o.error.issues.every(f=>a(f)!==void 0))return n;let s=e,u=[];for(let f of[...o.error.issues,...t.skippedIssues(s)]){let R=a(f);if(R===void 0)return n;let b=f.code===N.ZodIssueCode.custom?f.params?.reason:void 0,v=b??(pe(s[f.path[0]])?"REQUIRED":"MALFORMED"),h=t.fieldError.safeParse({path:R,reason:v});if(!h.success){if(b!==void 0)throw new RangeError(`A rule reported ${JSON.stringify(b)} at ${JSON.stringify(R)}, which the form does not pair`);return n}u.push(h.data)}return{ok:!1,rejection:{code:"FIELD_INVALID",fieldErrors:t.fields.flatMap(f=>{let R=u.find(b=>b.path===f);return R===void 0?[]:[R]})}}},fe=(e,t,o)=>{e.forEach((n,a)=>{a>0&&t.indexOf(n)<=t.indexOf(e[a-1])&&i(o,["fieldErrors",a],"Each field appears once, in the form's order")})},ye=()=>e=>e,p=N.number().int().positive().max(Number.MAX_SAFE_INTEGER),g=N.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),he=N.number().int().min(rt.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min).max(rt.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.max),Y=e=>N.number().int().min(1).max(e),F=N.string().min(1).max(Xe),so=/\p{Cs}/u,te=e=>!so.test(e),Ae=(e,t)=>{let o=0,n=e.length;for(;o<n&&t.has(e.charCodeAt(o));)o+=1;for(;n>o&&t.has(e.charCodeAt(n-1));)n-=1;return e.slice(o,n)},$=(e,t,o)=>{e.forEach((n,a)=>{a>0&&n>=e[a-1]&&i(o,["rows",a],"Rows are in strictly descending order of their key")}),t!==null&&t!==e.at(-1)&&i(o,["nextAfter"],"nextAfter is absent or the key of the last row")},oe=(e,t,o,n)=>{e>=t&&i(n,o,"The source governs the smaller document version (source < target)")},Ce=(e,t,o,n,a,s)=>{(e?!(t===o||t===n):t!==null)&&i(s,a,"A resolution records one document of the pair as prevailing, and only a resolution does")},lo=(e,t)=>{let o=t===null?null:O(t,e);return o!==null&&o<=0},ne=(e,t,o,n)=>{lo(e,t)&&i(n,o,"validUntil must be after validFrom","NOT_AFTER_VALID_FROM")},Se=(e,t,o,n,a)=>{e!=="DRAFT"&&!t&&i(a,n.approval,"An APPROVED or DEPRECATED row carries its approval"),o&&!t&&i(a,n.withdrawal,"Only an approval once given can be withdrawn"),e==="DRAFT"&&t&&!o&&i(a,n.withdrawal,"A DRAFT row that was approved carries its withdrawal")};function fo(e){let t=_e(e);if(t===null)throw new RangeError(`Not a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff: ${JSON.stringify(e)}`);return t}var x=l.string().transform((e,t)=>{let o=_e(e);return o===null?(t.addIssue({code:l.ZodIssueCode.custom,message:"Must be a UTC instant of the form yyyy-mm-dd hh:mi:ss.fffffff"}),l.NEVER):o});function On(e){let t=J(e);if(t===null)throw new RangeError(`Not an ISO 8601 instant with a UTC offset that datetimeoffset(7) can hold: ${JSON.stringify(e)}`);return t}var S=l.string().refine(e=>J(e)!==null,{message:"Must be an ISO 8601 instant yyyy-mm-ddThh:mi:ss[.f] with Z or a \xB1hh:mi offset within \xB114:00, at most seven fractional digits and a year between 0001 and 9999 both as written and in UTC"});function _n(e){let t=fo(e);return`${t.slice(0,10)}T${t.slice(11)}Z`}var Un=l.object({metadataId:p,authorityTier:D,approvalStatus:T,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict();function yo(e,t,o){return e.approvalStatus===T.enum.APPROVED&&e.validFromUtc<=t&&(e.validUntilUtc===null||e.validUntilUtc>t)&&e.txCreatedAtUtc<=o&&(e.txSupersededAtUtc===null||e.txSupersededAtUtc>o)}var lt=(e,t)=>e.metadataId-t.metadataId,Me=e=>`${e.authorityTier} ${e.validFromUtc}`;function Nn(e,t,o){let n=new Set,a=new Map;for(let s of e){if(n.has(s.metadataId))throw new RangeError(`Two authority rows govern the same document version: metadataId ${s.metadataId}`);if(n.add(s.metadataId),!yo(s,t,o))continue;let u=Me(s),m=a.get(u);m===void 0?a.set(u,[s]):m.push(s)}return[...a.values()].filter(s=>s.length>=2).map(s=>[...s].sort(lt)).sort((s,u)=>s[0].metadataId-u[0].metadataId)}function Fn(e){let t=[...e].sort(lt);return t.forEach((o,n)=>{if(Me(o)!==Me(t[0]))throw new RangeError(`An equal-rank group mixes ranks: metadataId ${t[0].metadataId} and ${o.metadataId}`);if(n>0&&o.metadataId===t[n-1].metadataId)throw new RangeError(`An equal-rank group repeats a document version: metadataId ${o.metadataId}`)}),t.flatMap((o,n)=>t.slice(n+1).map(a=>[o,a]))}var dt=Object.freeze({1:"CRITICAL",2:"HIGH",3:"MEDIUM",4:"LOW",5:"LOW"}),ze=50,Ln="17.0",ut=l.enum(["MALFORMED","EMPTY","TOO_LONG"]),ho=Object.freeze([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]),pt=new Set(ho),Ao=e=>{let t=[],o=0;for(let n=0;n<=e.length;n+=1)(n===e.length||pt.has(e.charCodeAt(n)))&&(n>o&&t.push(e.slice(o,n)),o=n+1);return t.join(" ")};function mt(e){if(!te(e))return{ok:!1,reason:"MALFORMED"};let t=Ao(e.normalize("NFKC"));return t.length===0?{ok:!1,reason:"EMPTY"}:t.length>ze?{ok:!1,reason:"TOO_LONG"}:{ok:!0,value:t}}var Co=l.string().transform((e,t)=>{let o=mt(e);return o.ok?o.value:(i(t,[],`A policy category must be well-formed text of 1 to ${ze} UTF-16 code units after normalization`,o.reason),l.NEVER)}),w=l.string().refine(e=>{let t=mt(e);return t.ok&&t.value===e},{message:`A stored policy category must be well-formed, normalized (NFKC, single spaces, trimmed) and 1 to ${ze} UTF-16 code units`}),ft=50,yt=50,ht=50,it=2,So=200,Eo=e=>[...e].length,At=l.string().transform(e=>Ae(e,pt)).pipe(l.string().max(So).refine(te,{message:"A search text is well-formed text without an unpaired surrogate"}).refine(e=>Eo(e)>=it,{message:`A search text has at least ${it} characters (code points) once trimmed`})),ie=l.string().regex(/^[0-9a-f]{16}$/,"Must be a rowversion as 16 lowercase hexadecimal digits"),M=l.object({metadataId:p,fileName:l.string().min(1),fileUri:po,revision:l.number().int().min(1),isCurrent:l.boolean(),isDeleted:l.boolean(),confidentialityLevel:uo.exclude([mo])}).strict(),_=l.object({authorityId:p,document:M,authorityTier:D,policyCategory:w,validFrom:S,validUntil:S.nullable(),txCreatedAt:S,txSupersededAt:S.nullable(),approvalStatus:T,approvedBy:F.nullable(),approvedAt:S.nullable(),withdrawnBy:F.nullable(),withdrawnAt:S.nullable(),replaces:M.nullable(),supersededBy:M.nullable(),replacesAnother:l.boolean(),isSuperseded:l.boolean(),rowVersion:ie,updatedBy:F,updatedAt:S}).strict().superRefine((e,t)=>{ne(e.validFrom,e.validUntil,["validUntil"],t),e.approvedBy===null!=(e.approvedAt===null)&&i(t,["approvedAt"],"approvedBy and approvedAt are present together or absent together"),e.withdrawnBy===null!=(e.withdrawnAt===null)&&i(t,["withdrawnAt"],"withdrawnBy and withdrawnAt are present together or absent together"),Se(e.approvalStatus,e.approvedAt!==null,e.withdrawnAt!==null,{approval:["approvedAt"],withdrawal:["withdrawnAt"]},t);let o=e.approvedAt===null||e.withdrawnAt===null?null:O(e.withdrawnAt,e.approvedAt);e.approvalStatus==="DRAFT"&&o!==null&&o<0&&i(t,["withdrawnAt"],"A DRAFT row's withdrawal is no earlier than its approval");let n=e.txSupersededAt!==null;(e.approvalStatus==="DEPRECATED"?!n:n)&&i(t,["txSupersededAt"],"txSupersededAt is recorded exactly when the row is DEPRECATED"),e.replaces!==null&&!e.replacesAnother&&i(t,["replacesAnother"],"A row that names the document it replaces replaces another"),e.supersededBy!==null&&!e.isSuperseded&&i(t,["isSuperseded"],"A row that names its successor is superseded"),e.replaces?.metadataId===e.document.metadataId&&i(t,["replaces"],"A row does not replace its own document version"),e.supersededBy?.metadataId===e.document.metadataId&&i(t,["supersededBy"],"A row is not superseded by its own document version")}),Ro=l.object({rows:l.array(_).max(ft),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{$(e.rows.map(o=>o.authorityId),e.nextAfter,t)}),Mn=l.object({page:Ro,categories:l.array(w).nullable()}).strict().superRefine((e,t)=>{e.categories!==null&&new Set(e.categories).size!==e.categories.length&&i(t,["categories"],"Each category appears once")}),zn=l.object({rows:l.array(M).max(yt),nextAfter:p.nullable()}).strict().superRefine((e,t)=>{$(e.rows.map(o=>o.metadataId),e.nextAfter,t),e.rows.forEach((o,n)=>{(!o.isCurrent||o.isDeleted)&&i(t,["rows",n],"A candidate is a current, undeleted document version")})}),kn=l.object({rows:l.array(_).max(ht),nextAfter:p.nullable(),totalCount:g}).strict().superRefine((e,t)=>{$(e.rows.map(o=>o.authorityId),e.nextAfter,t),e.totalCount<e.rows.length&&i(t,["totalCount"],"totalCount counts at least the rows of the page"),e.rows.forEach((o,n)=>{(o.approvalStatus!=="APPROVED"||o.isSuperseded)&&i(t,["rows",n],"A row a replacement may name is approved and not yet superseded"),o.policyCategory!==e.rows[0].policyCategory&&i(t,["rows",n,"policyCategory"],"The rows a replacement may name share one category")})}),Gn=l.object({status:T.optional(),category:w.optional(),after:p.optional(),limit:Y(ft)}).strict(),jn=l.object({q:At,after:p.optional(),limit:Y(yt)}).strict(),Vn=l.object({category:w,q:At.optional(),after:p.optional(),limit:Y(ht)}).strict(),I=l.enum(["create","update","approve","withdraw","deprecate","delete"]),L=l.enum(["authorityTier","policyCategory","validFrom","validUntil","replacesMetadataId"]),ct={authorityTier:D,policyCategory:Co,validFrom:S,validUntil:S.nullable(),replacesMetadataId:p.nullable()},st=Object.freeze([...L.options]),Q=Object.freeze({create:Object.freeze({before:null,after:"DRAFT",changes:st,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!1}),update:Object.freeze({before:"DRAFT",after:"DRAFT",changes:st,requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1}),approve:Object.freeze({before:"DRAFT",after:"APPROVED",changes:Object.freeze(["approvedBy"]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!0,runsDetection:!0}),withdraw:Object.freeze({before:"APPROVED",after:"DRAFT",changes:Object.freeze(["withdrawnBy"]),requiresNeverApproved:!1,requiresNoReplacement:!0,requiresCurrentDocument:!1,runsDetection:!0}),deprecate:Object.freeze({before:"APPROVED",after:"DEPRECATED",changes:Object.freeze([]),requiresNeverApproved:!1,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!0}),delete:Object.freeze({before:"DRAFT",after:null,changes:Object.freeze([]),requiresNeverApproved:!0,requiresNoReplacement:!1,requiresCurrentDocument:!1,runsDetection:!1})}),qn=l.enum(["STATUS","APPROVED_ONCE","REPLACES_ANOTHER","DOCUMENT_NOT_CURRENT"]);function Ct(e,t){let o=Q[e];return t.approvalStatus!==o.before?"STATUS":o.requiresNeverApproved&&t.approvedAt!==null?"APPROVED_ONCE":o.requiresNoReplacement&&t.replacesAnother?"REPLACES_ANOTHER":o.requiresCurrentDocument&&(!t.document.isCurrent||t.document.isDeleted)?"DOCUMENT_NOT_CURRENT":null}function Bn(e,t){return Ct(e,t)===null}var re={authorityId:p,expectedRowVersion:ie},go=e=>e.kind===I.enum.create&&e.replacesMetadataId===e.metadataId&&p.safeParse(e.replacesMetadataId).success,St=(e,t)=>{let{validFrom:o,validUntil:n}=e;typeof o=="string"&&(n===null||typeof n=="string")&&ne(o,n,["validUntil"],t),go(e)&&i(t,["replacesMetadataId"],"A document version does not replace itself","SELF_REPLACEMENT")},Do=l.discriminatedUnion("kind",[l.object({kind:l.literal(I.enum.create),metadataId:p,...ct}).strict(),l.object({kind:l.literal(I.enum.update),...re,...ct}).strict(),l.object({kind:l.literal(I.enum.approve),...re}).strict(),l.object({kind:l.literal(I.enum.withdraw),...re}).strict(),l.object({kind:l.literal(I.enum.deprecate),...re}).strict(),l.object({kind:l.literal(I.enum.delete),...re}).strict()]).superRefine(St),ae=l.enum(["REQUIRED",...ut.options,"NOT_AFTER_VALID_FROM","SELF_REPLACEMENT"]),Et=l.discriminatedUnion("path",[l.object({path:l.literal(L.enum.authorityTier),reason:ae.extract(["REQUIRED","MALFORMED"])}).strict(),l.object({path:l.literal(L.enum.policyCategory),reason:ae.extract(["REQUIRED",...ut.options])}).strict(),l.object({path:l.literal(L.enum.validFrom),reason:ae.extract(["REQUIRED","MALFORMED"])}).strict(),l.object({path:l.literal(L.enum.validUntil),reason:ae.extract(["REQUIRED","MALFORMED","NOT_AFTER_VALID_FROM"])}).strict(),l.object({path:l.literal(L.enum.replacesMetadataId),reason:ae.extract(["REQUIRED","MALFORMED","SELF_REPLACEMENT"])}).strict()]),K=l.enum(["BODY_INVALID","FIELD_INVALID","NOT_FOUND","REPLACEMENT_NOT_FOUND","STALE","ALREADY_REGISTERED","RANK_LIMIT_REACHED","NOT_AFTER_REPLACED","DOCUMENT_NOT_CURRENT","DEADLOCK","DEPLOYMENT_DISABLED"]),Hn=ye()(l.discriminatedUnion("code",[l.object({code:K.extract(["FIELD_INVALID"]),fieldErrors:l.array(Et).min(1)}).strict(),l.object({code:K.extract(["STALE"]),row:_}).strict(),l.object({code:K.extract(["ALREADY_REGISTERED"]),row:_}).strict(),l.object({code:K.extract(["DOCUMENT_NOT_CURRENT"]),row:_}).strict(),l.object({code:K.extract(["RANK_LIMIT_REACHED"]),rowScopeApplied:l.boolean(),limit:he.nullable()}).strict(),l.object({code:K.exclude(["FIELD_INVALID","STALE","ALREADY_REGISTERED","DOCUMENT_NOT_CURRENT","RANK_LIMIT_REACHED"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&fe(e.fieldErrors.map(o=>o.path),L.options,t),e.code==="ALREADY_REGISTERED"&&(!e.row.document.isCurrent||e.row.document.isDeleted)&&i(t,["row","document"],"The registered row's document version is current and not deleted, as the create requires"),e.code==="DOCUMENT_NOT_CURRENT"&&Ct("approve",e.row)!=="DOCUMENT_NOT_CURRENT"&&i(t,["row"],"The row is a DRAFT whose document version is no longer current or has been deleted"),e.code==="RANK_LIMIT_REACHED"&&e.limit===null!==e.rowScopeApplied&&i(t,["limit"],"The limit is shown exactly to an operator whose row scope is unrestricted")})),Io={schema:Do,fieldOfKey:new Map(L.options.map(e=>[e,e])),fields:L.options,fieldError:Et,skippedIssues:e=>at(t=>St(e,t))};function Yn(e){return me(e,Io)}var V=class extends Error{statusCode;responseBody;parsedBody;constructor(t,o,n,a){super(t),this.name="GovernanceClientError",this.statusCode=o,this.responseBody=n,this.parsedBody=a}},Z=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for GovernanceClient.");let o=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey){let n;try{n=new URL(o)}catch{throw new Error(`Invalid baseUrl format: ${t.baseUrl}`)}if(n.protocol==="http:"){let a=n.hostname.toLowerCase();if(!(a==="localhost"||a==="127.0.0.1"||a==="[::1]"||a==="::1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.")}}this.baseUrl=o,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,o,n,a,s){let u=new URL(t.startsWith("/")?t.slice(1):t,`${this.baseUrl}/`);if(a)for(let[h,y]of Object.entries(a))y!=null&&y.trim().length>0&&u.searchParams.append(h,y);let m=u.toString(),f={Accept:"application/json"};this.apiKey&&(f.Authorization=`Bearer ${this.apiKey}`),n!==void 0&&(f["Content-Type"]="application/json");let R=new AbortController,b=setTimeout(()=>R.abort(),this.timeoutMs),v=R.signal;s&&(v=AbortSignal.any([R.signal,s]));try{let h=await this.fetchFn(m,{method:o,headers:f,body:n!==void 0?JSON.stringify(n):void 0,signal:v}),y=await h.text();if(!h.ok){let C;try{C=JSON.parse(y)}catch{}throw new V(`API request failed with status ${h.status}: ${y}`,h.status,y,C)}if(y.trim().length===0)return;try{return JSON.parse(y)}catch(C){let z=C.message;throw new V(`Failed to parse response JSON from ${m}: ${z}`,h.status,y)}}catch(h){if(h instanceof V)throw h;let y=h instanceof Error?h.message:String(h);throw new V(`Network request failed for ${o} ${m}: ${y}`,0,"")}finally{clearTimeout(b)}}};var ke=new Uint8Array([0]),Ee=new Uint8Array([1]),xo=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function U(e,t){return e>>>t|e<<32-t}function Re(e){let t=1779033703,o=3144134277,n=1013904242,a=2773480762,s=1359893119,u=2600822924,m=528734635,f=1541459225,R=e.length,b=R*8,v=(R+8>>6)+1<<6,h=new Uint8Array(v);h.set(e),h[R]=128;let y=new DataView(h.buffer,h.byteOffset,h.byteLength);y.setUint32(v-4,b>>>0,!1),y.setUint32(v-8,Math.floor(b/4294967296),!1);let C=new Uint32Array(64);for(let xe=0;xe<v;xe+=64){for(let A=0;A<16;A++)C[A]=y.getUint32(xe+A*4,!1);for(let A=16;A<64;A++){let Te=U(C[A-15],7)^U(C[A-15],18)^C[A-15]>>>3,we=U(C[A-2],17)^U(C[A-2],19)^C[A-2]>>>10;C[A]=C[A-16]+Te+C[A-7]+we>>>0}let k=t,X=o,W=n,be=a,G=s,se=u,le=m,ve=f;for(let A=0;A<64;A++){let Te=U(G,6)^U(G,11)^U(G,25),we=G&se^~G&le,He=ve+Te+we+xo[A]+C[A]>>>0,Bt=U(k,2)^U(k,13)^U(k,22),Ht=k&X^k&W^X&W,Yt=Bt+Ht>>>0;ve=le,le=se,se=G,G=be+He>>>0,be=W,W=X,X=k,k=He+Yt>>>0}t=t+k>>>0,o=o+X>>>0,n=n+W>>>0,a=a+be>>>0,s=s+G>>>0,u=u+se>>>0,m=m+le>>>0,f=f+ve>>>0}let z=new Uint8Array(32),P=new DataView(z.buffer,z.byteOffset,z.byteLength);return P.setUint32(0,t,!1),P.setUint32(4,o,!1),P.setUint32(8,n,!1),P.setUint32(12,a,!1),P.setUint32(16,s,!1),P.setUint32(20,u,!1),P.setUint32(24,m,!1),P.setUint32(28,f,!1),z}function Ge(e){let t="";for(let o=0;o<e.length;o++)t+=e[o].toString(16).padStart(2,"0");return t}function bo(e,t){if(e.length!==t.length)return!1;let o=0;for(let n=0;n<e.length;n++)o|=e.charCodeAt(n)^t.charCodeAt(n);return o===0}function vo(e,t,o){if(!(e?.trim()&&t?.trim()&&o?.trim()))throw new Error("tenantId, chunkUid, and chunkHash must be non-empty strings.");if(e.includes("")||t.includes("")||o.includes(""))throw new Error("Parameters must not contain delimiter control characters.");let a=new TextEncoder().encode(`${e}${t}${o}`),s=new Uint8Array(ke.length+a.length);return s.set(ke,0),s.set(a,ke.length),Re(s)}function To(e){if(!e||e.length===0)return null;for(let o=0;o<e.length;o++)if(!(e[o]instanceof Uint8Array)||e[o].length!==32)throw new Error(`Leaf at index ${o} must be a 32-byte Uint8Array.`);let t=[...e];for(;t.length>1;){let o=[];for(let n=0;n<t.length-1;n+=2){let a=t[n],s=t[n+1],u=new Uint8Array(Ee.length+a.length+s.length);u.set(Ee,0),u.set(a,Ee.length),u.set(s,Ee.length+a.length),o.push(Re(u))}t.length%2===1&&o.push(t[t.length-1]),t=o}return Ge(t[0])}function Rt(e,t){try{if(!e||typeof e!="object"||e.algorithm!=="SHA-256"||t?.expectedTenantId&&e.tenantId!==t.expectedTenantId||!Array.isArray(e.leaves)||e.leafCount!==e.leaves.length||e.leafCount===0)return!1;if(t?.expectedCitations){if(t.expectedCitations.length!==e.leaves.length)return!1;for(let a=0;a<e.leaves.length;a++)if(t.expectedCitations[a].chunkUid!==e.leaves[a].chunkUid||t.expectedCitations[a].chunkHash!==e.leaves[a].chunkHash)return!1}for(let a=0;a<e.leaves.length;a++){let s=e.leaves[a];if(!s||typeof s!="object"||!s.chunkUid||!s.chunkHash||a>0&&e.leaves[a].chunkUid<=e.leaves[a-1].chunkUid)return!1}let o=[];for(let a of e.leaves)o.push(vo(e.tenantId,a.chunkUid,a.chunkHash));let n=To(o);return!n||typeof e.merkleRoot!="string"?!1:bo(n,e.merkleRoot)}catch{return!1}}var gt=class extends Z{async search(t,o){let n=Ze.parse(t),a=o?{tenant_id:de.parse(o)}:void 0,s=await this.request("/ai/governance/search","POST",n,a);return We.parse(s)}async answer(t,o){let n=Je.parse(t),a=o?{tenant_id:de.parse(o)}:void 0,s=await this.request("/ai/governance/answer","POST",n,a);return et.parse(s)}verifyCitationProof(t,o){return Rt(t,o)}};import{TenantIdSchema as wo}from"@aiquants/enrichment-core";var Dt=class extends Z{async simulate(t,o){let n=tt.parse(t),a=o?{tenant_id:wo.parse(o)}:void 0,s=await this.request("/ai/governance/simulate","POST",n,a);return ot.parse(s)}};import{z as E}from"zod";import{canonicalJson as Pt,SYSTEM_PARAMETER_RANGES as Po}from"@aiquants/enrichment-core";import{z as c}from"zod";var Ot=c.enum(["UNRESOLVED_ACTIVE","UNRESOLVED_CLEARED","RESOLVED","IGNORED"]),_t=50,Ut=2e3,Oo=Object.freeze([9,10,13,32,12288]),_o=new Set(Oo),Nt=e=>Ae(e,_o),Uo=1e3,No=g.min(Po.POLICY_CONFLICT_MAX_TIE_GROUP_SIZE.min+1),Fo=c.enum(["TIE_GROUP_OVER_LIMIT"]),qe=c.object({policyCategory:w,authorityTier:D,validFromUtc:x,reason:Fo,tieGroupSize:No}).strict(),Lo=c.enum(["NEVER_DETECTED","DETECTION_INCOMPLETE_FOR_READABLE"]),Mo={UNRESOLVED_ACTIVE:g,UNRESOLVED_CLEARED:g,RESOLVED:g,IGNORED:g},zo=c.discriminatedUnion("kind",[c.object({kind:c.literal("measured"),values:c.object(Mo).strict(),partial:c.boolean()}).strict(),c.object({kind:c.literal("unmeasured"),reason:Lo}).strict()]),ko=c.object({lastDetectedAt:S,nextTransitionAt:S.nullable(),isStale:c.boolean(),failedGroups:c.array(qe).nullable(),tieGroupLimit:he.nullable()}).strict().superRefine((e,t)=>{e.failedGroups===null!=(e.tieGroupLimit===null)&&i(t,["tieGroupLimit"],"failedGroups and tieGroupLimit are present together or absent together")}),Go=c.object({canDecide:c.boolean(),rowScopeApplied:c.boolean()}).strict(),jo=c.object({counts:zo,detection:ko.nullable(),viewer:Go}).strict().superRefine((e,t)=>{let{counts:o,detection:n,viewer:a}=e,s=o.kind==="unmeasured"&&o.reason==="NEVER_DETECTED";n===null!==s&&i(t,["detection"],"The detection is absent exactly when the counts were never detected"),n!==null&&a.rowScopeApplied!==(n.failedGroups===null)&&i(t,["detection","failedGroups"],"Only an operator whose row scope is unrestricted sees the failed groups"),o.kind==="unmeasured"&&o.reason==="DETECTION_INCOMPLETE_FOR_READABLE"&&!a.rowScopeApplied&&i(t,["counts","reason"],"Only an operator with a row scope has counts left unmeasured by a failed group");let u=n===null?null:n.failedGroups,m=u!==null&&u.length>0;o.kind==="measured"&&o.partial!==m&&i(t,["counts","partial"],"The counts are partial exactly when failed groups are shown")}),It=c.object({metadataId:p,approvalStatus:T,validFromUtc:x,validUntilUtc:x.nullable(),txCreatedAtUtc:x,txSupersededAtUtc:x.nullable()}).strict(),ce=c.object({policyCategory:w,authorityTier:D,validFromUtc:x,source:It,target:It}).strict().superRefine((e,t)=>{oe(e.source.metadataId,e.target.metadataId,["target","metadataId"],t);for(let o of["source","target"])e[o].validFromUtc!==e.validFromUtc&&i(t,[o,"validFromUtc"],"Both documents share the effective date of the rank"),e[o].approvalStatus!==T.enum.APPROVED&&i(t,[o,"approvalStatus"],"Both documents were approved when the pair was detected")}),Ft=e=>Ge(Re(new TextEncoder().encode(Pt(e))));function ur(e){return Pt(ce.parse(e))}function pr(e){return Ft(ce.parse(e))}var xt=e=>({metadataId:e.metadataId,approvalStatus:e.approvalStatus,validFromUtc:e.validFromUtc,validUntilUtc:e.validUntilUtc,txCreatedAtUtc:e.txCreatedAtUtc,txSupersededAtUtc:e.txSupersededAtUtc});function mr(e,t,o){if(t.authorityTier!==o.authorityTier)throw new RangeError(`A pair shares one rank: metadataId ${t.metadataId} has tier ${t.authorityTier} and ${o.metadataId} tier ${o.authorityTier}`);return ce.parse({policyCategory:e,authorityTier:t.authorityTier,validFromUtc:t.validFromUtc,source:xt(t),target:xt(o)})}var Lt=c.object({conflictId:p,state:Ot,severity:ue,policyCategory:w,authorityTier:D,source:M,target:M,lastDetectedAt:S,clearedAt:S.nullable()}).strict().superRefine((e,t)=>{oe(e.source.metadataId,e.target.metadataId,["target","metadataId"],t),e.severity!==dt[e.authorityTier]&&i(t,["severity"],"The severity is the one the tier derives"),e.state==="UNRESOLVED_ACTIVE"&&e.clearedAt!==null&&i(t,["clearedAt"],"A pair still detected has not been cleared"),e.state==="UNRESOLVED_CLEARED"&&e.clearedAt===null&&i(t,["clearedAt"],"A pair no longer detected carries when it was cleared")}),fr=c.discriminatedUnion("kind",[c.object({kind:c.literal("unmeasured")}).strict(),c.object({kind:c.literal("page"),rows:c.array(Lt).max(_t),nextAfter:p.nullable()}).strict()]).superRefine((e,t)=>{e.kind==="page"&&$(e.rows.map(o=>o.conflictId),e.nextAfter,t)}),yr=c.object({state:Ot,severity:ue.optional(),after:p.optional(),limit:Y(_t)}).strict(),q=c.enum(["verdict","reason"]),bt=c.enum(["REQUIRED","MALFORMED","EMPTY","TOO_LONG"]),Vo=e=>te(e)?e.length===0?"EMPTY":e.length>Ut?"TOO_LONG":null:"MALFORMED",Ie=c.string().superRefine((e,t)=>{e!==Nt(e)&&i(t,[],"A stored reason has no blank character at either end");let o=Vo(e);o!==null&&i(t,[],`A reason is well-formed text of 1 to ${Ut} UTF-16 code units`,o)}),qo=c.object({status:ee.exclude(["UNRESOLVED"]),prevailingMetadataId:p.nullable(),reason:Ie,decidedBy:F,decidedAt:S,factsChangedSinceDecision:c.boolean()}).strict(),vt=c.object({document:M,authority:_}).strict(),Bo=Object.keys(M.shape),De=(e,t,o,n,a)=>{for(let s of Bo)e[s]!==t[s]&&i(a,[...o,s],n)},Ho=c.object({conflict:Lt,conflictSummary:c.string().min(1).max(Uo),facts:ce,factsHash:j,relatedReadablePairs:g,source:vt,target:vt,decision:qo.nullable()}).strict().superRefine((e,t)=>{let{conflict:o,facts:n,decision:a}=e;for(let m of["source","target"])n[m].metadataId!==o[m].metadataId&&i(t,["facts",m,"metadataId"],"The facts name the documents of the pair"),De(e[m].document,o[m],[m,"document"],"The detail shows the pair's document as the pair's row does",t),De(e[m].authority.document,o[m],[m,"authority","document"],"The authority row shows the pair's document as the pair's row does",t);(n.policyCategory!==o.policyCategory||n.authorityTier!==o.authorityTier)&&i(t,["facts"],"The facts carry the subject and the tier of the pair");let s=ce.safeParse(n);s.success&&e.factsHash!==Ft(s.data)&&i(t,["factsHash"],"The facts hash is the SHA-256 of the canonical text of the facts shown");let u=o.state==="UNRESOLVED_ACTIVE"||o.state==="UNRESOLVED_CLEARED";if(a===null){u||i(t,["decision"],"A resolved or ignored pair carries its decision");return}a.status!==o.state&&i(t,["decision","status"],"An unresolved pair carries no decision, and a decided pair's state is its verdict"),Ce(a.status==="RESOLVED",a.prevailingMetadataId,o.source.metadataId,o.target.metadataId,["decision","prevailingMetadataId"],t)}),Tt=c.enum(["RESOLVE","IGNORE"]),je=c.string().transform(Nt).pipe(Ie),Ve={conflictId:p,expectedFactsHash:j},Yo=c.discriminatedUnion("kind",[c.object({kind:c.literal(Tt.enum.RESOLVE),...Ve,prevailingMetadataId:p,reason:je}).strict(),c.object({kind:c.literal(Tt.enum.IGNORE),...Ve,reason:je}).strict()]),wt=c.custom(pe),$o=c.object({kind:wt,...Ve,prevailingMetadataId:wt,reason:je}).strict(),Ko=c.enum(["SUBJECT_WRITE_FAILED","DETECTION_FAILED"]),Qo=c.discriminatedUnion("kind",[c.object({kind:c.literal("detected"),summary:jo}).strict(),c.object({kind:c.literal("busy")}).strict(),c.object({kind:c.literal("failed"),reason:Ko,failedCategory:w.nullable(),rowScopeApplied:c.boolean()}).strict()]).superRefine((e,t)=>{e.kind==="detected"&&e.summary.detection===null&&i(t,["summary","detection"],"A completed detection leaves its state"),e.kind==="failed"&&e.failedCategory!==null!=(e.reason==="SUBJECT_WRITE_FAILED"&&!e.rowScopeApplied)&&i(t,["failedCategory"],"The failed category is shown exactly for a subject that failed, to an operator whose row scope is unrestricted")}),Zo=(e,t,o)=>{e.replaces===null?i(o,["row","replaces"],"An approved row that replaces a row the operator reads names it"):De(t.document,e.replaces,["replaced","document"],"The replaced row is the one the approved row names",o),t.supersededBy===null?i(o,["replaced","supersededBy"],"The replaced row names the approved document version as its successor"):De(t.supersededBy,e.document,["replaced","supersededBy"],"The replaced row names the approved document version as its successor",o),t.approvalStatus!==T.enum.APPROVED&&i(o,["replaced","approvalStatus"],"The replaced row stays approved"),t.policyCategory!==e.policyCategory&&i(o,["replaced","policyCategory"],"The replaced row shares the approved row's category");let n=t.validUntil===null?null:O(t.validUntil,e.validFrom);(t.validUntil===null||n!==null&&n>0)&&i(o,["replaced","validUntil"],"The replaced row ends no later than the approved row takes effect")},hr=c.discriminatedUnion("kind",[c.object({kind:I.extract(["create","update"]),row:_,detection:c.null()}).strict(),c.object({kind:I.extract(["approve","withdraw","deprecate"]),row:_,detection:Qo,replaced:_.nullable()}).strict(),c.object({kind:I.extract(["delete"]),row:c.null(),detection:c.null()}).strict()]).superRefine((e,t)=>{e.row!==null&&(e.row.approvalStatus!==Q[e.kind].after&&i(t,["row","approvalStatus"],"The row has the approval status the command leaves"),"replaced"in e&&(e.replaced!==null!==(e.kind==="approve"&&e.row.replacesAnother)?i(t,["replaced"],"An approval of a row that replaces another carries that row, and no other result does"):e.replaced!==null&&Zo(e.row,e.replaced,t)))}),Mt=c.discriminatedUnion("path",[c.object({path:c.literal(q.enum.verdict),reason:bt.extract(["REQUIRED"])}).strict(),c.object({path:c.literal(q.enum.reason),reason:bt}).strict()]),ge=c.enum(["BODY_INVALID","FIELD_INVALID","ID_MISMATCH","PREVAILING_NOT_IN_PAIR","NOT_FOUND","STALE","DEADLOCK","DEPLOYMENT_DISABLED"]),Ar=ye()(c.discriminatedUnion("code",[c.object({code:ge.extract(["FIELD_INVALID"]),fieldErrors:c.array(Mt).min(1)}).strict(),c.object({code:ge.extract(["STALE"]),detail:Ho}).strict(),c.object({code:ge.exclude(["FIELD_INVALID","STALE"])}).strict()]).superRefine((e,t)=>{e.code==="FIELD_INVALID"&&fe(e.fieldErrors.map(o=>o.path),q.options,t)})),Xo={schema:Yo,fieldOfKey:new Map([["kind",q.enum.verdict],["prevailingMetadataId",q.enum.verdict],["reason",q.enum.reason]]),fields:q.options,fieldError:Mt,skippedIssues:e=>{if(!pe(e.kind))return[];let t=$o.safeParse(e);return t.success?[]:t.error.issues}};function Cr(e){return me(e,Xo)}var Sr=c.object({intent:c.literal("detect")}).strict(),Wo=ge.extract(["BODY_INVALID","DEPLOYMENT_DISABLED"]),Er=c.object({code:Wo}).strict();var Be=E.enum(["document_authority.command","policy_conflict.decided","policy_conflict.detected","governance.maintenance"]),zt=E.object({validUntil:S.nullable(),supersededByMetadataId:p.nullable()}).strict(),Jo=E.object({metadataId:p,before:zt,after:zt}).strict(),jt={authorityTier:D,policyCategory:w,validFrom:S,validUntil:S.nullable(),approvedBy:F.nullable(),withdrawnBy:F.nullable(),replacesMetadataId:p.nullable(),supersededByMetadataId:p.nullable()},en=Object.keys(jt),kt=E.object({approvalStatus:T,...jt,replaced:Jo.optional()}).strict().superRefine((e,t)=>{ne(e.validFrom,e.validUntil,["validUntil"],t),Se(e.approvalStatus,e.approvedBy!==null,e.withdrawnBy!==null,{approval:["approvedBy"],withdrawal:["withdrawnBy"]},t)}),tn=E.object({deleted:E.literal(!0)}).strict(),Gt=E.object({resolutionStatus:ee,sourceMetadataId:p,targetMetadataId:p,prevailingMetadataId:p.nullable(),arbitrationDecision:Ie.nullable(),factsHash:j}).strict().superRefine((e,t)=>{oe(e.sourceMetadataId,e.targetMetadataId,["targetMetadataId"],t),Ce(e.resolutionStatus==="RESOLVED",e.prevailingMetadataId,e.sourceMetadataId,e.targetMetadataId,["prevailingMetadataId"],t),e.resolutionStatus==="UNRESOLVED"!=(e.arbitrationDecision===null)&&i(t,["arbitrationDecision"],"A decided pair carries its reason, and an unresolved pair none")}),on=qe.omit({reason:!0}),nn=E.object({policyCategory:w,asOf:x,inserted:g,factsChanged:g,reopened:g,cleared:g,activePairs:g,failedGroups:E.array(on)}).strict().superRefine((e,t)=>{e.inserted+e.factsChanged+e.reopened+e.cleared===0&&e.failedGroups.length===0&&i(t,[],"A detection is recorded only for a subject it changed"),e.inserted+e.factsChanged>e.activePairs&&i(t,["factsChanged"],"The pairs whose facts changed are among the standing pairs the detection did not insert"),e.inserted+e.reopened>e.activePairs&&i(t,["reopened"],"The pairs that reappeared are among the standing pairs the detection did not insert"),e.failedGroups.forEach((o,n)=>{o.policyCategory!==e.policyCategory&&i(t,["failedGroups",n,"policyCategory"],"A subject records its own failed groups")})}),rn=E.object({event:E.literal(Be.enum["document_authority.command"]),command:I,authorityId:p,metadataId:p,before:kt.nullable(),after:E.union([kt,tn]),rowVersionBefore:ie.nullable(),rowVersionAfter:ie.nullable()}).strict(),an=E.object({event:E.literal(Be.enum["policy_conflict.decided"]),conflictId:p,before:Gt,after:Gt}).strict(),cn=E.object({event:E.literal(Be.enum["policy_conflict.detected"]),before:E.null(),after:nn}).strict(),sn=(e,t,o)=>{if((e.command==="approve"&&t.replacesMetadataId!==null)!==(t.replaced!==void 0)&&i(o,["after","replaced"],"An approval that replaces another row records that row's change, and nothing else does"),t.replaced===void 0)return;let{replaced:a}=t;a.metadataId!==t.replacesMetadataId&&i(o,["after","replaced","metadataId"],"The replaced row is the one the approved row names"),a.before.supersededByMetadataId!==null&&i(o,["after","replaced","before","supersededByMetadataId"],"The replaced row was not yet superseded"),a.after.supersededByMetadataId!==e.metadataId&&i(o,["after","replaced","after","supersededByMetadataId"],"The replaced row is superseded by the approved document version");let s=a.before.validUntil,u=s===null?null:O(s,t.validFrom),m=s===null?t.validFrom:u===null?null:u===1?t.validFrom:s,f=a.after.validUntil===null||m===null?null:O(a.after.validUntil,m);(a.after.validUntil===null||f!==null&&f!==0)&&i(o,["after","replaced","after","validUntil"],"The replaced row ends when the approved row takes effect, unless it had already ended")},ln=(e,t,o)=>{let n=t[e],a=o[e];if(n===a)return!0;if(e!=="validFrom"&&e!=="validUntil"||typeof n!="string"||typeof a!="string")return!1;let s=O(n,a);return s===null||s===0},dn=(e,t,o,n)=>{let a=Q[e.command],s=en.filter(u=>!a.changes.includes(u));for(let u of s)a.before===null?o!==null&&o[u]!==null&&i(n,["after",u],`The ${e.command} command leaves ${u} empty`):t!==null&&o!==null&&!ln(u,t,o)&&i(n,["after",u],`The ${e.command} command keeps ${u}`)},un=(e,t)=>{let o=Q[e.command],{before:n}=e,a="deleted"in e.after?null:e.after;o.before===null!=(n===null)?i(t,["before"],"Only a create records no image before the command"):n!==null&&n.approvalStatus!==o.before&&i(t,["before","approvalStatus"],`The ${e.command} command finds a row whose status is ${o.before}`),o.after===null!=(a===null)?i(t,["after"],"Only a delete records the deleted marker after the command"):a!==null&&a.approvalStatus!==o.after&&i(t,["after","approvalStatus"],`The ${e.command} command leaves a row whose status is ${o.after}`),o.before===null!=(e.rowVersionBefore===null)&&i(t,["rowVersionBefore"],"The row version before is recorded exactly when a row existed before the command"),o.after===null!=(e.rowVersionAfter===null)&&i(t,["rowVersionAfter"],"The row version after is recorded exactly when a row exists after the command"),n?.replaced!==void 0&&i(t,["before","replaced"],"Only the image after an approval records the replaced row's change"),o.requiresNeverApproved&&n!==null&&n.approvedBy!==null&&i(t,["before","approvedBy"],`The ${e.command} command applies only to a row never approved`),o.requiresNoReplacement&&n!==null&&n.replacesMetadataId!==null&&i(t,["before","replacesMetadataId"],`The ${e.command} command applies only to a row that replaces no other; a replacing approval ends by deprecation`);for(let[s,u]of[["before",n],["after",a]])u!==null&&u.replacesMetadataId===e.metadataId&&i(t,[s,"replacesMetadataId"],"A row does not replace its own document version");dn(e,n,a,t),a!==null&&sn(e,a,t)},pn=(e,t)=>{let{before:o,after:n}=e;o.resolutionStatus!=="UNRESOLVED"&&i(t,["before","resolutionStatus"],"A decision is taken on an unresolved pair"),n.resolutionStatus==="UNRESOLVED"&&i(t,["after","resolutionStatus"],"A decision resolves or ignores the pair"),(n.sourceMetadataId!==o.sourceMetadataId||n.targetMetadataId!==o.targetMetadataId)&&i(t,["after"],"A decision keeps the pair"),n.factsHash!==o.factsHash&&i(t,["after","factsHash"],"A decision records the facts it was taken on")},Tr=E.discriminatedUnion("event",[rn,an,cn]).superRefine((e,t)=>{e.event==="document_authority.command"?un(e,t):e.event==="policy_conflict.decided"&&pn(e,t)});import{TenantIdSchema as B}from"@aiquants/enrichment-core";import{z as d}from"zod";var qt=d.enum(["ENABLE_VECTOR_SEARCH","ENABLE_VECTOR_INDEXING","ENABLE_GRAPH_SEARCH","ENABLE_GRAPH_INDEXING","ENABLE_ASSET_EXTRACTION","ENABLE_MEDIA_ANALYSIS","ENABLE_OCR","ENABLE_DYNAMIC_CLASSIFIER_RULES","ENABLE_SEMANTIC_CACHE","ENABLE_CONTEXT_COMPRESSION","ENABLE_MULTI_AGENT_SWARM","ENABLE_AUTONOMOUS_ONTOLOGY","ENABLE_MERKLE_CITATION_PROOF","ENABLE_REALTIME_CDC_INGESTION","ENABLE_COLPALI_IMAGE_INDEXING"]),Ur=d.object({tenantId:B,flagKey:qt,isEnabled:d.boolean(),description:d.string(),updatedBy:d.string(),updatedAt:d.string()}),mn=d.enum(["ocr","enrichment","transcription","asset_extraction","vector_indexing","graph_indexing","governance_answer"]),Nr=["ocr","enrichment","transcription","governance_answer"],Fr=d.object({tenantId:B,confidentialityLevel:nt,capability:mn,isEnabled:d.boolean(),allowCloudProvider:d.boolean(),promptKey:d.string().min(1).nullable(),description:d.string().nullable(),updatedBy:d.string(),updatedAt:d.string()}),Lr=d.object({tenantId:B,parameterKey:d.string().min(1),parameterValue:d.string(),dataType:d.enum(["string","int","float","bool","json"]),description:d.string(),isSecret:d.boolean(),updatedBy:d.string(),updatedAt:d.string()}),Mr=d.object({tenantId:B,promptKey:d.string().min(1),promptVersion:d.number().int(),promptTemplate:d.string(),provider:d.string(),modelName:d.string(),temperature:d.number(),maxTokens:d.number().int(),isSystemPrompt:d.boolean(),description:d.string(),updatedBy:d.string(),updatedAt:d.string()}),zr=d.object({tenantId:B,flagKey:qt,isEnabled:d.boolean(),updatedBy:d.string().min(1)}),kr=d.object({tenantId:B,parameterKey:d.string().min(1),parameterValue:d.string(),updatedBy:d.string().min(1)}),Gr=d.object({tenantId:B,promptKey:d.string().min(1),promptTemplate:d.string().min(1,"promptTemplate must not be empty"),provider:d.string().min(1),modelName:d.string().min(1),temperature:d.number().min(0).max(2).optional(),maxTokens:d.number().int().positive().optional(),updatedBy:d.string().min(1)}),fn=d.union([d.string(),d.number(),d.boolean(),d.null()]),Vt=d.lazy(()=>d.union([fn,d.array(Vt),d.record(Vt)]));export{yt as AUTHORITY_CANDIDATE_PAGE_LIMIT_MAX,So as AUTHORITY_SEARCH_QUERY_MAX_LENGTH,it as AUTHORITY_SEARCH_QUERY_MIN_LENGTH,T as ApprovalStatusSchema,Ke as AuthoritativeSourceSchema,zn as AuthorityCandidatePageSchema,jn as AuthorityCandidateQuerySchema,Un as AuthorityCandidateSchema,At as AuthoritySearchTextSchema,D as AuthorityTierSchema,Z as BaseGovernanceClient,Nr as CLOUD_CAPABLE_CAPABILITIES,io as CitationProofLeafSchema,co as CitationProofSchema,Fr as ConfidentialityCapabilityPolicyDtoSchema,nt as ConfidentialityLevelSchema,Q as DOCUMENT_AUTHORITY_COMMAND_RULES,ft as DOCUMENT_AUTHORITY_PAGE_LIMIT_MAX,tn as DeletedDocumentAuthorityEventImageSchema,qn as DocumentAuthorityCommandBlockerSchema,Et as DocumentAuthorityCommandFieldErrorSchema,ae as DocumentAuthorityCommandFieldReasonSchema,L as DocumentAuthorityCommandFieldSchema,I as DocumentAuthorityCommandKindSchema,K as DocumentAuthorityCommandRejectionCodeSchema,Hn as DocumentAuthorityCommandRejectionSchema,hr as DocumentAuthorityCommandResultSchema,Do as DocumentAuthorityCommandSchema,kt as DocumentAuthorityEventImageSchema,Gn as DocumentAuthorityPageQuerySchema,Ro as DocumentAuthorityPageSchema,Mn as DocumentAuthorityPageWithCategoriesSchema,_ as DocumentAuthorityRowSchema,M as DocumentRefSchema,Fo as FailedTieGroupReasonSchema,qe as FailedTieGroupSchema,qt as FeatureFlagKeySchema,eo as FileUriSchema,Dt as GovernanceAdminClient,Je as GovernanceAnswerRequestSchema,et as GovernanceAnswerResponseSchema,gt as GovernanceClient,V as GovernanceClientError,no as GovernanceSearchHitSchema,Le as GovernanceSearchMetadataSchema,Ze as GovernanceSearchRequestSchema,We as GovernanceSearchResponseSchema,to as GovernanceSearchSnippetSchema,Qe as GovernanceSimulateCaseDiffSchema,Fe as GovernanceSimulateCaseScoresSchema,tt as GovernanceSimulateRequestSchema,ot as GovernanceSimulateResponseSchema,Ne as GovernanceSimulateScoresSchema,mn as GovernedCapabilitySchema,fn as JsonPrimitiveSchema,Vt as JsonValueSchema,Tr as KnowledgeGovernanceEventRecordSchema,Be as KnowledgeGovernanceEventSchema,w as NormalizedPolicyCategorySchema,Ue as NormalizedScoreSchema,Xe as OPERATOR_IDENTIFIER_MAX_LENGTH,S as OffsetIsoInstantSchema,ze as POLICY_CATEGORY_MAX_LENGTH,Ln as POLICY_CATEGORY_UNICODE_VERSION,ho as POLICY_CATEGORY_WHITESPACE_CODE_POINTS,Oo as POLICY_CONFLICT_DECISION_REASON_BLANK_CODE_POINTS,Ut as POLICY_CONFLICT_DECISION_REASON_MAX_LENGTH,_t as POLICY_CONFLICT_PAGE_LIMIT_MAX,Uo as POLICY_CONFLICT_SUMMARY_MAX_LENGTH,ut as PolicyCategoryRejectionSchema,Co as PolicyCategorySchema,zo as PolicyConflictCountsSchema,Gt as PolicyConflictDecisionEventImageSchema,Mt as PolicyConflictDecisionFieldErrorSchema,bt as PolicyConflictDecisionFieldReasonSchema,q as PolicyConflictDecisionFieldSchema,Tt as PolicyConflictDecisionKindSchema,ge as PolicyConflictDecisionRejectionCodeSchema,Ar as PolicyConflictDecisionRejectionSchema,Yo as PolicyConflictDecisionSchema,Ho as PolicyConflictDetailSchema,nn as PolicyConflictDetectedEventImageSchema,on as PolicyConflictDetectedFailedGroupSchema,Ko as PolicyConflictDetectionFailureReasonSchema,Qo as PolicyConflictDetectionOutcomeSchema,Wo as PolicyConflictDetectionRequestRejectionCodeSchema,Er as PolicyConflictDetectionRequestRejectionSchema,Sr as PolicyConflictDetectionRequestSchema,ko as PolicyConflictDetectionStateSchema,ce as PolicyConflictFactsSchema,yr as PolicyConflictPageQuerySchema,fr as PolicyConflictPageSchema,ro as PolicyConflictRefSchema,ee as PolicyConflictResolutionStatusSchema,Lt as PolicyConflictRowSchema,ue as PolicyConflictSeveritySchema,Ot as PolicyConflictStateSchema,jo as PolicyConflictSummarySchema,Lo as PolicyConflictUnmeasuredReasonSchema,Go as PolicyConflictViewerSchema,Mr as PromptTemplateDtoSchema,ht as REPLACEABLE_AUTHORITY_PAGE_LIMIT_MAX,qo as RecordedPolicyConflictDecisionSchema,oo as RelatedDecisionSchema,kn as ReplaceableAuthorityPageSchema,Vn as ReplaceableAuthorityQuerySchema,Jo as ReplacedAuthorityChangeSchema,ie as RowVersionSchema,dt as SEVERITY_BY_TIER,j as Sha256HexSchema,Ie as StoredDecisionReasonSchema,Ur as SystemFeatureFlagDtoSchema,Lr as SystemParameterDtoSchema,de as TenantIdSchema,zr as UpdateFeatureFlagRequestSchema,kr as UpdateParameterRequestSchema,Gr as UpdatePromptTemplateRequestSchema,x as UtcInstantSchema,ao as VerifiedCitationSchema,Ge as bytesToHex,ur as canonicalPolicyConflictFactsJson,Yn as checkDocumentAuthorityCommand,Cr as checkPolicyConflictDecision,vo as computeCitationLeafHash,To as computeCitationMerkleRoot,bo as constantTimeCompare,Ct as documentAuthorityCommandBlocker,Nn as equalRankGroups,Bn as isDocumentAuthorityCommandAvailable,yo as isEligibleAuthority,mt as normalizePolicyCategory,_n as offsetIsoOfUtcInstant,fo as parseUtcInstant,pr as policyConflictFactsHash,mr as policyConflictFactsOf,Re as sha256,Fn as tiePairs,On as utcInstantOfOffsetIso,Rt as verifyCitationProof};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiquants/enrichment-governance-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Enterprise knowledge governance core: canonical schemas, document authority ledger rules, policy conflict contracts, governance event record, Merkle proof, dry-run simulation, and API client SDK.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"governance",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"LICENSE"
|
|
47
47
|
],
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@aiquants/enrichment-core": "^0.
|
|
49
|
+
"@aiquants/enrichment-core": "^0.5.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@vitest/coverage-v8": "^4.1.8",
|