@fortemi/core 2026.7.7 → 2026.7.9
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/README.md +2 -2
- package/dist/aiwg-index.d.ts +13 -3
- package/dist/aiwg-index.js +19 -18
- package/dist/aiwg-index.js.map +1 -1
- package/dist/index.d.ts +398 -92
- package/dist/index.js +10928 -2640
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@ Most browser note and knowledge apps choose between a thin IndexedDB wrapper, a
|
|
|
39
39
|
| Queryable knowledge | SQL-backed repositories for notes, links, tags, collections, SKOS concepts, jobs, and search |
|
|
40
40
|
| Retrieval quality | Full-text search, pgvector-backed semantic search, hybrid ranking, snippets, facets, and filters |
|
|
41
41
|
| AI-ready workflows | Optional embeddings, local LLM capability discovery, job provenance, and fallback routing |
|
|
42
|
-
| Portable archives | Knowledge Shard tar.gz import/export with set-scoped exports, chunked imports, checksums,
|
|
42
|
+
| Portable archives | Knowledge Shard tar.gz import/export with set-scoped exports, chunked imports, checksums, BLAKE3-addressed blob sidecars, and profile-scoped conformance |
|
|
43
43
|
| Agent integration | Manifest-backed tools and direct helper functions for bridge adapters and automation |
|
|
44
44
|
| UI freedom | A headless package you can use from React, another framework, a browser extension, or a custom host |
|
|
45
45
|
|
|
@@ -262,7 +262,7 @@ bytes.
|
|
|
262
262
|
| Event bus | Typed subscriptions for note, job, archive, and capability events |
|
|
263
263
|
| Capability system | Embeddings, local LLM, GPU detection, local-provider discovery, fallback routing |
|
|
264
264
|
| Job queue | Server-compatible background workflow for revisions, titles, embeddings, concepts, and links |
|
|
265
|
-
| Knowledge Shards | Tar.gz import/export with checksums,
|
|
265
|
+
| Knowledge Shards | Tar.gz import/export with checksums, BLAKE3-addressed blob sidecars, progress callbacks, yielding imports, set-scoped embedding exports, and profile-scoped conformance |
|
|
266
266
|
| Service-worker helpers | Route registration primitives for standalone browser integration |
|
|
267
267
|
|
|
268
268
|
## Search and Knowledge Model
|
package/dist/aiwg-index.d.ts
CHANGED
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A shard is a gzip-compressed tar archive (.shard) containing serialized
|
|
5
5
|
* knowledge data with a manifest for integrity verification.
|
|
6
|
+
*
|
|
7
|
+
* @implements @.aiwg/adrs/ADR-011-shard-server-conformance-and-version-negotiation.md
|
|
8
|
+
* @schema @packages/core/schemas/knowledge-shard.schema.receipt.json
|
|
9
|
+
* @created 2026-07-17
|
|
10
|
+
* @agent Codex
|
|
6
11
|
*/
|
|
7
12
|
|
|
8
13
|
interface ShardAttachmentReference {
|
|
@@ -14,6 +19,12 @@ interface ShardAttachmentReference {
|
|
|
14
19
|
}
|
|
15
20
|
interface ShardAttachmentProjection {
|
|
16
21
|
extracted_text: string | null;
|
|
22
|
+
/** Legacy unprofiled relationship timestamp; outside core-v1. */
|
|
23
|
+
created_at?: string;
|
|
24
|
+
/** Legacy unprofiled attachment tombstone; outside core-v1. */
|
|
25
|
+
deleted_at?: string | null;
|
|
26
|
+
extraction_status?: 'extracted' | 'pending' | 'failed' | 'blocked' | 'deferred';
|
|
27
|
+
reason?: null | 'extraction_pending' | 'extractor_failed' | 'quarantined' | 'large_binary' | 'unsupported_mime' | 'no_extracted_text';
|
|
17
28
|
attachment: ShardAttachmentReference;
|
|
18
29
|
}
|
|
19
30
|
/** @deprecated Legacy React shard field name. Server shards use `attachments`. */
|
|
@@ -199,9 +210,8 @@ interface AiwgKnowledgeShardOptions {
|
|
|
199
210
|
createdAt?: string;
|
|
200
211
|
matricVersion?: string;
|
|
201
212
|
/**
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
* shard remains importable by the current Fortemi server.
|
|
213
|
+
* Reserved for a future full-v1 converter. Passing true currently fails
|
|
214
|
+
* closed because a partial rich-component inventory is not a valid profile.
|
|
205
215
|
*/
|
|
206
216
|
includeNativeRichComponents?: boolean;
|
|
207
217
|
}
|
package/dist/aiwg-index.js
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
|
-
import {gzipSync,gunzipSync}from'fflate';import {v5}from'uuid';var J="1.0.0",oe="matric-shard";async function ae(e){let t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join("")}var C=512,Oe="ustar\x0000";function N(e,t,r,i){for(let n=0;n<Math.min(r.length,i);n++)e[t+n]=r.charCodeAt(n);}function L(e,t,r,i){let n=r.toString(8).padStart(i-1,"0");N(e,t,n,i-1);}function je(e){let t=0;for(let r=0;r<C;r++)t+=r>=148&&r<156?32:e[r];return t}function De(e,t){let r=new Uint8Array(C);N(r,0,e,100),L(r,100,420,8),L(r,108,0,8),L(r,116,0,8),L(r,124,t,12),L(r,136,Math.floor(Date.now()/1e3),12),r[156]=48,N(r,257,Oe,8);let n=je(r).toString(8).padStart(6,"0");return N(r,148,n,6),r[154]=0,r[155]=32,r}function Le(e){let t=[];for(let[s,o]of e){t.push(De(s,o.byteLength)),t.push(o);let a=o.byteLength%C;a>0&&t.push(new Uint8Array(C-a));}t.push(new Uint8Array(C*2));let r=0;for(let s of t)r+=s.byteLength;let i=new Uint8Array(r),n=0;for(let s of t)i.set(s,n),n+=s.byteLength;return i}function ce(e,t,r){let i=t,n=t+r;for(;i<n&&e[i]!==0;)i++;return String.fromCharCode(...e.slice(t,i))}function Te(e,t,r){let i=ce(e,t,r).trim();return i.length>0?parseInt(i,8):0}function Qe(e,t){for(let r=0;r<C;r++)if(e[t+r]!==0)return false;return true}function Ue(e){let t=new Map,r=0;for(;r+C<=e.byteLength&&!Qe(e,r);){let i=ce(e,r,100),n=Te(e,r+124,12),s=e[r+156];r+=C,(s===48||s===0)&&t.set(i,e.slice(r,r+n));let o=Math.ceil(n/C);r+=o*C;}return t}function de(e,t){let r=Le(e),i=ue;if(r.byteLength>i)throw new Error("Refusing to create archive: uncompressed size "+r.byteLength+" exceeds cap "+i+" bytes");return gzipSync(r)}var ue=256*1024*1024;function ge(e,t){let r=ue;if(e.byteLength<18)throw new Error("Invalid gzip archive: too short");let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(e.byteLength-4,true);if(n>r)throw new Error("Refusing to decompress archive: declared size "+n+" exceeds cap "+r+" bytes");let s=gunzipSync(e);if(s.byteLength>r)throw new Error("Refusing to decompress archive: decompressed size "+s.byteLength+" exceeds cap "+r+" bytes");return Ue(s)}var qe=["schema_version","id","type","title","text","facets","tags","concepts","privacy"];function Be(e,t){let r=e.privacy;return !!(!r||!j(r.classification)||typeof r.pii!="boolean"||r.classification==="private"&&!t?.includePrivate||r.pii&&!t?.includePii)}function we(e,t){return e.filter(r=>!Be(r,t))}var Ge=["schema_version","id","type","source","facets","tags","concepts","relationships","provenance","privacy","updated_at"],ie={title:4,tag:3,concept:2,text:1,facet:2,id:1,source:.25};function w(e){return typeof e=="string"&&e.length>0}function T(e,t,r){let i=e[t];i===void 0&&(i=Object.create(null),e[t]=i),i[r]=(i[r]??0)+1;}function E(e){return Number.isInteger(e)&&typeof e=="number"&&e>=0}function O(e){return Number.isInteger(e)&&typeof e=="number"&&e>0}function $e(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(r=>E(r)))}function y(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function q(e){return e===void 0||Array.isArray(e)&&e.every(t=>typeof t=="string")}function ye(e){return e==="aiwg.fortemi.index.export.v1"||e==="aiwg.fortemi.index.export.v2"}function be(e){return e==="aiwg.fortemi.index.record.v1"||e==="aiwg.fortemi.index.record.v2"}function ze(e,t,r){if(e.skos_concepts!==void 0)if(!Array.isArray(e.skos_concepts))r.push("items["+t+"].skos_concepts must be an array when present");else for(let[i,n]of e.skos_concepts.entries()){if(!y(n)){r.push("items["+t+"].skos_concepts["+i+"] must be an object");continue}w(n.id)||r.push("items["+t+"].skos_concepts["+i+"].id is required"),w(n.prefLabel)||r.push("items["+t+"].skos_concepts["+i+"].prefLabel is required"),q(n.altLabels)||r.push("items["+t+"].skos_concepts["+i+"].altLabels must be a string array"),n.metadata!==void 0&&!y(n.metadata)&&r.push("items["+t+"].skos_concepts["+i+"].metadata must be an object");}if(e.skos_relations!==void 0)if(!Array.isArray(e.skos_relations))r.push("items["+t+"].skos_relations must be an array when present");else for(let[i,n]of e.skos_relations.entries()){if(!y(n)){r.push("items["+t+"].skos_relations["+i+"] must be an object");continue}w(n.type)||r.push("items["+t+"].skos_relations["+i+"].type is required"),w(n.source_id)||r.push("items["+t+"].skos_relations["+i+"].source_id is required"),w(n.target_id)||r.push("items["+t+"].skos_relations["+i+"].target_id is required"),n.metadata!==void 0&&!y(n.metadata)&&r.push("items["+t+"].skos_relations["+i+"].metadata must be an object");}if(e.provenance_events!==void 0)if(!Array.isArray(e.provenance_events))r.push("items["+t+"].provenance_events must be an array when present");else for(let[i,n]of e.provenance_events.entries()){if(!y(n)){r.push("items["+t+"].provenance_events["+i+"] must be an object");continue}w(n.activity)||r.push("items["+t+"].provenance_events["+i+"].activity is required"),n.attributes!==void 0&&!y(n.attributes)&&r.push("items["+t+"].provenance_events["+i+"].attributes must be an object");}if(Array.isArray(e.relationships))for(let[i,n]of e.relationships.entries()){if(!y(n)){r.push("items["+t+"].relationships["+i+"] must be an object");continue}n.metadata!==void 0&&!y(n.metadata)&&r.push("items["+t+"].relationships["+i+"].metadata must be an object"),n.direction!==void 0&&n.direction!=="upstream"&&n.direction!=="downstream"&&n.direction!=="related"&&r.push("items["+t+"].relationships["+i+"].direction must be upstream, downstream, or related"),n.target_path!==void 0&&typeof n.target_path!="string"&&r.push("items["+t+"].relationships["+i+"].target_path must be a string");}if(e.search!==void 0&&(y(e.search)?(q(e.search.triggers)||r.push("items["+t+"].search.triggers must be a string array"),q(e.search.aliases)||r.push("items["+t+"].search.aliases must be a string array"),q(e.search.tags)||r.push("items["+t+"].search.tags must be a string array"),e.search.frontmatter!==void 0&&!y(e.search.frontmatter)&&r.push("items["+t+"].search.frontmatter must be an object")):r.push("items["+t+"].search must be an object")),e.chunks!==void 0)if(!Array.isArray(e.chunks))r.push("items["+t+"].chunks must be an array when present");else for(let[i,n]of e.chunks.entries()){if(!y(n)){r.push("items["+t+"].chunks["+i+"] must be an object");continue}n.metadata!==void 0&&!y(n.metadata)&&r.push("items["+t+"].chunks["+i+"].metadata must be an object");}if(e.embeddings!==void 0)if(!Array.isArray(e.embeddings))r.push("items["+t+"].embeddings must be an array when present");else for(let[i,n]of e.embeddings.entries()){if(!y(n)){r.push("items["+t+"].embeddings["+i+"] must be an object");continue}let s=n.embedding??n.vector;s!==void 0&&(!Array.isArray(s)||!s.every(o=>typeof o=="number"))&&r.push("items["+t+"].embeddings["+i+"].embedding/vector must be a number array"),n.metadata!==void 0&&!y(n.metadata)&&r.push("items["+t+"].embeddings["+i+"].metadata must be an object");}e.compatibility!==void 0&&!y(e.compatibility)&&r.push("items["+t+"].compatibility must be an object");}function j(e){return e==="private"||e==="sanitized"||e==="public"}function Ae(e){return e==="source"||e==="candidate"||e==="reviewed"||e==="rejected"}function We(e,t,r){if(Array.isArray(e.provenance))for(let[i,n]of e.provenance.entries()){let s="items["+t+"].provenance["+i+"]";if(!y(n)){r.push(s+" must be an object");continue}w(n.field)||r.push(s+".field is required"),w(n.source)||r.push(s+".source is required"),w(n.path)||r.push(s+".path is required"),Ae(n.confidence)||r.push(s+".confidence must be one of source, candidate, reviewed, rejected"),j(n.privacy)||r.push(s+".privacy must be one of private, sanitized, public");}}var Ve=["search","chunks","embeddings","skos_concepts","skos_relations","provenance_events","compatibility"],He=["origin","generated","checksum","updated_at"],Ke=["target_path","direction","metadata"];function Je(e,t,r){if(e.schema_version!=="aiwg.fortemi.index.record.v1")return;let i="items["+t+"]",n=e,s=" is a v2-only field and must be absent on a record.v1 record";for(let o of Ve)n[o]!==void 0&&r.push(i+"."+o+s);if(y(e.source)){let o=e.source;for(let a of He)o[a]!==void 0&&r.push(i+".source."+a+s);}if(y(e.privacy)&&e.privacy.locality!==void 0&&r.push(i+".privacy.locality"+s),Array.isArray(e.relationships))for(let[o,a]of e.relationships.entries()){if(!y(a))continue;let c=a;for(let g of Ke)c[g]!==void 0&&r.push(i+".relationships["+o+"]."+g+s);}}function z(e){let t=[],r=Object.create(null),i=y(e)?e:{};y(e)||t.push("index export must be an object"),ye(i?.schema_version)||t.push("schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2"),w(i?.generated_at)||t.push("generated_at is required"),w(i?.source?.repo)||t.push("source.repo is required"),w(i?.source?.privacy)?j(i?.source?.privacy)||t.push("source.privacy must be one of private, sanitized, public"):t.push("source.privacy is required"),Array.isArray(i?.items)||t.push("items must be an array"),i.compatibility!==void 0&&!y(i.compatibility)&&t.push("compatibility must be an object"),i?.schema_version==="aiwg.fortemi.index.export.v1"&&(y(i.source)&&i.source.graph!==void 0&&t.push("source.graph is a v2-only field and must be absent on an export.v1 export"),i.compatibility!==void 0&&t.push("compatibility is a v2-only field and must be absent on an export.v1 export"));let n=new Set,s="",o=Array.isArray(i.items)?i.items:[];for(let[a,c]of o.entries()){if(!y(c)){t.push("items["+a+"] must be an object");continue}for(let g of Ge)g in c||t.push("items["+a+"]."+g+" is required");be(c.schema_version)||t.push("items["+a+"].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2"),i.schema_version==="aiwg.fortemi.index.export.v1"&&c.schema_version==="aiwg.fortemi.index.record.v2"&&t.push("items["+a+"].schema_version must match aiwg.fortemi.index.export.v1"),w(c.id)||t.push("items["+a+"].id is required"),w(c.id)&&n.has(c.id)&&t.push("duplicate id: "+c.id),w(c.id)&&n.add(c.id),s&&w(c.id)&&s>c.id&&t.push("items must be sorted by id: "+s+" before "+c.id),w(c.id)&&(s=c.id),w(c.type)?r[c.type]=(r[c.type]??0)+1:t.push("items["+a+"].type must be a non-empty string"),w(c.source?.path)||t.push("items["+a+"].source.path is required"),w(c.source?.repo_relative_path)||t.push("items["+a+"].source.repo_relative_path is required"),w(c.source?.locator)||t.push("items["+a+"].source.locator is required"),typeof c.title!="string"&&typeof c.search?.title!="string"&&typeof c.search?.name!="string"&&t.push("items["+a+"].title or search.title/search.name is required"),typeof c.text!="string"&&typeof c.search?.body!="string"&&typeof c.search?.summary!="string"&&t.push("items["+a+"].text or search.body/search.summary is required"),Array.isArray(c.tags)||t.push("items["+a+"].tags must be an array"),Array.isArray(c.concepts)||t.push("items["+a+"].concepts must be an array"),Array.isArray(c.relationships)||t.push("items["+a+"].relationships must be an array"),(!Array.isArray(c.provenance)||c.provenance.length===0)&&t.push("items["+a+"].provenance must be a non-empty array"),ze(c,a,t),We(c,a,t),Je(c,a,t),!c.privacy||typeof c.privacy.pii!="boolean"||!w(c.privacy.classification)?t.push("items["+a+"].privacy requires classification and pii"):j(c.privacy.classification)||t.push("items["+a+"].privacy.classification must be one of private, sanitized, public");}return {valid:t.length===0,errors:t,counts:r}}function W(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 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:
|
|
2
3
|
`+t.errors.join(`
|
|
3
|
-
`));return e}function
|
|
4
|
+
`));return e}function fr(e){let t=[],n=y(e)?e:{};if(y(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"),g(n?.generated_at)||t.push("generated_at is required"),g(n?.source?.repo)||t.push("source.repo is required"),g(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&&!y(n.detail)?t.push("detail must be an object"):n.detail!==void 0&&(g(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(!y(o)){t.push("parts["+s+"] must be an object");continue}g(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:
|
|
4
5
|
`+t.errors.join(`
|
|
5
|
-
`));return e}function
|
|
6
|
-
`+
|
|
7
|
-
`));return e}var
|
|
8
|
-
`)??"",
|
|
9
|
-
`)}function
|
|
10
|
-
`)??"":""}function
|
|
11
|
-
`):[r
|
|
12
|
-
`)}function
|
|
13
|
-
`),
|
|
6
|
+
`));return e}function gr(e,t,n){let r="items["+t+"]";if(!e.privacy||!y(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(!y(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(!y(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"),g(o.id)||n.push("items["+s+"].id is required"),g(o.id)&&r.has(o.id)&&n.push("duplicate id: "+o.id),g(o.id)&&r.add(o.id),i&&g(o.id)&&i>o.id&&n.push("items must be sorted by id: "+i+" before "+o.id),g(o.id)&&(i=o.id),g(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=y(e)?e:{};if(y(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
|
+
`+r.errors.join(`
|
|
8
|
+
`));return e}var vt=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&&!vt.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(!vt.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 vr(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}",vr(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
|
+
`)??"",n=Et(e);return [t,n].filter(Boolean).join(`
|
|
10
|
+
`)}function Et(e){return "binary_sources"in e?e.binary_sources?.map(t=>t.extracted_text).filter(Boolean).join(`
|
|
11
|
+
`)??"":""}function wr(e,t){let n=P(e),r=V(e);return t==="title-summary"?[n,e.search?.summary??"",Et(e)].filter(Boolean).join(`
|
|
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,c=528734635,u=1541459225,m=new Uint32Array(64);for(let p=0;p<n.length;p+=64){for(let w=0;w<16;w++)m[w]=r.getUint32(p+w*4);for(let w=16;w<64;w++){let _=j(m[w-15],7)^j(m[w-15],18)^m[w-15]>>>3,C=j(m[w-2],17)^j(m[w-2],19)^m[w-2]>>>10;m[w]=m[w-16]+_+m[w-7]+C>>>0;}let f=i,b=s,h=o,v=a,$=d,k=l,x=c,A=u;for(let w=0;w<64;w++){let _=j($,6)^j($,11)^j($,25),C=$&k^~$&x,E=A+_+C+kr[w]+m[w]>>>0,ee=j(f,2)^j(f,13)^j(f,22),te=f&b^f&h^b&h,q=ee+te>>>0;A=x,x=k,k=$,$=v+E>>>0,v=h,h=b,b=f,f=E+q>>>0;}i=i+f>>>0,s=s+b>>>0,o=o+h>>>0,a=a+v>>>0,d=d+$>>>0,l=l+k>>>0,c=c+x>>>0,u=u+A>>>0;}return [i,s,o,a,d,l,c,u].map(p=>p.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)??wr(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=m=>String(m).padStart(4,"0"),d=m=>{if(!r)return m;let p={};for(let f of r)p[f]=m[f];return p},l=[],c=[];for(let m=0,p=0;m<o.length;m+=n,p+=1){let f=o.slice(m,m+n),b="part-"+a(p)+".json";l.push({href:b,part:{schema_version:"aiwg.fortemi.index.chunk.v1",manifest_schema_version:"aiwg.fortemi.index.chunk-manifest.v1",offset:m,items:f.map(d)}}),c.push({href:b,offset:m,count:f.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:c,...r?{projection:r,detail:{href:s,encoding:i}}:{}},parts:l,details:r?o.map(m=>({id:m.id,href:Ft({href:s,encoding:i},m.id),record:m})):[]}}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 wt(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(_=>g(_)),l=[...oe(e,["trigger","triggers","trigger_phrase","trigger_phrases"]),...e.search?.triggers??[]],c=[...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(_=>g(_)),u=[e.source?.path,e.source?.repo_relative_path,e.source?.locator].filter(_=>g(_)),m=P(e),p=[e.search?.summary,V(e)].filter(_=>g(_)).join(`
|
|
14
|
+
`),f=e.search?.type??e.type,b=[...e.search?.tags??[],...e.tags],h=i.length>1,v=h?n.relaxOverlap?1:Math.ceil(i.length/2):1,$=_=>h&&_>=v,k=_=>wt(r,{..._,score:0}),x=_=>{_>0&&wt(r,{field:"id",value:e.id,score:_,reason:"aiwg discovery score"});};for(let _ of d){if(J(t)===J(_))return k({field:"id",value:_,reason:"exact canonical name"}),x(1.001),r;if(Pr(t,_))return k({field:"id",value:_,reason:"near canonical name"}),x(.951),r}let A=0,w=(_,C,E,ee,te,q,Vt=0)=>{let ne=C.toLowerCase();if(ne.includes(s))A+=ee*q,ne===s&&(A+=Vt),k({field:_,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:_,value:C,reason:E}));}};for(let _ of Er(l))if(_===s||_===o)return k({field:"facet",value:_,reason:"trigger phrase"}),x(1.0008),r;for(let _ of l)w("facet",_,"trigger phrase",.25,.06,4);for(let _ of c)w("concept",_,"capability overlap",.2,.1,2);w("title",m,"title token overlap",.3,.08,3,.2);for(let _ of b)w("tag",_,"tag token overlap",.2,.05,2);p&&w("text",p,"body token overlap",.15,.04,1);for(let _ of u)w("source",_,"path overlap",.1,.03,1);return f.toLowerCase().includes(s)&&(A+=.1,k({field:"facet",value:f,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?"...":"",c=d<e.length?"...":"";return `${l}${e.slice(a,d).trim()}${c}`}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=y(e)?e:{};y(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"),g(n?.id)||t.push("id is required"),g(n?.model)||t.push("model is required"),I(n?.dimensions)||t.push("dimensions must be a positive integer"),g(n?.generated_at)||t.push("generated_at is required"),g(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(!y(s)){t.push("embeddings["+i+"] must be an object");continue}g(s.record_id)||t.push("embeddings["+i+"].record_id is required"),g(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:
|
|
14
15
|
`+t.errors.join(`
|
|
15
|
-
`));return e}function kt(e,t,r,i={}){if(ne(t),r.length!==t.dimensions)throw new Error("query embedding length must match embedding set dimensions");let n=new Map(e.items.map(a=>[a.id,a])),s=i.offset??0,o=i.limit??20;return t.embeddings.map(a=>{let c=n.get(a.record_id);return c?{item:c,embedding:a,score:Se(r,a.embedding)}:null}).filter(a=>a!==null&&a.score>=(i.minScore??-1)).sort((a,c)=>c.score-a.score||a.item.id.localeCompare(c.item.id)).slice(s,s+o)}function ar(e,t,r,i,n={}){let s={...n};delete s.limit,delete s.offset;let o=Re(e,r,{...s,rank:true}),a=kt(e,t,i,{limit:e.items.length}),c=n.lexicalWeight??.5,g=n.semanticWeight??.5,d=new Map(o.rankedItems?.map(x=>[x.item.id,x.rank])??[]),p=Math.max(1,...d.values()),u=new Map(a.flatMap(x=>x.embedding?[[x.item.id,x.embedding]]:[])),h=new Map(a.map(x=>[x.item.id,x.score])),A=new Set([...d.keys(),...h.keys()]),v=n.offset??0,_=n.limit??20;return [...A].map(x=>{let k=e.items.find(S=>S.id===x),R=u.get(x);return k?{item:k,...R?{embedding:R}:{},score:(d.get(x)??0)/p*c+(h.get(x)??0)*g}:null}).filter(x=>x!==null&&x.score>=(n.minScore??-1)).sort((x,k)=>k.score-x.score||x.item.id.localeCompare(k.item.id)).slice(v,v+_)}var Rt=5e3;function cr(e,t,r=.9,i){ne(t);let n=i?.maxEmbeddings??Rt;if(t.embeddings.length>n)throw new Error("Embedding set too large for duplicate scan: "+t.embeddings.length+" > "+n+" (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 c=a+1;c<t.embeddings.length;c+=1){let g=t.embeddings[a],d=t.embeddings[c],p=s.get(g.record_id),u=s.get(d.record_id);if(!p||!u)continue;let h=Se(g.embedding,d.embedding);h>=r&&o.push({left:p,right:u,score:h});}return o.sort((a,c)=>c.score-a.score||a.left.id.localeCompare(c.left.id))}function St(e){return `${e.offset}:${e.href}`}function It(e){return O(e)?e:3}function Ct(e){return O(e)?e:32}function Ft(e){return O(e)?e:5e3}function Et(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:{...ie,...t.weights}})}function Pt(e,t,r){e.matchCache.delete(t),e.matchCache.set(t,r);let i=0;for(let n of e.matchCache.values())i+=n.length;for(;i>e.maxCachedMatches&&e.matchCache.size>1;){let n=e.matchCache.keys().next().value;if(n===void 0||n===t)break;i-=e.matchCache.get(n)?.length??0,e.matchCache.delete(n);}}function Mt(e,t){return e.trim()===""&&!t.rank&&!t.snippets&&!t.includeMatches&&!t.types&&!t.facets&&!t.tags&&!t.concepts&&!t.privacy&&!t.relationshipTargetId}function Ot(e,t,r){let i=t+r;return e.parts.filter(n=>n.count>0&&n.offset<i&&n.offset+n.count>t)}async function te(e,t){let r=St(t),i=e.partCache.get(r);if(i)return e.partCache.delete(r),e.partCache.set(r,i),{part:i,fetched:false};let n=rt(await e.loader(t,e.manifest),t,e.manifest);for(e.partCache.set(r,n);e.partCache.size>e.maxCachedParts;){let s=e.partCache.keys().next().value;if(s===void 0)break;e.partCache.delete(s);}return {part:n,fetched:true}}async function Ie(e,t){let r=e.detailCache.get(t);if(r)return e.detailCache.delete(t),e.detailCache.set(t,r),r;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 i=await e.detailLoader(t,e.manifest),n=W({schema_version:"aiwg.fortemi.index.export.v1",generated_at:e.manifest.generated_at,source:e.manifest.source,items:[i]}).items[0];if(n.id!==t)throw new Error("Detail record id mismatch: expected "+t+", got "+n.id);for(e.detailCache.set(t,n);e.detailCache.size>e.maxCachedDetails;){let s=e.detailCache.keys().next().value;if(s===void 0)break;e.detailCache.delete(s);}return n}function jt(e){return e?.relationshipType??e?.type}function Dt(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 Lt(e,t={}){let r=jt(t);return !(r&&e.type!==r||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 Tt(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 Qt(e){return {id:e.id,type:e.type,title:D(e)}}function fe(e,t){t&&e.set(t.id,Qt(t));}function re(e,t={}){Tt(t);let r=new Map(e.map(a=>[a.id,a])),i=[];for(let a of e)for(let c of a.relationships??[]){let g=Dt(a.id,c);Lt(g,t)&&i.push(g);}let n=i.sort((a,c)=>a.source_id.localeCompare(c.source_id)||a.target_id.localeCompare(c.target_id)||a.type.localeCompare(c.type)),s=t.limit?n.slice(0,t.limit):n,o=new Map;for(let a of s)fe(o,r.get(a.source_id)),fe(o,r.get(a.target_id));return {nodes:[...o.values()].sort((a,c)=>a.id.localeCompare(c.id)),edges:s,complete:true}}function Ut(e,t={}){let r=t.direction??"both";return {...t,...r==="out"?{sourceId:e}:{},...r==="in"?{targetId:e}:{},...r==="both"?{endpointId:e}:{}}}function Nt(e,t,r={}){let i=r.direction??"both",n=t.edges.filter(o=>i==="out"?o.source_id===e:i==="in"?o.target_id===e:o.source_id===e||o.target_id===e),s=new Set;for(let o of n)s.add(o.source_id),s.add(o.target_id);return {...t,edges:n,nodes:t.nodes.filter(o=>s.has(o.id))}}async function Ce(e,t){let r=0,i=0,n=[];for(let s of e.manifest.parts){let o=await te(e,s);o.fetched&&(i+=1),r+=1,t?.({phase:"part",done:r,total:e.manifest.parts.length,href:s.href});for(let a of o.part.items)n.push(a.relationships?a:await Ie(e,a.id));}return {records:n,scannedParts:r,fetchedParts:i}}async function pe(e,t={}){let r=await Ce(e);return {...re(r.records,t),scannedParts:r.scannedParts,fetchedParts:r.fetchedParts}}async function qt(e,t="",r={}){let i=t.trim().toLowerCase(),n=0,s=0;if(Mt(t,r)){let g=r.offset??0,d=r.limit??e.manifest.total,p=Ot(e.manifest,g,d),u=[];for(let h of p){let A=await te(e,h);A.fetched&&(s+=1),n+=1,r.onProgress?.({phase:"part",done:n,total:p.length,href:h.href});let v=Math.max(0,g-h.offset),_=Math.min(A.part.items.length,g+d-h.offset);u.push(...A.part.items.slice(v,_));}return {items:u,total:e.manifest.total,facets:e.manifest.facets??{},manifestTotal:e.manifest.total,scannedParts:n,fetchedParts:s,complete:true}}let o=Et(i,r),a=e.matchCache.get(o);if(a)return e.matchCache.delete(o),e.matchCache.set(o,a),{...$(a,i,r),manifestTotal:e.manifest.total,scannedParts:0,fetchedParts:0,complete:true};let c=[];for(let g of e.manifest.parts){let d=await te(e,g);d.fetched&&(s+=1),n+=1,r.onProgress?.({phase:"part",done:n,total:e.manifest.parts.length,href:g.href}),c.push(...ee(d.part.items,i,r,g.offset)),r.onProgress?.({phase:"query",done:n,total:e.manifest.parts.length,href:g.href});}return Pt(e,o,c),{...$(c,i,r),manifestTotal:e.manifest.total,scannedParts:n,fetchedParts:s,complete:true}}function Bt(e,t,r=new Date().toISOString()){return {schema_version:"aiwg.fortemi.review-decisions.v1",generated_at:r,source_export_schema_version:e.schema_version,decisions:[...t].sort((i,n)=>i.item_id.localeCompare(n.item_id))}}function dr(e){let t=e??null,r=null,i=null,n=null,s=[],o=new Set,a=()=>({index:t,chunked:r?{manifest:r.manifest,cachedParts:r.partCache.size,maxCachedParts:r.maxCachedParts}:null,data:i,error:n,reviewDecisions:[...s]}),c=()=>{let d=a();for(let p of o)p(d);},g=()=>{if(!t)throw new Error("No AIWG index export loaded");return t};return {loadIndex(d){try{let p=W(d);return t=p,r=null,i=null,s=[],n=null,c(),p}catch(p){throw n=p instanceof Error?p:new Error(String(p)),c(),n}},loadChunkedIndex(d,p,u={}){try{let h=Ze(d);return t=null,r={manifest:h,loader:p,maxCachedParts:It(u.maxCachedParts),partCache:new Map,detailLoader:u.detailLoader,maxCachedDetails:Ct(u.maxCachedDetails),detailCache:new Map,maxCachedMatches:Ft(u.maxCachedMatches),matchCache:new Map},i=null,s=[],n=null,c(),h}catch(h){throw n=h instanceof Error?h:new Error(String(h)),c(),n}},getIndex(){return t},getChunkedManifest(){return r?.manifest??null},getSnapshot(){return a()},query(d="",p){let u=Re(g(),d,p);return i=u,n=null,c(),u},async queryChunked(d="",p){if(!r)throw new Error("No AIWG chunked index manifest loaded");try{let u=await qt(r,d,p);return i=u,n=null,c(),u}catch(u){throw n=u instanceof Error?u:new Error(String(u)),c(),n}},async getRecord(d){if(r)try{return await Ie(r,d)}catch(u){throw n=u instanceof Error?u:new Error(String(u)),c(),n}let p=g().items.find(u=>u.id===d);if(!p)throw new Error("Record not found: "+d);return p},async neighbors(d,p){try{let u=Ut(d,p),h=r?await pe(r,u):re(g().items,u);return Nt(d,h,p)}catch(u){throw n=u instanceof Error?u:new Error(String(u)),c(),n}},async relationshipQuery(d){try{return r?await pe(r,d):re(g().items,d)}catch(p){throw n=p instanceof Error?p:new Error(String(p)),c(),n}},async relationshipSet(d){let[p,u]=await Promise.all([this.neighbors(d.a,d),this.neighbors(d.b,d)]),h=new Set(p.nodes.map(_=>_.id).filter(_=>_!==d.a)),A=new Set(u.nodes.map(_=>_.id).filter(_=>_!==d.b)),v;return d.op==="intersection"?v=[...h].filter(_=>A.has(_)):d.op==="difference"?v=[...h].filter(_=>!A.has(_)):v=[...new Set([...h,...A])],{op:d.op,ids:v.sort()}},clearChunkCache(){r?.partCache.clear(),r?.detailCache.clear(),r?.matchCache.clear(),n=null,c();},toCommunityGraph(d){return Z(g(),d)},async toCommunityGraphChunked(d){if(!r)return Z(g(),d);let p=await Ce(r,d?.onProgress);return Z({generated_at:r.manifest.generated_at,source:r.manifest.source,items:p.records},d)},setReviewDecision(d){let p={...d,updated_at:new Date().toISOString()};return s=[...s.filter(u=>u.item_id!==p.item_id),p].sort((u,h)=>u.item_id.localeCompare(h.item_id)),n=null,c(),p},clearReviewDecision(d){s=s.filter(p=>p.item_id!==d),n=null,c();},createReviewDecisionExport(d){let p=t??(r?{schema_version:r.manifest.source_export_schema_version??"aiwg.fortemi.index.export.v1"}:null);if(!p)throw new Error("No AIWG index export or chunked manifest loaded");return Bt(p,s,d)},subscribe(d){return o.add(d),()=>{o.delete(d);}}}}function Z(e,t={}){let r=new Set(e.items.map(o=>o.id)),i=t.relationshipWeights??Object.create(null),n=new Map;for(let o of e.items)for(let a of o.relationships){if(!r.has(a.target_id)&&!t.includeDanglingRelationships)continue;let c=a.type,g=Object.prototype.hasOwnProperty.call(i,c)?i[c]:void 0,d=typeof g=="number"&&Number.isFinite(g)?g:1,p=`${o.id}\0${a.target_id}\0${c}`,u=n.get(p);u?u.weight+=d:n.set(p,{source:o.id,target:a.target_id,kind:c,weight:d});}let s=new Map;for(let o of e.items){let a=Gt(o,t);for(let c of a){let g=s.get(c)??[];g.push(o.id),s.set(c,g);}}return {nodes:e.items.map(o=>({id:o.id})),edges:Array.from(n.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 Gt(e,t){if(t.communityFacet){let r=e.facets[t.communityFacet]??[];if(r.length>0)return r.map(i=>`${t.communityFacet}:${i}`)}if(t.communityTagPrefix){let r=t.communityTagPrefix,i=e.tags.filter(n=>n.startsWith(r));if(i.length>0)return i}return e.concepts.length>0?e.concepts.map(r=>`concept:${r}`):[`type:${e.type}`]}var $t="7ab5d1f8-29d2-5e35-9e2f-3a45de171a9e",B=new TextEncoder,zt=new TextDecoder;function I(e,t){return v5(`${e}:${t}`,$t)}function M(e,t){return !e||Number.isNaN(Date.parse(e))?t:new Date(e).toISOString()}function Wt(e){return e.title??e.search?.title??e.search?.name??e.id}function Vt(e){if(e.text)return e.text;if(e.search?.body)return e.search.body;let t=e.chunks?.map(r=>r.text??r.body??r.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,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
17
|
|
|
17
|
-
`):e.search?.summary??""}function
|
|
18
|
-
`))}async function
|
|
19
|
-
${
|
|
20
|
-
`)}`);if(e.schema_version!=="aiwg.fortemi.index.export.v2")throw new Error("Knowledge Shard conversion requires aiwg.fortemi.index.export.v2");let
|
|
21
|
-
`).filter(Boolean).map(
|
|
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
|
+
`))}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
|
+
${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(f=>[f.id,xt("record",f.id)])),s=e.items.map(f=>{let b=ci(f);return {id:i.get(f.id),title:di(f),original_content:b,revised_content:b,metadata:li(e,f),collection_id:null,attachments:[],format:"markdown",source:"aiwg-index",starred:false,archived:false,tags:[...new Set(f.tags)].sort(),created_at:H(f.source.updated_at??f.updated_at,r),updated_at:H(f.updated_at,r),deleted_at:null}}),o=[];for(let f of e.items)for(let[b,h]of f.relationships.entries()){let v=i.get(h.target_id)??null;o.push({id:xt("relationship",`${f.id}\0${b}\0${h.type}\0${h.target_id}`),from_note_id:i.get(f.id),to_note_id:v,to_url:v?null:`aiwg://record/${encodeURIComponent(h.target_id)}`,kind:h.type,score:h.confidence??1,created_at:H(f.updated_at,r),metadata:{aiwg_fortemi_index:{source_record_id:f.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(f=>f.tags))].length};a.set("notes.jsonl",St(s)),a.set("tags.json",W.encode(JSON.stringify([...new Set(s.flatMap(f=>f.tags))].sort().map(f=>({name:f,created_at:r}))))),((f,b,h,v=true)=>{h.length!==0&&(d.push(f),l[f]=h.length,a.set(b,v?St(h):W.encode(JSON.stringify(h))));})("links","links.jsonl",o);let u={};for(let[f,b]of a)u[f]=await re(b);let m={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:u,min_reader_version:L};a.set("manifest.json",W.encode(JSON.stringify(m,null,2)));let p=await bt(a);if(!p.valid)throw new Error(`Generated AIWG core-v1 shard failed canonical validation: ${p.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 c=l;i??=c.envelope,s.push(c.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:
|
|
22
23
|
${a.errors.join(`
|
|
23
|
-
`)}`);return o}export{
|
|
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,vr 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
|
|
24
25
|
//# sourceMappingURL=aiwg-index.js.map
|