@aiquants/governance-core 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +76 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +1905 -0
- package/dist/index.d.ts +1905 -0
- package/dist/index.js +1 -0
- package/package.json +83 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var v=class extends Error{statusCode;responseBody;parsedBody;constructor(t,a,i,o){super(t),this.name="GovernanceClientError",this.statusCode=a,this.responseBody=i,this.parsedBody=o}},C=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 a=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey){let i;try{i=new URL(a)}catch{throw new Error(`Invalid baseUrl format: ${t.baseUrl}`)}if(i.protocol==="http:"){let o=i.hostname.toLowerCase();if(!(o==="localhost"||o==="127.0.0.1"||o==="[::1]"||o==="::1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.")}}this.baseUrl=a,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,a,i,o,s){let u=new URL(t.startsWith("/")?t.slice(1):t,`${this.baseUrl}/`);if(o)for(let[l,p]of Object.entries(o))p!=null&&p.trim().length>0&&u.searchParams.append(l,p);let d=u.toString(),h={Accept:"application/json"};this.apiKey&&(h.Authorization=`Bearer ${this.apiKey}`),i!==void 0&&(h["Content-Type"]="application/json");let g=new AbortController,U=setTimeout(()=>g.abort(),this.timeoutMs),b=g.signal;s&&(b=AbortSignal.any([g.signal,s]));try{let l=await this.fetchFn(d,{method:a,headers:h,body:i!==void 0?JSON.stringify(i):void 0,signal:b}),p=await l.text();if(!l.ok){let m;try{m=JSON.parse(p)}catch{}throw new v(`API request failed with status ${l.status}: ${p}`,l.status,p,m)}if(p.trim().length===0)return;try{return JSON.parse(p)}catch(m){let R=m.message;throw new v(`Failed to parse response JSON from ${d}: ${R}`,l.status,p)}}catch(l){if(l instanceof v)throw l;let p=l instanceof Error?l.message:String(l);throw new v(`Network request failed for ${a} ${d}: ${p}`,0,"")}finally{clearTimeout(U)}}};import{ConfidentialityLevelSchema as le,FileUriSchema as pe,TenantIdSchema as I}from"@aiquants/enrichment-core";import{z as e}from"zod";import{ConfidentialityLevelSchema as Z}from"@aiquants/enrichment-core";var $=e.object({query:e.string().min(1,"Search query must not be empty"),policyCategory:e.string().optional(),includeHistoricalRevisions:e.boolean().optional(),maxAuthorityTier:e.union([e.literal(1),e.literal(2),e.literal(3),e.literal(4),e.literal(5)]).optional(),limit:e.number().int().positive().optional()}),me=e.object({text:e.string(),citationText:e.string(),chunkHash:e.string(),chunkIndex:e.number().int().nonnegative(),parentChunkUid:e.string().optional(),clauseIdentifier:e.string().optional(),breadcrumbPath:e.array(e.string()).optional(),page:e.number().int().optional(),sheetName:e.string().optional(),slideIndex:e.number().int().optional(),timestampSec:e.number().optional(),score:e.number()}),ue=e.object({decisionId:e.string(),title:e.string(),approvedBy:e.string()}),H=e.union([e.literal(1),e.literal(2),e.literal(3),e.literal(4),e.literal(5)]),fe=e.object({metadataId:e.number().int(),fileUri:pe,fileName:e.string(),documentTitle:e.string(),authorityTier:H.nullable(),validFrom:e.string().nullable(),validUntil:e.string().nullable(),isCurrentlyAuthoritative:e.boolean(),confidentialityLevel:le,snippets:e.array(me),relatedDecisions:e.array(ue).optional(),policyWarning:e.string().optional()}),M=e.object({searchMode:e.enum(["tri_store","sql_vector","sql_keyword_degraded"]),qualityTier:e.enum(["HIGH_TRI_STORE","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),isDegraded:e.boolean(),degradationReason:e.string().nullable(),circuitBreakerStatus:e.record(e.enum(["CLOSED","OPEN","HALF_OPEN","HEALTHY"])),executionTimeMs:e.number().nonnegative()}),J=e.object({hits:e.array(fe),tiers:e.object({sql:e.boolean(),vector:e.boolean(),graph:e.boolean()}),masked:e.boolean(),searchMetadata:M}),X=e.object({question:e.string().min(1,"Question must not be empty"),asOf:e.string().optional(),asOfTx:e.string().optional()}),V=e.object({metadataId:e.number().int(),documentTitle:e.string(),authorityTier:H,approvalStatus:e.enum(["DRAFT","APPROVED","DEPRECATED"]),validFrom:e.string(),validUntil:e.string().nullable(),isCurrentlyAuthoritative:e.boolean()}),de=e.object({conflictId:e.number().int(),sourceMetadataId:e.number().int(),targetMetadataId:e.number().int(),conflictSummary:e.string(),severity:e.enum(["LOW","MEDIUM","HIGH","CRITICAL"]),resolutionStatus:e.enum(["OPEN","IN_REVIEW","RESOLVED"])}),he=e.object({chunkUid:e.string().uuid("chunkUid must be a valid UUID"),metadataId:e.number().int(),documentTitle:e.string(),clauseIdentifier:e.string(),breadcrumbPath:e.array(e.string()),exactQuotedText:e.string(),chunkHash:e.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),authorityTier:H,isVerified:e.boolean()}),F=e.string().regex(/^[0-9a-f]{64}$/,"Must be a 64-character lowercase hexadecimal SHA-256 digest"),ye=e.object({chunkUid:e.string().uuid("chunkUid must be a valid UUID"),chunkHash:F}),xe=e.object({algorithm:e.literal("SHA-256"),merkleRoot:F,leafCount:e.number().int().positive(),leaves:e.array(ye).min(1),tenantId:I,scopeDigest:F,asOf:e.string().datetime(),asOfTx:e.string().datetime(),generatedAt:e.string().datetime(),signature:e.string().min(1,"Signature must not be empty")}),W=e.object({answer:e.string(),authoritative:e.array(V),superseded:e.array(V),conflicts:e.array(de),verifiedCitations:e.array(he),citationProof:xe.nullable(),isFullyGrounded:e.boolean(),requiresHumanArbitration:e.boolean(),tiers:e.object({sql:e.boolean(),vector:e.boolean(),graph:e.boolean()}),searchMetadata:M}),Y=e.object({promptOverrides:e.record(e.string()).optional(),parameterOverrides:e.record(e.union([e.string(),e.number(),e.boolean()])).optional(),strategyOverrides:e.record(e.record(e.union([e.string(),e.number(),e.boolean()]))).optional(),intentTypes:e.array(e.enum(["SET","DIFF","PATH","NEGATION","COUNT"])).optional()}),D=e.number().min(0).max(1),k=e.object({contextRelevance:D,groundedness:D,answerRelevance:D}),z=k.extend({meanAnswerChars:e.number().nonnegative(),meanLatencyMs:e.number().nonnegative()}),K=e.object({caseId:e.string(),intentType:e.enum(["SET","DIFF","PATH","NEGATION","COUNT"]),beforeScores:k,afterScores:k}),Q=e.object({simulationId:e.string(),evaluatedCount:e.number().int().nonnegative(),before:z,after:z,delta:z,regressions:e.array(K),improvements:e.array(K),searchMetadata:M});var j=new Uint8Array([0]),P=new Uint8Array([1]),Se=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 f(r,t){return r>>>t|r<<32-t}function ee(r){let t=1779033703,a=3144134277,i=1013904242,o=2773480762,s=1359893119,u=2600822924,d=528734635,h=1541459225,g=r.length,U=g*8,b=(g+8>>6)+1<<6,l=new Uint8Array(b);l.set(r),l[g]=128;let p=new DataView(l.buffer,l.byteOffset,l.byteLength);p.setUint32(b-4,U>>>0,!1),p.setUint32(b-8,Math.floor(U/4294967296),!1);let m=new Uint32Array(64);for(let q=0;q<b;q+=64){for(let c=0;c<16;c++)m[c]=p.getUint32(q+c*4,!1);for(let c=16;c<64;c++){let L=f(m[c-15],7)^f(m[c-15],18)^m[c-15]>>>3,_=f(m[c-2],17)^f(m[c-2],19)^m[c-2]>>>10;m[c]=m[c-16]+L+m[c-7]+_>>>0}let x=t,E=a,T=i,O=o,S=s,G=u,w=d,N=h;for(let c=0;c<64;c++){let L=f(S,6)^f(S,11)^f(S,25),_=S&G^~S&w,B=N+L+_+Se[c]+m[c]>>>0,ie=f(x,2)^f(x,13)^f(x,22),se=x&E^x&T^E&T,ce=ie+se>>>0;N=w,w=G,G=S,S=O+B>>>0,O=T,T=E,E=x,x=B+ce>>>0}t=t+x>>>0,a=a+E>>>0,i=i+T>>>0,o=o+O>>>0,s=s+S>>>0,u=u+G>>>0,d=d+w>>>0,h=h+N>>>0}let R=new Uint8Array(32),y=new DataView(R.buffer,R.byteOffset,R.byteLength);return y.setUint32(0,t,!1),y.setUint32(4,a,!1),y.setUint32(8,i,!1),y.setUint32(12,o,!1),y.setUint32(16,s,!1),y.setUint32(20,u,!1),y.setUint32(24,d,!1),y.setUint32(28,h,!1),R}function ge(r){let t="";for(let a=0;a<r.length;a++)t+=r[a].toString(16).padStart(2,"0");return t}function be(r,t){if(r.length!==t.length)return!1;let a=0;for(let i=0;i<r.length;i++)a|=r.charCodeAt(i)^t.charCodeAt(i);return a===0}function ve(r,t,a){if(!(r?.trim()&&t?.trim()&&a?.trim()))throw new Error("tenantId, chunkUid, and chunkHash must be non-empty strings.");if(r.includes("")||t.includes("")||a.includes(""))throw new Error("Parameters must not contain delimiter control characters.");let o=new TextEncoder().encode(`${r}${t}${a}`),s=new Uint8Array(j.length+o.length);return s.set(j,0),s.set(o,j.length),ee(s)}function Ae(r){if(!r||r.length===0)return null;for(let a=0;a<r.length;a++)if(!(r[a]instanceof Uint8Array)||r[a].length!==32)throw new Error(`Leaf at index ${a} must be a 32-byte Uint8Array.`);let t=[...r];for(;t.length>1;){let a=[];for(let i=0;i<t.length-1;i+=2){let o=t[i],s=t[i+1],u=new Uint8Array(P.length+o.length+s.length);u.set(P,0),u.set(o,P.length),u.set(s,P.length+o.length),a.push(ee(u))}t.length%2===1&&a.push(t[t.length-1]),t=a}return ge(t[0])}function te(r,t){try{if(!r||typeof r!="object"||r.algorithm!=="SHA-256"||t?.expectedTenantId&&r.tenantId!==t.expectedTenantId||!Array.isArray(r.leaves)||r.leafCount!==r.leaves.length||r.leafCount===0)return!1;if(t?.expectedCitations){if(t.expectedCitations.length!==r.leaves.length)return!1;for(let o=0;o<r.leaves.length;o++)if(t.expectedCitations[o].chunkUid!==r.leaves[o].chunkUid||t.expectedCitations[o].chunkHash!==r.leaves[o].chunkHash)return!1}for(let o=0;o<r.leaves.length;o++){let s=r.leaves[o];if(!s||typeof s!="object"||!s.chunkUid||!s.chunkHash||o>0&&r.leaves[o].chunkUid<=r.leaves[o-1].chunkUid)return!1}let a=[];for(let o of r.leaves)a.push(ve(r.tenantId,o.chunkUid,o.chunkHash));let i=Ae(a);return!i||typeof r.merkleRoot!="string"?!1:be(i,r.merkleRoot)}catch{return!1}}var ne=class extends C{async search(t,a){let i=$.parse(t),o=a?{tenant_id:I.parse(a)}:void 0,s=await this.request("/ai/governance/search","POST",i,o);return J.parse(s)}async answer(t,a){let i=X.parse(t),o=a?{tenant_id:I.parse(a)}:void 0,s=await this.request("/ai/governance/answer","POST",i,o);return W.parse(s)}verifyCitationProof(t,a){return te(t,a)}};import{TenantIdSchema as Re}from"@aiquants/enrichment-core";var re=class extends C{async simulate(t,a){let i=Y.parse(t),o=a?{tenant_id:Re.parse(a)}:void 0,s=await this.request("/ai/governance/simulate","POST",i,o);return Q.parse(s)}};import{TenantIdSchema as A}from"@aiquants/enrichment-core";import{z as n}from"zod";var oe=n.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"]),je=n.object({tenantId:A,flagKey:oe,isEnabled:n.boolean(),description:n.string(),updatedBy:n.string(),updatedAt:n.string()}),Ce=n.enum(["ocr","enrichment","transcription","asset_extraction","vector_indexing","graph_indexing","governance_answer"]),Be=["ocr","enrichment","transcription","governance_answer"],Ve=n.object({tenantId:A,confidentialityLevel:Z,capability:Ce,isEnabled:n.boolean(),allowCloudProvider:n.boolean(),promptKey:n.string().min(1).nullable(),description:n.string().nullable(),updatedBy:n.string(),updatedAt:n.string()}),Ke=n.object({tenantId:A,parameterKey:n.string().min(1),parameterValue:n.string(),dataType:n.enum(["string","int","float","bool","json"]),description:n.string(),isSecret:n.boolean(),updatedBy:n.string(),updatedAt:n.string()}),$e=n.object({tenantId:A,promptKey:n.string().min(1),promptVersion:n.number().int(),promptTemplate:n.string(),provider:n.string(),modelName:n.string(),temperature:n.number(),maxTokens:n.number().int(),isSystemPrompt:n.boolean(),description:n.string(),updatedBy:n.string(),updatedAt:n.string()}),Je=n.object({tenantId:A,flagKey:oe,isEnabled:n.boolean(),updatedBy:n.string().min(1)}),Xe=n.object({tenantId:A,parameterKey:n.string().min(1),parameterValue:n.string(),updatedBy:n.string().min(1)}),We=n.object({tenantId:A,promptKey:n.string().min(1),promptTemplate:n.string().min(1,"promptTemplate must not be empty"),provider:n.string().min(1),modelName:n.string().min(1),temperature:n.number().min(0).max(2).optional(),maxTokens:n.number().int().positive().optional(),updatedBy:n.string().min(1)}),Ee=n.union([n.string(),n.number(),n.boolean(),n.null()]),ae=n.lazy(()=>n.union([Ee,n.array(ae),n.record(ae)]));export{V as AuthoritativeSourceSchema,H as AuthorityTierSchema,C as BaseGovernanceClient,Be as CLOUD_CAPABLE_CAPABILITIES,ye as CitationProofLeafSchema,xe as CitationProofSchema,Ve as ConfidentialityCapabilityPolicyDtoSchema,Z as ConfidentialityLevelSchema,oe as FeatureFlagKeySchema,pe as FileUriSchema,re as GovernanceAdminClient,X as GovernanceAnswerRequestSchema,W as GovernanceAnswerResponseSchema,ne as GovernanceClient,v as GovernanceClientError,fe as GovernanceSearchHitSchema,M as GovernanceSearchMetadataSchema,$ as GovernanceSearchRequestSchema,J as GovernanceSearchResponseSchema,me as GovernanceSearchSnippetSchema,K as GovernanceSimulateCaseDiffSchema,k as GovernanceSimulateCaseScoresSchema,Y as GovernanceSimulateRequestSchema,Q as GovernanceSimulateResponseSchema,z as GovernanceSimulateScoresSchema,Ce as GovernedCapabilitySchema,Ee as JsonPrimitiveSchema,ae as JsonValueSchema,D as NormalizedScoreSchema,de as PolicyConflictRefSchema,$e as PromptTemplateDtoSchema,ue as RelatedDecisionSchema,F as Sha256HexSchema,je as SystemFeatureFlagDtoSchema,Ke as SystemParameterDtoSchema,I as TenantIdSchema,Je as UpdateFeatureFlagRequestSchema,Xe as UpdateParameterRequestSchema,We as UpdatePromptTemplateRequestSchema,he as VerifiedCitationSchema,ge as bytesToHex,ve as computeCitationLeafHash,Ae as computeCitationMerkleRoot,be as constantTimeCompare,ee as sha256,te as verifyCitationProof};
|
package/package.json
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aiquants/governance-core",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Enterprise knowledge governance core: canonical schemas, Merkle proof, dry-run simulation, and API client SDK.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"governance",
|
|
7
|
+
"knowledge-graph",
|
|
8
|
+
"rag",
|
|
9
|
+
"merkle-tree",
|
|
10
|
+
"citation-proof",
|
|
11
|
+
"dry-run",
|
|
12
|
+
"typescript"
|
|
13
|
+
],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"author": "AI Quants",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/fehde-k/aiquants.git",
|
|
19
|
+
"directory": "packages/governance-core"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/fehde-k/aiquants/tree/main/packages/governance-core#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/fehde-k/aiquants/issues"
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "./dist/index.cjs",
|
|
28
|
+
"module": "./dist/index.js",
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"import": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"require": {
|
|
37
|
+
"types": "./dist/index.d.cts",
|
|
38
|
+
"default": "./dist/index.cjs"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist",
|
|
44
|
+
"README.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
],
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@aiquants/enrichment-core": "^0.1.1"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@vitest/coverage-v8": "^4.1.8",
|
|
52
|
+
"rimraf": "^6.1.2",
|
|
53
|
+
"tsup": "^8.5.1",
|
|
54
|
+
"typescript": "^5.9.3",
|
|
55
|
+
"vitest": "^4.1.8",
|
|
56
|
+
"zod": "^3.25.76"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"zod": "^3.25.0"
|
|
60
|
+
},
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=18.0.0",
|
|
63
|
+
"pnpm": ">=8.0.0"
|
|
64
|
+
},
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public"
|
|
67
|
+
},
|
|
68
|
+
"scripts": {
|
|
69
|
+
"build": "tsup && node ../../.config/scripts/strip-dts-comments.mjs dist",
|
|
70
|
+
"build:watch": "tsup --watch",
|
|
71
|
+
"dev": "tsup --watch",
|
|
72
|
+
"publish:patch": "pnpm run typecheck && pnpm run --if-present test && pnpm version patch --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
73
|
+
"publish:minor": "pnpm run typecheck && pnpm run --if-present test && pnpm version minor --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
74
|
+
"publish:major": "pnpm run typecheck && pnpm run --if-present test && pnpm version major --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
75
|
+
"typecheck": "tsc --noEmit",
|
|
76
|
+
"clean": "rimraf dist",
|
|
77
|
+
"lint": "biome lint src/",
|
|
78
|
+
"check": "biome check src/ tests/",
|
|
79
|
+
"check:fix": "biome check --write src/ tests/",
|
|
80
|
+
"test": "vitest run",
|
|
81
|
+
"test:coverage": "vitest run --coverage"
|
|
82
|
+
}
|
|
83
|
+
}
|