@fortemi/core 2026.7.9 → 2026.7.11
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/aiwg-index.js +12 -12
- package/dist/aiwg-index.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.js +136 -27
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/aiwg-index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import Gn from'ajv/dist/2020.js';import {gzipSync,gunzipSync}from'fflate';import {v5}from'uuid';var L="1.2.0",ge="matric-shard";async function re(e){let t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(n);return Array.from(r).map(i=>i.toString(16).padStart(2,"0")).join("")}async function he(e,t){let n=[];for(let[r,i]of Object.entries(e)){let s=t.get(r);if(!s){n.push(r);continue}await re(s)!==i&&n.push(r);}return {valid:n.length===0,failures:n}}var _e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/manifest.schema.json",title:"Fortemi Knowledge Shard core-v1 manifest",type:"object",additionalProperties:false,required:["version","profile","producer","format","created_at","components","counts","checksums","min_reader_version"],properties:{version:{$ref:"#/$defs/strictSemVer"},profile:{const:"core-v1"},producer:{type:"object",additionalProperties:false,required:["name","version"],properties:{name:{type:"string",minLength:1},version:{type:"string",minLength:1},revision:{type:"string",minLength:1}}},matric_version:{type:"string",minLength:1,deprecated:true},format:{const:"matric-shard"},created_at:{type:"string",format:"date-time"},components:{type:"array",minItems:1,uniqueItems:true,items:{enum:["notes","collections","tags","templates","links"]}},counts:{$ref:"#/$defs/counts"},checksums:{type:"object",propertyNames:{enum:["notes.jsonl","collections.json","tags.json","templates.json","links.jsonl"]},additionalProperties:{$ref:"#/$defs/sha256"}},min_reader_version:{$ref:"#/$defs/strictSemVer"},migrated_from:{$ref:"#/$defs/strictSemVer"},migration_history:{type:"array",items:{type:"object",additionalProperties:false,required:["from_version","to_version","migrated_at","migrated_by","changes"],properties:{from_version:{$ref:"#/$defs/strictSemVer"},to_version:{$ref:"#/$defs/strictSemVer"},migrated_at:{type:"string",format:"date-time"},migrated_by:{type:"string",minLength:1},changes:{type:"array",minItems:1,items:{type:"string",minLength:1}}}}}},$defs:{strictSemVer:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"},sha256:{type:"string",pattern:"^[0-9a-f]{64}$"},count:{type:"integer",minimum:0},counts:{type:"object",additionalProperties:false,required:["notes","collections","tags","templates","links","embedding_sets","embedding_set_members","embeddings","embedding_configs"],properties:{notes:{$ref:"#/$defs/count"},collections:{$ref:"#/$defs/count"},tags:{$ref:"#/$defs/count"},templates:{$ref:"#/$defs/count"},links:{$ref:"#/$defs/count"},embedding_sets:{const:0},embedding_set_members:{const:0},embeddings:{const:0},embedding_configs:{const:0}}}}};var ye={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/note.schema.json",title:"Fortemi Knowledge Shard core-v1 note record",type:"object",additionalProperties:false,required:["id","title","original_content","revised_content","metadata","format","source","starred","archived","collection_id","created_at","updated_at","tags","attachments"],properties:{id:{$ref:"#/$defs/uuid"},title:{type:["string","null"]},original_content:{type:"string"},revised_content:{type:"string"},metadata:true,format:{type:"string",minLength:1},source:{type:"string",minLength:1},starred:{type:"boolean"},archived:{type:"boolean"},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{$ref:"#/$defs/dateTime"},updated_at:{$ref:"#/$defs/dateTime"},tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},attachments:{type:"array",items:{$ref:"#/$defs/attachmentProjection"}}},$defs:{uuid:{type:"string",format:"uuid"},dateTime:{type:"string",format:"date-time"},sha256:{type:"string",pattern:"^blake3:[0-9a-f]{64}$"},attachmentProjection:{type:"object",additionalProperties:false,required:["extracted_text","extraction_status","reason","attachment"],properties:{extracted_text:{type:["string","null"]},extraction_status:{enum:["extracted","pending","failed","blocked","deferred"]},reason:{enum:[null,"extraction_pending","extractor_failed","quarantined","large_binary","unsupported_mime","no_extracted_text"]},attachment:{type:"object",additionalProperties:false,required:["id","path","mime","checksum","bytes"],properties:{id:{$ref:"#/$defs/uuid"},path:{type:"string",minLength:1},mime:{type:"string",minLength:1},checksum:{$ref:"#/$defs/sha256"},bytes:{type:"integer",minimum:0}}}}}}};var be={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/collection.schema.json",title:"Fortemi Knowledge Shard core-v1 collection record",type:"object",additionalProperties:false,required:["id","name","description","parent_id","created_at","note_count"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},parent_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},note_count:{type:"integer",minimum:0}},$defs:{uuid:{type:"string",format:"uuid"}}};var ve={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/tag.schema.json",title:"Fortemi Knowledge Shard core-v1 tag record",type:"object",additionalProperties:false,required:["name","created_at"],properties:{name:{type:"string",minLength:1},created_at:{type:"string",format:"date-time"}}};var we={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/template.schema.json",title:"Fortemi Knowledge Shard core-v1 template record",type:"object",additionalProperties:false,required:["id","name","description","content","format","default_tags","collection_id","created_at","updated_at"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},content:{type:"string"},format:{type:"string",minLength:1},default_tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},$defs:{uuid:{type:"string",format:"uuid"}}};var $e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/link.schema.json",title:"Fortemi Knowledge Shard core-v1 link record",type:"object",additionalProperties:false,required:["id","from_note_id","to_note_id","to_url","kind","score","created_at","metadata"],properties:{id:{$ref:"#/$defs/uuid"},from_note_id:{$ref:"#/$defs/uuid"},to_note_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},to_url:{type:["string","null"],format:"uri"},kind:{type:"string",minLength:1},score:{type:"number"},created_at:{type:"string",format:"date-time"},metadata:true},oneOf:[{properties:{to_note_id:{$ref:"#/$defs/uuid"},to_url:{type:"null"}}},{properties:{to_note_id:{type:"null"},to_url:{type:"string",format:"uri"}}}],$defs:{uuid:{type:"string",format:"uuid"}}};var ke={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.1.0/core-v1/manifest.schema.json",title:"Fortemi Knowledge Shard core-v1 manifest",type:"object",additionalProperties:false,required:["version","profile","producer","format","created_at","components","counts","checksums","min_reader_version"],properties:{version:{const:"1.1.0"},profile:{const:"core-v1"},producer:{type:"object",additionalProperties:false,required:["name","version"],properties:{name:{type:"string",minLength:1},version:{type:"string",minLength:1},revision:{type:"string",minLength:1}}},matric_version:{type:"string",minLength:1,deprecated:true},format:{const:"matric-shard"},created_at:{type:"string",format:"date-time"},components:{type:"array",minItems:1,uniqueItems:true,items:{enum:["notes","collections","tags","templates","links"]}},counts:{$ref:"#/$defs/counts"},checksums:{type:"object",propertyNames:{enum:["notes.jsonl","collections.json","tags.json","templates.json","links.jsonl"]},additionalProperties:{$ref:"#/$defs/sha256"}},min_reader_version:{const:"1.1.0"},migrated_from:{$ref:"#/$defs/strictSemVer"},migration_history:{type:"array",items:{type:"object",additionalProperties:false,required:["from_version","to_version","migrated_at","migrated_by","changes"],properties:{from_version:{$ref:"#/$defs/strictSemVer"},to_version:{$ref:"#/$defs/strictSemVer"},migrated_at:{type:"string",format:"date-time"},migrated_by:{type:"string",minLength:1},changes:{type:"array",minItems:1,items:{type:"string",minLength:1}}}}}},$defs:{strictSemVer:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"},sha256:{type:"string",pattern:"^[0-9a-f]{64}$"},count:{type:"integer",minimum:0},counts:{type:"object",additionalProperties:false,required:["notes","collections","tags","templates","links","embedding_sets","embedding_set_members","embeddings","embedding_configs"],properties:{notes:{$ref:"#/$defs/count"},collections:{$ref:"#/$defs/count"},tags:{$ref:"#/$defs/count"},templates:{$ref:"#/$defs/count"},links:{$ref:"#/$defs/count"},embedding_sets:{const:0},embedding_set_members:{const:0},embeddings:{const:0},embedding_configs:{const:0}}}}};var Ae={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/manifest.schema.json",title:"Fortemi Knowledge Shard core-v1 manifest",type:"object",additionalProperties:false,required:["version","profile","producer","format","created_at","components","counts","checksums","min_reader_version"],properties:{version:{const:"1.2.0"},profile:{const:"core-v1"},producer:{type:"object",additionalProperties:false,required:["name","version"],properties:{name:{type:"string",minLength:1},version:{type:"string",minLength:1},revision:{type:"string",minLength:1}}},matric_version:{type:"string",minLength:1,deprecated:true},format:{const:"matric-shard"},created_at:{type:"string",format:"date-time"},components:{type:"array",minItems:1,uniqueItems:true,items:{enum:["notes","collections","tags","templates","links"]}},counts:{$ref:"#/$defs/counts"},checksums:{type:"object",propertyNames:{enum:["notes.jsonl","collections.json","tags.json","templates.json","links.jsonl"]},additionalProperties:{$ref:"#/$defs/sha256"}},min_reader_version:{const:"1.2.0"},migrated_from:{$ref:"#/$defs/strictSemVer"},migration_history:{type:"array",items:{type:"object",additionalProperties:false,required:["from_version","to_version","migrated_at","migrated_by","changes"],properties:{from_version:{$ref:"#/$defs/strictSemVer"},to_version:{$ref:"#/$defs/strictSemVer"},migrated_at:{type:"string",format:"date-time"},migrated_by:{type:"string",minLength:1},changes:{type:"array",minItems:1,items:{type:"string",minLength:1}}}}}},$defs:{strictSemVer:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"},sha256:{type:"string",pattern:"^[0-9a-f]{64}$"},count:{type:"integer",minimum:0},counts:{type:"object",additionalProperties:false,required:["notes","collections","tags","templates","links","embedding_sets","embedding_set_members","embeddings","embedding_configs"],properties:{notes:{$ref:"#/$defs/count"},collections:{$ref:"#/$defs/count"},tags:{$ref:"#/$defs/count"},templates:{$ref:"#/$defs/count"},links:{$ref:"#/$defs/count"},embedding_sets:{const:0},embedding_set_members:{const:0},embeddings:{const:0},embedding_configs:{const:0}}}}};var D={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/note.schema.json",title:"Fortemi Knowledge Shard core-v1 note record",type:"object",additionalProperties:false,required:["id","title","original_content","revised_content","metadata","format","source","starred","archived","collection_id","created_at","updated_at","tags","attachments"],properties:{id:{$ref:"#/$defs/uuid"},title:{type:["string","null"]},original_content:{type:"string"},revised_content:{type:"string"},metadata:true,format:{type:"string",minLength:1},source:{type:"string",minLength:1},starred:{type:"boolean"},archived:{type:"boolean"},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{$ref:"#/$defs/dateTime"},updated_at:{$ref:"#/$defs/dateTime"},deleted_at:{oneOf:[{$ref:"#/$defs/dateTime"},{type:"null"}],default:null},tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},attachments:{type:"array",items:{$ref:"#/$defs/attachmentProjection"}}},$defs:{uuid:{type:"string",format:"uuid"},dateTime:{type:"string",format:"date-time"},sha256:{type:"string",pattern:"^blake3:[0-9a-f]{64}$"},attachmentProjection:{type:"object",additionalProperties:false,required:["extracted_text","extraction_status","reason","attachment"],properties:{extracted_text:{type:["string","null"]},extraction_status:{enum:["extracted","pending","failed","blocked","deferred"]},reason:{enum:[null,"extraction_pending","extractor_failed","quarantined","large_binary","unsupported_mime","no_extracted_text"]},attachment:{type:"object",additionalProperties:false,required:["id","path","mime","checksum","bytes"],properties:{id:{$ref:"#/$defs/uuid"},path:{type:"string",minLength:1},mime:{type:"string",minLength:1},checksum:{$ref:"#/$defs/sha256"},bytes:{type:"integer",minimum:0}}}}}}};var N={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/collection.schema.json",title:"Fortemi Knowledge Shard core-v1 collection record",type:"object",additionalProperties:false,required:["id","name","description","parent_id","created_at","note_count"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},parent_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},note_count:{type:"integer",minimum:0}},$defs:{uuid:{type:"string",format:"uuid"}}};var U={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/tag.schema.json",title:"Fortemi Knowledge Shard core-v1 tag record",type:"object",additionalProperties:false,required:["name","created_at"],properties:{name:{type:"string",minLength:1},created_at:{type:"string",format:"date-time"}}};var K={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/template.schema.json",title:"Fortemi Knowledge Shard core-v1 template record",type:"object",additionalProperties:false,required:["id","name","description","content","format","default_tags","collection_id","created_at","updated_at"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},content:{type:"string"},format:{type:"string",minLength:1},default_tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},$defs:{uuid:{type:"string",format:"uuid"}}};var B={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/link.schema.json",title:"Fortemi Knowledge Shard core-v1 link record",type:"object",additionalProperties:false,required:["id","from_note_id","to_note_id","to_url","kind","score","created_at","metadata"],properties:{id:{$ref:"#/$defs/uuid"},from_note_id:{$ref:"#/$defs/uuid"},to_note_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},to_url:{type:["string","null"],format:"uri"},kind:{type:"string",minLength:1},score:{type:"number"},created_at:{type:"string",format:"date-time"},metadata:true},oneOf:[{properties:{to_note_id:{$ref:"#/$defs/uuid"},to_url:{type:"null"}}},{properties:{to_note_id:{type:"null"},to_url:{type:"string",format:"uri"}}}],$defs:{uuid:{type:"string",format:"uuid"}}};var S=512,Dn="ustar\x0000";function Q(e,t,n,r){for(let i=0;i<Math.min(n.length,r);i++)e[t+i]=n.charCodeAt(i);}function O(e,t,n,r){let i=n.toString(8).padStart(r-1,"0");Q(e,t,i,r-1);}function Nn(e){let t=0;for(let n=0;n<S;n++)t+=n>=148&&n<156?32:e[n];return t}function Un(e,t){let n=new Uint8Array(S);Q(n,0,e,100),O(n,100,420,8),O(n,108,0,8),O(n,116,0,8),O(n,124,t,12),O(n,136,Math.floor(Date.now()/1e3),12),n[156]=48,Q(n,257,Dn,8);let i=Nn(n).toString(8).padStart(6,"0");return Q(n,148,i,6),n[154]=0,n[155]=32,n}function Kn(e){let t=[];for(let[s,o]of e){t.push(Un(s,o.byteLength)),t.push(o);let a=o.byteLength%S;a>0&&t.push(new Uint8Array(S-a));}t.push(new Uint8Array(S*2));let n=0;for(let s of t)n+=s.byteLength;let r=new Uint8Array(n),i=0;for(let s of t)r.set(s,i),i+=s.byteLength;return r}function ct(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return String.fromCharCode(...e.slice(t,r))}function Bn(e,t,n){let r=ct(e,t,n).trim();return r.length>0?parseInt(r,8):0}function Qn(e,t){for(let n=0;n<S;n++)if(e[t+n]!==0)return false;return true}function zn(e){let t=new Map,n=0;for(;n+S<=e.byteLength&&!Qn(e,n);){let r=ct(e,n,100),i=Bn(e,n+124,12),s=e[n+156];n+=S,(s===48||s===0)&&t.set(r,e.slice(n,n+i));let o=Math.ceil(i/S);n+=o*S;}return t}function lt(e,t){let n=Kn(e),r=mt;if(n.byteLength>r)throw new Error("Refusing to create archive: uncompressed size "+n.byteLength+" exceeds cap "+r+" bytes");return gzipSync(n)}var mt=256*1024*1024;function z(e,t){let n=mt;if(e.byteLength<18)throw new Error("Invalid gzip archive: too short");let i=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(e.byteLength-4,true);if(i>n)throw new Error("Refusing to decompress archive: declared size "+i+" exceeds cap "+n+" bytes");let s=gunzipSync(e);if(s.byteLength>n)throw new Error("Refusing to decompress archive: decompressed size "+s.byteLength+" exceeds cap "+n+" bytes");return zn(s)}var se=new TextDecoder;var ie={notes:{file:"notes.jsonl",encoding:"jsonl"},collections:{file:"collections.json",encoding:"json-array"},tags:{file:"tags.json",encoding:"json-array"},templates:{file:"templates.json",encoding:"json-array"},links:{file:"links.jsonl",encoding:"jsonl"}};var yt={"1.0.0":{manifest:_e,notes:ye,collections:be,tags:ve,templates:we,links:$e},"1.1.0":{manifest:ke,notes:D,collections:N,tags:U,templates:K,links:B},"1.2.0":{manifest:Ae,notes:D,collections:N,tags:U,templates:K,links:B}};var M;var pt=new Map;function Hn(e){e.addFormat("uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),e.addFormat("date-time",{type:"string",validate:t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(t)&&!Number.isNaN(Date.parse(t))}),e.addFormat("uri",{type:"string",validate:t=>{try{return !!new URL(t).protocol}catch{return false}}});}function gt(){if(!M){M=new Gn({allErrors:true,strict:true,validateFormats:true}),Hn(M);let e=new Set;for(let t of Object.values(yt))for(let n of Object.values(t))e.has(n.$id)||(M.addSchema(n),e.add(n.$id));}return M}function Wn(e){return e==="1.0.0"||e==="1.1.0"||e==="1.2.0"?e:void 0}function ht(e,t=L){let n=`${t}:${e}`,r=pt.get(n);if(r)return r;let i=yt[t][e],s=gt().getSchema(i.$id)??gt().compile(i);return pt.set(n,s),s}function _t(e){return (e??[]).map(t=>`${t.instancePath||"(root)"} ${t.message??"is invalid"}`)}function Jn(e,t){if(!e)return {records:[],errors:[]};try{let n=JSON.parse(se.decode(e));return Array.isArray(n)?{records:n,errors:[]}:{records:[],errors:[`${t} must be a JSON array`]}}catch{return {records:[],errors:[`${t} failed to parse as JSON`]}}}function Yn(e,t){if(!e)return {records:[],errors:[]};let n=se.decode(e).trim();if(!n)return {records:[],errors:[]};let r=[],i=[];for(let[s,o]of n.split(`
|
|
2
|
-
`).entries())try{r.push(JSON.parse(o));}catch{i.push(`${t}:${s+1} failed to parse as JSON`);}return {records:r,errors:i}}function Zn(e){return e instanceof Map?e:z(e instanceof ArrayBuffer?new Uint8Array(e):e)}function Xn(e,t,n){return n==="json-array"?Jn(e,t):Yn(e,t)}function er(e){let t=[],n=e.get("notes"),r=e.get("collections"),i=e.get("tags"),s=e.get("templates"),o=e.get("links"),a=new Set(n.map(c=>c.id)),d=new Set(r.map(c=>c.id)),l=new Set(i.map(c=>c.name));for(let[c,u]of r.entries())u.parent_id!==null&&!d.has(u.parent_id)&&t.push(`collections.json[${c}] parent_id does not reference a declared collection`);for(let[c,u]of n.entries()){u.collection_id!==null&&!d.has(u.collection_id)&&t.push(`notes.jsonl[${c}] collection_id does not reference a declared collection`);for(let m of u.tags)l.has(m)||t.push(`notes.jsonl[${c}] tag does not reference a declared tag`);}for(let[c,u]of s.entries()){u.collection_id!==null&&!d.has(u.collection_id)&&t.push(`templates.json[${c}] collection_id does not reference a declared collection`);for(let m of u.default_tags)l.has(m)||t.push(`templates.json[${c}] default tag does not reference a declared tag`);}for(let[c,u]of o.entries())a.has(u.from_note_id)||t.push(`links.jsonl[${c}] from_note_id does not reference a declared note`),u.to_note_id!==null&&!a.has(u.to_note_id)&&t.push(`links.jsonl[${c}] to_note_id does not reference a declared note`);return t}function tr(e,t){let n=[],r=Wn(t.version);if(!r)return ["manifest.json uses an unsupported canonical core-v1 schema version"];let i=ht("manifest",r);if(!i(t))return _t(i.errors).map(d=>`manifest.json ${d}`);let s=t.components,o=new Set(s.map(d=>ie[d].file));for(let d of o)e.has(d)||n.push(`${d} is declared but missing`),d in t.checksums||n.push(`${d} is missing its declared checksum`);for(let d of Object.keys(t.checksums))o.has(d)||n.push(`manifest checksum references undeclared file ${d}`);for(let d of e.keys())d!=="manifest.json"&&!o.has(d)&&n.push(`archive contains undeclared file ${d}`);let a=new Map;for(let d of s){let l=ie[d],c=Xn(e.get(l.file),l.file,l.encoding);n.push(...c.errors);let u=ht(d,r);for(let[p,f]of c.records.entries())u(f)||n.push(..._t(u.errors).map(b=>`${l.file}[${p}] ${b}`));let m=t.counts[d];m!==c.records.length&&n.push(`${l.file} count mismatch: manifest=${String(m)} actual=${c.records.length}`),a.set(d,c.records);}for(let d of Object.keys(ie))a.has(d)||a.set(d,[]);return n.length===0&&n.push(...er(a)),n}async function bt(e){let t;try{t=Zn(e);}catch{return {valid:false,errors:["archive failed to unpack"]}}let n=t.get("manifest.json");if(!n)return {valid:false,errors:["manifest.json is missing"]};let r;try{r=JSON.parse(se.decode(n));}catch{return {valid:false,errors:["manifest.json failed to parse as JSON"]}}let i=tr(t,r);if(i.length>0)return {valid:false,errors:i};let s=await he(r.checksums,t);return s.valid||i.push(...s.failures.map(o=>`${o} checksum mismatch`)),{valid:i.length===0,errors:i}}var rr=["schema_version","id","type","title","text","facets","tags","concepts","privacy"];function ir(e,t){let n=e.privacy;return !!(!n||!F(n.classification)||typeof n.pii!="boolean"||n.classification==="private"&&!t?.includePrivate||n.pii&&!t?.includePii)}function jt(e,t){return e.filter(n=>!ir(n,t))}var sr=["schema_version","id","type","source","facets","tags","concepts","relationships","provenance","privacy","updated_at"],ue={title:4,tag:3,concept:2,text:1,facet:2,id:1,source:.25};function g(e){return typeof e=="string"&&e.length>0}function T(e,t,n){let r=e[t];r===void 0&&(r=Object.create(null),e[t]=r),r[n]=(r[n]??0)+1;}function R(e){return Number.isInteger(e)&&typeof e=="number"&&e>=0}function I(e){return Number.isInteger(e)&&typeof e=="number"&&e>0}function or(e){return !e||typeof e!="object"||Array.isArray(e)?false:Object.values(e).every(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(n=>R(n)))}function y(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function G(e){return e===void 0||Array.isArray(e)&&e.every(t=>typeof t=="string")}function At(e){return e==="aiwg.fortemi.index.export.v1"||e==="aiwg.fortemi.index.export.v2"}function Rt(e){return e==="aiwg.fortemi.index.record.v1"||e==="aiwg.fortemi.index.record.v2"}function ar(e,t,n){if(e.skos_concepts!==void 0)if(!Array.isArray(e.skos_concepts))n.push("items["+t+"].skos_concepts must be an array when present");else for(let[r,i]of e.skos_concepts.entries()){if(!y(i)){n.push("items["+t+"].skos_concepts["+r+"] must be an object");continue}g(i.id)||n.push("items["+t+"].skos_concepts["+r+"].id is required"),g(i.prefLabel)||n.push("items["+t+"].skos_concepts["+r+"].prefLabel is required"),G(i.altLabels)||n.push("items["+t+"].skos_concepts["+r+"].altLabels must be a string array"),i.metadata!==void 0&&!y(i.metadata)&&n.push("items["+t+"].skos_concepts["+r+"].metadata must be an object");}if(e.skos_relations!==void 0)if(!Array.isArray(e.skos_relations))n.push("items["+t+"].skos_relations must be an array when present");else for(let[r,i]of e.skos_relations.entries()){if(!y(i)){n.push("items["+t+"].skos_relations["+r+"] must be an object");continue}g(i.type)||n.push("items["+t+"].skos_relations["+r+"].type is required"),g(i.source_id)||n.push("items["+t+"].skos_relations["+r+"].source_id is required"),g(i.target_id)||n.push("items["+t+"].skos_relations["+r+"].target_id is required"),i.metadata!==void 0&&!y(i.metadata)&&n.push("items["+t+"].skos_relations["+r+"].metadata must be an object");}if(e.provenance_events!==void 0)if(!Array.isArray(e.provenance_events))n.push("items["+t+"].provenance_events must be an array when present");else for(let[r,i]of e.provenance_events.entries()){if(!y(i)){n.push("items["+t+"].provenance_events["+r+"] must be an object");continue}g(i.activity)||n.push("items["+t+"].provenance_events["+r+"].activity is required"),i.attributes!==void 0&&!y(i.attributes)&&n.push("items["+t+"].provenance_events["+r+"].attributes must be an object");}if(Array.isArray(e.relationships))for(let[r,i]of e.relationships.entries()){if(!y(i)){n.push("items["+t+"].relationships["+r+"] must be an object");continue}i.metadata!==void 0&&!y(i.metadata)&&n.push("items["+t+"].relationships["+r+"].metadata must be an object"),i.direction!==void 0&&i.direction!=="upstream"&&i.direction!=="downstream"&&i.direction!=="related"&&n.push("items["+t+"].relationships["+r+"].direction must be upstream, downstream, or related"),i.target_path!==void 0&&typeof i.target_path!="string"&&n.push("items["+t+"].relationships["+r+"].target_path must be a string");}if(e.search!==void 0&&(y(e.search)?(G(e.search.triggers)||n.push("items["+t+"].search.triggers must be a string array"),G(e.search.aliases)||n.push("items["+t+"].search.aliases must be a string array"),G(e.search.tags)||n.push("items["+t+"].search.tags must be a string array"),e.search.frontmatter!==void 0&&!y(e.search.frontmatter)&&n.push("items["+t+"].search.frontmatter must be an object")):n.push("items["+t+"].search must be an object")),e.chunks!==void 0)if(!Array.isArray(e.chunks))n.push("items["+t+"].chunks must be an array when present");else for(let[r,i]of e.chunks.entries()){if(!y(i)){n.push("items["+t+"].chunks["+r+"] must be an object");continue}i.metadata!==void 0&&!y(i.metadata)&&n.push("items["+t+"].chunks["+r+"].metadata must be an object");}if(e.embeddings!==void 0)if(!Array.isArray(e.embeddings))n.push("items["+t+"].embeddings must be an array when present");else for(let[r,i]of e.embeddings.entries()){if(!y(i)){n.push("items["+t+"].embeddings["+r+"] must be an object");continue}let s=i.embedding??i.vector;s!==void 0&&(!Array.isArray(s)||!s.every(o=>typeof o=="number"))&&n.push("items["+t+"].embeddings["+r+"].embedding/vector must be a number array"),i.metadata!==void 0&&!y(i.metadata)&&n.push("items["+t+"].embeddings["+r+"].metadata must be an object");}e.compatibility!==void 0&&!y(e.compatibility)&&n.push("items["+t+"].compatibility must be an object");}function F(e){return e==="private"||e==="sanitized"||e==="public"}function Ct(e){return e==="source"||e==="candidate"||e==="reviewed"||e==="rejected"}function dr(e,t,n){if(Array.isArray(e.provenance))for(let[r,i]of e.provenance.entries()){let s="items["+t+"].provenance["+r+"]";if(!y(i)){n.push(s+" must be an object");continue}g(i.field)||n.push(s+".field is required"),g(i.source)||n.push(s+".source is required"),g(i.path)||n.push(s+".path is required"),Ct(i.confidence)||n.push(s+".confidence must be one of source, candidate, reviewed, rejected"),F(i.privacy)||n.push(s+".privacy must be one of private, sanitized, public");}}var cr=["search","chunks","embeddings","skos_concepts","skos_relations","provenance_events","compatibility"],lr=["origin","generated","checksum","updated_at"],mr=["target_path","direction","metadata"];function ur(e,t,n){if(e.schema_version!=="aiwg.fortemi.index.record.v1")return;let r="items["+t+"]",i=e,s=" is a v2-only field and must be absent on a record.v1 record";for(let o of cr)i[o]!==void 0&&n.push(r+"."+o+s);if(y(e.source)){let o=e.source;for(let a of lr)o[a]!==void 0&&n.push(r+".source."+a+s);}if(y(e.privacy)&&e.privacy.locality!==void 0&&n.push(r+".privacy.locality"+s),Array.isArray(e.relationships))for(let[o,a]of e.relationships.entries()){if(!y(a))continue;let d=a;for(let l of mr)d[l]!==void 0&&n.push(r+".relationships["+o+"]."+l+s);}}function Z(e){let t=[],n=Object.create(null),r=y(e)?e:{};y(e)||t.push("index export must be an object"),At(r?.schema_version)||t.push("schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2"),g(r?.generated_at)||t.push("generated_at is required"),g(r?.source?.repo)||t.push("source.repo is required"),g(r?.source?.privacy)?F(r?.source?.privacy)||t.push("source.privacy must be one of private, sanitized, public"):t.push("source.privacy is required"),Array.isArray(r?.items)||t.push("items must be an array"),r.compatibility!==void 0&&!y(r.compatibility)&&t.push("compatibility must be an object"),r?.schema_version==="aiwg.fortemi.index.export.v1"&&(y(r.source)&&r.source.graph!==void 0&&t.push("source.graph is a v2-only field and must be absent on an export.v1 export"),r.compatibility!==void 0&&t.push("compatibility is a v2-only field and must be absent on an export.v1 export"));let i=new Set,s="",o=Array.isArray(r.items)?r.items:[];for(let[a,d]of o.entries()){if(!y(d)){t.push("items["+a+"] must be an object");continue}for(let l of sr)l in d||t.push("items["+a+"]."+l+" is required");Rt(d.schema_version)||t.push("items["+a+"].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2"),r.schema_version==="aiwg.fortemi.index.export.v1"&&d.schema_version==="aiwg.fortemi.index.record.v2"&&t.push("items["+a+"].schema_version must match aiwg.fortemi.index.export.v1"),g(d.id)||t.push("items["+a+"].id is required"),g(d.id)&&i.has(d.id)&&t.push("duplicate id: "+d.id),g(d.id)&&i.add(d.id),s&&g(d.id)&&s>d.id&&t.push("items must be sorted by id: "+s+" before "+d.id),g(d.id)&&(s=d.id),g(d.type)?n[d.type]=(n[d.type]??0)+1:t.push("items["+a+"].type must be a non-empty string"),g(d.source?.path)||t.push("items["+a+"].source.path is required"),g(d.source?.repo_relative_path)||t.push("items["+a+"].source.repo_relative_path is required"),g(d.source?.locator)||t.push("items["+a+"].source.locator is required"),typeof d.title!="string"&&typeof d.search?.title!="string"&&typeof d.search?.name!="string"&&t.push("items["+a+"].title or search.title/search.name is required"),typeof d.text!="string"&&typeof d.search?.body!="string"&&typeof d.search?.summary!="string"&&t.push("items["+a+"].text or search.body/search.summary is required"),Array.isArray(d.tags)||t.push("items["+a+"].tags must be an array"),Array.isArray(d.concepts)||t.push("items["+a+"].concepts must be an array"),Array.isArray(d.relationships)||t.push("items["+a+"].relationships must be an array"),(!Array.isArray(d.provenance)||d.provenance.length===0)&&t.push("items["+a+"].provenance must be a non-empty array"),ar(d,a,t),dr(d,a,t),ur(d,a,t),!d.privacy||typeof d.privacy.pii!="boolean"||!g(d.privacy.classification)?t.push("items["+a+"].privacy requires classification and pii"):F(d.privacy.classification)||t.push("items["+a+"].privacy.classification must be one of private, sanitized, public");}return {valid:t.length===0,errors:t,counts:n}}function X(e){let t=Z(e);if(!t.valid)throw new Error(`Invalid AIWG Fortemi index export:
|
|
1
|
+
import Gn from'ajv/dist/2020.js';import {gzipSync,gunzipSync}from'fflate';import {v5}from'uuid';var L="1.2.0",ge="matric-shard";async function re(e){let t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(n);return Array.from(r).map(i=>i.toString(16).padStart(2,"0")).join("")}async function he(e,t){let n=[];for(let[r,i]of Object.entries(e)){let s=t.get(r);if(!s){n.push(r);continue}await re(s)!==i&&n.push(r);}return {valid:n.length===0,failures:n}}var _e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/manifest.schema.json",title:"Fortemi Knowledge Shard core-v1 manifest",type:"object",additionalProperties:false,required:["version","profile","producer","format","created_at","components","counts","checksums","min_reader_version"],properties:{version:{$ref:"#/$defs/strictSemVer"},profile:{const:"core-v1"},producer:{type:"object",additionalProperties:false,required:["name","version"],properties:{name:{type:"string",minLength:1},version:{type:"string",minLength:1},revision:{type:"string",minLength:1}}},matric_version:{type:"string",minLength:1,deprecated:true},format:{const:"matric-shard"},created_at:{type:"string",format:"date-time"},components:{type:"array",minItems:1,uniqueItems:true,items:{enum:["notes","collections","tags","templates","links"]}},counts:{$ref:"#/$defs/counts"},checksums:{type:"object",propertyNames:{enum:["notes.jsonl","collections.json","tags.json","templates.json","links.jsonl"]},additionalProperties:{$ref:"#/$defs/sha256"}},min_reader_version:{$ref:"#/$defs/strictSemVer"},migrated_from:{$ref:"#/$defs/strictSemVer"},migration_history:{type:"array",items:{type:"object",additionalProperties:false,required:["from_version","to_version","migrated_at","migrated_by","changes"],properties:{from_version:{$ref:"#/$defs/strictSemVer"},to_version:{$ref:"#/$defs/strictSemVer"},migrated_at:{type:"string",format:"date-time"},migrated_by:{type:"string",minLength:1},changes:{type:"array",minItems:1,items:{type:"string",minLength:1}}}}}},$defs:{strictSemVer:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"},sha256:{type:"string",pattern:"^[0-9a-f]{64}$"},count:{type:"integer",minimum:0},counts:{type:"object",additionalProperties:false,required:["notes","collections","tags","templates","links","embedding_sets","embedding_set_members","embeddings","embedding_configs"],properties:{notes:{$ref:"#/$defs/count"},collections:{$ref:"#/$defs/count"},tags:{$ref:"#/$defs/count"},templates:{$ref:"#/$defs/count"},links:{$ref:"#/$defs/count"},embedding_sets:{const:0},embedding_set_members:{const:0},embeddings:{const:0},embedding_configs:{const:0}}}}};var ye={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/note.schema.json",title:"Fortemi Knowledge Shard core-v1 note record",type:"object",additionalProperties:false,required:["id","title","original_content","revised_content","metadata","format","source","starred","archived","collection_id","created_at","updated_at","tags","attachments"],properties:{id:{$ref:"#/$defs/uuid"},title:{type:["string","null"]},original_content:{type:"string"},revised_content:{type:"string"},metadata:true,format:{type:"string",minLength:1},source:{type:"string",minLength:1},starred:{type:"boolean"},archived:{type:"boolean"},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{$ref:"#/$defs/dateTime"},updated_at:{$ref:"#/$defs/dateTime"},tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},attachments:{type:"array",items:{$ref:"#/$defs/attachmentProjection"}}},$defs:{uuid:{type:"string",format:"uuid"},dateTime:{type:"string",format:"date-time"},sha256:{type:"string",pattern:"^blake3:[0-9a-f]{64}$"},attachmentProjection:{type:"object",additionalProperties:false,required:["extracted_text","extraction_status","reason","attachment"],properties:{extracted_text:{type:["string","null"]},extraction_status:{enum:["extracted","pending","failed","blocked","deferred"]},reason:{enum:[null,"extraction_pending","extractor_failed","quarantined","large_binary","unsupported_mime","no_extracted_text"]},attachment:{type:"object",additionalProperties:false,required:["id","path","mime","checksum","bytes"],properties:{id:{$ref:"#/$defs/uuid"},path:{type:"string",minLength:1},mime:{type:"string",minLength:1},checksum:{$ref:"#/$defs/sha256"},bytes:{type:"integer",minimum:0}}}}}}};var be={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/collection.schema.json",title:"Fortemi Knowledge Shard core-v1 collection record",type:"object",additionalProperties:false,required:["id","name","description","parent_id","created_at","note_count"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},parent_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},note_count:{type:"integer",minimum:0}},$defs:{uuid:{type:"string",format:"uuid"}}};var we={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/tag.schema.json",title:"Fortemi Knowledge Shard core-v1 tag record",type:"object",additionalProperties:false,required:["name","created_at"],properties:{name:{type:"string",minLength:1},created_at:{type:"string",format:"date-time"}}};var ve={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/template.schema.json",title:"Fortemi Knowledge Shard core-v1 template record",type:"object",additionalProperties:false,required:["id","name","description","content","format","default_tags","collection_id","created_at","updated_at"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},content:{type:"string"},format:{type:"string",minLength:1},default_tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},$defs:{uuid:{type:"string",format:"uuid"}}};var $e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/link.schema.json",title:"Fortemi Knowledge Shard core-v1 link record",type:"object",additionalProperties:false,required:["id","from_note_id","to_note_id","to_url","kind","score","created_at","metadata"],properties:{id:{$ref:"#/$defs/uuid"},from_note_id:{$ref:"#/$defs/uuid"},to_note_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},to_url:{type:["string","null"],format:"uri"},kind:{type:"string",minLength:1},score:{type:"number"},created_at:{type:"string",format:"date-time"},metadata:true},oneOf:[{properties:{to_note_id:{$ref:"#/$defs/uuid"},to_url:{type:"null"}}},{properties:{to_note_id:{type:"null"},to_url:{type:"string",format:"uri"}}}],$defs:{uuid:{type:"string",format:"uuid"}}};var ke={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.1.0/core-v1/manifest.schema.json",title:"Fortemi Knowledge Shard core-v1 manifest",type:"object",additionalProperties:false,required:["version","profile","producer","format","created_at","components","counts","checksums","min_reader_version"],properties:{version:{const:"1.1.0"},profile:{const:"core-v1"},producer:{type:"object",additionalProperties:false,required:["name","version"],properties:{name:{type:"string",minLength:1},version:{type:"string",minLength:1},revision:{type:"string",minLength:1}}},matric_version:{type:"string",minLength:1,deprecated:true},format:{const:"matric-shard"},created_at:{type:"string",format:"date-time"},components:{type:"array",minItems:1,uniqueItems:true,items:{enum:["notes","collections","tags","templates","links"]}},counts:{$ref:"#/$defs/counts"},checksums:{type:"object",propertyNames:{enum:["notes.jsonl","collections.json","tags.json","templates.json","links.jsonl"]},additionalProperties:{$ref:"#/$defs/sha256"}},min_reader_version:{const:"1.1.0"},migrated_from:{$ref:"#/$defs/strictSemVer"},migration_history:{type:"array",items:{type:"object",additionalProperties:false,required:["from_version","to_version","migrated_at","migrated_by","changes"],properties:{from_version:{$ref:"#/$defs/strictSemVer"},to_version:{$ref:"#/$defs/strictSemVer"},migrated_at:{type:"string",format:"date-time"},migrated_by:{type:"string",minLength:1},changes:{type:"array",minItems:1,items:{type:"string",minLength:1}}}}}},$defs:{strictSemVer:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"},sha256:{type:"string",pattern:"^[0-9a-f]{64}$"},count:{type:"integer",minimum:0},counts:{type:"object",additionalProperties:false,required:["notes","collections","tags","templates","links","embedding_sets","embedding_set_members","embeddings","embedding_configs"],properties:{notes:{$ref:"#/$defs/count"},collections:{$ref:"#/$defs/count"},tags:{$ref:"#/$defs/count"},templates:{$ref:"#/$defs/count"},links:{$ref:"#/$defs/count"},embedding_sets:{const:0},embedding_set_members:{const:0},embeddings:{const:0},embedding_configs:{const:0}}}}};var Ae={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/manifest.schema.json",title:"Fortemi Knowledge Shard core-v1 manifest",type:"object",additionalProperties:false,required:["version","profile","producer","format","created_at","components","counts","checksums","min_reader_version"],properties:{version:{const:"1.2.0"},profile:{const:"core-v1"},producer:{type:"object",additionalProperties:false,required:["name","version"],properties:{name:{type:"string",minLength:1},version:{type:"string",minLength:1},revision:{type:"string",minLength:1}}},matric_version:{type:"string",minLength:1,deprecated:true},format:{const:"matric-shard"},created_at:{type:"string",format:"date-time"},components:{type:"array",minItems:1,uniqueItems:true,items:{enum:["notes","collections","tags","templates","links"]}},counts:{$ref:"#/$defs/counts"},checksums:{type:"object",propertyNames:{enum:["notes.jsonl","collections.json","tags.json","templates.json","links.jsonl"]},additionalProperties:{$ref:"#/$defs/sha256"}},min_reader_version:{const:"1.2.0"},migrated_from:{$ref:"#/$defs/strictSemVer"},migration_history:{type:"array",items:{type:"object",additionalProperties:false,required:["from_version","to_version","migrated_at","migrated_by","changes"],properties:{from_version:{$ref:"#/$defs/strictSemVer"},to_version:{$ref:"#/$defs/strictSemVer"},migrated_at:{type:"string",format:"date-time"},migrated_by:{type:"string",minLength:1},changes:{type:"array",minItems:1,items:{type:"string",minLength:1}}}}}},$defs:{strictSemVer:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"},sha256:{type:"string",pattern:"^[0-9a-f]{64}$"},count:{type:"integer",minimum:0},counts:{type:"object",additionalProperties:false,required:["notes","collections","tags","templates","links","embedding_sets","embedding_set_members","embeddings","embedding_configs"],properties:{notes:{$ref:"#/$defs/count"},collections:{$ref:"#/$defs/count"},tags:{$ref:"#/$defs/count"},templates:{$ref:"#/$defs/count"},links:{$ref:"#/$defs/count"},embedding_sets:{const:0},embedding_set_members:{const:0},embeddings:{const:0},embedding_configs:{const:0}}}}};var D={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/note.schema.json",title:"Fortemi Knowledge Shard core-v1 note record",type:"object",additionalProperties:false,required:["id","title","original_content","revised_content","metadata","format","source","starred","archived","collection_id","created_at","updated_at","tags","attachments"],properties:{id:{$ref:"#/$defs/uuid"},title:{type:["string","null"]},original_content:{type:"string"},revised_content:{type:"string"},metadata:true,format:{type:"string",minLength:1},source:{type:"string",minLength:1},starred:{type:"boolean"},archived:{type:"boolean"},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{$ref:"#/$defs/dateTime"},updated_at:{$ref:"#/$defs/dateTime"},deleted_at:{oneOf:[{$ref:"#/$defs/dateTime"},{type:"null"}],default:null},tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},attachments:{type:"array",items:{$ref:"#/$defs/attachmentProjection"}}},$defs:{uuid:{type:"string",format:"uuid"},dateTime:{type:"string",format:"date-time"},sha256:{type:"string",pattern:"^blake3:[0-9a-f]{64}$"},attachmentProjection:{type:"object",additionalProperties:false,required:["extracted_text","extraction_status","reason","attachment"],properties:{extracted_text:{type:["string","null"]},extraction_status:{enum:["extracted","pending","failed","blocked","deferred"]},reason:{enum:[null,"extraction_pending","extractor_failed","quarantined","large_binary","unsupported_mime","no_extracted_text"]},attachment:{type:"object",additionalProperties:false,required:["id","path","mime","checksum","bytes"],properties:{id:{$ref:"#/$defs/uuid"},path:{type:"string",minLength:1},mime:{type:"string",minLength:1},checksum:{$ref:"#/$defs/sha256"},bytes:{type:"integer",minimum:0}}}}}}};var N={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/collection.schema.json",title:"Fortemi Knowledge Shard core-v1 collection record",type:"object",additionalProperties:false,required:["id","name","description","parent_id","created_at","note_count"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},parent_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},note_count:{type:"integer",minimum:0}},$defs:{uuid:{type:"string",format:"uuid"}}};var U={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/tag.schema.json",title:"Fortemi Knowledge Shard core-v1 tag record",type:"object",additionalProperties:false,required:["name","created_at"],properties:{name:{type:"string",minLength:1},created_at:{type:"string",format:"date-time"}}};var K={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/template.schema.json",title:"Fortemi Knowledge Shard core-v1 template record",type:"object",additionalProperties:false,required:["id","name","description","content","format","default_tags","collection_id","created_at","updated_at"],properties:{id:{$ref:"#/$defs/uuid"},name:{type:"string",minLength:1},description:{type:["string","null"]},content:{type:"string"},format:{type:"string",minLength:1},default_tags:{type:"array",uniqueItems:true,items:{type:"string",minLength:1}},collection_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},$defs:{uuid:{type:"string",format:"uuid"}}};var B={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/link.schema.json",title:"Fortemi Knowledge Shard core-v1 link record",type:"object",additionalProperties:false,required:["id","from_note_id","to_note_id","to_url","kind","score","created_at","metadata"],properties:{id:{$ref:"#/$defs/uuid"},from_note_id:{$ref:"#/$defs/uuid"},to_note_id:{oneOf:[{$ref:"#/$defs/uuid"},{type:"null"}]},to_url:{type:["string","null"],format:"uri"},kind:{type:"string",minLength:1},score:{type:"number"},created_at:{type:"string",format:"date-time"},metadata:true},oneOf:[{properties:{to_note_id:{$ref:"#/$defs/uuid"},to_url:{type:"null"}}},{properties:{to_note_id:{type:"null"},to_url:{type:"string",format:"uri"}}}],$defs:{uuid:{type:"string",format:"uuid"}}};var S=512,Dn="ustar\x0000";function Q(e,t,n,r){for(let i=0;i<Math.min(n.length,r);i++)e[t+i]=n.charCodeAt(i);}function O(e,t,n,r){let i=n.toString(8).padStart(r-1,"0");Q(e,t,i,r-1);}function Nn(e){let t=0;for(let n=0;n<S;n++)t+=n>=148&&n<156?32:e[n];return t}function Un(e,t){let n=new Uint8Array(S);Q(n,0,e,100),O(n,100,420,8),O(n,108,0,8),O(n,116,0,8),O(n,124,t,12),O(n,136,0,12),n[156]=48,Q(n,257,Dn,8);let i=Nn(n).toString(8).padStart(6,"0");return Q(n,148,i,6),n[154]=0,n[155]=32,n}function Kn(e){let t=[];for(let[s,o]of e){t.push(Un(s,o.byteLength)),t.push(o);let a=o.byteLength%S;a>0&&t.push(new Uint8Array(S-a));}t.push(new Uint8Array(S*2));let n=0;for(let s of t)n+=s.byteLength;let r=new Uint8Array(n),i=0;for(let s of t)r.set(s,i),i+=s.byteLength;return r}function ct(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return String.fromCharCode(...e.slice(t,r))}function Bn(e,t,n){let r=ct(e,t,n).trim();return r.length>0?parseInt(r,8):0}function Qn(e,t){for(let n=0;n<S;n++)if(e[t+n]!==0)return false;return true}function zn(e){let t=new Map,n=0;for(;n+S<=e.byteLength&&!Qn(e,n);){let r=ct(e,n,100),i=Bn(e,n+124,12),s=e[n+156];n+=S,(s===48||s===0)&&t.set(r,e.slice(n,n+i));let o=Math.ceil(i/S);n+=o*S;}return t}function lt(e,t){let n=Kn(e),r=mt;if(n.byteLength>r)throw new Error("Refusing to create archive: uncompressed size "+n.byteLength+" exceeds cap "+r+" bytes");return gzipSync(n,{mtime:0})}var mt=256*1024*1024;function z(e,t){let n=mt;if(e.byteLength<18)throw new Error("Invalid gzip archive: too short");let i=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(e.byteLength-4,true);if(i>n)throw new Error("Refusing to decompress archive: declared size "+i+" exceeds cap "+n+" bytes");let s=gunzipSync(e);if(s.byteLength>n)throw new Error("Refusing to decompress archive: decompressed size "+s.byteLength+" exceeds cap "+n+" bytes");return zn(s)}var se=new TextDecoder;var ie={notes:{file:"notes.jsonl",encoding:"jsonl"},collections:{file:"collections.json",encoding:"json-array"},tags:{file:"tags.json",encoding:"json-array"},templates:{file:"templates.json",encoding:"json-array"},links:{file:"links.jsonl",encoding:"jsonl"}};var yt={"1.0.0":{manifest:_e,notes:ye,collections:be,tags:we,templates:ve,links:$e},"1.1.0":{manifest:ke,notes:D,collections:N,tags:U,templates:K,links:B},"1.2.0":{manifest:Ae,notes:D,collections:N,tags:U,templates:K,links:B}};var M;var pt=new Map;function Hn(e){e.addFormat("uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),e.addFormat("date-time",{type:"string",validate:t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(t)&&!Number.isNaN(Date.parse(t))}),e.addFormat("uri",{type:"string",validate:t=>{try{return !!new URL(t).protocol}catch{return false}}});}function gt(){if(!M){M=new Gn({allErrors:true,strict:true,validateFormats:true}),Hn(M);let e=new Set;for(let t of Object.values(yt))for(let n of Object.values(t))e.has(n.$id)||(M.addSchema(n),e.add(n.$id));}return M}function Wn(e){return e==="1.0.0"||e==="1.1.0"||e==="1.2.0"?e:void 0}function ht(e,t=L){let n=`${t}:${e}`,r=pt.get(n);if(r)return r;let i=yt[t][e],s=gt().getSchema(i.$id)??gt().compile(i);return pt.set(n,s),s}function _t(e){return (e??[]).map(t=>`${t.instancePath||"(root)"} ${t.message??"is invalid"}`)}function Jn(e,t){if(!e)return {records:[],errors:[]};try{let n=JSON.parse(se.decode(e));return Array.isArray(n)?{records:n,errors:[]}:{records:[],errors:[`${t} must be a JSON array`]}}catch{return {records:[],errors:[`${t} failed to parse as JSON`]}}}function Yn(e,t){if(!e)return {records:[],errors:[]};let n=se.decode(e).trim();if(!n)return {records:[],errors:[]};let r=[],i=[];for(let[s,o]of n.split(`
|
|
2
|
+
`).entries())try{r.push(JSON.parse(o));}catch{i.push(`${t}:${s+1} failed to parse as JSON`);}return {records:r,errors:i}}function Zn(e){return e instanceof Map?e:z(e instanceof ArrayBuffer?new Uint8Array(e):e)}function Xn(e,t,n){return n==="json-array"?Jn(e,t):Yn(e,t)}function er(e){let t=[],n=e.get("notes"),r=e.get("collections"),i=e.get("tags"),s=e.get("templates"),o=e.get("links"),a=new Set(n.map(c=>c.id)),d=new Set(r.map(c=>c.id)),l=new Set(i.map(c=>c.name));for(let[c,p]of r.entries())p.parent_id!==null&&!d.has(p.parent_id)&&t.push(`collections.json[${c}] parent_id does not reference a declared collection`);let m=new Map(r.map(c=>[c.id,c])),f=new Set,u=new Set,g=c=>{if(u.has(c.id))return;if(f.has(c.id)){t.push(`collection hierarchy contains a cycle at ${String(c.id)}`);return}f.add(c.id);let p=c.parent_id===null?void 0:m.get(c.parent_id);p&&g(p),f.delete(c.id),u.add(c.id);};for(let c of r)g(c);for(let[c,p]of n.entries()){p.collection_id!==null&&!d.has(p.collection_id)&&t.push(`notes.jsonl[${c}] collection_id does not reference a declared collection`);for(let h of p.tags)l.has(h)||t.push(`notes.jsonl[${c}] tag does not reference a declared tag`);}for(let[c,p]of s.entries()){p.collection_id!==null&&!d.has(p.collection_id)&&t.push(`templates.json[${c}] collection_id does not reference a declared collection`);for(let h of p.default_tags)l.has(h)||t.push(`templates.json[${c}] default tag does not reference a declared tag`);}for(let[c,p]of o.entries())a.has(p.from_note_id)||t.push(`links.jsonl[${c}] from_note_id does not reference a declared note`),p.to_note_id!==null&&!a.has(p.to_note_id)&&t.push(`links.jsonl[${c}] to_note_id does not reference a declared note`);return t}function tr(e,t){let n=[],r=Wn(t.version);if(!r)return ["manifest.json uses an unsupported canonical core-v1 schema version"];let i=ht("manifest",r);if(!i(t))return _t(i.errors).map(d=>`manifest.json ${d}`);let s=t.components,o=new Set(s.map(d=>ie[d].file));for(let d of o)e.has(d)||n.push(`${d} is declared but missing`),d in t.checksums||n.push(`${d} is missing its declared checksum`);for(let d of Object.keys(t.checksums))o.has(d)||n.push(`manifest checksum references undeclared file ${d}`);for(let d of e.keys())d!=="manifest.json"&&!o.has(d)&&n.push(`archive contains undeclared file ${d}`);let a=new Map;for(let d of s){let l=ie[d],m=Xn(e.get(l.file),l.file,l.encoding);n.push(...m.errors);let f=ht(d,r);for(let[g,c]of m.records.entries())f(c)||n.push(..._t(f.errors).map(p=>`${l.file}[${g}] ${p}`));let u=t.counts[d];u!==m.records.length&&n.push(`${l.file} count mismatch: manifest=${String(u)} actual=${m.records.length}`),a.set(d,m.records);}for(let d of Object.keys(ie))a.has(d)||a.set(d,[]);return n.length===0&&n.push(...er(a)),n}async function bt(e){let t;try{t=Zn(e);}catch{return {valid:false,errors:["archive failed to unpack"]}}let n=t.get("manifest.json");if(!n)return {valid:false,errors:["manifest.json is missing"]};let r;try{r=JSON.parse(se.decode(n));}catch{return {valid:false,errors:["manifest.json failed to parse as JSON"]}}let i=tr(t,r);if(i.length>0)return {valid:false,errors:i};let s=await he(r.checksums,t);return s.valid||i.push(...s.failures.map(o=>`${o} checksum mismatch`)),{valid:i.length===0,errors:i}}var rr=["schema_version","id","type","title","text","facets","tags","concepts","privacy"];function ir(e,t){let n=e.privacy;return !!(!n||!F(n.classification)||typeof n.pii!="boolean"||n.classification==="private"&&!t?.includePrivate||n.pii&&!t?.includePii)}function jt(e,t){return e.filter(n=>!ir(n,t))}var sr=["schema_version","id","type","source","facets","tags","concepts","relationships","provenance","privacy","updated_at"],ue={title:4,tag:3,concept:2,text:1,facet:2,id:1,source:.25};function _(e){return typeof e=="string"&&e.length>0}function T(e,t,n){let r=e[t];r===void 0&&(r=Object.create(null),e[t]=r),r[n]=(r[n]??0)+1;}function R(e){return Number.isInteger(e)&&typeof e=="number"&&e>=0}function I(e){return Number.isInteger(e)&&typeof e=="number"&&e>0}function or(e){return !e||typeof e!="object"||Array.isArray(e)?false:Object.values(e).every(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(n=>R(n)))}function b(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function G(e){return e===void 0||Array.isArray(e)&&e.every(t=>typeof t=="string")}function At(e){return e==="aiwg.fortemi.index.export.v1"||e==="aiwg.fortemi.index.export.v2"}function Rt(e){return e==="aiwg.fortemi.index.record.v1"||e==="aiwg.fortemi.index.record.v2"}function ar(e,t,n){if(e.skos_concepts!==void 0)if(!Array.isArray(e.skos_concepts))n.push("items["+t+"].skos_concepts must be an array when present");else for(let[r,i]of e.skos_concepts.entries()){if(!b(i)){n.push("items["+t+"].skos_concepts["+r+"] must be an object");continue}_(i.id)||n.push("items["+t+"].skos_concepts["+r+"].id is required"),_(i.prefLabel)||n.push("items["+t+"].skos_concepts["+r+"].prefLabel is required"),G(i.altLabels)||n.push("items["+t+"].skos_concepts["+r+"].altLabels must be a string array"),i.metadata!==void 0&&!b(i.metadata)&&n.push("items["+t+"].skos_concepts["+r+"].metadata must be an object");}if(e.skos_relations!==void 0)if(!Array.isArray(e.skos_relations))n.push("items["+t+"].skos_relations must be an array when present");else for(let[r,i]of e.skos_relations.entries()){if(!b(i)){n.push("items["+t+"].skos_relations["+r+"] must be an object");continue}_(i.type)||n.push("items["+t+"].skos_relations["+r+"].type is required"),_(i.source_id)||n.push("items["+t+"].skos_relations["+r+"].source_id is required"),_(i.target_id)||n.push("items["+t+"].skos_relations["+r+"].target_id is required"),i.metadata!==void 0&&!b(i.metadata)&&n.push("items["+t+"].skos_relations["+r+"].metadata must be an object");}if(e.provenance_events!==void 0)if(!Array.isArray(e.provenance_events))n.push("items["+t+"].provenance_events must be an array when present");else for(let[r,i]of e.provenance_events.entries()){if(!b(i)){n.push("items["+t+"].provenance_events["+r+"] must be an object");continue}_(i.activity)||n.push("items["+t+"].provenance_events["+r+"].activity is required"),i.attributes!==void 0&&!b(i.attributes)&&n.push("items["+t+"].provenance_events["+r+"].attributes must be an object");}if(Array.isArray(e.relationships))for(let[r,i]of e.relationships.entries()){if(!b(i)){n.push("items["+t+"].relationships["+r+"] must be an object");continue}i.metadata!==void 0&&!b(i.metadata)&&n.push("items["+t+"].relationships["+r+"].metadata must be an object"),i.direction!==void 0&&i.direction!=="upstream"&&i.direction!=="downstream"&&i.direction!=="related"&&n.push("items["+t+"].relationships["+r+"].direction must be upstream, downstream, or related"),i.target_path!==void 0&&typeof i.target_path!="string"&&n.push("items["+t+"].relationships["+r+"].target_path must be a string");}if(e.search!==void 0&&(b(e.search)?(G(e.search.triggers)||n.push("items["+t+"].search.triggers must be a string array"),G(e.search.aliases)||n.push("items["+t+"].search.aliases must be a string array"),G(e.search.tags)||n.push("items["+t+"].search.tags must be a string array"),e.search.frontmatter!==void 0&&!b(e.search.frontmatter)&&n.push("items["+t+"].search.frontmatter must be an object")):n.push("items["+t+"].search must be an object")),e.chunks!==void 0)if(!Array.isArray(e.chunks))n.push("items["+t+"].chunks must be an array when present");else for(let[r,i]of e.chunks.entries()){if(!b(i)){n.push("items["+t+"].chunks["+r+"] must be an object");continue}i.metadata!==void 0&&!b(i.metadata)&&n.push("items["+t+"].chunks["+r+"].metadata must be an object");}if(e.embeddings!==void 0)if(!Array.isArray(e.embeddings))n.push("items["+t+"].embeddings must be an array when present");else for(let[r,i]of e.embeddings.entries()){if(!b(i)){n.push("items["+t+"].embeddings["+r+"] must be an object");continue}let s=i.embedding??i.vector;s!==void 0&&(!Array.isArray(s)||!s.every(o=>typeof o=="number"))&&n.push("items["+t+"].embeddings["+r+"].embedding/vector must be a number array"),i.metadata!==void 0&&!b(i.metadata)&&n.push("items["+t+"].embeddings["+r+"].metadata must be an object");}e.compatibility!==void 0&&!b(e.compatibility)&&n.push("items["+t+"].compatibility must be an object");}function F(e){return e==="private"||e==="sanitized"||e==="public"}function Ct(e){return e==="source"||e==="candidate"||e==="reviewed"||e==="rejected"}function dr(e,t,n){if(Array.isArray(e.provenance))for(let[r,i]of e.provenance.entries()){let s="items["+t+"].provenance["+r+"]";if(!b(i)){n.push(s+" must be an object");continue}_(i.field)||n.push(s+".field is required"),_(i.source)||n.push(s+".source is required"),_(i.path)||n.push(s+".path is required"),Ct(i.confidence)||n.push(s+".confidence must be one of source, candidate, reviewed, rejected"),F(i.privacy)||n.push(s+".privacy must be one of private, sanitized, public");}}var cr=["search","chunks","embeddings","skos_concepts","skos_relations","provenance_events","compatibility"],lr=["origin","generated","checksum","updated_at"],mr=["target_path","direction","metadata"];function ur(e,t,n){if(e.schema_version!=="aiwg.fortemi.index.record.v1")return;let r="items["+t+"]",i=e,s=" is a v2-only field and must be absent on a record.v1 record";for(let o of cr)i[o]!==void 0&&n.push(r+"."+o+s);if(b(e.source)){let o=e.source;for(let a of lr)o[a]!==void 0&&n.push(r+".source."+a+s);}if(b(e.privacy)&&e.privacy.locality!==void 0&&n.push(r+".privacy.locality"+s),Array.isArray(e.relationships))for(let[o,a]of e.relationships.entries()){if(!b(a))continue;let d=a;for(let l of mr)d[l]!==void 0&&n.push(r+".relationships["+o+"]."+l+s);}}function Z(e){let t=[],n=Object.create(null),r=b(e)?e:{};b(e)||t.push("index export must be an object"),At(r?.schema_version)||t.push("schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2"),_(r?.generated_at)||t.push("generated_at is required"),_(r?.source?.repo)||t.push("source.repo is required"),_(r?.source?.privacy)?F(r?.source?.privacy)||t.push("source.privacy must be one of private, sanitized, public"):t.push("source.privacy is required"),Array.isArray(r?.items)||t.push("items must be an array"),r.compatibility!==void 0&&!b(r.compatibility)&&t.push("compatibility must be an object"),r?.schema_version==="aiwg.fortemi.index.export.v1"&&(b(r.source)&&r.source.graph!==void 0&&t.push("source.graph is a v2-only field and must be absent on an export.v1 export"),r.compatibility!==void 0&&t.push("compatibility is a v2-only field and must be absent on an export.v1 export"));let i=new Set,s="",o=Array.isArray(r.items)?r.items:[];for(let[a,d]of o.entries()){if(!b(d)){t.push("items["+a+"] must be an object");continue}for(let l of sr)l in d||t.push("items["+a+"]."+l+" is required");Rt(d.schema_version)||t.push("items["+a+"].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2"),r.schema_version==="aiwg.fortemi.index.export.v1"&&d.schema_version==="aiwg.fortemi.index.record.v2"&&t.push("items["+a+"].schema_version must match aiwg.fortemi.index.export.v1"),_(d.id)||t.push("items["+a+"].id is required"),_(d.id)&&i.has(d.id)&&t.push("duplicate id: "+d.id),_(d.id)&&i.add(d.id),s&&_(d.id)&&s>d.id&&t.push("items must be sorted by id: "+s+" before "+d.id),_(d.id)&&(s=d.id),_(d.type)?n[d.type]=(n[d.type]??0)+1:t.push("items["+a+"].type must be a non-empty string"),_(d.source?.path)||t.push("items["+a+"].source.path is required"),_(d.source?.repo_relative_path)||t.push("items["+a+"].source.repo_relative_path is required"),_(d.source?.locator)||t.push("items["+a+"].source.locator is required"),typeof d.title!="string"&&typeof d.search?.title!="string"&&typeof d.search?.name!="string"&&t.push("items["+a+"].title or search.title/search.name is required"),typeof d.text!="string"&&typeof d.search?.body!="string"&&typeof d.search?.summary!="string"&&t.push("items["+a+"].text or search.body/search.summary is required"),Array.isArray(d.tags)||t.push("items["+a+"].tags must be an array"),Array.isArray(d.concepts)||t.push("items["+a+"].concepts must be an array"),Array.isArray(d.relationships)||t.push("items["+a+"].relationships must be an array"),(!Array.isArray(d.provenance)||d.provenance.length===0)&&t.push("items["+a+"].provenance must be a non-empty array"),ar(d,a,t),dr(d,a,t),ur(d,a,t),!d.privacy||typeof d.privacy.pii!="boolean"||!_(d.privacy.classification)?t.push("items["+a+"].privacy requires classification and pii"):F(d.privacy.classification)||t.push("items["+a+"].privacy.classification must be one of private, sanitized, public");}return {valid:t.length===0,errors:t,counts:n}}function X(e){let t=Z(e);if(!t.valid)throw new Error(`Invalid AIWG Fortemi index export:
|
|
3
3
|
`+t.errors.join(`
|
|
4
|
-
`));return e}function fr(e){let t=[],n=
|
|
4
|
+
`));return e}function fr(e){let t=[],n=b(e)?e:{};if(b(e)||t.push("chunk manifest must be an object"),n?.schema_version!=="aiwg.fortemi.index.chunk-manifest.v1"&&t.push("schema_version must be aiwg.fortemi.index.chunk-manifest.v1"),_(n?.generated_at)||t.push("generated_at is required"),_(n?.source?.repo)||t.push("source.repo is required"),_(n?.source?.privacy)||t.push("source.privacy is required"),n?.source_export_schema_version!==void 0&&!At(n.source_export_schema_version)&&t.push("source_export_schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2 when present"),R(n?.total)||t.push("total must be a non-negative integer"),I(n?.part_size)||t.push("part_size must be a positive integer"),n.facets!==void 0&&!or(n.facets)&&t.push("facets must be a nested string-to-number count object"),n.projection!==void 0)if(!Array.isArray(n.projection)||!n.projection.every(s=>typeof s=="string"))t.push("projection must be an array of field names");else {let s=new Set(n.projection);for(let o of rr)s.has(o)||t.push("projection must include scan-required field "+o);}n.detail!==void 0&&!b(n.detail)?t.push("detail must be an object"):n.detail!==void 0&&(_(n.detail.href)?n.detail.href.includes("{id}")||t.push("detail.href must contain the {id} placeholder"):t.push("detail.href is required"),n.detail.encoding!==void 0&&n.detail.encoding!=="uri"&&n.detail.encoding!=="base64url"&&t.push("detail.encoding must be 'uri' or 'base64url'")),Array.isArray(n?.parts)||t.push("parts must be an array");let r=0,i=Array.isArray(n?.parts)?n.parts:[];for(let[s,o]of i.entries()){if(!b(o)){t.push("parts["+s+"] must be an object");continue}_(o.href)||t.push("parts["+s+"].href is required"),R(o.offset)||t.push("parts["+s+"].offset must be a non-negative integer"),R(o.count)||t.push("parts["+s+"].count must be a non-negative integer"),R(o.offset)&&o.offset!==r&&t.push("parts["+s+"].offset must be "+r),R(o.count)&&(r+=o.count);}return R(n?.total)&&r!==n.total&&t.push("parts counts must add up to total"),{valid:t.length===0,errors:t}}function pr(e){let t=fr(e);if(!t.valid)throw new Error(`Invalid AIWG Fortemi chunk manifest:
|
|
5
5
|
`+t.errors.join(`
|
|
6
|
-
`));return e}function gr(e,t,n){let r="items["+t+"]";if(!e.privacy||!
|
|
6
|
+
`));return e}function gr(e,t,n){let r="items["+t+"]";if(!e.privacy||!b(e.privacy)?n.push(r+"/privacy requires classification and pii"):(F(e.privacy.classification)||n.push(r+"/privacy/classification must be one of private, sanitized, public"),typeof e.privacy.pii!="boolean"&&n.push(r+"/privacy/pii must be boolean")),Array.isArray(e.provenance))for(let[i,s]of e.provenance.entries()){if(!b(s)){n.push(r+"/provenance/"+i+" must be an object");continue}Ct(s.confidence)||n.push(r+"/provenance/"+i+"/confidence must be one of source, candidate, reviewed, rejected"),F(s.privacy)||n.push(r+"/provenance/"+i+"/privacy must be one of private, sanitized, public");}}function hr(e,t){let n=[],r=new Set,i="";for(let[s,o]of e.entries()){if(!b(o)){n.push("items["+s+"] must be an object");continue}gr(o,s,n);let a=t==="aiwg.fortemi.index.export.v2"?"aiwg.fortemi.index.record.v2":"aiwg.fortemi.index.record.v1";o.schema_version!==a&&n.push(`items[${s}].schema_version must match ${t}`),Rt(o.schema_version)||n.push("items["+s+"].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2"),_(o.id)||n.push("items["+s+"].id is required"),_(o.id)&&r.has(o.id)&&n.push("duplicate id: "+o.id),_(o.id)&&r.add(o.id),i&&_(o.id)&&i>o.id&&n.push("items must be sorted by id: "+i+" before "+o.id),_(o.id)&&(i=o.id),_(o.type)||n.push("items["+s+"].type must be a non-empty string"),typeof o.title!="string"&&typeof o.search?.title!="string"&&typeof o.search?.name!="string"&&n.push("items["+s+"].title or search.title/search.name is required"),typeof o.text!="string"&&typeof o.search?.body!="string"&&typeof o.search?.summary!="string"&&n.push("items["+s+"].text or search.body/search.summary is required"),(!o.facets||typeof o.facets!="object"||Array.isArray(o.facets))&&n.push("items["+s+"].facets must be an object"),Array.isArray(o.tags)||n.push("items["+s+"].tags must be an array"),Array.isArray(o.concepts)||n.push("items["+s+"].concepts must be an array");}return n}function _r(e,t,n){let r=[],i=b(e)?e:{};if(b(e)||r.push("chunk part must be an object"),i?.schema_version!=="aiwg.fortemi.index.chunk.v1"&&r.push("schema_version must be aiwg.fortemi.index.chunk.v1"),i?.manifest_schema_version!=="aiwg.fortemi.index.chunk-manifest.v1"&&r.push("manifest_schema_version must be aiwg.fortemi.index.chunk-manifest.v1"),R(i?.offset)||r.push("offset must be a non-negative integer"),Array.isArray(i?.items)||r.push("items must be an array"),t&&R(i?.offset)&&i.offset!==t.offset&&r.push("offset must match manifest part offset "+t.offset),t&&Array.isArray(i?.items)&&i.items.length!==t.count&&r.push("items length must match manifest part count "+t.count),Array.isArray(i?.items))if(n?.projection)r.push(...hr(i.items,n.source_export_schema_version??"aiwg.fortemi.index.export.v1").map(s=>"items."+s));else {let s=Z({schema_version:n?.source_export_schema_version??"aiwg.fortemi.index.export.v1",generated_at:n?.generated_at??"1970-01-01T00:00:00.000Z",source:n?.source??{repo:"chunk",privacy:"public"},...(n?.source_export_schema_version??"aiwg.fortemi.index.export.v1")==="aiwg.fortemi.index.export.v2"?{compatibility:{previous_schema_version:"aiwg.fortemi.index.export.v1",strategy:"supported"}}:{},items:i.items});r.push(...s.errors.map(o=>"items."+o));}return {valid:r.length===0,errors:r}}function yr(e,t,n){let r=_r(e,t,n);if(!r.valid)throw new Error(`Invalid AIWG Fortemi chunk part:
|
|
7
7
|
`+r.errors.join(`
|
|
8
|
-
`));return e}var
|
|
8
|
+
`));return e}var wt=new Set(["http:","https:","blob:","data:"]);function br(e){try{return new URL(e)}catch{return null}}function It(e,t){if(t===void 0){let i=br(e);if(i&&!wt.has(i.protocol))throw new Error("Refusing AIWG index fetch with disallowed scheme: "+i.protocol);return e}let n=new URL(t),r=new URL(e,n);if(!wt.has(r.protocol))throw new Error("Refusing AIWG index fetch with disallowed scheme: "+r.protocol);if(r.origin!==n.origin)throw new Error("Refusing cross-origin AIWG index fetch: "+r.origin+" != "+n.origin);return r.toString()}function $o(e){return async t=>{let n=It(t.href,e),r=await fetch(n);if(!r.ok)throw new Error("Failed to fetch AIWG index chunk "+n+": "+r.status);return r.json()}}function wr(e,t="base64url"){if(t==="uri")return encodeURIComponent(e);let n=new TextEncoder().encode(e),r="";for(let i of n)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ft(e,t){return e.href.replace("{id}",wr(t,e.encoding??"uri"))}function ko(e){return async(t,n)=>{if(!n.detail?.href)throw new Error("Manifest has no detail.href for record resolution");let r=Ft(n.detail,t),i=It(r,e),s=await fetch(i);if(!s.ok)throw new Error("Failed to fetch AIWG index detail "+i+": "+s.status);return s.json()}}function Pt(e){let t=Object.create(null);for(let n of e){T(t,"type",n.type),T(t,"privacy",n.privacy.classification);for(let r of n.tags)T(t,"tag",r);for(let r of n.concepts)T(t,"concept",r);for(let[r,i]of Object.entries(n.facets))for(let s of i)T(t,r,s);}return t}function P(e){return e.title??e.search?.title??e.search?.name??e.id}function V(e){let t=e.text??e.search?.body??e.search?.summary??e.chunks?.map(r=>r.text??r.body??r.summary??"").filter(Boolean).join(`
|
|
9
9
|
`)??"",n=Et(e);return [t,n].filter(Boolean).join(`
|
|
10
10
|
`)}function Et(e){return "binary_sources"in e?e.binary_sources?.map(t=>t.extracted_text).filter(Boolean).join(`
|
|
11
|
-
`)??"":""}function
|
|
11
|
+
`)??"":""}function vr(e,t){let n=P(e),r=V(e);return t==="title-summary"?[n,e.search?.summary??"",Et(e)].filter(Boolean).join(`
|
|
12
12
|
`):[n,r].filter(Boolean).join(`
|
|
13
|
-
`)}function $r(e){return e instanceof Date?e.toISOString():e??new Date().toISOString()}var kr=[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 j(e,t){return e>>>t|e<<32-t}function xr(e){let t=e.length*8,n=new Uint8Array(e.length+9+63>>6<<6);n.set(e),n[e.length]=128;let r=new DataView(n.buffer);r.setUint32(n.length-4,t>>>0),r.setUint32(n.length-8,Math.floor(t/4294967296));let i=1779033703,s=3144134277,o=1013904242,a=2773480762,d=1359893119,l=2600822924,
|
|
14
|
-
`),
|
|
13
|
+
`)}function $r(e){return e instanceof Date?e.toISOString():e??new Date().toISOString()}var kr=[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 j(e,t){return e>>>t|e<<32-t}function xr(e){let t=e.length*8,n=new Uint8Array(e.length+9+63>>6<<6);n.set(e),n[e.length]=128;let r=new DataView(n.buffer);r.setUint32(n.length-4,t>>>0),r.setUint32(n.length-8,Math.floor(t/4294967296));let i=1779033703,s=3144134277,o=1013904242,a=2773480762,d=1359893119,l=2600822924,m=528734635,f=1541459225,u=new Uint32Array(64);for(let g=0;g<n.length;g+=64){for(let v=0;v<16;v++)u[v]=r.getUint32(g+v*4);for(let v=16;v<64;v++){let y=j(u[v-15],7)^j(u[v-15],18)^u[v-15]>>>3,C=j(u[v-2],17)^j(u[v-2],19)^u[v-2]>>>10;u[v]=u[v-16]+y+u[v-7]+C>>>0;}let c=i,p=s,h=o,w=a,$=d,k=l,x=m,A=f;for(let v=0;v<64;v++){let y=j($,6)^j($,11)^j($,25),C=$&k^~$&x,E=A+y+C+kr[v]+u[v]>>>0,ee=j(c,2)^j(c,13)^j(c,22),te=c&p^c&h^p&h,q=ee+te>>>0;A=x,x=k,k=$,$=w+E>>>0,w=h,h=p,p=c,c=E+q>>>0;}i=i+c>>>0,s=s+p>>>0,o=o+h>>>0,a=a+w>>>0,d=d+$>>>0,l=l+k>>>0,m=m+x>>>0,f=f+A>>>0;}return [i,s,o,a,d,l,m,f].map(g=>g.toString(16).padStart(8,"0")).join("")}function Sr(e){return `sha256:${xr(e)}`}async function xo(e,t){X(e);let n=t.granularity??"body",r=jt(t.records??e.items,t.privacy),i=[];for(let o of r){let a=t.textForRecord?.(o)??vr(o,n),d=await t.backend.embed(a,o);if(d.length!==t.backend.dimensions)throw new Error(`Embedding for ${o.id} has ${d.length} dimensions; expected ${t.backend.dimensions}`);i.push({record_id:o.id,embedding:d,granularity:n,input_hash:Sr(new TextEncoder().encode(a)),source_path:o.source.path});}let s={schema_version:"aiwg.fortemi.embedding.set.v1",id:t.id,model:t.backend.model,dimensions:t.backend.dimensions,generated_at:$r(t.generatedAt),granularity:n,...t.metric?{metric:t.metric}:{},input_hash_algorithm:"sha256",embeddings:i};return fe(s),s}function jr(e){let t=e.search,n=[e.id,P(e),V(e),t?.title,t?.name,t?.summary,t?.body,t?.capability,t?.phase,t?.type,...t?.triggers??[],...t?.aliases??[],...t?.tags??[],...(e.chunks??[]).flatMap(r=>[r.text,r.body,r.summary,r.source_path])];if(t?.frontmatter)for(let r of Object.values(t.frontmatter))typeof r=="string"?n.push(r):Array.isArray(r)&&n.push(...r.filter(i=>typeof i=="string"));return n.filter(r=>typeof r=="string"&&r.length>0)}function So(e,t={}){X(e);let n=I(t.partSize)?t.partSize:500,r=t.projection,i=t.idEncoding??"base64url",s=t.detailHref??"detail/{id}.json",o=jt(e.items,t.privacy),a=u=>String(u).padStart(4,"0"),d=u=>{if(!r)return u;let g={};for(let c of r)g[c]=u[c];return g},l=[],m=[];for(let u=0,g=0;u<o.length;u+=n,g+=1){let c=o.slice(u,u+n),p="part-"+a(g)+".json";l.push({href:p,part:{schema_version:"aiwg.fortemi.index.chunk.v1",manifest_schema_version:"aiwg.fortemi.index.chunk-manifest.v1",offset:u,items:c.map(d)}}),m.push({href:p,offset:u,count:c.length});}return {manifest:{schema_version:"aiwg.fortemi.index.chunk-manifest.v1",generated_at:t.generatedAt??e.generated_at,source:e.source,source_export_schema_version:e.schema_version,total:o.length,part_size:n,facets:Pt(o),parts:m,...r?{projection:r,detail:{href:s,encoding:i}}:{}},parts:l,details:r?o.map(u=>({id:u.id,href:Ft({href:s,encoding:i},u.id),record:u})):[]}}function de(e,t){if(!t||t.length===0)return true;let n=new Set(e);return t.every(r=>n.has(r))}function Ar(e,t){return t?Object.entries(t).every(([n,r])=>de(e.facets[n]??[],r)):true}function Rr(e,t){if(!t)return [];let n=[],r=P(e),i=V(e);r.toLowerCase().includes(t)&&n.push({field:"title",value:r}),i.toLowerCase().includes(t)&&n.push({field:"text",value:i});for(let s of e.tags)s.toLowerCase().includes(t)&&n.push({field:"tag",value:s});for(let s of e.concepts)s.toLowerCase().includes(t)&&n.push({field:"concept",value:s});for(let s of jr(e))s!==r&&s!==i&&s.toLowerCase().includes(t)&&n.push({field:"text",value:s,score:ue.text});return n}var Cr=new Set(["the","a","an","and","or","of","for","to","in","on","with","into","from","is","are","be","i","we","my","it","you","me","us","your","our","this","that","these","those","there","here","some","any","all","also","please","about","how","what","which","where","when","who","why","find","give","show","need","want","looking","look","help","do","does","did","can","could","should","would","will","handle","handles","handling","aiwg","skill","skills","agent","agents","command","commands","rule","rules","flow","flows","workflow","workflows"]);function J(e){return e.toLowerCase().replace(/[-_\s]+/g," ").trim()}function Ir(e){return e.toLowerCase().split(/[^a-z0-9-]+/).filter(t=>t.length>1&&!Cr.has(t))}function oe(e,t){return t.flatMap(n=>e.facets[n]??[])}function vt(e,t){e.some(n=>n.field===t.field&&n.value===t.value&&n.reason===t.reason)||e.push(t);}function Fr(e,t){if(e===t)return true;if(Math.abs(e.length-t.length)>1)return false;if(e.length===t.length){let a=-1,d=0;for(let l=0;l<e.length;l+=1)e[l]!==t[l]&&(a<0&&(a=l),d+=1);return d===1?true:d===2&&a+1<e.length&&e[a]===t[a+1]&&e[a+1]===t[a]}let n=e.length<t.length?e:t,r=e.length<t.length?t:e,i=0,s=0,o=0;for(;i<n.length&&s<r.length;)if(n[i]===r[s])i+=1,s+=1;else {if(o+=1,o>1)return false;s+=1;}return true}function Pr(e,t){let n=J(e).split(/\s+/).filter(Boolean),r=J(t).split(/\s+/).filter(Boolean);return n.length!==r.length?false:n.every((i,s)=>{let o=r[s];return i===o?true:i.length<5||o.length<5?false:Fr(i,o)})}function Er(e){return e.map(t=>t.toLowerCase())}function Lr(e,t,n={}){if(!t)return [];let r=[],i=Ir(t),s=i.length>0?i.join(" "):t.toLowerCase().trim(),o=t.toLowerCase().trim(),a=e.id.split(/[:/]/),d=[e.id,P(e),e.search?.name,e.search?.title,...e.search?.aliases??[],...a,...oe(e,["name","canonical_name","command","skill","agent","rule"])].filter(y=>_(y)),l=[...oe(e,["trigger","triggers","trigger_phrase","trigger_phrases"]),...e.search?.triggers??[]],m=[...oe(e,["capability","capabilities","summary","description"]),e.search?.capability,e.search?.summary,e.search?.phase,e.search?.type,...e.search?.tags??[],...e.concepts,...e.tags].filter(y=>_(y)),f=[e.source?.path,e.source?.repo_relative_path,e.source?.locator].filter(y=>_(y)),u=P(e),g=[e.search?.summary,V(e)].filter(y=>_(y)).join(`
|
|
14
|
+
`),c=e.search?.type??e.type,p=[...e.search?.tags??[],...e.tags],h=i.length>1,w=h?n.relaxOverlap?1:Math.ceil(i.length/2):1,$=y=>h&&y>=w,k=y=>vt(r,{...y,score:0}),x=y=>{y>0&&vt(r,{field:"id",value:e.id,score:y,reason:"aiwg discovery score"});};for(let y of d){if(J(t)===J(y))return k({field:"id",value:y,reason:"exact canonical name"}),x(1.001),r;if(Pr(t,y))return k({field:"id",value:y,reason:"near canonical name"}),x(.951),r}let A=0,v=(y,C,E,ee,te,q,Vt=0)=>{let ne=C.toLowerCase();if(ne.includes(s))A+=ee*q,ne===s&&(A+=Vt),k({field:y,value:C,reason:E});else if(h){let pe=i.filter(qt=>ne.includes(qt)).length;$(pe)&&(A+=te*q*(pe/i.length),k({field:y,value:C,reason:E}));}};for(let y of Er(l))if(y===s||y===o)return k({field:"facet",value:y,reason:"trigger phrase"}),x(1.0008),r;for(let y of l)v("facet",y,"trigger phrase",.25,.06,4);for(let y of m)v("concept",y,"capability overlap",.2,.1,2);v("title",u,"title token overlap",.3,.08,3,.2);for(let y of p)v("tag",y,"tag token overlap",.2,.05,2);g&&v("text",g,"body token overlap",.15,.04,1);for(let y of f)v("source",y,"path overlap",.1,.03,1);return c.toLowerCase().includes(s)&&(A+=.1,k({field:"facet",value:c,reason:"type overlap"})),x(Math.min(A,1)),r}function Or(e,t){return e.reduce((n,r)=>n+(r.score??t[r.field]),0)}function Mr(e,t,n){let r=Math.max(20,n);if(!e)return "";if(!t)return e.length>r?`${e.slice(0,r).trimEnd()}...`:e;let s=e.toLowerCase().indexOf(t);if(s<0)return e.length>r?`${e.slice(0,r).trimEnd()}...`:e;let o=Math.max(0,Math.floor((r-t.length)/2)),a=Math.max(0,s-o),d=Math.min(e.length,a+r),l=a>0?"...":"",m=d<e.length?"...":"";return `${l}${e.slice(a,d).trim()}${m}`}function Tr(e,t,n,r){let i=t.find(a=>a.field==="text"),s=t.find(a=>a.field==="title"),o=i??s??t[0];return Mr(o?.value??V(e),n,r)}function ce(e,t,n,r=0,i={}){let s={...ue,...n.weights},o=n.searchProfile??"default";return e.map((a,d)=>({item:a,ordinal:r+d,matches:o==="aiwg-discovery"?Lr(a,t,i):Rr(a,t)})).filter(({item:a,matches:d})=>!(t&&d.length===0||n.types&&!n.types.includes(a.type)||n.privacy&&!n.privacy.includes(a.privacy.classification)||!de(a.tags,n.tags)||!de(a.concepts,n.concepts)||!Ar(a,n.facets)||n.relationshipTargetId&&!(a.relationships??[]).some(l=>l.target_id===n.relationshipTargetId))).map(({item:a,ordinal:d,matches:l})=>({item:a,ordinal:d,rank:Or(l,s),matches:l}))}function Vr(e,t){return [...e].sort((n,r)=>t&&r.rank-n.rank||n.ordinal-r.ordinal)}function Y(e,t,n){let r=Vr(e,n.rank),i=n.offset??0,s=n.limit??r.length,o=r.slice(i,i+s),a={items:o.map(d=>d.item),total:r.length,facets:Pt(r.map(d=>d.item))};if(n.rank||n.snippets||n.includeMatches){let d=n.snippetLength??160;a.rankedItems=o.map(l=>({item:l.item,rank:l.rank,...n.snippets?{snippet:Tr(l.item,l.matches,t,d)}:{},...n.includeMatches?{matches:l.matches}:{}}));}return a}function Lt(e,t="",n={}){let r=t.trim().toLowerCase(),i=ce(e.items,r,n);return i.length===0&&r&&n.searchProfile==="aiwg-discovery"?Y(ce(e.items,r,n,0,{relaxOverlap:true}),r,n):Y(i,r,n)}function Ot(e,t){if(e.length!==t.length||e.length===0)return 0;let n=0,r=0,i=0;for(let s=0;s<e.length;s+=1){let o=e[s],a=t[s];n+=o*a,r+=o*o,i+=a*a;}return r===0||i===0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function qr(e){let t=[],n=b(e)?e:{};b(e)||t.push("embedding set must be an object"),n?.schema_version!=="aiwg.fortemi.embedding.set.v1"&&t.push("schema_version must be aiwg.fortemi.embedding.set.v1"),_(n?.id)||t.push("id is required"),_(n?.model)||t.push("model is required"),I(n?.dimensions)||t.push("dimensions must be a positive integer"),_(n?.generated_at)||t.push("generated_at is required"),_(n?.granularity)||t.push("granularity is required"),Array.isArray(n?.embeddings)||t.push("embeddings must be an array");let r=Array.isArray(n.embeddings)?n.embeddings:[];for(let[i,s]of r.entries()){if(!b(s)){t.push("embeddings["+i+"] must be an object");continue}_(s.record_id)||t.push("embeddings["+i+"].record_id is required"),_(s.input_hash)||t.push("embeddings["+i+"].input_hash is required"),Array.isArray(s.embedding)?I(n?.dimensions)&&s.embedding.length!==n.dimensions?t.push("embeddings["+i+"].embedding length must match dimensions"):s.embedding.every(o=>typeof o=="number"&&Number.isFinite(o))||t.push("embeddings["+i+"].embedding must contain finite numbers"):t.push("embeddings["+i+"].embedding must be an array");}return {valid:t.length===0,errors:t}}function fe(e){let t=qr(e);if(!t.valid)throw new Error(`Invalid AIWG Fortemi embedding set:
|
|
15
15
|
`+t.errors.join(`
|
|
16
|
-
`));return e}function Dr(e,t,n,r={}){if(fe(t),n.length!==t.dimensions)throw new Error("query embedding length must match embedding set dimensions");let i=new Map(e.items.map(a=>[a.id,a])),s=r.offset??0,o=r.limit??20;return t.embeddings.map(a=>{let d=i.get(a.record_id);return d?{item:d,embedding:a,score:Ot(n,a.embedding)}:null}).filter(a=>a!==null&&a.score>=(r.minScore??-1)).sort((a,d)=>d.score-a.score||a.item.id.localeCompare(d.item.id)).slice(s,s+o)}function jo(e,t,n,r,i={}){let s={...i};delete s.limit,delete s.offset;let o=Lt(e,n,{...s,rank:true}),a=Dr(e,t,r,{limit:e.items.length}),d=i.lexicalWeight??.5,l=i.semanticWeight??.5,c=new Map(o.rankedItems?.map(v=>[v.item.id,v.rank])??[]),u=Math.max(1,...c.values()),m=new Map(a.flatMap(v=>v.embedding?[[v.item.id,v.embedding]]:[])),p=new Map(a.map(v=>[v.item.id,v.score])),f=new Set([...c.keys(),...p.keys()]),b=i.offset??0,h=i.limit??20;return [...f].map(v=>{let $=e.items.find(x=>x.id===v),k=m.get(v);return $?{item:$,...k?{embedding:k}:{},score:(c.get(v)??0)/u*d+(p.get(v)??0)*l}:null}).filter(v=>v!==null&&v.score>=(i.minScore??-1)).sort((v,$)=>$.score-v.score||v.item.id.localeCompare($.item.id)).slice(b,b+h)}var Nr=5e3;function Ao(e,t,n=.9,r){fe(t);let i=r?.maxEmbeddings??Nr;if(t.embeddings.length>i)throw new Error("Embedding set too large for duplicate scan: "+t.embeddings.length+" > "+i+" (raise options.maxEmbeddings to override for trusted input)");let s=new Map(e.items.map(a=>[a.id,a])),o=[];for(let a=0;a<t.embeddings.length;a+=1)for(let d=a+1;d<t.embeddings.length;d+=1){let l=t.embeddings[a],c=t.embeddings[d],u=s.get(l.record_id),m=s.get(c.record_id);if(!u||!m)continue;let p=Ot(l.embedding,c.embedding);p>=n&&o.push({left:u,right:m,score:p});}return o.sort((a,d)=>d.score-a.score||a.left.id.localeCompare(d.left.id))}function Ur(e){return `${e.offset}:${e.href}`}function Kr(e){return I(e)?e:3}function Br(e){return I(e)?e:32}function Qr(e){return I(e)?e:5e3}function zr(e,t){return JSON.stringify({q:e,types:t.types??null,facets:t.facets??null,tags:t.tags??null,concepts:t.concepts??null,privacy:t.privacy??null,rel:t.relationshipTargetId??null,searchProfile:t.searchProfile??"default",weights:{...ue,...t.weights}})}function Gr(e,t,n){e.matchCache.delete(t),e.matchCache.set(t,n);let r=0;for(let i of e.matchCache.values())r+=i.length;for(;r>e.maxCachedMatches&&e.matchCache.size>1;){let i=e.matchCache.keys().next().value;if(i===void 0||i===t)break;r-=e.matchCache.get(i)?.length??0,e.matchCache.delete(i);}}function Hr(e,t){return e.trim()===""&&!t.rank&&!t.snippets&&!t.includeMatches&&!t.types&&!t.facets&&!t.tags&&!t.concepts&&!t.privacy&&!t.relationshipTargetId}function Wr(e,t,n){let r=t+n;return e.parts.filter(i=>i.count>0&&i.offset<r&&i.offset+i.count>t)}async function le(e,t){let n=Ur(t),r=e.partCache.get(n);if(r)return e.partCache.delete(n),e.partCache.set(n,r),{part:r,fetched:false};let i=yr(await e.loader(t,e.manifest),t,e.manifest);for(e.partCache.set(n,i);e.partCache.size>e.maxCachedParts;){let s=e.partCache.keys().next().value;if(s===void 0)break;e.partCache.delete(s);}return {part:i,fetched:true}}async function Mt(e,t){let n=e.detailCache.get(t);if(n)return e.detailCache.delete(t),e.detailCache.set(t,n),n;if(!e.manifest.projection)for(let s of e.partCache.values()){let o=s.items.find(a=>a.id===t);if(o)return o}if(!e.detailLoader)throw new Error("No detailLoader configured to resolve record "+t);let r=await e.detailLoader(t,e.manifest),i=X({schema_version:"aiwg.fortemi.index.export.v1",generated_at:e.manifest.generated_at,source:e.manifest.source,items:[r]}).items[0];if(i.id!==t)throw new Error("Detail record id mismatch: expected "+t+", got "+i.id);for(e.detailCache.set(t,i);e.detailCache.size>e.maxCachedDetails;){let s=e.detailCache.keys().next().value;if(s===void 0)break;e.detailCache.delete(s);}return i}function Jr(e){return e?.relationshipType??e?.type}function Yr(e,t){return {source_id:e,target_id:t.target_id,type:t.type,...t.source_path?{source_path:t.source_path}:{},...t.target_path?{target_path:t.target_path}:{},...t.direction?{direction:t.direction}:{}}}function Zr(e,t={}){let n=Jr(t);return !(n&&e.type!==n||t.relationshipDirection&&e.direction!==t.relationshipDirection||t.sourceId&&e.source_id!==t.sourceId||t.targetId&&e.target_id!==t.targetId||t.endpointId&&e.source_id!==t.endpointId&&e.target_id!==t.endpointId)}function Xr(e){if(e.direction==="out"&&!e.sourceId)throw new Error("relationship direction 'out' requires sourceId");if(e.direction==="in"&&!e.targetId)throw new Error("relationship direction 'in' requires targetId")}function ei(e){return {id:e.id,type:e.type,title:P(e)}}function $t(e,t){t&&e.set(t.id,ei(t));}function me(e,t={}){Xr(t);let n=new Map(e.map(a=>[a.id,a])),r=[];for(let a of e)for(let d of a.relationships??[]){let l=Yr(a.id,d);Zr(l,t)&&r.push(l);}let i=r.sort((a,d)=>a.source_id.localeCompare(d.source_id)||a.target_id.localeCompare(d.target_id)||a.type.localeCompare(d.type)),s=t.limit?i.slice(0,t.limit):i,o=new Map;for(let a of s)$t(o,n.get(a.source_id)),$t(o,n.get(a.target_id));return {nodes:[...o.values()].sort((a,d)=>a.id.localeCompare(d.id)),edges:s,complete:true}}function ti(e,t={}){let n=t.direction??"both";return {...t,...n==="out"?{sourceId:e}:{},...n==="in"?{targetId:e}:{},...n==="both"?{endpointId:e}:{}}}function ni(e,t,n={}){let r=n.direction??"both",i=t.edges.filter(o=>r==="out"?o.source_id===e:r==="in"?o.target_id===e:o.source_id===e||o.target_id===e),s=new Set;for(let o of i)s.add(o.source_id),s.add(o.target_id);return {...t,edges:i,nodes:t.nodes.filter(o=>s.has(o.id))}}async function Tt(e,t){let n=0,r=0,i=[];for(let s of e.manifest.parts){let o=await le(e,s);o.fetched&&(r+=1),n+=1,t?.({phase:"part",done:n,total:e.manifest.parts.length,href:s.href});for(let a of o.part.items)i.push(a.relationships?a:await Mt(e,a.id));}return {records:i,scannedParts:n,fetchedParts:r}}async function kt(e,t={}){let n=await Tt(e);return {...me(n.records,t),scannedParts:n.scannedParts,fetchedParts:n.fetchedParts}}async function ri(e,t="",n={}){let r=t.trim().toLowerCase(),i=0,s=0;if(Hr(t,n)){let l=n.offset??0,c=n.limit??e.manifest.total,u=Wr(e.manifest,l,c),m=[];for(let p of u){let f=await le(e,p);f.fetched&&(s+=1),i+=1,n.onProgress?.({phase:"part",done:i,total:u.length,href:p.href});let b=Math.max(0,l-p.offset),h=Math.min(f.part.items.length,l+c-p.offset);m.push(...f.part.items.slice(b,h));}return {items:m,total:e.manifest.total,facets:e.manifest.facets??{},manifestTotal:e.manifest.total,scannedParts:i,fetchedParts:s,complete:true}}let o=zr(r,n),a=e.matchCache.get(o);if(a)return e.matchCache.delete(o),e.matchCache.set(o,a),{...Y(a,r,n),manifestTotal:e.manifest.total,scannedParts:0,fetchedParts:0,complete:true};let d=[];for(let l of e.manifest.parts){let c=await le(e,l);c.fetched&&(s+=1),i+=1,n.onProgress?.({phase:"part",done:i,total:e.manifest.parts.length,href:l.href}),d.push(...ce(c.part.items,r,n,l.offset)),n.onProgress?.({phase:"query",done:i,total:e.manifest.parts.length,href:l.href});}return Gr(e,o,d),{...Y(d,r,n),manifestTotal:e.manifest.total,scannedParts:i,fetchedParts:s,complete:true}}function ii(e,t,n=new Date().toISOString()){return {schema_version:"aiwg.fortemi.review-decisions.v1",generated_at:n,source_export_schema_version:e.schema_version,decisions:[...t].sort((r,i)=>r.item_id.localeCompare(i.item_id))}}function Ro(e){let t=e??null,n=null,r=null,i=null,s=[],o=new Set,a=()=>({index:t,chunked:n?{manifest:n.manifest,cachedParts:n.partCache.size,maxCachedParts:n.maxCachedParts}:null,data:r,error:i,reviewDecisions:[...s]}),d=()=>{let c=a();for(let u of o)u(c);},l=()=>{if(!t)throw new Error("No AIWG index export loaded");return t};return {loadIndex(c){try{let u=X(c);return t=u,n=null,r=null,s=[],i=null,d(),u}catch(u){throw i=u instanceof Error?u:new Error(String(u)),d(),i}},loadChunkedIndex(c,u,m={}){try{let p=pr(c);return t=null,n={manifest:p,loader:u,maxCachedParts:Kr(m.maxCachedParts),partCache:new Map,detailLoader:m.detailLoader,maxCachedDetails:Br(m.maxCachedDetails),detailCache:new Map,maxCachedMatches:Qr(m.maxCachedMatches),matchCache:new Map},r=null,s=[],i=null,d(),p}catch(p){throw i=p instanceof Error?p:new Error(String(p)),d(),i}},getIndex(){return t},getChunkedManifest(){return n?.manifest??null},getSnapshot(){return a()},query(c="",u){let m=Lt(l(),c,u);return r=m,i=null,d(),m},async queryChunked(c="",u){if(!n)throw new Error("No AIWG chunked index manifest loaded");try{let m=await ri(n,c,u);return r=m,i=null,d(),m}catch(m){throw i=m instanceof Error?m:new Error(String(m)),d(),i}},async getRecord(c){if(n)try{return await Mt(n,c)}catch(m){throw i=m instanceof Error?m:new Error(String(m)),d(),i}let u=l().items.find(m=>m.id===c);if(!u)throw new Error("Record not found: "+c);return u},async neighbors(c,u){try{let m=ti(c,u),p=n?await kt(n,m):me(l().items,m);return ni(c,p,u)}catch(m){throw i=m instanceof Error?m:new Error(String(m)),d(),i}},async relationshipQuery(c){try{return n?await kt(n,c):me(l().items,c)}catch(u){throw i=u instanceof Error?u:new Error(String(u)),d(),i}},async relationshipSet(c){let[u,m]=await Promise.all([this.neighbors(c.a,c),this.neighbors(c.b,c)]),p=new Set(u.nodes.map(h=>h.id).filter(h=>h!==c.a)),f=new Set(m.nodes.map(h=>h.id).filter(h=>h!==c.b)),b;return c.op==="intersection"?b=[...p].filter(h=>f.has(h)):c.op==="difference"?b=[...p].filter(h=>!f.has(h)):b=[...new Set([...p,...f])],{op:c.op,ids:b.sort()}},clearChunkCache(){n?.partCache.clear(),n?.detailCache.clear(),n?.matchCache.clear(),i=null,d();},toCommunityGraph(c){return ae(l(),c)},async toCommunityGraphChunked(c){if(!n)return ae(l(),c);let u=await Tt(n,c?.onProgress);return ae({generated_at:n.manifest.generated_at,source:n.manifest.source,items:u.records},c)},setReviewDecision(c){let u={...c,updated_at:new Date().toISOString()};return s=[...s.filter(m=>m.item_id!==u.item_id),u].sort((m,p)=>m.item_id.localeCompare(p.item_id)),i=null,d(),u},clearReviewDecision(c){s=s.filter(u=>u.item_id!==c),i=null,d();},createReviewDecisionExport(c){let u=t??(n?{schema_version:n.manifest.source_export_schema_version??"aiwg.fortemi.index.export.v1"}:null);if(!u)throw new Error("No AIWG index export or chunked manifest loaded");return ii(u,s,c)},subscribe(c){return o.add(c),()=>{o.delete(c);}}}}function ae(e,t={}){let n=new Set(e.items.map(o=>o.id)),r=t.relationshipWeights??Object.create(null),i=new Map;for(let o of e.items)for(let a of o.relationships){if(!n.has(a.target_id)&&!t.includeDanglingRelationships)continue;let d=a.type,l=Object.prototype.hasOwnProperty.call(r,d)?r[d]:void 0,c=typeof l=="number"&&Number.isFinite(l)?l:1,u=`${o.id}\0${a.target_id}\0${d}`,m=i.get(u);m?m.weight+=c:i.set(u,{source:o.id,target:a.target_id,kind:d,weight:c});}let s=new Map;for(let o of e.items){let a=si(o,t);for(let d of a){let l=s.get(d)??[];l.push(o.id),s.set(d,l);}}return {nodes:e.items.map(o=>({id:o.id})),edges:Array.from(i.values()).sort((o,a)=>o.source.localeCompare(a.source)||o.target.localeCompare(a.target)||o.kind.localeCompare(a.kind)),communities:Array.from(s.entries()).map(([o,a])=>({id:o,nodes:[...new Set(a)].sort()})).sort((o,a)=>o.id.localeCompare(a.id))}}function si(e,t){if(t.communityFacet){let n=e.facets[t.communityFacet]??[];if(n.length>0)return n.map(r=>`${t.communityFacet}:${r}`)}if(t.communityTagPrefix){let n=t.communityTagPrefix,r=e.tags.filter(i=>i.startsWith(n));if(r.length>0)return r}return e.concepts.length>0?e.concepts.map(n=>`concept:${n}`):[`type:${e.type}`]}var oi="7ab5d1f8-29d2-5e35-9e2f-3a45de171a9e",W=new TextEncoder,ai=new TextDecoder;function xt(e,t){return v5(`${e}:${t}`,oi)}function H(e,t){return !e||Number.isNaN(Date.parse(e))?t:new Date(e).toISOString()}function di(e){return e.title??e.search?.title??e.search?.name??e.id}function ci(e){if(e.text)return e.text;if(e.search?.body)return e.search.body;let t=e.chunks?.map(n=>n.text??n.body??n.summary??"").filter(Boolean);return t?.length?t.join(`
|
|
16
|
+
`));return e}function Dr(e,t,n,r={}){if(fe(t),n.length!==t.dimensions)throw new Error("query embedding length must match embedding set dimensions");let i=new Map(e.items.map(a=>[a.id,a])),s=r.offset??0,o=r.limit??20;return t.embeddings.map(a=>{let d=i.get(a.record_id);return d?{item:d,embedding:a,score:Ot(n,a.embedding)}:null}).filter(a=>a!==null&&a.score>=(r.minScore??-1)).sort((a,d)=>d.score-a.score||a.item.id.localeCompare(d.item.id)).slice(s,s+o)}function jo(e,t,n,r,i={}){let s={...i};delete s.limit,delete s.offset;let o=Lt(e,n,{...s,rank:true}),a=Dr(e,t,r,{limit:e.items.length}),d=i.lexicalWeight??.5,l=i.semanticWeight??.5,m=new Map(o.rankedItems?.map(w=>[w.item.id,w.rank])??[]),f=Math.max(1,...m.values()),u=new Map(a.flatMap(w=>w.embedding?[[w.item.id,w.embedding]]:[])),g=new Map(a.map(w=>[w.item.id,w.score])),c=new Set([...m.keys(),...g.keys()]),p=i.offset??0,h=i.limit??20;return [...c].map(w=>{let $=e.items.find(x=>x.id===w),k=u.get(w);return $?{item:$,...k?{embedding:k}:{},score:(m.get(w)??0)/f*d+(g.get(w)??0)*l}:null}).filter(w=>w!==null&&w.score>=(i.minScore??-1)).sort((w,$)=>$.score-w.score||w.item.id.localeCompare($.item.id)).slice(p,p+h)}var Nr=5e3;function Ao(e,t,n=.9,r){fe(t);let i=r?.maxEmbeddings??Nr;if(t.embeddings.length>i)throw new Error("Embedding set too large for duplicate scan: "+t.embeddings.length+" > "+i+" (raise options.maxEmbeddings to override for trusted input)");let s=new Map(e.items.map(a=>[a.id,a])),o=[];for(let a=0;a<t.embeddings.length;a+=1)for(let d=a+1;d<t.embeddings.length;d+=1){let l=t.embeddings[a],m=t.embeddings[d],f=s.get(l.record_id),u=s.get(m.record_id);if(!f||!u)continue;let g=Ot(l.embedding,m.embedding);g>=n&&o.push({left:f,right:u,score:g});}return o.sort((a,d)=>d.score-a.score||a.left.id.localeCompare(d.left.id))}function Ur(e){return `${e.offset}:${e.href}`}function Kr(e){return I(e)?e:3}function Br(e){return I(e)?e:32}function Qr(e){return I(e)?e:5e3}function zr(e,t){return JSON.stringify({q:e,types:t.types??null,facets:t.facets??null,tags:t.tags??null,concepts:t.concepts??null,privacy:t.privacy??null,rel:t.relationshipTargetId??null,searchProfile:t.searchProfile??"default",weights:{...ue,...t.weights}})}function Gr(e,t,n){e.matchCache.delete(t),e.matchCache.set(t,n);let r=0;for(let i of e.matchCache.values())r+=i.length;for(;r>e.maxCachedMatches&&e.matchCache.size>1;){let i=e.matchCache.keys().next().value;if(i===void 0||i===t)break;r-=e.matchCache.get(i)?.length??0,e.matchCache.delete(i);}}function Hr(e,t){return e.trim()===""&&!t.rank&&!t.snippets&&!t.includeMatches&&!t.types&&!t.facets&&!t.tags&&!t.concepts&&!t.privacy&&!t.relationshipTargetId}function Wr(e,t,n){let r=t+n;return e.parts.filter(i=>i.count>0&&i.offset<r&&i.offset+i.count>t)}async function le(e,t){let n=Ur(t),r=e.partCache.get(n);if(r)return e.partCache.delete(n),e.partCache.set(n,r),{part:r,fetched:false};let i=yr(await e.loader(t,e.manifest),t,e.manifest);for(e.partCache.set(n,i);e.partCache.size>e.maxCachedParts;){let s=e.partCache.keys().next().value;if(s===void 0)break;e.partCache.delete(s);}return {part:i,fetched:true}}async function Mt(e,t){let n=e.detailCache.get(t);if(n)return e.detailCache.delete(t),e.detailCache.set(t,n),n;if(!e.manifest.projection)for(let s of e.partCache.values()){let o=s.items.find(a=>a.id===t);if(o)return o}if(!e.detailLoader)throw new Error("No detailLoader configured to resolve record "+t);let r=await e.detailLoader(t,e.manifest),i=X({schema_version:"aiwg.fortemi.index.export.v1",generated_at:e.manifest.generated_at,source:e.manifest.source,items:[r]}).items[0];if(i.id!==t)throw new Error("Detail record id mismatch: expected "+t+", got "+i.id);for(e.detailCache.set(t,i);e.detailCache.size>e.maxCachedDetails;){let s=e.detailCache.keys().next().value;if(s===void 0)break;e.detailCache.delete(s);}return i}function Jr(e){return e?.relationshipType??e?.type}function Yr(e,t){return {source_id:e,target_id:t.target_id,type:t.type,...t.source_path?{source_path:t.source_path}:{},...t.target_path?{target_path:t.target_path}:{},...t.direction?{direction:t.direction}:{}}}function Zr(e,t={}){let n=Jr(t);return !(n&&e.type!==n||t.relationshipDirection&&e.direction!==t.relationshipDirection||t.sourceId&&e.source_id!==t.sourceId||t.targetId&&e.target_id!==t.targetId||t.endpointId&&e.source_id!==t.endpointId&&e.target_id!==t.endpointId)}function Xr(e){if(e.direction==="out"&&!e.sourceId)throw new Error("relationship direction 'out' requires sourceId");if(e.direction==="in"&&!e.targetId)throw new Error("relationship direction 'in' requires targetId")}function ei(e){return {id:e.id,type:e.type,title:P(e)}}function $t(e,t){t&&e.set(t.id,ei(t));}function me(e,t={}){Xr(t);let n=new Map(e.map(a=>[a.id,a])),r=[];for(let a of e)for(let d of a.relationships??[]){let l=Yr(a.id,d);Zr(l,t)&&r.push(l);}let i=r.sort((a,d)=>a.source_id.localeCompare(d.source_id)||a.target_id.localeCompare(d.target_id)||a.type.localeCompare(d.type)),s=t.limit?i.slice(0,t.limit):i,o=new Map;for(let a of s)$t(o,n.get(a.source_id)),$t(o,n.get(a.target_id));return {nodes:[...o.values()].sort((a,d)=>a.id.localeCompare(d.id)),edges:s,complete:true}}function ti(e,t={}){let n=t.direction??"both";return {...t,...n==="out"?{sourceId:e}:{},...n==="in"?{targetId:e}:{},...n==="both"?{endpointId:e}:{}}}function ni(e,t,n={}){let r=n.direction??"both",i=t.edges.filter(o=>r==="out"?o.source_id===e:r==="in"?o.target_id===e:o.source_id===e||o.target_id===e),s=new Set;for(let o of i)s.add(o.source_id),s.add(o.target_id);return {...t,edges:i,nodes:t.nodes.filter(o=>s.has(o.id))}}async function Tt(e,t){let n=0,r=0,i=[];for(let s of e.manifest.parts){let o=await le(e,s);o.fetched&&(r+=1),n+=1,t?.({phase:"part",done:n,total:e.manifest.parts.length,href:s.href});for(let a of o.part.items)i.push(a.relationships?a:await Mt(e,a.id));}return {records:i,scannedParts:n,fetchedParts:r}}async function kt(e,t={}){let n=await Tt(e);return {...me(n.records,t),scannedParts:n.scannedParts,fetchedParts:n.fetchedParts}}async function ri(e,t="",n={}){let r=t.trim().toLowerCase(),i=0,s=0;if(Hr(t,n)){let l=n.offset??0,m=n.limit??e.manifest.total,f=Wr(e.manifest,l,m),u=[];for(let g of f){let c=await le(e,g);c.fetched&&(s+=1),i+=1,n.onProgress?.({phase:"part",done:i,total:f.length,href:g.href});let p=Math.max(0,l-g.offset),h=Math.min(c.part.items.length,l+m-g.offset);u.push(...c.part.items.slice(p,h));}return {items:u,total:e.manifest.total,facets:e.manifest.facets??{},manifestTotal:e.manifest.total,scannedParts:i,fetchedParts:s,complete:true}}let o=zr(r,n),a=e.matchCache.get(o);if(a)return e.matchCache.delete(o),e.matchCache.set(o,a),{...Y(a,r,n),manifestTotal:e.manifest.total,scannedParts:0,fetchedParts:0,complete:true};let d=[];for(let l of e.manifest.parts){let m=await le(e,l);m.fetched&&(s+=1),i+=1,n.onProgress?.({phase:"part",done:i,total:e.manifest.parts.length,href:l.href}),d.push(...ce(m.part.items,r,n,l.offset)),n.onProgress?.({phase:"query",done:i,total:e.manifest.parts.length,href:l.href});}return Gr(e,o,d),{...Y(d,r,n),manifestTotal:e.manifest.total,scannedParts:i,fetchedParts:s,complete:true}}function ii(e,t,n=new Date().toISOString()){return {schema_version:"aiwg.fortemi.review-decisions.v1",generated_at:n,source_export_schema_version:e.schema_version,decisions:[...t].sort((r,i)=>r.item_id.localeCompare(i.item_id))}}function Ro(e){let t=e??null,n=null,r=null,i=null,s=[],o=new Set,a=()=>({index:t,chunked:n?{manifest:n.manifest,cachedParts:n.partCache.size,maxCachedParts:n.maxCachedParts}:null,data:r,error:i,reviewDecisions:[...s]}),d=()=>{let m=a();for(let f of o)f(m);},l=()=>{if(!t)throw new Error("No AIWG index export loaded");return t};return {loadIndex(m){try{let f=X(m);return t=f,n=null,r=null,s=[],i=null,d(),f}catch(f){throw i=f instanceof Error?f:new Error(String(f)),d(),i}},loadChunkedIndex(m,f,u={}){try{let g=pr(m);return t=null,n={manifest:g,loader:f,maxCachedParts:Kr(u.maxCachedParts),partCache:new Map,detailLoader:u.detailLoader,maxCachedDetails:Br(u.maxCachedDetails),detailCache:new Map,maxCachedMatches:Qr(u.maxCachedMatches),matchCache:new Map},r=null,s=[],i=null,d(),g}catch(g){throw i=g instanceof Error?g:new Error(String(g)),d(),i}},getIndex(){return t},getChunkedManifest(){return n?.manifest??null},getSnapshot(){return a()},query(m="",f){let u=Lt(l(),m,f);return r=u,i=null,d(),u},async queryChunked(m="",f){if(!n)throw new Error("No AIWG chunked index manifest loaded");try{let u=await ri(n,m,f);return r=u,i=null,d(),u}catch(u){throw i=u instanceof Error?u:new Error(String(u)),d(),i}},async getRecord(m){if(n)try{return await Mt(n,m)}catch(u){throw i=u instanceof Error?u:new Error(String(u)),d(),i}let f=l().items.find(u=>u.id===m);if(!f)throw new Error("Record not found: "+m);return f},async neighbors(m,f){try{let u=ti(m,f),g=n?await kt(n,u):me(l().items,u);return ni(m,g,f)}catch(u){throw i=u instanceof Error?u:new Error(String(u)),d(),i}},async relationshipQuery(m){try{return n?await kt(n,m):me(l().items,m)}catch(f){throw i=f instanceof Error?f:new Error(String(f)),d(),i}},async relationshipSet(m){let[f,u]=await Promise.all([this.neighbors(m.a,m),this.neighbors(m.b,m)]),g=new Set(f.nodes.map(h=>h.id).filter(h=>h!==m.a)),c=new Set(u.nodes.map(h=>h.id).filter(h=>h!==m.b)),p;return m.op==="intersection"?p=[...g].filter(h=>c.has(h)):m.op==="difference"?p=[...g].filter(h=>!c.has(h)):p=[...new Set([...g,...c])],{op:m.op,ids:p.sort()}},clearChunkCache(){n?.partCache.clear(),n?.detailCache.clear(),n?.matchCache.clear(),i=null,d();},toCommunityGraph(m){return ae(l(),m)},async toCommunityGraphChunked(m){if(!n)return ae(l(),m);let f=await Tt(n,m?.onProgress);return ae({generated_at:n.manifest.generated_at,source:n.manifest.source,items:f.records},m)},setReviewDecision(m){let f={...m,updated_at:new Date().toISOString()};return s=[...s.filter(u=>u.item_id!==f.item_id),f].sort((u,g)=>u.item_id.localeCompare(g.item_id)),i=null,d(),f},clearReviewDecision(m){s=s.filter(f=>f.item_id!==m),i=null,d();},createReviewDecisionExport(m){let f=t??(n?{schema_version:n.manifest.source_export_schema_version??"aiwg.fortemi.index.export.v1"}:null);if(!f)throw new Error("No AIWG index export or chunked manifest loaded");return ii(f,s,m)},subscribe(m){return o.add(m),()=>{o.delete(m);}}}}function ae(e,t={}){let n=new Set(e.items.map(o=>o.id)),r=t.relationshipWeights??Object.create(null),i=new Map;for(let o of e.items)for(let a of o.relationships){if(!n.has(a.target_id)&&!t.includeDanglingRelationships)continue;let d=a.type,l=Object.prototype.hasOwnProperty.call(r,d)?r[d]:void 0,m=typeof l=="number"&&Number.isFinite(l)?l:1,f=`${o.id}\0${a.target_id}\0${d}`,u=i.get(f);u?u.weight+=m:i.set(f,{source:o.id,target:a.target_id,kind:d,weight:m});}let s=new Map;for(let o of e.items){let a=si(o,t);for(let d of a){let l=s.get(d)??[];l.push(o.id),s.set(d,l);}}return {nodes:e.items.map(o=>({id:o.id})),edges:Array.from(i.values()).sort((o,a)=>o.source.localeCompare(a.source)||o.target.localeCompare(a.target)||o.kind.localeCompare(a.kind)),communities:Array.from(s.entries()).map(([o,a])=>({id:o,nodes:[...new Set(a)].sort()})).sort((o,a)=>o.id.localeCompare(a.id))}}function si(e,t){if(t.communityFacet){let n=e.facets[t.communityFacet]??[];if(n.length>0)return n.map(r=>`${t.communityFacet}:${r}`)}if(t.communityTagPrefix){let n=t.communityTagPrefix,r=e.tags.filter(i=>i.startsWith(n));if(r.length>0)return r}return e.concepts.length>0?e.concepts.map(n=>`concept:${n}`):[`type:${e.type}`]}var oi="7ab5d1f8-29d2-5e35-9e2f-3a45de171a9e",W=new TextEncoder,ai=new TextDecoder;function xt(e,t){return v5(`${e}:${t}`,oi)}function H(e,t){return !e||Number.isNaN(Date.parse(e))?t:new Date(e).toISOString()}function di(e){return e.title??e.search?.title??e.search?.name??e.id}function ci(e){if(e.text)return e.text;if(e.search?.body)return e.search.body;let t=e.chunks?.map(n=>n.text??n.body??n.summary??"").filter(Boolean);return t?.length?t.join(`
|
|
17
17
|
|
|
18
18
|
`):e.search?.summary??""}function li(e,t){return {aiwg_fortemi_index:{envelope:{schema_version:e.schema_version,generated_at:e.generated_at,source:e.source,...e.compatibility?{compatibility:e.compatibility}:{}},record:t}}}function St(e){return W.encode(e.map(t=>JSON.stringify(t)).join(`
|
|
19
19
|
`))}async function Co(e,t={}){if(t.includeNativeRichComponents)throw new Error("Native AIWG rich components require the complete full-v1 inventory; use core-v1 metadata preservation until full-v1 conversion is available");let n=Z(e);if(!n.valid)throw new Error(`Invalid AIWG Fortemi index export:
|
|
20
20
|
${n.errors.join(`
|
|
21
|
-
`)}`);if(e.schema_version!=="aiwg.fortemi.index.export.v2")throw new Error("Knowledge Shard conversion requires aiwg.fortemi.index.export.v2");let r=H(t.createdAt??e.generated_at,new Date().toISOString()),i=new Map(e.items.map(
|
|
22
|
-
`).filter(Boolean).map(d=>JSON.parse(d));if(r.length===0)throw new Error("Knowledge Shard contains no AIWG index notes");let i,s=[];for(let d of r){let l=d.metadata?.aiwg_fortemi_index;if(!l||typeof l!="object"||Array.isArray(l))throw new Error(`Knowledge Shard note ${d.id} has no AIWG index metadata`);let
|
|
21
|
+
`)}`);if(e.schema_version!=="aiwg.fortemi.index.export.v2")throw new Error("Knowledge Shard conversion requires aiwg.fortemi.index.export.v2");let r=H(t.createdAt??e.generated_at,new Date().toISOString()),i=new Map(e.items.map(c=>[c.id,xt("record",c.id)])),s=e.items.map(c=>{let p=ci(c);return {id:i.get(c.id),title:di(c),original_content:p,revised_content:p,metadata:li(e,c),collection_id:null,attachments:[],format:"markdown",source:"aiwg-index",starred:false,archived:false,tags:[...new Set(c.tags)].sort(),created_at:H(c.source.updated_at??c.updated_at,r),updated_at:H(c.updated_at,r),deleted_at:null}}),o=[];for(let c of e.items)for(let[p,h]of c.relationships.entries()){let w=i.get(h.target_id)??null;o.push({id:xt("relationship",`${c.id}\0${p}\0${h.type}\0${h.target_id}`),from_note_id:i.get(c.id),to_note_id:w,to_url:w?null:`aiwg://record/${encodeURIComponent(h.target_id)}`,kind:h.type,score:h.confidence??1,created_at:H(c.updated_at,r),metadata:{aiwg_fortemi_index:{source_record_id:c.id,target_record_id:h.target_id,relationship:h}}});}let a=new Map,d=["notes","tags"],l={notes:s.length,tags:[...new Set(s.flatMap(c=>c.tags))].length};a.set("notes.jsonl",St(s)),a.set("tags.json",W.encode(JSON.stringify([...new Set(s.flatMap(c=>c.tags))].sort().map(c=>({name:c,created_at:r}))))),((c,p,h,w=true)=>{h.length!==0&&(d.push(c),l[c]=h.length,a.set(p,w?St(h):W.encode(JSON.stringify(h))));})("links","links.jsonl",o);let f={};for(let[c,p]of a)f[c]=await re(p);let u={version:L,profile:"core-v1",producer:{name:"fortemi-core-aiwg-index",version:t.matricVersion??"fortemi-core"},format:ge,created_at:r,components:d,counts:{notes:0,collections:0,tags:0,templates:0,links:0,embedding_sets:0,embedding_set_members:0,embeddings:0,embedding_configs:0,...l},checksums:f,min_reader_version:L};a.set("manifest.json",W.encode(JSON.stringify(u,null,2)));let g=await bt(a);if(!g.valid)throw new Error(`Generated AIWG core-v1 shard failed canonical validation: ${g.errors.join("; ")}`);return lt(a)}function Io(e){let n=z(e).get("notes.jsonl"),r=(n?ai.decode(n):"").split(`
|
|
22
|
+
`).filter(Boolean).map(d=>JSON.parse(d));if(r.length===0)throw new Error("Knowledge Shard contains no AIWG index notes");let i,s=[];for(let d of r){let l=d.metadata?.aiwg_fortemi_index;if(!l||typeof l!="object"||Array.isArray(l))throw new Error(`Knowledge Shard note ${d.id} has no AIWG index metadata`);let m=l;i??=m.envelope,s.push(m.record);}let o={...i,items:s.sort((d,l)=>d.id.localeCompare(l.id))},a=Z(o);if(!a.valid)throw new Error(`Knowledge Shard contains invalid AIWG index metadata:
|
|
23
23
|
${a.errors.join(`
|
|
24
|
-
`)}`);return o}export{rr as AIWG_SCAN_REQUIRED_FIELDS,Nr as DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS,Ft as aiwgDetailHrefForId,Io as aiwgFortemiIndexFromKnowledgeShard,ae as aiwgFortemiIndexToCommunityGraph,Co as aiwgFortemiIndexToKnowledgeShard,pr as assertAiwgFortemiChunkManifest,yr as assertAiwgFortemiChunkPart,X as assertAiwgFortemiIndexExport,fe as assertAiwgStaticEmbeddingSet,So as buildAiwgChunkedIndex,xo as buildAiwgStaticEmbeddingSet,$o as createAiwgFetchChunkLoader,ko as createAiwgFetchDetailLoader,Ro as createAiwgIndexController,ii as createAiwgReviewDecisionExport,
|
|
24
|
+
`)}`);return o}export{rr as AIWG_SCAN_REQUIRED_FIELDS,Nr as DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS,Ft as aiwgDetailHrefForId,Io as aiwgFortemiIndexFromKnowledgeShard,ae as aiwgFortemiIndexToCommunityGraph,Co as aiwgFortemiIndexToKnowledgeShard,pr as assertAiwgFortemiChunkManifest,yr as assertAiwgFortemiChunkPart,X as assertAiwgFortemiIndexExport,fe as assertAiwgStaticEmbeddingSet,So as buildAiwgChunkedIndex,xo as buildAiwgStaticEmbeddingSet,$o as createAiwgFetchChunkLoader,ko as createAiwgFetchDetailLoader,Ro as createAiwgIndexController,ii as createAiwgReviewDecisionExport,wr as encodeAiwgDetailId,jt as filterAiwgRecordsByPrivacy,Ao as findAiwgStaticDuplicatePairs,Pt as getAiwgFortemiFacets,Lt as queryAiwgFortemiIndex,jo as queryAiwgHybridIndex,Dr as queryAiwgSemanticIndex,It as resolveAiwgFetchUrl,fr as validateAiwgFortemiChunkManifest,_r as validateAiwgFortemiChunkPart,Z as validateAiwgFortemiIndexExport,qr as validateAiwgStaticEmbeddingSet};//# sourceMappingURL=aiwg-index.js.map
|
|
25
25
|
//# sourceMappingURL=aiwg-index.js.map
|