@fortemi/core 2026.7.8 → 2026.7.10

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shard/types.ts","../src/shard/checksum.ts","../src/shard/shard-tar.ts","../src/aiwg-index.ts"],"names":["CURRENT_SHARD_VERSION","SHARD_FORMAT","sha256Hex","data","buf","hashBuffer","hashArray","b","BLOCK_SIZE","USTAR_MAGIC","writeString","offset","str","len","i","writeOctal","value","computeHeaderChecksum","header","sum","createTarHeader","filename","size","csStr","encodeTar","files","blocks","remainder","totalLen","result","readString","end","limit","readOctal","isZeroBlock","decodeTar","tarData","name","typeflag","dataBlocks","packTarGz","opts","cap","DEFAULT_MAX_DECOMPRESSED_BYTES","gzipSync","unpackTarGz","declaredSize","gunzipSync","AIWG_SCAN_REQUIRED_FIELDS","isPrivacyExcluded","record","options","privacy","isPrivacyClassification","filterAiwgRecordsByPrivacy","records","REQUIRED_RECORD_FIELDS","DEFAULT_QUERY_WEIGHTS","hasString","pushFacet","counts","bucket","hasNonNegativeInteger","hasPositiveInteger","isFacetCounts","count","isPlainRecord","isOptionalStringArray","item","isSupportedIndexSchemaVersion","isSupportedRecordSchemaVersion","validateOptionalRichMetadata","index","errors","conceptIndex","concept","relationIndex","relation","eventIndex","event","relationshipIndex","relationship","chunkIndex","chunk","embeddingIndex","embedding","vector","entry","isProvenanceConfidence","validateProvenanceItems","provIndex","prov","at","V2_ONLY_RECORD_FIELDS","V2_ONLY_SOURCE_FIELDS","V2_ONLY_RELATIONSHIP_FIELDS","forbidV2FieldsOnV1Record","bag","v2msg","field","src","relIndex","rel","relBag","validateAiwgFortemiIndexExport","ids","previousId","items","assertAiwgFortemiIndexExport","validateAiwgFortemiChunkManifest","present","expectedOffset","parts","part","assertAiwgFortemiChunkManifest","validateProjectedRecordShape","validateProjectedRecords","sourceSchemaVersion","expectedRecordVersion","validateAiwgFortemiChunkPart","partRef","manifest","error","validation","assertAiwgFortemiChunkPart","ALLOWED_AIWG_FETCH_SCHEMES","tryParseUrl","resolveAiwgFetchUrl","href","baseUrl","absolute","base","resolved","createAiwgFetchChunkLoader","response","encodeAiwgDetailId","id","encoding","bytes","binary","byte","aiwgDetailHrefForId","detail","createAiwgFetchDetailLoader","relative","getAiwgFortemiFacets","tag","values","recordTitle","recordText","extractedText","binarySourceText","source","defaultEmbeddingInput","granularity","title","text","generatedAtString","SHA256_K","rotr","bits","bitLength","padded","view","h0","h1","h2","h3","h4","h5","h6","h7","w","s0","s1","a","c","d","e","f","g","h","ch","temp1","maj","temp2","computeAiwgIndexHash","buildAiwgStaticEmbeddingSet","embeddings","input","embeddingSet","assertAiwgStaticEmbeddingSet","recordSearchValues","search","buildAiwgChunkedIndex","partSize","projection","idEncoding","detailHref","pad","project","slim","partRefs","partIndex","slice","includesAll","actual","expected","actualSet","matchesFacetFilters","filters","queryMatches","q","matches","DISCOVERY_STOPWORDS","normalizeDiscoveryName","discoveryTokens","token","facetValues","names","addDiscoveryMatch","match","existing","damerauLevenshteinAtMostOne","left","right","firstDiff","diffCount","shorter","longer","shorterIndex","longerIndex","edits","nearDiscoveryNameMatch","query","queryParts","nameParts","target","lowerValues","discoveryMatches","tokens","lower","rawLower","idParts","triggers","capabilities","sourceValues","summary","type","tags","useMultiToken","minHits","overlapOK","hits","addInfo","addScore","score","scoreText","reason","exactScore","overlapScore","weight","exactBonus","normalized","trigger","capability","rankMatches","weights","total","clipSnippet","maxLength","normalizedLength","context","start","prefix","suffix","createSnippet","textMatch","titleMatch","firstMatch","createRankedEntries","ordinalBase","discoveryOptions","profile","ordinal","sortRankedEntries","entries","rank","createQueryResultFromRankedEntries","ranked","page","snippetLength","queryAiwgFortemiIndex","cosineSimilarity","dot","leftMag","rightMag","l","r","validateAiwgStaticEmbeddingSet","number","queryAiwgSemanticIndex","queryEmbedding","byId","queryAiwgHybridIndex","lexicalOptions","lexical","semantic","lexicalWeight","semanticWeight","lexicalScores","maxLexical","embeddingById","semanticScores","candidate","DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS","findAiwgStaticDuplicatePairs","threshold","maxEmbeddings","pairs","leftIndex","rightIndex","leftEmbedding","rightEmbedding","chunkPartCacheKey","clampMaxCachedParts","clampMaxCachedDetails","clampMaxCachedMatches","matchSetCacheKey","cacheMatchEntries","runtime","key","set","oldest","isDirectChunkBrowse","getPartsForRange","loadChunkPart","cached","parsed","getChunkRecord","found","raw","relationshipTypeFilter","edgeFromRelationship","sourceId","relationshipMatches","edge","assertRelationshipDirectionAnchor","nodeSummary","addNode","nodes","relationshipResultFromRecords","edges","sortedEdges","limitedEdges","neighborQueryOptions","direction","filterNeighborResult","node","recordsFromChunkedRuntime","onProgress","scannedParts","fetchedParts","loaded","relationshipResultFromChunkedRuntime","queryChunkedAiwgFortemiIndex","matchKey","createAiwgReviewDecisionExport","decisions","generatedAt","createAiwgIndexController","initialIndex","chunked","reviewDecisions","listeners","snapshot","notify","current","listener","requireIndex","err","loader","queryOptions","leftIds","rightIds","aiwgFortemiIndexToCommunityGraph","decision","itemId","relationshipWeights","edgeCounts","kind","configuredWeight","baseWeight","communities","communityIds","communityIdsFor","communityId","AIWG_SHARD_UUID_NAMESPACE","shardEncoder","shardDecoder","aiwgShardUuid","uuidv5","aiwgShardTimestamp","fallback","aiwgRecordTitle","aiwgRecordContent","chunks","aiwgShardMetadata","encodeJsonLines","aiwgFortemiIndexToKnowledgeShard","createdAt","noteIds","notes","links","position","targetNoteId","defaultScheme","concepts","conceptId","schemes","scheme","shardConcepts","noteSkosTags","skosRelations","provenanceEdges","recordConceptIds","relationType","provenance","components","note","addComponent","component","jsonLines","checksums","aiwgFortemiIndexFromKnowledgeShard","noteBytes","line","envelope","metadata","restored"],"mappings":"+DAUO,IAAMA,CAAAA,CAAwB,OAAA,CACxBC,EAAAA,CAAe,cAAA,CCF5B,eAAsBC,EAAAA,CAAUC,CAAAA,CAAmC,CACjE,IAAMC,CAAAA,CAAM,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,MAAM,IAAI,MAAM,CAAA,qBAAA,EAAwBT,CAAAA,CAAK,EAAE,CAAA,2BAAA,CAA6B,CAAA,CAE9E,IAAM7Z,CAAAA,CAAQsa,CAAAA,CACdD,IAAara,CAAAA,CAAM,QAAA,CACnB2F,EAAM,IAAA,CAAK3F,CAAAA,CAAM,MAA2B,EAC9C,CACA,IAAMua,CAAAA,CAAW,CACf,GAAGF,CAAAA,CACH,KAAA,CAAO1U,EAAM,IAAA,CAAK,CAACqH,EAAMC,CAAAA,GAAUD,CAAAA,CAAK,GAAG,aAAA,CAAcC,CAAAA,CAAM,EAAE,CAAC,CACpE,EACMtG,CAAAA,CAAanB,CAAAA,CAA+B+U,CAAQ,CAAA,CAC1D,GAAI,CAAC5T,CAAAA,CAAW,KAAA,CACd,MAAM,IAAI,KAAA,CAAM,CAAA;AAAA,EAA0DA,CAAAA,CAAW,OAAO,IAAA,CAAK;AAAA,CAAI,CAAC,CAAA,CAAE,CAAA,CAE1G,OAAO4T,CACT","file":"aiwg-index.js","sourcesContent":["/**\n * Shard format types — matches the fortemi server matric-shard specification.\n *\n * A shard is a gzip-compressed tar archive (.shard) containing serialized\n * knowledge data with a manifest for integrity verification.\n */\n\nimport type { BlobStore } from '../blob-store.js'\nimport type { ShardTrustStore } from './shard-signature.js'\n\nexport const CURRENT_SHARD_VERSION = '1.0.0'\nexport const SHARD_FORMAT = 'matric-shard'\n\nfunction parseVersion(value: string): number[] {\n return value.split('.').map((segment) => {\n const match = segment.match(/^\\d+/)\n return match ? Number.parseInt(match[0], 10) : 0\n })\n}\n\nexport function compareShardVersions(left: string, right: string): number {\n const leftParts = parseVersion(left)\n const rightParts = parseVersion(right)\n const length = Math.max(leftParts.length, rightParts.length)\n for (let index = 0; index < length; index += 1) {\n const leftValue = leftParts[index] ?? 0\n const rightValue = rightParts[index] ?? 0\n if (leftValue !== rightValue) return leftValue > rightValue ? 1 : -1\n }\n return 0\n}\n\n/** Components that can appear in a shard archive. */\nexport type ShardComponent =\n | 'notes'\n | 'collections'\n | 'tags'\n | 'templates'\n | 'links'\n | 'embedding_sets'\n | 'embedding_configs'\n | 'embedding_set_members'\n | 'embeddings'\n | 'skos_schemes'\n | 'skos_concepts'\n | 'skos_relations'\n | 'note_skos_tags'\n | 'provenance_edges'\n | 'community_assignments'\n | 'communities'\n | 'graph_edges'\n | 'graph_sources'\n\nexport interface ShardAttachmentReference {\n id: string\n path: string\n mime: string | null\n checksum: string\n bytes: number\n}\n\nexport interface ShardAttachmentProjection {\n extracted_text: string | null\n attachment: ShardAttachmentReference\n}\n\n/** @deprecated Legacy React shard field name. Server shards use `attachments`. */\nexport type ShardBinarySource = ShardAttachmentProjection\n\n/**\n * Reference to one cluster file of a component split across addressable files\n * (`notes/000.jsonl`, `notes/001.jsonl`, …). `offset` preserves deterministic\n * component order; readers discover each cluster's size from its contents.\n */\nexport interface ShardClusterRef {\n href: string // path within the shard, relative to manifest base\n offset: number // index of the first record in this cluster\n}\n\n/**\n * Optional clustered layout (additive — absent on monolithic shards). When a\n * component is present here, its records live in the listed cluster files instead\n * of (or in addition to) the single `<component>.jsonl`. Both `importShard` and\n * the in-place reader consume it; a monolithic shard omits `layout` entirely.\n */\nexport interface ShardLayout {\n clusters?: Partial<Record<ShardComponent, ShardClusterRef[]>>\n}\n\nexport interface ShardMigrationHistoryEntry {\n from_version: string\n to_version: string\n migrated_at: string\n migrated_by: string\n changes: string[]\n}\n\n/** Manifest included in every shard as manifest.json. */\nexport interface ShardManifest {\n version: string\n matric_version: string\n format: typeof SHARD_FORMAT\n created_at: string // ISO 8601\n components: ShardComponent[]\n counts: Partial<Record<ShardComponent | 'community_sets', number>>\n checksums: Record<string, string> // filename → sha256 hex\n min_reader_version: string\n migrated_from?: string | null\n migration_history?: ShardMigrationHistoryEntry[]\n /** Clustered component layout for partial fetch (issue #189). Absent → monolithic. */\n layout?: ShardLayout\n}\n\n/** Options for shard export. */\nexport interface ExportOptions {\n includeEmbeddings?: boolean\n /** Filter to specific collection (export only notes in this collection). */\n collectionId?: string\n /** Filter to notes with this tag (e.g. 'app:research' for app-scoped export). */\n tag?: string\n /** Export only these embedding sets and their member/vector rows. */\n embeddingSetIds?: string[]\n /** Preserve virtual selector materialization metadata and virtual member rows. */\n includeMaterializedSelectors?: boolean\n /**\n * When set to a positive integer, emit notes as clustered files\n * (`notes/000.jsonl`, …) of this many records each, and record the layout in\n * the manifest, so an in-place reader can fetch only the clusters it needs\n * (issue #189). Absent → a single monolithic `notes.jsonl` (unchanged).\n */\n clusterNotesSize?: number\n /**\n * Pack attachment bytes into a portable content-addressed `blobs/<hex>`\n * sidecar (Fortemi/fortemi#1046), producing a self-contained shard whose\n * attachments survive a round-trip (`getBlob()` returns real bytes on the\n * importing host). Requires {@link blobStore}. Absent/false → reference-only\n * (server default), which remains a valid shard.\n */\n includeBlobs?: boolean\n /**\n * Byte source for the sidecar. Required when `includeBlobs` is set; attachment\n * bytes are read by their `content_hash`. A blob the store cannot return is\n * skipped (its attachment stays reference-only) rather than failing export.\n */\n blobStore?: BlobStore\n}\n\n/** Conflict resolution strategy for shard import. */\nexport type ConflictStrategy = 'skip' | 'replace' | 'error'\n\n/** Options for shard import. */\nexport interface ImportOptions {\n conflictStrategy?: ConflictStrategy\n /** Rows processed between cooperative yields. Defaults to 250. */\n batchSize?: number\n /** Progress callback for long-running import phases. */\n onProgress?: (progress: ImportProgress) => void\n /**\n * Destination for hydrating attachment bytes from a portable `blobs/<hex>`\n * sidecar (Fortemi/fortemi#1046). When provided, sidecar entries whose bare\n * hex matches an imported attachment's `content_hash` are written to this\n * store after the import transaction commits, so `getBlob()` returns real\n * bytes. Absent → attachments import as reference-only metadata (unchanged).\n */\n blobStore?: BlobStore\n /**\n * Publisher-provenance policy for signed shards (#324, ADR-014):\n * - `require` — reject unsigned or bad-signature shards (default when a\n * `trustStore` is supplied);\n * - `prefer` — verify signed shards; import unsigned ones with a warning;\n * still reject a present-but-invalid signature;\n * - `trusted-local-only` — ignore signatures (own-export import).\n * When both `trustStore` and this are omitted, verification is skipped\n * entirely (checksum-only, unchanged behavior).\n */\n verifySignature?: 'require' | 'prefer' | 'trusted-local-only'\n /** Trust store resolving signer key_id → public key (required for `require`/`prefer`). */\n trustStore?: ShardTrustStore\n}\n\nexport type ImportProgressPhase =\n | 'unpack'\n | 'validate'\n | 'collections'\n | 'notes'\n | 'skos'\n | 'templates'\n | 'links'\n | 'provenance'\n | 'embedding_sets'\n | 'embedding_configs'\n | 'embeddings'\n | 'embedding_set_members'\n | 'graph'\n | 'communities'\n | 'index'\n\nexport interface ImportProgress {\n phase: ImportProgressPhase\n done: number\n total: number\n}\n\n/** Per-entity import counts. */\nexport interface ImportCounts {\n notes: number\n collections: number\n templates: number\n tags: number\n links: number\n embedding_sets: number\n embedding_configs: number\n embedding_set_members: number\n embeddings: number\n skos_schemes: number\n skos_concepts: number\n skos_relations: number\n note_skos_tags: number\n provenance_edges: number\n graph_sources: number\n graph_edges: number\n community_sets: number\n communities: number\n community_assignments: number\n}\n\n/** Result of a shard import operation. */\nexport interface ImportResult {\n success: boolean\n counts: ImportCounts\n skipped: Partial<ImportCounts>\n warnings: string[]\n errors: string[]\n duration_ms: number\n}\n\n// ── Shard-format entity shapes (server-compatible) ──────────────────────\n\n/** Note as serialized in the shard JSONL. */\nexport interface ShardNote {\n id: string\n title: string | null\n original_content: string\n revised_content: string | null\n metadata?: Record<string, unknown> | null\n collection_id?: string | null\n attachments?: ShardAttachmentProjection[]\n /** @deprecated Legacy React shard field name. Use `attachments`. */\n binary_sources?: ShardBinarySource[]\n format: string\n source: string\n starred: boolean\n archived: boolean\n tags: string[]\n created_at: string\n updated_at: string\n deleted_at: string | null\n}\n\n/** Collection as serialized in the shard JSON array. */\nexport interface ShardCollection {\n id: string\n name: string\n description: string | null\n parent_id: string | null\n created_at: string\n note_count?: number\n}\n\n/** Tag as serialized in the shard JSON array. */\nexport interface ShardTag {\n name: string\n created_at: string\n}\n\n/** Template as serialized in the shard JSON array. */\nexport interface ShardTemplate {\n id: string\n name: string\n description: string | null\n content: string\n format: string\n default_tags: string[]\n collection_id: string | null\n created_at: string\n updated_at: string\n}\n\n/** Link as serialized in the shard JSONL. */\nexport interface ShardLink {\n id: string\n from_note_id: string\n to_note_id: string | null\n /** Optional for legacy React shards exported before URL links existed. */\n to_url?: string | null\n kind: string\n score: number | null\n created_at: string\n /** Optional for legacy React shards exported before link metadata existed. */\n metadata?: Record<string, unknown> | null\n}\n\n/**\n * Embedding set as serialized in the shard JSON array.\n *\n * Fields beyond id/model/dimension are optional for backward compatibility:\n * legacy React shards omit them and import falls back to the same defaults\n * `embeddingSetFromShard` applies (name → model, is_system → false, …).\n */\nexport interface ShardEmbeddingSet {\n id: string\n name?: string\n slug?: string | null\n description?: string | null\n purpose?: string | null\n document_count?: number\n embedding_count?: number\n is_system?: boolean\n keywords?: string[]\n model: string\n dimension: number\n kind?: 'physical' | 'filter' | 'virtual'\n mode?: 'auto' | 'manual' | 'mixed' | null\n truncate_dimension?: number | null\n criteria?: Record<string, unknown> | null\n source?: Record<string, unknown> | null\n compatibility?: Record<string, unknown> | null\n materialization?: Record<string, unknown> | null\n freshness?: ShardArtifactFreshness | null\n created_at?: string\n updated_at?: string\n}\n\n/** Embedding set member as serialized in the shard JSONL. */\nexport interface ShardEmbeddingSetMember {\n embedding_set_id: string\n note_id: string\n /** Legacy React shard field; new exports use server membership metadata instead. */\n embedding_id?: string\n /** Optional for legacy React shards; import defaults to 'materialized'. */\n membership_type?: string\n /** Optional for legacy React shards; import falls back to the manifest timestamp. */\n added_at?: string\n /** Optional for legacy React shards; import defaults to NULL. */\n added_by?: string | null\n}\n\n/** Embedding config as serialized in the shard JSON array. */\nexport interface ShardEmbeddingConfig {\n id: string\n name: string\n description: string | null\n model: string\n dimension: number\n chunk_size: number\n chunk_overlap: number\n is_default: boolean\n}\n\n/**\n * Embedding as serialized in the shard JSONL.\n *\n * Server metadata fields (`chunk_index`, `text`, `model`) are optional for\n * backward compatibility: legacy React shards exported before migration 0016\n * carry only `id`, `note_id`, `embedding_set_id`, `vector`, `created_at`.\n * Import normalizes absent metadata to schema defaults (0, '', NULL).\n */\nexport interface ShardEmbedding {\n id: string\n note_id: string\n chunk_index?: number\n text?: string\n vector: number[]\n model?: string\n /** React shard extension used to preserve local embedding-set scoping. */\n embedding_set_id?: string\n /** React shard extension used to preserve local creation ordering. */\n created_at?: string\n}\n\n\n/** SKOS scheme as serialized in the shard JSON array. */\nexport interface ShardSkosScheme {\n id: string\n title: string\n description: string | null\n created_at: string\n updated_at: string\n}\n\n/** SKOS concept as serialized in the shard JSON array. */\nexport interface ShardSkosConcept {\n id: string\n scheme_id: string\n pref_label: string\n alt_labels: string[]\n definition: string | null\n created_at: string\n updated_at: string\n}\n\n/** SKOS concept relation as serialized in the shard JSONL. */\nexport interface ShardSkosRelation {\n id: string\n source_concept_id: string\n target_concept_id: string\n relation_type: 'broader' | 'narrower' | 'related'\n created_at: string\n}\n\n/** Note-to-SKOS-concept assignment as serialized in the shard JSONL. */\nexport interface ShardNoteSkosTag {\n id: string\n note_id: string\n concept_id: string\n created_at: string\n}\n\n/** Provenance edge as serialized in the shard JSONL. */\nexport interface ShardProvenanceEdge {\n id: string\n entity_type: string\n entity_id: string\n activity: string\n agent: string\n started_at: string\n ended_at: string | null\n attributes: Record<string, unknown> | null\n}\n\n\n// - Graph/community derived artifacts ---------------------------------------\n\nexport interface ShardArtifactFreshness {\n status: 'fresh' | 'stale' | 'unknown'\n checked_at?: string\n stale_reason?: string\n source_hashes?: {\n notes?: string\n links?: string\n embeddings?: string\n embedding_set_members?: string\n virtual_set_definition?: string\n parameters?: string\n }\n}\n\nexport interface ShardGraphSource {\n id: string\n name: string\n kind: 'link' | 'similarity' | 'search' | 'manual' | 'imported'\n source_table?: 'link' | 'embedding' | 'manual' | null\n embedding_set_id?: string | null\n virtual_set_id?: string | null\n model?: string | null\n dimension?: number | null\n truncate_dimension?: number | null\n metric?: 'cosine' | 'inner_product' | 'l2' | null\n algorithm?: string | null\n parameters?: Record<string, unknown>\n input_hash: string\n freshness: ShardArtifactFreshness\n created_at: string\n}\n\nexport interface ShardGraphEdge {\n graph_source_id: string\n from_note_id: string\n to_note_id: string\n weight: number\n kind: 'link' | 'similarity' | 'manual'\n rank?: number | null\n metadata?: Record<string, unknown>\n}\n\nexport interface ShardCommunitySet {\n id: string\n graph_source_id: string\n name: string\n source_type: 'precomputed' | 'dynamic-snapshot' | 'user-authored' | 'imported'\n algorithm?: string | null\n parameters?: Record<string, unknown>\n input_hash: string\n freshness: ShardArtifactFreshness\n communities: ShardCommunity[]\n created_at: string\n}\n\nexport interface ShardCommunity {\n id: string\n label?: string | null\n rank?: number | null\n size?: number | null\n confidence?: number | null\n representative_note_ids?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface ShardCommunityAssignment {\n community_set_id: string\n community_id: string\n note_id: string\n confidence?: number | null\n source_type: 'precomputed' | 'dynamic-snapshot' | 'user-authored' | 'imported'\n metadata?: Record<string, unknown>\n}\n","/**\n * SHA-256 checksum utilities for shard integrity verification.\n * Uses the Web Crypto API (browser-native, no extra dependencies).\n */\n\n/**\n * Compute SHA-256 hex digest of a Uint8Array.\n * Returns lowercase hex string (64 characters).\n */\nexport async function sha256Hex(data: Uint8Array): Promise<string> {\n const buf = new ArrayBuffer(data.byteLength)\n new Uint8Array(buf).set(data)\n const hashBuffer = await crypto.subtle.digest('SHA-256', buf)\n const hashArray = new Uint8Array(hashBuffer)\n return Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Validate checksums listed in a shard manifest against actual file contents.\n *\n * SECURITY (SEC7 — trust model): these checksums live *inside* the same archive\n * as the files they hash, so they detect **transport corruption**, not\n * **tampering**. An attacker who controls the archive controls both the file\n * bytes and the manifest hashes, so a passing result proves the archive is\n * internally consistent — nothing more. For provenance-sensitive imports, verify\n * integrity out-of-band: a signed manifest, or a caller-supplied expected digest\n * checked against the whole archive (see `prefetchShard`'s `expectedSha256`,\n * which is real integrity because the hash arrives on a separate channel).\n *\n * The signed-manifest path is now implemented: `verifyShardSignature`\n * (`shard-signature.ts`, #324/ADR-014) authenticates publisher provenance via\n * an Ed25519 signature over the manifest digest + blob-digest set, and\n * `importShard` runs it BEFORE any record or blob mutation. These in-archive\n * checksums remain the consistency layer *inside* that verified boundary.\n *\n * @returns Object with `valid` flag and list of failed filenames.\n */\nexport async function validateChecksums(\n checksums: Record<string, string>,\n files: Map<string, Uint8Array>,\n): Promise<{ valid: boolean; failures: string[] }> {\n const failures: string[] = []\n\n for (const [filename, expectedHash] of Object.entries(checksums)) {\n const fileData = files.get(filename)\n if (!fileData) {\n failures.push(filename)\n continue\n }\n const actualHash = await sha256Hex(fileData)\n if (actualHash !== expectedHash) {\n failures.push(filename)\n }\n }\n\n return { valid: failures.length === 0, failures }\n}\n","/**\n * Minimal tar + gzip packing/unpacking for shard archives.\n *\n * Uses fflate for gzip compression and implements a lightweight POSIX tar\n * encoder/decoder (512-byte block headers, ustar format).\n */\n\nimport { gzipSync, gunzipSync } from 'fflate'\n\n// ── Tar constants ────────────────────────────────────────────────────────\n\nconst BLOCK_SIZE = 512\nconst USTAR_MAGIC = 'ustar\\x0000'\n\n// ── Tar encoder ──────────────────────────────────────────────────────────\n\nfunction writeString(buf: Uint8Array, offset: number, str: string, len: number) {\n for (let i = 0; i < Math.min(str.length, len); i++) {\n buf[offset + i] = str.charCodeAt(i)\n }\n}\n\nfunction writeOctal(buf: Uint8Array, offset: number, value: number, len: number) {\n const str = value.toString(8).padStart(len - 1, '0')\n writeString(buf, offset, str, len - 1)\n}\n\nfunction computeHeaderChecksum(header: Uint8Array): number {\n // For checksum computation, treat the checksum field (offset 148, 8 bytes) as spaces\n let sum = 0\n for (let i = 0; i < BLOCK_SIZE; i++) {\n sum += i >= 148 && i < 156 ? 32 : header[i]\n }\n return sum\n}\n\nfunction createTarHeader(filename: string, size: number): Uint8Array {\n const header = new Uint8Array(BLOCK_SIZE)\n\n // name (0, 100)\n writeString(header, 0, filename, 100)\n // mode (100, 8) — 0644\n writeOctal(header, 100, 0o644, 8)\n // uid (108, 8)\n writeOctal(header, 108, 0, 8)\n // gid (116, 8)\n writeOctal(header, 116, 0, 8)\n // size (124, 12)\n writeOctal(header, 124, size, 12)\n // mtime (136, 12)\n writeOctal(header, 136, Math.floor(Date.now() / 1000), 12)\n // typeflag (156) — '0' for regular file\n header[156] = 48 // ASCII '0'\n // magic (257, 8) — ustar\\000\n writeString(header, 257, USTAR_MAGIC, 8)\n\n // compute and write checksum (148, 8)\n const checksum = computeHeaderChecksum(header)\n const csStr = checksum.toString(8).padStart(6, '0')\n writeString(header, 148, csStr, 6)\n header[154] = 0 // null terminator\n header[155] = 32 // space\n\n return header\n}\n\nfunction encodeTar(files: Map<string, Uint8Array>): Uint8Array {\n const blocks: Uint8Array[] = []\n\n for (const [filename, data] of files) {\n blocks.push(createTarHeader(filename, data.byteLength))\n blocks.push(data)\n\n // Pad to 512-byte boundary\n const remainder = data.byteLength % BLOCK_SIZE\n if (remainder > 0) {\n blocks.push(new Uint8Array(BLOCK_SIZE - remainder))\n }\n }\n\n // Two zero blocks mark end of archive\n blocks.push(new Uint8Array(BLOCK_SIZE * 2))\n\n // Concatenate\n let totalLen = 0\n for (const b of blocks) totalLen += b.byteLength\n const result = new Uint8Array(totalLen)\n let offset = 0\n for (const b of blocks) {\n result.set(b, offset)\n offset += b.byteLength\n }\n return result\n}\n\n// ── Tar decoder ──────────────────────────────────────────────────────────\n\nfunction readString(buf: Uint8Array, offset: number, len: number): string {\n let end = offset\n const limit = offset + len\n while (end < limit && buf[end] !== 0) end++\n return String.fromCharCode(...buf.slice(offset, end))\n}\n\nfunction readOctal(buf: Uint8Array, offset: number, len: number): number {\n const str = readString(buf, offset, len).trim()\n return str.length > 0 ? parseInt(str, 8) : 0\n}\n\nfunction isZeroBlock(buf: Uint8Array, offset: number): boolean {\n for (let i = 0; i < BLOCK_SIZE; i++) {\n if (buf[offset + i] !== 0) return false\n }\n return true\n}\n\nfunction decodeTar(tarData: Uint8Array): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>()\n let offset = 0\n\n while (offset + BLOCK_SIZE <= tarData.byteLength) {\n // Check for end-of-archive (two zero blocks)\n if (isZeroBlock(tarData, offset)) break\n\n const name = readString(tarData, offset, 100)\n const size = readOctal(tarData, offset + 124, 12)\n const typeflag = tarData[offset + 156]\n\n offset += BLOCK_SIZE // skip header\n\n // Only extract regular files (typeflag '0' or NUL)\n if (typeflag === 48 || typeflag === 0) {\n files.set(name, tarData.slice(offset, offset + size))\n }\n\n // Advance past data blocks (padded to 512-byte boundary)\n const dataBlocks = Math.ceil(size / BLOCK_SIZE)\n offset += dataBlocks * BLOCK_SIZE\n }\n\n return files\n}\n\n// ── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Pack files into a gzip-compressed tar archive.\n *\n * @param files Map of filename → file contents\n * @returns Compressed archive bytes (suitable for .shard file)\n */\nexport function packTarGz(\n files: Map<string, Uint8Array>,\n opts?: { maxDecompressedBytes?: number },\n): Uint8Array {\n const tarData = encodeTar(files)\n const cap = opts?.maxDecompressedBytes ?? DEFAULT_MAX_DECOMPRESSED_BYTES\n if (tarData.byteLength > cap) {\n throw new Error(\n 'Refusing to create archive: uncompressed size ' + tarData.byteLength +\n ' exceeds cap ' + cap + ' bytes',\n )\n }\n return gzipSync(tarData)\n}\n\n/**\n * Default cap on decompressed archive size (256 MiB). A gzip \"bomb\" is a tiny\n * compressed payload that expands to gigabytes; without a cap `gunzipSync`\n * allocates the whole thing before any checksum check runs (SEC3). Callers that\n * genuinely need larger archives can raise the cap explicitly.\n */\nexport const DEFAULT_MAX_DECOMPRESSED_BYTES = 256 * 1024 * 1024\n\n/**\n * Unpack a gzip-compressed tar archive.\n *\n * Before decompressing, the gzip ISIZE footer (declared uncompressed size) is\n * checked against `maxDecompressedBytes` and rejected if it exceeds the cap.\n * fflate independently verifies the actual output length against ISIZE, so a\n * lying footer fails during decompression — together this bounds the memory a\n * malicious archive can force us to allocate.\n *\n * @param data Compressed archive bytes\n * @param opts.maxDecompressedBytes Cap on decompressed size (default 256 MiB)\n * @returns Map of filename → file contents\n */\nexport function unpackTarGz(\n data: Uint8Array,\n opts?: { maxDecompressedBytes?: number },\n): Map<string, Uint8Array> {\n const cap = opts?.maxDecompressedBytes ?? DEFAULT_MAX_DECOMPRESSED_BYTES\n // gzip footer: last 4 bytes are ISIZE (uncompressed size mod 2^32, LE).\n if (data.byteLength < 18) {\n throw new Error('Invalid gzip archive: too short')\n }\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength)\n const declaredSize = view.getUint32(data.byteLength - 4, true)\n if (declaredSize > cap) {\n throw new Error(\n 'Refusing to decompress archive: declared size ' + declaredSize +\n ' exceeds cap ' + cap + ' bytes',\n )\n }\n const tarData = gunzipSync(data)\n if (tarData.byteLength > cap) {\n // Defense against a footer that wrapped past 2^32; fflate would normally\n // have thrown on the ISIZE mismatch, but guard the boundary explicitly.\n throw new Error(\n 'Refusing to decompress archive: decompressed size ' + tarData.byteLength +\n ' exceeds cap ' + cap + ' bytes',\n )\n }\n return decodeTar(tarData)\n}\n","import type { ShardAttachmentReference, ShardBinarySource } from './shard/types.js'\nimport {\n CURRENT_SHARD_VERSION,\n SHARD_FORMAT,\n type ShardComponent,\n type ShardLink,\n type ShardManifest,\n type ShardNote,\n type ShardNoteSkosTag,\n type ShardProvenanceEdge,\n type ShardSkosConcept,\n type ShardSkosRelation,\n type ShardSkosScheme,\n} from './shard/types.js'\nimport { sha256Hex as shardSha256Hex } from './shard/checksum.js'\nimport { packTarGz, unpackTarGz } from './shard/shard-tar.js'\nimport { v5 as uuidv5 } from 'uuid'\n\nexport type AiwgFortemiRecordType = string\n\nexport type AiwgFortemiRecordSchemaVersion = 'aiwg.fortemi.index.record.v1' | 'aiwg.fortemi.index.record.v2'\nexport type AiwgFortemiIndexExportSchemaVersion = 'aiwg.fortemi.index.export.v1' | 'aiwg.fortemi.index.export.v2'\nexport type AiwgPrivacyClassification = 'private' | 'sanitized' | 'public'\nexport type AiwgProvenanceConfidence = 'source' | 'candidate' | 'reviewed' | 'rejected'\nexport type AiwgReviewAction = 'accept' | 'reject' | 'defer'\nexport type AiwgFortemiRelationshipDirection = 'upstream' | 'downstream' | 'related'\n\nexport interface AiwgFortemiRecordSource {\n path: string\n repo_relative_path: string\n locator: string\n origin?: string\n generated?: boolean\n checksum?: string\n updated_at?: string\n}\n\nexport interface AiwgFortemiRelationship {\n type: string\n target_id: string\n source_path?: string\n target_path?: string\n direction?: AiwgFortemiRelationshipDirection\n label?: string\n confidence?: number\n privacy?: AiwgPrivacyClassification\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiProvenance {\n field: string\n source: string\n path: string\n confidence: AiwgProvenanceConfidence\n privacy: AiwgPrivacyClassification\n}\n\nexport type AiwgFortemiSkosRelationType = 'broader' | 'narrower' | 'related' | string\n\nexport interface AiwgFortemiSkosConcept {\n id: string\n prefLabel: string\n definition?: string\n scheme?: string\n notation?: string\n uri?: string\n altLabels?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiSkosRelation {\n type: AiwgFortemiSkosRelationType\n source_id: string\n target_id: string\n source_path?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiProvenanceEvent {\n id?: string\n activity: string\n agent?: string\n started_at?: string\n ended_at?: string\n source?: string\n path?: string\n confidence?: AiwgProvenanceConfidence\n privacy?: AiwgPrivacyClassification\n attributes?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiSearchProjection {\n title?: string\n name?: string\n summary?: string\n body?: string\n triggers?: string[]\n aliases?: string[]\n capability?: string\n tags?: string[]\n phase?: string\n type?: string\n frontmatter?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiChunk {\n id?: string\n text?: string\n body?: string\n summary?: string\n source_path?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiRecordEmbedding {\n id?: string\n embedding?: number[]\n vector?: number[]\n model?: string\n granularity?: string\n input_hash?: string\n source_path?: string\n metadata?: Record<string, unknown>\n}\n\nexport type AiwgFortemiAttachmentReference = ShardAttachmentReference\nexport type AiwgFortemiBinarySource = ShardBinarySource\n\nexport interface AiwgFortemiRecord {\n schema_version: AiwgFortemiRecordSchemaVersion\n id: string\n type: AiwgFortemiRecordType\n source: AiwgFortemiRecordSource\n title?: string\n text?: string\n facets: Record<string, string[]>\n tags: string[]\n concepts: string[]\n relationships: AiwgFortemiRelationship[]\n provenance: AiwgFortemiProvenance[]\n search?: AiwgFortemiSearchProjection\n chunks?: AiwgFortemiChunk[]\n binary_sources?: AiwgFortemiBinarySource[]\n embeddings?: AiwgFortemiRecordEmbedding[]\n compatibility?: Record<string, unknown>\n /** Optional rich SKOS metadata for static consumers that need labels/definitions without opening a shard. */\n skos_concepts?: AiwgFortemiSkosConcept[]\n /** Optional SKOS relationship edges among concepts referenced by this record. */\n skos_relations?: AiwgFortemiSkosRelation[]\n /** Optional W3C PROV-style activity chain for this record. */\n provenance_events?: AiwgFortemiProvenanceEvent[]\n privacy: {\n classification: AiwgPrivacyClassification\n pii: boolean\n locality?: string\n }\n updated_at: string\n}\n\nexport interface AiwgFortemiIndexExport {\n schema_version: AiwgFortemiIndexExportSchemaVersion\n generated_at: string\n source: {\n repo: string\n privacy: AiwgPrivacyClassification\n // v2-only upstream graph name; the vendored schema is authoritative.\n graph?: string\n }\n items: AiwgFortemiRecord[]\n // v2-only compatibility declaration defined by the vendored upstream schema.\n compatibility?: {\n previous_schema_version: 'aiwg.fortemi.index.export.v1'\n strategy: 'supported'\n }\n}\n\nexport interface AiwgFortemiChunkPartRef {\n href: string\n offset: number\n count: number\n}\n\n// Fields a scan part must retain for query/browse/rank/facet to work. The rest\n// (source, provenance, relationships, updated_at) are detail-only and may be\n// dropped from scan parts via `projection`, then resolved on demand by id.\nexport const AIWG_SCAN_REQUIRED_FIELDS: Array<keyof AiwgFortemiRecord> = [\n 'schema_version',\n 'id',\n 'type',\n 'title',\n 'text',\n 'facets',\n 'tags',\n 'concepts',\n 'privacy',\n]\n\n// A record as it appears in a scan part. With no manifest `projection`, this is a\n// full AiwgFortemiRecord. With a projection, detail-only fields are absent — read\n// them via the controller's getRecord(). Typed as the full record for ergonomics;\n// query/browse code guards the projectable fields.\nexport type AiwgFortemiProjectedRecord =\n Pick<AiwgFortemiRecord, 'schema_version' | 'id' | 'type' | 'title' | 'text' | 'facets' | 'tags' | 'concepts' | 'privacy'>\n & Partial<AiwgFortemiRecord>\n\n// How a record id is encoded into a detail filename/path segment.\n// - 'base64url': path-safe, single segment, no '%' — works on every static host,\n// including ids containing '/' (default for new builds; see #177).\n// - 'uri': encodeURIComponent — legacy. Breaks for ids containing '/' on static\n// servers that reject %2F (path-traversal protection → 404).\nexport type AiwgDetailIdEncoding = 'uri' | 'base64url'\n\n// How the controller resolves a full record by id when scan parts are projected.\nexport interface AiwgFortemiChunkDetailRef {\n // href template containing `{id}`, relative to the manifest base — e.g.\n // \"detail/{id}.json\". The `{id}` is encoded per `encoding` at substitution.\n href: string\n // id→segment encoding. Absent is treated as 'uri' for backward compatibility\n // with manifests built before #177; new builds default to 'base64url'.\n encoding?: AiwgDetailIdEncoding\n}\n\nexport interface AiwgFortemiChunkManifest {\n schema_version: 'aiwg.fortemi.index.chunk-manifest.v1'\n generated_at: string\n source: AiwgFortemiIndexExport['source']\n // The schema_version of the source index export this manifest was built from,\n // so chunked consumers (e.g. review-decision export) can report the true source\n // version rather than assuming v1 (#239 E8). Optional for backward compatibility.\n source_export_schema_version?: AiwgFortemiIndexExportSchemaVersion\n total: number\n part_size: number\n facets?: Record<string, Record<string, number>>\n // Field names present in scan-part items. Absent → scan parts carry whole records.\n // When set, must include AIWG_SCAN_REQUIRED_FIELDS.\n projection?: Array<keyof AiwgFortemiRecord>\n // Resolver for full records by id (used with `projection` to lazy-load detail).\n detail?: AiwgFortemiChunkDetailRef\n parts: AiwgFortemiChunkPartRef[]\n}\n\nexport interface AiwgFortemiChunkPart {\n schema_version: 'aiwg.fortemi.index.chunk.v1'\n manifest_schema_version: 'aiwg.fortemi.index.chunk-manifest.v1'\n offset: number\n items: AiwgFortemiRecord[]\n}\n\nexport interface AiwgIndexValidationResult {\n valid: boolean\n errors: string[]\n counts: Partial<Record<string, number>>\n}\n\nexport interface AiwgKnowledgeShardOptions {\n createdAt?: string\n matricVersion?: string\n /**\n * Include React-native SKOS and provenance component files. The default\n * portable profile keeps those projections in lossless note metadata so the\n * shard remains importable by the current Fortemi server.\n */\n includeNativeRichComponents?: boolean\n}\n\nexport interface AiwgChunkedIndexValidationResult {\n valid: boolean\n errors: string[]\n}\n\nexport interface AiwgIndexQueryOptions {\n types?: AiwgFortemiRecordType[]\n facets?: Record<string, string[]>\n tags?: string[]\n concepts?: string[]\n privacy?: AiwgPrivacyClassification[]\n relationshipTargetId?: string\n limit?: number\n offset?: number\n rank?: boolean\n snippets?: boolean\n snippetLength?: number\n weights?: Partial<AiwgIndexQueryWeights>\n includeMatches?: boolean\n searchProfile?: 'default' | 'aiwg-discovery'\n}\n\nexport interface AiwgIndexQueryWeights {\n title: number\n text: number\n tag: number\n concept: number\n facet: number\n id: number\n source: number\n}\n\nexport interface AiwgIndexQueryMatch {\n field: 'title' | 'text' | 'tag' | 'concept' | 'facet' | 'id' | 'source'\n value: string\n score?: number\n reason?: string\n}\n\nexport interface AiwgIndexQueryRankedItem {\n item: AiwgFortemiRecord\n rank: number\n snippet?: string\n matches?: AiwgIndexQueryMatch[]\n}\n\nexport interface AiwgIndexQueryResult {\n items: AiwgFortemiRecord[]\n total: number\n facets: Record<string, Record<string, number>>\n rankedItems?: AiwgIndexQueryRankedItem[]\n}\n\nexport type AiwgChunkedIndexLoader = (\n part: AiwgFortemiChunkPartRef,\n manifest: AiwgFortemiChunkManifest,\n) => Promise<unknown>\n\n// Resolves a full record by id (used with projected scan parts). Returns the\n// parsed record JSON; validated by the controller before use.\nexport type AiwgChunkedIndexDetailLoader = (\n id: string,\n manifest: AiwgFortemiChunkManifest,\n) => Promise<unknown>\n\nexport interface AiwgChunkedIndexLoadOptions {\n maxCachedParts?: number\n // Required to resolve detail for projected indexes via getRecord(); ignored otherwise.\n detailLoader?: AiwgChunkedIndexDetailLoader\n maxCachedDetails?: number\n // Bounds the filtered/ranked match-set cache used to page a query without\n // re-scanning every part. Counts total cached entries across all queries\n // (LRU-evicted). Defaults to 5000. The cache is keyed on query + filters +\n // weights, so paging the same query (varying only offset/limit/sort/snippets)\n // reuses the scan; see queryChunked.\n maxCachedMatches?: number\n}\n\nexport type AiwgChunkedIndexProgressPhase = 'part' | 'query'\n\nexport interface AiwgChunkedIndexProgress {\n phase: AiwgChunkedIndexProgressPhase\n done: number\n total: number\n href?: string\n}\n\nexport interface AiwgChunkedIndexQueryOptions extends AiwgIndexQueryOptions {\n onProgress?: (progress: AiwgChunkedIndexProgress) => void\n}\n\nexport interface AiwgChunkedIndexQueryResult extends AiwgIndexQueryResult {\n manifestTotal: number\n scannedParts: number\n fetchedParts: number\n complete: boolean\n}\n\nexport interface AiwgReviewDecision {\n item_id: string\n action: AiwgReviewAction\n reason?: string\n updated_at: string\n}\n\nexport interface AiwgReviewDecisionExport {\n schema_version: 'aiwg.fortemi.review-decisions.v1'\n generated_at: string\n source_export_schema_version: AiwgFortemiIndexExportSchemaVersion\n decisions: AiwgReviewDecision[]\n}\n\nexport interface AiwgIndexGraphOptions {\n communityFacet?: string\n communityTagPrefix?: string\n relationshipWeights?: Record<string, number>\n includeDanglingRelationships?: boolean\n}\n\nexport type AiwgRelationshipDirection = 'in' | 'out' | 'both'\nexport type AiwgRelationshipSetOperation = 'intersection' | 'union' | 'difference'\n\nexport interface AiwgRelationshipTraversalOptions {\n direction?: AiwgRelationshipDirection\n relationshipType?: string\n relationshipDirection?: AiwgFortemiRelationshipDirection\n limit?: number\n}\n\nexport interface AiwgRelationshipQueryOptions extends AiwgRelationshipTraversalOptions {\n sourceId?: string\n targetId?: string\n endpointId?: string\n type?: string\n}\n\nexport interface AiwgRelationshipEdgeSummary {\n source_id: string\n target_id: string\n type: string\n source_path?: string\n target_path?: string\n direction?: AiwgFortemiRelationshipDirection\n}\n\nexport interface AiwgRelationshipNodeSummary {\n id: string\n type: AiwgFortemiRecordType\n title: string\n}\n\nexport interface AiwgRelationshipTraversalResult {\n nodes: AiwgRelationshipNodeSummary[]\n edges: AiwgRelationshipEdgeSummary[]\n complete: boolean\n scannedParts?: number\n fetchedParts?: number\n}\n\nexport interface AiwgRelationshipSetOptions extends AiwgRelationshipTraversalOptions {\n op: AiwgRelationshipSetOperation\n a: string\n b: string\n}\n\nexport interface AiwgRelationshipSetResult {\n ids: string[]\n op: AiwgRelationshipSetOperation\n}\n\nexport interface AiwgStaticEmbeddingRecord {\n record_id: string\n embedding: number[]\n embedding_id?: string\n granularity?: string\n input_hash: string\n source_path?: string\n}\n\nexport interface AiwgStaticEmbeddingSet {\n schema_version: 'aiwg.fortemi.embedding.set.v1'\n id: string\n model: string\n dimensions: number\n generated_at: string\n granularity: 'title-summary' | 'body' | 'chunked-body' | string\n metric?: 'cosine' | 'dot' | 'euclidean'\n input_hash_algorithm?: string\n embeddings: AiwgStaticEmbeddingRecord[]\n}\n\nexport interface AiwgHeadlessEmbeddingBackend {\n model: string\n dimensions: number\n embed(input: string, record: AiwgFortemiRecord): number[] | Promise<number[]>\n}\n\n// Privacy filtering for generated index/embedding artifacts (SEC6). Generation\n// is default-safe: records classified `private`, or flagged `pii`, are excluded\n// unless the caller explicitly opts them in. This keeps the query-time privacy\n// gate from being the *only* enforcement point — a leaked embedding set or scan\n// part can no longer carry private/PII-derived vectors by default.\nexport interface AiwgPrivacyFilterOptions {\n /** Include records classified `private` (default false). */\n includePrivate?: boolean\n /** Include records flagged `pii` (default false). */\n includePii?: boolean\n}\n\nfunction isPrivacyExcluded(record: AiwgFortemiRecord, options?: AiwgPrivacyFilterOptions): boolean {\n const privacy = record.privacy\n if (!privacy || !isPrivacyClassification(privacy.classification) || typeof privacy.pii !== 'boolean') return true\n if (privacy.classification === 'private' && !options?.includePrivate) return true\n if (privacy.pii && !options?.includePii) return true\n return false\n}\n\n/** Drop `private`/`pii` records unless explicitly opted in (SEC6, default-safe). */\nexport function filterAiwgRecordsByPrivacy(\n records: AiwgFortemiRecord[],\n options?: AiwgPrivacyFilterOptions,\n): AiwgFortemiRecord[] {\n return records.filter((record) => !isPrivacyExcluded(record, options))\n}\n\nexport interface BuildAiwgStaticEmbeddingSetOptions {\n id: string\n backend: AiwgHeadlessEmbeddingBackend\n records?: AiwgFortemiRecord[]\n generatedAt?: string | Date\n granularity?: AiwgStaticEmbeddingSet['granularity']\n metric?: AiwgStaticEmbeddingSet['metric']\n textForRecord?: (record: AiwgFortemiRecord) => string\n /** Privacy filtering (SEC6). Default-safe: excludes `private`/`pii` records. */\n privacy?: AiwgPrivacyFilterOptions\n}\n\nexport interface AiwgStaticSemanticQueryOptions {\n limit?: number\n offset?: number\n minScore?: number\n}\n\nexport interface AiwgStaticSemanticResult {\n item: AiwgFortemiRecord\n score: number\n embedding?: AiwgStaticEmbeddingRecord\n}\n\nexport interface AiwgStaticHybridQueryOptions extends AiwgStaticSemanticQueryOptions, AiwgIndexQueryOptions {\n lexicalWeight?: number\n semanticWeight?: number\n}\n\nexport interface AiwgStaticDuplicatePair {\n left: AiwgFortemiRecord\n right: AiwgFortemiRecord\n score: number\n}\n\nexport interface AiwgReviewInput {\n item_id: string\n action: AiwgReviewAction\n reason?: string\n}\n\nexport interface AiwgIndexControllerSnapshot {\n index: AiwgFortemiIndexExport | null\n chunked: {\n manifest: AiwgFortemiChunkManifest\n cachedParts: number\n maxCachedParts: number\n } | null\n data: AiwgIndexQueryResult | null\n error: Error | null\n reviewDecisions: AiwgReviewDecision[]\n}\n\nexport type AiwgIndexControllerListener = (snapshot: AiwgIndexControllerSnapshot) => void\n\nexport interface AiwgIndexController {\n loadIndex(value: unknown): AiwgFortemiIndexExport\n loadChunkedIndex(\n manifest: unknown,\n loader: AiwgChunkedIndexLoader,\n options?: AiwgChunkedIndexLoadOptions,\n ): AiwgFortemiChunkManifest\n getIndex(): AiwgFortemiIndexExport | null\n getChunkedManifest(): AiwgFortemiChunkManifest | null\n getSnapshot(): AiwgIndexControllerSnapshot\n query(query?: string, options?: AiwgIndexQueryOptions): AiwgIndexQueryResult\n queryChunked(query?: string, options?: AiwgChunkedIndexQueryOptions): Promise<AiwgChunkedIndexQueryResult>\n // Resolve a full record by id. For a projected chunked index, fetches detail via\n // the detailLoader (bounded cache); for a whole-record index/parts, returns the\n // record from loaded data. Rejects if detail is unavailable.\n getRecord(id: string): Promise<AiwgFortemiRecord>\n neighbors(id: string, options?: AiwgRelationshipTraversalOptions): Promise<AiwgRelationshipTraversalResult>\n relationshipQuery(options?: AiwgRelationshipQueryOptions): Promise<AiwgRelationshipTraversalResult>\n relationshipSet(options: AiwgRelationshipSetOptions): Promise<AiwgRelationshipSetResult>\n clearChunkCache(): void\n toCommunityGraph(options?: AiwgIndexGraphOptions): ReturnType<typeof aiwgFortemiIndexToCommunityGraph>\n toCommunityGraphChunked(options?: AiwgIndexGraphOptions & { onProgress?: (progress: AiwgChunkedIndexProgress) => void }): Promise<ReturnType<typeof aiwgFortemiIndexToCommunityGraph>>\n setReviewDecision(input: AiwgReviewInput): AiwgReviewDecision\n clearReviewDecision(itemId: string): void\n createReviewDecisionExport(generatedAt?: string): AiwgReviewDecisionExport\n subscribe(listener: AiwgIndexControllerListener): () => void\n}\n\nconst REQUIRED_RECORD_FIELDS: Array<keyof AiwgFortemiRecord> = [\n 'schema_version',\n 'id',\n 'type',\n 'source',\n 'facets',\n 'tags',\n 'concepts',\n 'relationships',\n 'provenance',\n 'privacy',\n 'updated_at',\n]\n\nconst DEFAULT_QUERY_WEIGHTS: AiwgIndexQueryWeights = {\n title: 4,\n tag: 3,\n concept: 2,\n text: 1,\n facet: 2,\n id: 1,\n source: 0.25,\n}\n\nfunction hasString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0\n}\n\nfunction pushFacet(counts: Record<string, Record<string, number>>, name: string, value: string) {\n // `name`/`value` come from untrusted index records (item.facets). Using a\n // prototype-bearing accumulator would let a key such as `__proto__` (or any\n // inherited name like `toString`) read through the prototype chain and mutate\n // shared built-ins. Null-prototype buckets make every access own-property\n // only, so exotic keys are counted as plain data. See SEC1 / #236.\n let bucket = counts[name]\n if (bucket === undefined) {\n bucket = Object.create(null) as Record<string, number>\n counts[name] = bucket\n }\n bucket[value] = (bucket[value] ?? 0) + 1\n}\n\nfunction hasNonNegativeInteger(value: unknown): value is number {\n return Number.isInteger(value) && typeof value === 'number' && value >= 0\n}\n\nfunction hasPositiveInteger(value: unknown): value is number {\n return Number.isInteger(value) && typeof value === 'number' && value > 0\n}\n\nfunction isFacetCounts(value: unknown): value is Record<string, Record<string, number>> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n return Object.values(value).every((counts) => (\n !!counts\n && typeof counts === 'object'\n && !Array.isArray(counts)\n && Object.values(counts).every((count) => hasNonNegativeInteger(count))\n ))\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isOptionalStringArray(value: unknown): boolean {\n return value === undefined || (Array.isArray(value) && value.every((item) => typeof item === 'string'))\n}\n\nfunction isSupportedIndexSchemaVersion(value: unknown): value is AiwgFortemiIndexExportSchemaVersion {\n return value === 'aiwg.fortemi.index.export.v1' || value === 'aiwg.fortemi.index.export.v2'\n}\n\nfunction isSupportedRecordSchemaVersion(value: unknown): value is AiwgFortemiRecordSchemaVersion {\n return value === 'aiwg.fortemi.index.record.v1' || value === 'aiwg.fortemi.index.record.v2'\n}\n\nfunction validateOptionalRichMetadata(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n if (item.skos_concepts !== undefined) {\n if (!Array.isArray(item.skos_concepts)) {\n errors.push('items[' + index + '].skos_concepts must be an array when present')\n } else {\n for (const [conceptIndex, concept] of item.skos_concepts.entries()) {\n if (!isPlainRecord(concept)) {\n errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '] must be an object')\n continue\n }\n if (!hasString(concept.id)) errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].id is required')\n if (!hasString(concept.prefLabel)) errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].prefLabel is required')\n if (!isOptionalStringArray(concept.altLabels)) errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].altLabels must be a string array')\n if (concept.metadata !== undefined && !isPlainRecord(concept.metadata)) {\n errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.skos_relations !== undefined) {\n if (!Array.isArray(item.skos_relations)) {\n errors.push('items[' + index + '].skos_relations must be an array when present')\n } else {\n for (const [relationIndex, relation] of item.skos_relations.entries()) {\n if (!isPlainRecord(relation)) {\n errors.push('items[' + index + '].skos_relations[' + relationIndex + '] must be an object')\n continue\n }\n if (!hasString(relation.type)) errors.push('items[' + index + '].skos_relations[' + relationIndex + '].type is required')\n if (!hasString(relation.source_id)) errors.push('items[' + index + '].skos_relations[' + relationIndex + '].source_id is required')\n if (!hasString(relation.target_id)) errors.push('items[' + index + '].skos_relations[' + relationIndex + '].target_id is required')\n if (relation.metadata !== undefined && !isPlainRecord(relation.metadata)) {\n errors.push('items[' + index + '].skos_relations[' + relationIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.provenance_events !== undefined) {\n if (!Array.isArray(item.provenance_events)) {\n errors.push('items[' + index + '].provenance_events must be an array when present')\n } else {\n for (const [eventIndex, event] of item.provenance_events.entries()) {\n if (!isPlainRecord(event)) {\n errors.push('items[' + index + '].provenance_events[' + eventIndex + '] must be an object')\n continue\n }\n if (!hasString(event.activity)) errors.push('items[' + index + '].provenance_events[' + eventIndex + '].activity is required')\n if (event.attributes !== undefined && !isPlainRecord(event.attributes)) {\n errors.push('items[' + index + '].provenance_events[' + eventIndex + '].attributes must be an object')\n }\n }\n }\n }\n if (Array.isArray(item.relationships)) {\n for (const [relationshipIndex, relationship] of item.relationships.entries()) {\n if (!isPlainRecord(relationship)) {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '] must be an object')\n continue\n }\n if (relationship.metadata !== undefined && !isPlainRecord(relationship.metadata)) {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '].metadata must be an object')\n }\n if (\n relationship.direction !== undefined &&\n relationship.direction !== 'upstream' &&\n relationship.direction !== 'downstream' &&\n relationship.direction !== 'related'\n ) {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '].direction must be upstream, downstream, or related')\n }\n if (relationship.target_path !== undefined && typeof relationship.target_path !== 'string') {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '].target_path must be a string')\n }\n }\n }\n if (item.search !== undefined) {\n if (!isPlainRecord(item.search)) {\n errors.push('items[' + index + '].search must be an object')\n } else {\n if (!isOptionalStringArray(item.search.triggers)) errors.push('items[' + index + '].search.triggers must be a string array')\n if (!isOptionalStringArray(item.search.aliases)) errors.push('items[' + index + '].search.aliases must be a string array')\n if (!isOptionalStringArray(item.search.tags)) errors.push('items[' + index + '].search.tags must be a string array')\n if (item.search.frontmatter !== undefined && !isPlainRecord(item.search.frontmatter)) {\n errors.push('items[' + index + '].search.frontmatter must be an object')\n }\n }\n }\n if (item.chunks !== undefined) {\n if (!Array.isArray(item.chunks)) {\n errors.push('items[' + index + '].chunks must be an array when present')\n } else {\n for (const [chunkIndex, chunk] of item.chunks.entries()) {\n if (!isPlainRecord(chunk)) {\n errors.push('items[' + index + '].chunks[' + chunkIndex + '] must be an object')\n continue\n }\n if (chunk.metadata !== undefined && !isPlainRecord(chunk.metadata)) {\n errors.push('items[' + index + '].chunks[' + chunkIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.embeddings !== undefined) {\n if (!Array.isArray(item.embeddings)) {\n errors.push('items[' + index + '].embeddings must be an array when present')\n } else {\n for (const [embeddingIndex, embedding] of item.embeddings.entries()) {\n if (!isPlainRecord(embedding)) {\n errors.push('items[' + index + '].embeddings[' + embeddingIndex + '] must be an object')\n continue\n }\n const vector = embedding.embedding ?? embedding.vector\n if (vector !== undefined && (!Array.isArray(vector) || !vector.every((entry) => typeof entry === 'number'))) {\n errors.push('items[' + index + '].embeddings[' + embeddingIndex + '].embedding/vector must be a number array')\n }\n if (embedding.metadata !== undefined && !isPlainRecord(embedding.metadata)) {\n errors.push('items[' + index + '].embeddings[' + embeddingIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.compatibility !== undefined && !isPlainRecord(item.compatibility)) {\n errors.push('items[' + index + '].compatibility must be an object')\n }\n}\n\nfunction isPrivacyClassification(value: unknown): value is AiwgPrivacyClassification {\n return value === 'private' || value === 'sanitized' || value === 'public'\n}\n\nfunction isProvenanceConfidence(value: unknown): value is AiwgProvenanceConfidence {\n return value === 'source' || value === 'candidate' || value === 'reviewed' || value === 'rejected'\n}\n\n// Provenance item shape + enum validation (#239 A4). Each item requires\n// field/source/path and enum-valid confidence/privacy — the schema marks all five\n// required, but the parser previously only checked \"non-empty array\".\nfunction validateProvenanceItems(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n if (!Array.isArray(item.provenance)) return\n for (const [provIndex, prov] of item.provenance.entries()) {\n const at = 'items[' + index + '].provenance[' + provIndex + ']'\n if (!isPlainRecord(prov)) {\n errors.push(at + ' must be an object')\n continue\n }\n if (!hasString(prov.field)) errors.push(at + '.field is required')\n if (!hasString(prov.source)) errors.push(at + '.source is required')\n if (!hasString(prov.path)) errors.push(at + '.path is required')\n if (!isProvenanceConfidence(prov.confidence)) errors.push(at + '.confidence must be one of source, candidate, reviewed, rejected')\n if (!isPrivacyClassification(prov.privacy)) errors.push(at + '.privacy must be one of private, sanitized, public')\n }\n}\n\n// v1/v2 field forbiddance (#239 A2): a record.v1 record must not carry fields the\n// schema defines only for record.v2. Keeps the parser as strict as the schema, so\n// a too-loose generator output is rejected rather than silently accepted.\nconst V2_ONLY_RECORD_FIELDS = [\n 'search',\n 'chunks',\n 'embeddings',\n 'skos_concepts',\n 'skos_relations',\n 'provenance_events',\n 'compatibility',\n] as const\nconst V2_ONLY_SOURCE_FIELDS = ['origin', 'generated', 'checksum', 'updated_at'] as const\nconst V2_ONLY_RELATIONSHIP_FIELDS = ['target_path', 'direction', 'metadata'] as const\n\nfunction forbidV2FieldsOnV1Record(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n if (item.schema_version !== 'aiwg.fortemi.index.record.v1') return\n const at = 'items[' + index + ']'\n const bag = item as Record<string, unknown>\n const v2msg = ' is a v2-only field and must be absent on a record.v1 record'\n for (const field of V2_ONLY_RECORD_FIELDS) {\n if (bag[field] !== undefined) errors.push(at + '.' + field + v2msg)\n }\n if (isPlainRecord(item.source)) {\n const src = item.source as Record<string, unknown>\n for (const field of V2_ONLY_SOURCE_FIELDS) {\n if (src[field] !== undefined) errors.push(at + '.source.' + field + v2msg)\n }\n }\n if (isPlainRecord(item.privacy) && (item.privacy as Record<string, unknown>).locality !== undefined) {\n errors.push(at + '.privacy.locality' + v2msg)\n }\n if (Array.isArray(item.relationships)) {\n for (const [relIndex, rel] of item.relationships.entries()) {\n if (!isPlainRecord(rel)) continue\n const relBag = rel as Record<string, unknown>\n for (const field of V2_ONLY_RELATIONSHIP_FIELDS) {\n if (relBag[field] !== undefined) errors.push(at + '.relationships[' + relIndex + '].' + field + v2msg)\n }\n }\n }\n}\n\nexport function validateAiwgFortemiIndexExport(value: unknown): AiwgIndexValidationResult {\n const errors: string[] = []\n const counts: Partial<Record<string, number>> = Object.create(null)\n const data = isPlainRecord(value) ? value as Partial<AiwgFortemiIndexExport> : {}\n if (!isPlainRecord(value)) errors.push('index export must be an object')\n\n if (!isSupportedIndexSchemaVersion(data?.schema_version)) {\n errors.push('schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2')\n }\n if (!hasString(data?.generated_at)) errors.push('generated_at is required')\n if (!hasString(data?.source?.repo)) errors.push('source.repo is required')\n if (!hasString(data?.source?.privacy)) errors.push('source.privacy is required')\n else if (!isPrivacyClassification(data?.source?.privacy)) {\n errors.push('source.privacy must be one of private, sanitized, public')\n }\n if (!Array.isArray(data?.items)) errors.push('items must be an array')\n if (data.compatibility !== undefined && !isPlainRecord(data.compatibility)) {\n errors.push('compatibility must be an object')\n }\n // A5: export-level v1/v2 gating — source.graph and compatibility are v2-only.\n if (data?.schema_version === 'aiwg.fortemi.index.export.v1') {\n if (isPlainRecord(data.source) && (data.source as Record<string, unknown>).graph !== undefined) {\n errors.push('source.graph is a v2-only field and must be absent on an export.v1 export')\n }\n if (data.compatibility !== undefined) {\n errors.push('compatibility is a v2-only field and must be absent on an export.v1 export')\n }\n }\n\n const ids = new Set<string>()\n let previousId = ''\n const items = Array.isArray(data.items) ? data.items : []\n for (const [index, item] of items.entries()) {\n if (!isPlainRecord(item)) {\n errors.push('items[' + index + '] must be an object')\n continue\n }\n for (const field of REQUIRED_RECORD_FIELDS) {\n if (!(field in item)) errors.push('items[' + index + '].' + field + ' is required')\n }\n if (!isSupportedRecordSchemaVersion(item.schema_version)) {\n errors.push('items[' + index + '].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2')\n }\n if (data.schema_version === 'aiwg.fortemi.index.export.v1' && item.schema_version === 'aiwg.fortemi.index.record.v2') {\n errors.push('items[' + index + '].schema_version must match aiwg.fortemi.index.export.v1')\n }\n if (!hasString(item.id)) errors.push('items[' + index + '].id is required')\n if (hasString(item.id) && ids.has(item.id)) errors.push('duplicate id: ' + item.id)\n if (hasString(item.id)) ids.add(item.id)\n if (previousId && hasString(item.id) && previousId > item.id) {\n errors.push('items must be sorted by id: ' + previousId + ' before ' + item.id)\n }\n if (hasString(item.id)) previousId = item.id\n if (!hasString(item.type)) errors.push('items[' + index + '].type must be a non-empty string')\n else counts[item.type] = (counts[item.type] ?? 0) + 1\n if (!hasString(item.source?.path)) errors.push('items[' + index + '].source.path is required')\n if (!hasString(item.source?.repo_relative_path)) errors.push('items[' + index + '].source.repo_relative_path is required')\n if (!hasString(item.source?.locator)) errors.push('items[' + index + '].source.locator is required')\n if (typeof item.title !== 'string' && typeof item.search?.title !== 'string' && typeof item.search?.name !== 'string') {\n errors.push('items[' + index + '].title or search.title/search.name is required')\n }\n if (typeof item.text !== 'string' && typeof item.search?.body !== 'string' && typeof item.search?.summary !== 'string') {\n errors.push('items[' + index + '].text or search.body/search.summary is required')\n }\n if (!Array.isArray(item.tags)) errors.push('items[' + index + '].tags must be an array')\n if (!Array.isArray(item.concepts)) errors.push('items[' + index + '].concepts must be an array')\n if (!Array.isArray(item.relationships)) errors.push('items[' + index + '].relationships must be an array')\n if (!Array.isArray(item.provenance) || item.provenance.length === 0) {\n errors.push('items[' + index + '].provenance must be a non-empty array')\n }\n validateOptionalRichMetadata(item, index, errors)\n validateProvenanceItems(item, index, errors)\n forbidV2FieldsOnV1Record(item, index, errors)\n if (!item.privacy || typeof item.privacy.pii !== 'boolean' || !hasString(item.privacy.classification)) {\n errors.push('items[' + index + '].privacy requires classification and pii')\n } else if (!isPrivacyClassification(item.privacy.classification)) {\n errors.push('items[' + index + '].privacy.classification must be one of private, sanitized, public')\n }\n }\n\n return { valid: errors.length === 0, errors, counts }\n}\n\nexport function assertAiwgFortemiIndexExport(value: unknown): AiwgFortemiIndexExport {\n const result = validateAiwgFortemiIndexExport(value)\n if (!result.valid) {\n throw new Error('Invalid AIWG Fortemi index export:\\n' + result.errors.join('\\n'))\n }\n return value as AiwgFortemiIndexExport\n}\n\nexport function validateAiwgFortemiChunkManifest(value: unknown): AiwgChunkedIndexValidationResult {\n const errors: string[] = []\n const data = isPlainRecord(value) ? value as Partial<AiwgFortemiChunkManifest> : {}\n if (!isPlainRecord(value)) errors.push('chunk manifest must be an object')\n\n if (data?.schema_version !== 'aiwg.fortemi.index.chunk-manifest.v1') {\n errors.push('schema_version must be aiwg.fortemi.index.chunk-manifest.v1')\n }\n if (!hasString(data?.generated_at)) errors.push('generated_at is required')\n if (!hasString(data?.source?.repo)) errors.push('source.repo is required')\n if (!hasString(data?.source?.privacy)) errors.push('source.privacy is required')\n if (data?.source_export_schema_version !== undefined && !isSupportedIndexSchemaVersion(data.source_export_schema_version)) {\n errors.push('source_export_schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2 when present')\n }\n if (!hasNonNegativeInteger(data?.total)) errors.push('total must be a non-negative integer')\n if (!hasPositiveInteger(data?.part_size)) errors.push('part_size must be a positive integer')\n if (data.facets !== undefined && !isFacetCounts(data.facets)) {\n errors.push('facets must be a nested string-to-number count object')\n }\n if (data.projection !== undefined) {\n if (!Array.isArray(data.projection) || !data.projection.every((field) => typeof field === 'string')) {\n errors.push('projection must be an array of field names')\n } else {\n const present = new Set(data.projection)\n for (const field of AIWG_SCAN_REQUIRED_FIELDS) {\n if (!present.has(field)) errors.push('projection must include scan-required field ' + field)\n }\n }\n }\n if (data.detail !== undefined && !isPlainRecord(data.detail)) {\n errors.push('detail must be an object')\n } else if (data.detail !== undefined) {\n if (!hasString(data.detail.href)) errors.push('detail.href is required')\n else if (!data.detail.href.includes('{id}')) errors.push('detail.href must contain the {id} placeholder')\n if (\n data.detail.encoding !== undefined &&\n data.detail.encoding !== 'uri' &&\n data.detail.encoding !== 'base64url'\n ) {\n errors.push(\"detail.encoding must be 'uri' or 'base64url'\")\n }\n }\n if (!Array.isArray(data?.parts)) errors.push('parts must be an array')\n\n let expectedOffset = 0\n const parts = Array.isArray(data?.parts) ? data.parts : []\n for (const [index, part] of parts.entries()) {\n if (!isPlainRecord(part)) {\n errors.push('parts[' + index + '] must be an object')\n continue\n }\n if (!hasString(part.href)) errors.push('parts[' + index + '].href is required')\n if (!hasNonNegativeInteger(part.offset)) errors.push('parts[' + index + '].offset must be a non-negative integer')\n if (!hasNonNegativeInteger(part.count)) errors.push('parts[' + index + '].count must be a non-negative integer')\n if (hasNonNegativeInteger(part.offset) && part.offset !== expectedOffset) {\n errors.push('parts[' + index + '].offset must be ' + expectedOffset)\n }\n if (hasNonNegativeInteger(part.count)) expectedOffset += part.count\n }\n if (hasNonNegativeInteger(data?.total) && expectedOffset !== data.total) {\n errors.push('parts counts must add up to total')\n }\n\n return { valid: errors.length === 0, errors }\n}\n\nexport function assertAiwgFortemiChunkManifest(value: unknown): AiwgFortemiChunkManifest {\n const result = validateAiwgFortemiChunkManifest(value)\n if (!result.valid) {\n throw new Error('Invalid AIWG Fortemi chunk manifest:\\n' + result.errors.join('\\n'))\n }\n return value as AiwgFortemiChunkManifest\n}\n\nfunction validateProjectedRecordShape(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n const at = 'items[' + index + ']'\n if (!item.privacy || !isPlainRecord(item.privacy)) {\n errors.push(at + '/privacy requires classification and pii')\n } else {\n if (!isPrivacyClassification(item.privacy.classification)) {\n errors.push(at + '/privacy/classification must be one of private, sanitized, public')\n }\n if (typeof item.privacy.pii !== 'boolean') {\n errors.push(at + '/privacy/pii must be boolean')\n }\n }\n if (Array.isArray(item.provenance)) {\n for (const [provIndex, prov] of item.provenance.entries()) {\n if (!isPlainRecord(prov)) {\n errors.push(at + '/provenance/' + provIndex + ' must be an object')\n continue\n }\n if (!isProvenanceConfidence(prov.confidence)) {\n errors.push(at + '/provenance/' + provIndex + '/confidence must be one of source, candidate, reviewed, rejected')\n }\n if (!isPrivacyClassification(prov.privacy)) {\n errors.push(at + '/provenance/' + provIndex + '/privacy must be one of private, sanitized, public')\n }\n }\n }\n}\n\n// Validate projected (slim) scan-part items: scan-required fields only, ids unique + sorted.\nfunction validateProjectedRecords(\n items: Array<Partial<AiwgFortemiRecord>>,\n sourceSchemaVersion: AiwgFortemiIndexExportSchemaVersion,\n): string[] {\n const errors: string[] = []\n const ids = new Set<string>()\n let previousId = ''\n for (const [index, item] of items.entries()) {\n if (!isPlainRecord(item)) {\n errors.push('items[' + index + '] must be an object')\n continue\n }\n validateProjectedRecordShape(item, index, errors)\n const expectedRecordVersion = sourceSchemaVersion === 'aiwg.fortemi.index.export.v2'\n ? 'aiwg.fortemi.index.record.v2'\n : 'aiwg.fortemi.index.record.v1'\n if (item.schema_version !== expectedRecordVersion) {\n errors.push(`items[${index}].schema_version must match ${sourceSchemaVersion}`)\n }\n if (!isSupportedRecordSchemaVersion(item.schema_version)) {\n errors.push('items[' + index + '].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2')\n }\n if (!hasString(item.id)) errors.push('items[' + index + '].id is required')\n if (hasString(item.id) && ids.has(item.id)) errors.push('duplicate id: ' + item.id)\n if (hasString(item.id)) ids.add(item.id)\n if (previousId && hasString(item.id) && previousId > item.id) {\n errors.push('items must be sorted by id: ' + previousId + ' before ' + item.id)\n }\n if (hasString(item.id)) previousId = item.id\n if (!hasString(item.type)) errors.push('items[' + index + '].type must be a non-empty string')\n if (typeof item.title !== 'string' && typeof item.search?.title !== 'string' && typeof item.search?.name !== 'string') {\n errors.push('items[' + index + '].title or search.title/search.name is required')\n }\n if (typeof item.text !== 'string' && typeof item.search?.body !== 'string' && typeof item.search?.summary !== 'string') {\n errors.push('items[' + index + '].text or search.body/search.summary is required')\n }\n if (!item.facets || typeof item.facets !== 'object' || Array.isArray(item.facets)) {\n errors.push('items[' + index + '].facets must be an object')\n }\n if (!Array.isArray(item.tags)) errors.push('items[' + index + '].tags must be an array')\n if (!Array.isArray(item.concepts)) errors.push('items[' + index + '].concepts must be an array')\n }\n return errors\n}\n\nexport function validateAiwgFortemiChunkPart(\n value: unknown,\n partRef?: AiwgFortemiChunkPartRef,\n manifest?: AiwgFortemiChunkManifest,\n): AiwgChunkedIndexValidationResult {\n const errors: string[] = []\n const data = isPlainRecord(value) ? value as Partial<AiwgFortemiChunkPart> : {}\n if (!isPlainRecord(value)) errors.push('chunk part must be an object')\n\n if (data?.schema_version !== 'aiwg.fortemi.index.chunk.v1') {\n errors.push('schema_version must be aiwg.fortemi.index.chunk.v1')\n }\n if (data?.manifest_schema_version !== 'aiwg.fortemi.index.chunk-manifest.v1') {\n errors.push('manifest_schema_version must be aiwg.fortemi.index.chunk-manifest.v1')\n }\n if (!hasNonNegativeInteger(data?.offset)) errors.push('offset must be a non-negative integer')\n if (!Array.isArray(data?.items)) errors.push('items must be an array')\n\n if (partRef && hasNonNegativeInteger(data?.offset) && data.offset !== partRef.offset) {\n errors.push('offset must match manifest part offset ' + partRef.offset)\n }\n if (partRef && Array.isArray(data?.items) && data.items.length !== partRef.count) {\n errors.push('items length must match manifest part count ' + partRef.count)\n }\n\n if (Array.isArray(data?.items)) {\n if (manifest?.projection) {\n errors.push(...validateProjectedRecords(\n data.items,\n manifest.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1',\n ).map((error) => 'items.' + error))\n } else {\n const validation = validateAiwgFortemiIndexExport({\n schema_version: manifest?.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1',\n generated_at: manifest?.generated_at ?? '1970-01-01T00:00:00.000Z',\n source: manifest?.source ?? { repo: 'chunk', privacy: 'public' },\n ...((manifest?.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1') === 'aiwg.fortemi.index.export.v2'\n ? { compatibility: { previous_schema_version: 'aiwg.fortemi.index.export.v1', strategy: 'supported' } }\n : {}),\n items: data.items,\n })\n errors.push(...validation.errors.map((error) => 'items.' + error))\n }\n }\n\n return { valid: errors.length === 0, errors }\n}\n\nexport function assertAiwgFortemiChunkPart(\n value: unknown,\n partRef?: AiwgFortemiChunkPartRef,\n manifest?: AiwgFortemiChunkManifest,\n): AiwgFortemiChunkPart {\n const result = validateAiwgFortemiChunkPart(value, partRef, manifest)\n if (!result.valid) {\n throw new Error('Invalid AIWG Fortemi chunk part:\\n' + result.errors.join('\\n'))\n }\n return value as AiwgFortemiChunkPart\n}\n\n// Schemes an index fetch may target. Blocks file:, ftp:, ws:, etc. so a\n// manifest-controlled href cannot pivot the browser into a non-web protocol.\nconst ALLOWED_AIWG_FETCH_SCHEMES = new Set(['http:', 'https:', 'blob:', 'data:'])\n\nfunction tryParseUrl(value: string): URL | null {\n try {\n return new URL(value)\n } catch {\n return null\n }\n}\n\n// Resolve and vet a manifest-controlled fetch target (SEC2 — SSRF).\n// - With a baseUrl: the href is resolved against it and MUST stay same-origin,\n// so an absolute `href` (which `new URL` would otherwise honor, ignoring the\n// base) cannot redirect the fetch to an attacker origin.\n// - Without a baseUrl: the caller opted into a bare href; only the scheme is\n// vetted (relative hrefs are passed through unchanged).\nexport function resolveAiwgFetchUrl(href: string, baseUrl?: string | URL): string {\n if (baseUrl === undefined) {\n const absolute = tryParseUrl(href)\n if (absolute && !ALLOWED_AIWG_FETCH_SCHEMES.has(absolute.protocol)) {\n throw new Error('Refusing AIWG index fetch with disallowed scheme: ' + absolute.protocol)\n }\n return href\n }\n const base = new URL(baseUrl)\n const resolved = new URL(href, base)\n if (!ALLOWED_AIWG_FETCH_SCHEMES.has(resolved.protocol)) {\n throw new Error('Refusing AIWG index fetch with disallowed scheme: ' + resolved.protocol)\n }\n if (resolved.origin !== base.origin) {\n throw new Error('Refusing cross-origin AIWG index fetch: ' + resolved.origin + ' != ' + base.origin)\n }\n return resolved.toString()\n}\n\nexport function createAiwgFetchChunkLoader(baseUrl?: string | URL): AiwgChunkedIndexLoader {\n return async (part) => {\n const href = resolveAiwgFetchUrl(part.href, baseUrl)\n const response = await fetch(href)\n if (!response.ok) throw new Error('Failed to fetch AIWG index chunk ' + href + ': ' + response.status)\n return response.json()\n }\n}\n\n// Encode a record id into a single, path-safe detail filename segment.\n// - 'base64url' (default): UTF-8 → base64url (no '+', '/', '=', '%'). Safe for ids\n// containing '/' on static hosts that reject %2F (#177).\n// - 'uri': encodeURIComponent (legacy).\nexport function encodeAiwgDetailId(id: string, encoding: AiwgDetailIdEncoding = 'base64url'): string {\n if (encoding === 'uri') return encodeURIComponent(id)\n const bytes = new TextEncoder().encode(id)\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n // btoa is available in browsers and Node ≥16.\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// Resolve a manifest detail.href template for a given id, honoring detail.encoding\n// (absent → 'uri' for backward compatibility). The writer and the loader both go\n// through this so emitted filenames and fetched paths always agree.\nexport function aiwgDetailHrefForId(detail: AiwgFortemiChunkDetailRef, id: string): string {\n return detail.href.replace('{id}', encodeAiwgDetailId(id, detail.encoding ?? 'uri'))\n}\n\n// Detail loader for projected indexes: resolves the manifest's detail.href {id}\n// template (encoded per detail.encoding) against baseUrl and fetches the full record.\nexport function createAiwgFetchDetailLoader(baseUrl?: string | URL): AiwgChunkedIndexDetailLoader {\n return async (id, manifest) => {\n if (!manifest.detail?.href) throw new Error('Manifest has no detail.href for record resolution')\n const relative = aiwgDetailHrefForId(manifest.detail, id)\n const href = resolveAiwgFetchUrl(relative, baseUrl)\n const response = await fetch(href)\n if (!response.ok) throw new Error('Failed to fetch AIWG index detail ' + href + ': ' + response.status)\n return response.json()\n }\n}\n\nexport function getAiwgFortemiFacets(items: AiwgFortemiRecord[]): Record<string, Record<string, number>> {\n // Null-prototype accumulator: untrusted facet names must never resolve to an\n // inherited property (see pushFacet / SEC1 / #236). Round-trips to a plain\n // object through JSON serialization, so no downstream consumer is affected.\n const result: Record<string, Record<string, number>> = Object.create(null)\n for (const item of items) {\n pushFacet(result, 'type', item.type)\n pushFacet(result, 'privacy', item.privacy.classification)\n for (const tag of item.tags) pushFacet(result, 'tag', tag)\n for (const concept of item.concepts) pushFacet(result, 'concept', concept)\n for (const [name, values] of Object.entries(item.facets)) {\n for (const value of values) pushFacet(result, name, value)\n }\n }\n return result\n}\n\nfunction recordTitle(item: AiwgFortemiProjectedRecord): string {\n return item.title ?? item.search?.title ?? item.search?.name ?? item.id\n}\n\nfunction recordText(item: AiwgFortemiProjectedRecord): string {\n const base = item.text\n ?? item.search?.body\n ?? item.search?.summary\n ?? item.chunks?.map((chunk) => chunk.text ?? chunk.body ?? chunk.summary ?? '').filter(Boolean).join('\\n')\n ?? ''\n const extractedText = binarySourceText(item)\n return [base, extractedText].filter(Boolean).join('\\n')\n}\n\nfunction binarySourceText(item: AiwgFortemiProjectedRecord): string {\n return 'binary_sources' in item\n ? item.binary_sources?.map((source) => source.extracted_text).filter(Boolean).join('\\n') ?? ''\n : ''\n}\n\nfunction defaultEmbeddingInput(record: AiwgFortemiRecord, granularity: AiwgStaticEmbeddingSet['granularity']): string {\n const title = recordTitle(record)\n const text = recordText(record)\n if (granularity === 'title-summary') {\n // Attachment text remains part of title-summary embeddings so binary-only\n // knowledge is searchable even when the record has no authored summary.\n return [title, record.search?.summary ?? '', binarySourceText(record)].filter(Boolean).join('\\n')\n }\n return [title, text].filter(Boolean).join('\\n')\n}\n\nfunction generatedAtString(value: string | Date | undefined): string {\n if (value instanceof Date) return value.toISOString()\n return value ?? new Date().toISOString()\n}\n\nconst SHA256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n] as const\n\nfunction rotr(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits))\n}\n\nfunction sha256Hex(data: Uint8Array): string {\n const bitLength = data.length * 8\n const padded = new Uint8Array((((data.length + 9 + 63) >> 6) << 6))\n padded.set(data)\n padded[data.length] = 0x80\n const view = new DataView(padded.buffer)\n view.setUint32(padded.length - 4, bitLength >>> 0)\n view.setUint32(padded.length - 8, Math.floor(bitLength / 0x100000000))\n let h0 = 0x6a09e667\n let h1 = 0xbb67ae85\n let h2 = 0x3c6ef372\n let h3 = 0xa54ff53a\n let h4 = 0x510e527f\n let h5 = 0x9b05688c\n let h6 = 0x1f83d9ab\n let h7 = 0x5be0cd19\n const w = new Uint32Array(64)\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4)\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3)\n const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10)\n w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0\n }\n let a = h0\n let b = h1\n let c = h2\n let d = h3\n let e = h4\n let f = h5\n let g = h6\n let h = h7\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)\n const ch = (e & f) ^ (~e & g)\n const temp1 = (h + s1 + ch + SHA256_K[i] + w[i]) >>> 0\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)\n const maj = (a & b) ^ (a & c) ^ (b & c)\n const temp2 = (s0 + maj) >>> 0\n h = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n h0 = (h0 + a) >>> 0\n h1 = (h1 + b) >>> 0\n h2 = (h2 + c) >>> 0\n h3 = (h3 + d) >>> 0\n h4 = (h4 + e) >>> 0\n h5 = (h5 + f) >>> 0\n h6 = (h6 + g) >>> 0\n h7 = (h7 + h) >>> 0\n }\n return [h0, h1, h2, h3, h4, h5, h6, h7].map((part) => part.toString(16).padStart(8, '0')).join('')\n}\n\nfunction computeAiwgIndexHash(data: Uint8Array): string {\n return `sha256:${sha256Hex(data)}`\n}\n\nexport async function buildAiwgStaticEmbeddingSet(\n index: AiwgFortemiIndexExport,\n options: BuildAiwgStaticEmbeddingSetOptions,\n): Promise<AiwgStaticEmbeddingSet> {\n assertAiwgFortemiIndexExport(index)\n const granularity = options.granularity ?? 'body'\n // SEC6: default-safe privacy filter over the source records.\n const records = filterAiwgRecordsByPrivacy(options.records ?? index.items, options.privacy)\n const embeddings: AiwgStaticEmbeddingRecord[] = []\n\n for (const record of records) {\n const input = options.textForRecord?.(record) ?? defaultEmbeddingInput(record, granularity)\n const embedding = await options.backend.embed(input, record)\n if (embedding.length !== options.backend.dimensions) {\n throw new Error(`Embedding for ${record.id} has ${embedding.length} dimensions; expected ${options.backend.dimensions}`)\n }\n embeddings.push({\n record_id: record.id,\n embedding,\n granularity,\n input_hash: computeAiwgIndexHash(new TextEncoder().encode(input)),\n source_path: record.source.path,\n })\n }\n\n const embeddingSet: AiwgStaticEmbeddingSet = {\n schema_version: 'aiwg.fortemi.embedding.set.v1',\n id: options.id,\n model: options.backend.model,\n dimensions: options.backend.dimensions,\n generated_at: generatedAtString(options.generatedAt),\n granularity,\n ...(options.metric ? { metric: options.metric } : {}),\n input_hash_algorithm: 'sha256',\n embeddings,\n }\n assertAiwgStaticEmbeddingSet(embeddingSet)\n return embeddingSet\n}\n\nfunction recordSearchValues(item: AiwgFortemiProjectedRecord): string[] {\n const search = item.search\n const values = [\n item.id,\n recordTitle(item),\n recordText(item),\n search?.title,\n search?.name,\n search?.summary,\n search?.body,\n search?.capability,\n search?.phase,\n search?.type,\n ...(search?.triggers ?? []),\n ...(search?.aliases ?? []),\n ...(search?.tags ?? []),\n ...(item.chunks ?? []).flatMap((chunk) => [chunk.text, chunk.body, chunk.summary, chunk.source_path]),\n ]\n if (search?.frontmatter) {\n for (const value of Object.values(search.frontmatter)) {\n if (typeof value === 'string') values.push(value)\n else if (Array.isArray(value)) values.push(...value.filter((entry): entry is string => typeof entry === 'string'))\n }\n }\n return values.filter((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\nexport interface AiwgChunkedIndexBuildOptions {\n partSize?: number\n // When set, scan parts carry only these fields; full records go to `details`.\n projection?: Array<keyof AiwgFortemiRecord>\n // Detail href template (with {id}); defaults to \"detail/{id}.json\" when projecting.\n detailHref?: string\n // id→filename encoding for detail files; defaults to 'base64url' (path-safe,\n // works for ids containing '/'; see #177).\n idEncoding?: AiwgDetailIdEncoding\n generatedAt?: string\n /** Privacy filtering (SEC6). Default-safe: excludes `private`/`pii` records. */\n privacy?: AiwgPrivacyFilterOptions\n}\n\nexport interface AiwgChunkedIndexBuildResult {\n manifest: AiwgFortemiChunkManifest\n parts: Array<{ href: string; part: AiwgFortemiChunkPart }>\n // Empty unless projecting. Each entry carries the full record plus the resolved,\n // encoding-correct `href` to host it at — write the record to that path so the\n // detail loader (which uses the same encoding) can fetch it back.\n details: Array<{ id: string; href: string; record: AiwgFortemiRecord }>\n}\n\n// Pure builder (no I/O): project an index export into the chunked manifest + parts\n// (+ detail records when projecting). The caller writes the returned objects to disk.\n// Manifest facets are computed from the full records, so global counts are exact even\n// when scan parts are slim.\nexport function buildAiwgChunkedIndex(\n index: AiwgFortemiIndexExport,\n options: AiwgChunkedIndexBuildOptions = {},\n): AiwgChunkedIndexBuildResult {\n assertAiwgFortemiIndexExport(index)\n const partSize = hasPositiveInteger(options.partSize) ? options.partSize : 500\n const projection = options.projection\n const idEncoding = options.idEncoding ?? 'base64url'\n const detailHref = options.detailHref ?? 'detail/{id}.json'\n // SEC6: default-safe privacy filter — `private`/`pii` records never enter the\n // generated scan parts, detail files, or manifest facet counts.\n const items = filterAiwgRecordsByPrivacy(index.items, options.privacy)\n const pad = (value: number): string => String(value).padStart(4, '0')\n const project = (record: AiwgFortemiRecord): AiwgFortemiRecord => {\n if (!projection) return record\n const slim: Record<string, unknown> = {}\n for (const field of projection) slim[field] = record[field]\n return slim as unknown as AiwgFortemiRecord\n }\n\n const parts: Array<{ href: string; part: AiwgFortemiChunkPart }> = []\n const partRefs: AiwgFortemiChunkPartRef[] = []\n for (let offset = 0, partIndex = 0; offset < items.length; offset += partSize, partIndex += 1) {\n const slice = items.slice(offset, offset + partSize)\n const href = 'part-' + pad(partIndex) + '.json'\n parts.push({\n href,\n part: {\n schema_version: 'aiwg.fortemi.index.chunk.v1',\n manifest_schema_version: 'aiwg.fortemi.index.chunk-manifest.v1',\n offset,\n items: slice.map(project),\n },\n })\n partRefs.push({ href, offset, count: slice.length })\n }\n\n const manifest: AiwgFortemiChunkManifest = {\n schema_version: 'aiwg.fortemi.index.chunk-manifest.v1',\n generated_at: options.generatedAt ?? index.generated_at,\n source: index.source,\n source_export_schema_version: index.schema_version,\n total: items.length,\n part_size: partSize,\n facets: getAiwgFortemiFacets(items),\n parts: partRefs,\n ...(projection ? { projection, detail: { href: detailHref, encoding: idEncoding } } : {}),\n }\n\n return {\n manifest,\n parts,\n details: projection\n ? items.map((record) => ({\n id: record.id,\n href: aiwgDetailHrefForId({ href: detailHref, encoding: idEncoding }, record.id),\n record,\n }))\n : [],\n }\n}\n\nfunction includesAll(actual: string[], expected: string[] | undefined): boolean {\n if (!expected || expected.length === 0) return true\n const actualSet = new Set(actual)\n return expected.every((value) => actualSet.has(value))\n}\n\nfunction matchesFacetFilters(item: AiwgFortemiRecord, filters: Record<string, string[]> | undefined): boolean {\n if (!filters) return true\n return Object.entries(filters).every(([name, expected]) => includesAll(item.facets[name] ?? [], expected))\n}\n\nfunction queryMatches(item: AiwgFortemiRecord, q: string): AiwgIndexQueryMatch[] {\n if (!q) return []\n const matches: AiwgIndexQueryMatch[] = []\n const title = recordTitle(item)\n const text = recordText(item)\n if (title.toLowerCase().includes(q)) matches.push({ field: 'title', value: title })\n if (text.toLowerCase().includes(q)) matches.push({ field: 'text', value: text })\n for (const tag of item.tags) {\n if (tag.toLowerCase().includes(q)) matches.push({ field: 'tag', value: tag })\n }\n for (const concept of item.concepts) {\n if (concept.toLowerCase().includes(q)) matches.push({ field: 'concept', value: concept })\n }\n for (const value of recordSearchValues(item)) {\n if (value !== title && value !== text && value.toLowerCase().includes(q)) {\n matches.push({ field: 'text', value, score: DEFAULT_QUERY_WEIGHTS.text })\n }\n }\n return matches\n}\n\nconst DISCOVERY_STOPWORDS = new Set([\n 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'in', 'on',\n 'with', 'into', 'from', 'is', 'are', 'be', 'i', 'we', 'my',\n 'it', 'you', 'me', 'us', 'your', 'our', 'this', 'that', 'these', 'those',\n 'there', 'here', 'some', 'any', 'all', 'also', 'please', 'about',\n 'how', 'what', 'which', 'where', 'when', 'who', 'why',\n 'find', 'give', 'show', 'need', 'want', 'looking', 'look', 'help',\n 'do', 'does', 'did', 'can', 'could', 'should', 'would', 'will',\n 'handle', 'handles', 'handling',\n 'aiwg', 'skill', 'skills', 'agent', 'agents', 'command', 'commands',\n 'rule', 'rules', 'flow', 'flows', 'workflow', 'workflows',\n])\n\nfunction normalizeDiscoveryName(value: string): string {\n return value.toLowerCase().replace(/[-_\\s]+/g, ' ').trim()\n}\n\nfunction discoveryTokens(value: string): string[] {\n return value\n .toLowerCase()\n .split(/[^a-z0-9-]+/)\n .filter((token) => token.length > 1 && !DISCOVERY_STOPWORDS.has(token))\n}\n\nfunction facetValues(item: AiwgFortemiRecord, names: string[]): string[] {\n return names.flatMap((name) => item.facets[name] ?? [])\n}\n\nfunction addDiscoveryMatch(matches: AiwgIndexQueryMatch[], match: AiwgIndexQueryMatch) {\n if (!matches.some((existing) => existing.field === match.field && existing.value === match.value && existing.reason === match.reason)) {\n matches.push(match)\n }\n}\n\nfunction damerauLevenshteinAtMostOne(left: string, right: string): boolean {\n if (left === right) return true\n if (Math.abs(left.length - right.length) > 1) return false\n\n if (left.length === right.length) {\n let firstDiff = -1\n let diffCount = 0\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n if (firstDiff < 0) firstDiff = index\n diffCount += 1\n }\n }\n if (diffCount === 1) return true\n return diffCount === 2\n && firstDiff + 1 < left.length\n && left[firstDiff] === right[firstDiff + 1]\n && left[firstDiff + 1] === right[firstDiff]\n }\n\n const shorter = left.length < right.length ? left : right\n const longer = left.length < right.length ? right : left\n let shorterIndex = 0\n let longerIndex = 0\n let edits = 0\n while (shorterIndex < shorter.length && longerIndex < longer.length) {\n if (shorter[shorterIndex] === longer[longerIndex]) {\n shorterIndex += 1\n longerIndex += 1\n } else {\n edits += 1\n if (edits > 1) return false\n longerIndex += 1\n }\n }\n return true\n}\n\nfunction nearDiscoveryNameMatch(query: string, name: string): boolean {\n const queryParts = normalizeDiscoveryName(query).split(/\\s+/).filter(Boolean)\n const nameParts = normalizeDiscoveryName(name).split(/\\s+/).filter(Boolean)\n if (queryParts.length !== nameParts.length) return false\n\n return queryParts.every((part, index) => {\n const target = nameParts[index]\n if (part === target) return true\n if (part.length < 5 || target.length < 5) return false\n return damerauLevenshteinAtMostOne(part, target)\n })\n}\n\nfunction lowerValues(values: string[]): string[] {\n return values.map((value) => value.toLowerCase())\n}\n\ninterface DiscoveryScoringOptions {\n relaxOverlap?: boolean\n}\n\nfunction discoveryMatches(item: AiwgFortemiRecord, query: string, options: DiscoveryScoringOptions = {}): AiwgIndexQueryMatch[] {\n if (!query) return []\n const matches: AiwgIndexQueryMatch[] = []\n const tokens = discoveryTokens(query)\n const lower = tokens.length > 0 ? tokens.join(' ') : query.toLowerCase().trim()\n const rawLower = query.toLowerCase().trim()\n const idParts = item.id.split(/[:/]/)\n const names = [\n item.id,\n recordTitle(item),\n item.search?.name,\n item.search?.title,\n ...(item.search?.aliases ?? []),\n ...idParts,\n ...facetValues(item, ['name', 'canonical_name', 'command', 'skill', 'agent', 'rule']),\n ].filter((value): value is string => hasString(value))\n const triggers = [\n ...facetValues(item, ['trigger', 'triggers', 'trigger_phrase', 'trigger_phrases']),\n ...(item.search?.triggers ?? []),\n ]\n const capabilities = [\n ...facetValues(item, ['capability', 'capabilities', 'summary', 'description']),\n item.search?.capability,\n item.search?.summary,\n item.search?.phase,\n item.search?.type,\n ...(item.search?.tags ?? []),\n ...item.concepts,\n ...item.tags,\n ].filter((value): value is string => hasString(value))\n const sourceValues = [item.source?.path, item.source?.repo_relative_path, item.source?.locator].filter((value): value is string => hasString(value))\n const title = recordTitle(item)\n const summary = [item.search?.summary, recordText(item)].filter((value): value is string => hasString(value)).join('\\n')\n const type = item.search?.type ?? item.type\n const tags = [...(item.search?.tags ?? []), ...item.tags]\n const useMultiToken = tokens.length > 1\n const minHits = useMultiToken ? (options.relaxOverlap ? 1 : Math.ceil(tokens.length / 2)) : 1\n const overlapOK = (hits: number): boolean => useMultiToken && hits >= minHits\n\n const addInfo = (match: AiwgIndexQueryMatch) => addDiscoveryMatch(matches, { ...match, score: 0 })\n const addScore = (score: number) => {\n if (score > 0) addDiscoveryMatch(matches, { field: 'id', value: item.id, score, reason: 'aiwg discovery score' })\n }\n\n for (const name of names) {\n if (normalizeDiscoveryName(query) === normalizeDiscoveryName(name)) {\n addInfo({ field: 'id', value: name, reason: 'exact canonical name' })\n addScore(1.001)\n return matches\n }\n if (nearDiscoveryNameMatch(query, name)) {\n addInfo({ field: 'id', value: name, reason: 'near canonical name' })\n addScore(0.951)\n return matches\n }\n }\n\n let score = 0\n const scoreText = (\n field: AiwgIndexQueryMatch['field'],\n value: string,\n reason: string,\n exactScore: number,\n overlapScore: number,\n weight: number,\n exactBonus = 0,\n ) => {\n const normalized = value.toLowerCase()\n if (normalized.includes(lower)) {\n score += exactScore * weight\n if (normalized === lower) score += exactBonus\n addInfo({ field, value, reason })\n } else if (useMultiToken) {\n const hits = tokens.filter((token) => normalized.includes(token)).length\n if (overlapOK(hits)) {\n score += overlapScore * weight * (hits / tokens.length)\n addInfo({ field, value, reason })\n }\n }\n }\n\n for (const trigger of lowerValues(triggers)) {\n if (trigger === lower || trigger === rawLower) {\n addInfo({ field: 'facet', value: trigger, reason: 'trigger phrase' })\n addScore(1.0008)\n return matches\n }\n }\n for (const trigger of triggers) {\n scoreText('facet', trigger, 'trigger phrase', 0.25, 0.06, 4)\n }\n for (const capability of capabilities) scoreText('concept', capability, 'capability overlap', 0.2, 0.1, 2)\n scoreText('title', title, 'title token overlap', 0.3, 0.08, 3, 0.2)\n for (const tag of tags) scoreText('tag', tag, 'tag token overlap', 0.2, 0.05, 2)\n if (summary) scoreText('text', summary, 'body token overlap', 0.15, 0.04, 1)\n for (const source of sourceValues) {\n scoreText('source', source, 'path overlap', 0.1, 0.03, 1)\n }\n if (type.toLowerCase().includes(lower)) {\n score += 0.1\n addInfo({ field: 'facet', value: type, reason: 'type overlap' })\n }\n addScore(Math.min(score, 1.0))\n\n return matches\n}\n\nfunction rankMatches(matches: AiwgIndexQueryMatch[], weights: AiwgIndexQueryWeights): number {\n return matches.reduce((total, match) => total + (match.score ?? weights[match.field]), 0)\n}\n\nfunction clipSnippet(value: string, q: string, maxLength: number): string {\n const normalizedLength = Math.max(20, maxLength)\n if (!value) return ''\n if (!q) return value.length > normalizedLength ? `${value.slice(0, normalizedLength).trimEnd()}...` : value\n\n const lower = value.toLowerCase()\n const index = lower.indexOf(q)\n if (index < 0) return value.length > normalizedLength ? `${value.slice(0, normalizedLength).trimEnd()}...` : value\n\n const context = Math.max(0, Math.floor((normalizedLength - q.length) / 2))\n const start = Math.max(0, index - context)\n const end = Math.min(value.length, start + normalizedLength)\n const prefix = start > 0 ? '...' : ''\n const suffix = end < value.length ? '...' : ''\n return `${prefix}${value.slice(start, end).trim()}${suffix}`\n}\n\nfunction createSnippet(item: AiwgFortemiRecord, matches: AiwgIndexQueryMatch[], q: string, maxLength: number): string {\n const textMatch = matches.find((match) => match.field === 'text')\n const titleMatch = matches.find((match) => match.field === 'title')\n const firstMatch = textMatch ?? titleMatch ?? matches[0]\n return clipSnippet(firstMatch?.value ?? recordText(item), q, maxLength)\n}\n\ninterface AiwgRankedEntry {\n item: AiwgFortemiRecord\n ordinal: number\n rank: number\n matches: AiwgIndexQueryMatch[]\n}\n\nfunction createRankedEntries(\n items: AiwgFortemiRecord[],\n q: string,\n options: AiwgIndexQueryOptions,\n ordinalBase = 0,\n discoveryOptions: DiscoveryScoringOptions = {},\n): AiwgRankedEntry[] {\n const weights = { ...DEFAULT_QUERY_WEIGHTS, ...options.weights }\n const profile = options.searchProfile ?? 'default'\n return items.map((item, ordinal) => ({\n item,\n ordinal: ordinalBase + ordinal,\n matches: profile === 'aiwg-discovery' ? discoveryMatches(item, q, discoveryOptions) : queryMatches(item, q),\n }))\n .filter(({ item, matches }) => {\n if (q && matches.length === 0) return false\n if (options.types && !options.types.includes(item.type)) return false\n if (options.privacy && !options.privacy.includes(item.privacy.classification)) return false\n if (!includesAll(item.tags, options.tags)) return false\n if (!includesAll(item.concepts, options.concepts)) return false\n if (!matchesFacetFilters(item, options.facets)) return false\n if (options.relationshipTargetId && !(item.relationships ?? []).some((rel) => rel.target_id === options.relationshipTargetId)) {\n return false\n }\n return true\n })\n .map(({ item, ordinal, matches }) => ({\n item,\n ordinal,\n rank: rankMatches(matches, weights),\n matches,\n }))\n}\n\nfunction sortRankedEntries(entries: AiwgRankedEntry[], rank?: boolean): AiwgRankedEntry[] {\n return [...entries].sort((left, right) => {\n if (rank) return right.rank - left.rank || left.ordinal - right.ordinal\n return left.ordinal - right.ordinal\n })\n}\n\nfunction createQueryResultFromRankedEntries(\n entries: AiwgRankedEntry[],\n query: string,\n options: AiwgIndexQueryOptions,\n): AiwgIndexQueryResult {\n const ranked = sortRankedEntries(entries, options.rank)\n const offset = options.offset ?? 0\n const limit = options.limit ?? ranked.length\n const page = ranked.slice(offset, offset + limit)\n const result: AiwgIndexQueryResult = {\n items: page.map((entry) => entry.item),\n total: ranked.length,\n facets: getAiwgFortemiFacets(ranked.map((entry) => entry.item)),\n }\n if (options.rank || options.snippets || options.includeMatches) {\n const snippetLength = options.snippetLength ?? 160\n result.rankedItems = page.map((entry) => ({\n item: entry.item,\n rank: entry.rank,\n ...(options.snippets ? { snippet: createSnippet(entry.item, entry.matches, query, snippetLength) } : {}),\n ...(options.includeMatches ? { matches: entry.matches } : {}),\n }))\n }\n return result\n}\n\nexport function queryAiwgFortemiIndex(\n index: AiwgFortemiIndexExport,\n query = '',\n options: AiwgIndexQueryOptions = {},\n): AiwgIndexQueryResult {\n const q = query.trim().toLowerCase()\n const entries = createRankedEntries(index.items, q, options)\n if (entries.length === 0 && q && options.searchProfile === 'aiwg-discovery') {\n return createQueryResultFromRankedEntries(createRankedEntries(index.items, q, options, 0, { relaxOverlap: true }), q, options)\n }\n return createQueryResultFromRankedEntries(entries, q, options)\n}\n\nfunction cosineSimilarity(left: number[], right: number[]): number {\n if (left.length !== right.length || left.length === 0) return 0\n let dot = 0\n let leftMag = 0\n let rightMag = 0\n for (let i = 0; i < left.length; i += 1) {\n const l = left[i]\n const r = right[i]\n dot += l * r\n leftMag += l * l\n rightMag += r * r\n }\n if (leftMag === 0 || rightMag === 0) return 0\n return dot / (Math.sqrt(leftMag) * Math.sqrt(rightMag))\n}\n\nexport function validateAiwgStaticEmbeddingSet(value: unknown): AiwgChunkedIndexValidationResult {\n const errors: string[] = []\n const data = isPlainRecord(value) ? value as Partial<AiwgStaticEmbeddingSet> : {}\n if (!isPlainRecord(value)) errors.push('embedding set must be an object')\n if (data?.schema_version !== 'aiwg.fortemi.embedding.set.v1') errors.push('schema_version must be aiwg.fortemi.embedding.set.v1')\n if (!hasString(data?.id)) errors.push('id is required')\n if (!hasString(data?.model)) errors.push('model is required')\n if (!hasPositiveInteger(data?.dimensions)) errors.push('dimensions must be a positive integer')\n if (!hasString(data?.generated_at)) errors.push('generated_at is required')\n if (!hasString(data?.granularity)) errors.push('granularity is required')\n if (!Array.isArray(data?.embeddings)) errors.push('embeddings must be an array')\n const embeddings = Array.isArray(data.embeddings) ? data.embeddings : []\n for (const [index, embedding] of embeddings.entries()) {\n if (!isPlainRecord(embedding)) {\n errors.push('embeddings[' + index + '] must be an object')\n continue\n }\n if (!hasString(embedding.record_id)) errors.push('embeddings[' + index + '].record_id is required')\n if (!hasString(embedding.input_hash)) errors.push('embeddings[' + index + '].input_hash is required')\n if (!Array.isArray(embedding.embedding)) errors.push('embeddings[' + index + '].embedding must be an array')\n else if (hasPositiveInteger(data?.dimensions) && embedding.embedding.length !== data.dimensions) {\n errors.push('embeddings[' + index + '].embedding length must match dimensions')\n } else if (!embedding.embedding.every((number) => typeof number === 'number' && Number.isFinite(number))) {\n errors.push('embeddings[' + index + '].embedding must contain finite numbers')\n }\n }\n return { valid: errors.length === 0, errors }\n}\n\nexport function assertAiwgStaticEmbeddingSet(value: unknown): AiwgStaticEmbeddingSet {\n const result = validateAiwgStaticEmbeddingSet(value)\n if (!result.valid) throw new Error('Invalid AIWG Fortemi embedding set:\\n' + result.errors.join('\\n'))\n return value as AiwgStaticEmbeddingSet\n}\n\nexport function queryAiwgSemanticIndex(\n index: AiwgFortemiIndexExport,\n embeddingSet: AiwgStaticEmbeddingSet,\n queryEmbedding: number[],\n options: AiwgStaticSemanticQueryOptions = {},\n): AiwgStaticSemanticResult[] {\n assertAiwgStaticEmbeddingSet(embeddingSet)\n if (queryEmbedding.length !== embeddingSet.dimensions) throw new Error('query embedding length must match embedding set dimensions')\n const byId = new Map(index.items.map((item) => [item.id, item]))\n const offset = options.offset ?? 0\n const limit = options.limit ?? 20\n return embeddingSet.embeddings\n .map((embedding): AiwgStaticSemanticResult | null => {\n const item = byId.get(embedding.record_id)\n if (!item) return null\n return { item, embedding, score: cosineSimilarity(queryEmbedding, embedding.embedding) }\n })\n .filter((result): result is AiwgStaticSemanticResult => result !== null && result.score >= (options.minScore ?? -1))\n .sort((left, right) => right.score - left.score || left.item.id.localeCompare(right.item.id))\n .slice(offset, offset + limit)\n}\n\nexport function queryAiwgHybridIndex(\n index: AiwgFortemiIndexExport,\n embeddingSet: AiwgStaticEmbeddingSet,\n query: string,\n queryEmbedding: number[],\n options: AiwgStaticHybridQueryOptions = {},\n): AiwgStaticSemanticResult[] {\n const lexicalOptions: AiwgStaticHybridQueryOptions = { ...options }\n delete lexicalOptions.limit\n delete lexicalOptions.offset\n const lexical = queryAiwgFortemiIndex(index, query, { ...lexicalOptions, rank: true })\n const semantic = queryAiwgSemanticIndex(index, embeddingSet, queryEmbedding, { limit: index.items.length })\n const lexicalWeight = options.lexicalWeight ?? 0.5\n const semanticWeight = options.semanticWeight ?? 0.5\n const lexicalScores = new Map(lexical.rankedItems?.map((entry) => [entry.item.id, entry.rank]) ?? [])\n const maxLexical = Math.max(1, ...lexicalScores.values())\n const embeddingById = new Map(semantic.flatMap((entry) => entry.embedding ? [[entry.item.id, entry.embedding] as const] : []))\n const semanticScores = new Map(semantic.map((entry) => [entry.item.id, entry.score]))\n const ids = new Set([...lexicalScores.keys(), ...semanticScores.keys()])\n const offset = options.offset ?? 0\n const limit = options.limit ?? 20\n return [...ids]\n .map((id) => {\n const item = index.items.find((candidate) => candidate.id === id)\n const embedding = embeddingById.get(id)\n if (!item) return null\n return {\n item,\n ...(embedding ? { embedding } : {}),\n score: ((lexicalScores.get(id) ?? 0) / maxLexical) * lexicalWeight + (semanticScores.get(id) ?? 0) * semanticWeight,\n }\n })\n .filter((result): result is AiwgStaticSemanticResult => result !== null && result.score >= (options.minScore ?? -1))\n .sort((left, right) => right.score - left.score || left.item.id.localeCompare(right.item.id))\n .slice(offset, offset + limit)\n}\n\n// Default cap for the pairwise duplicate scan. The scan is O(n²) in the number\n// of embeddings, so an unbounded attacker-supplied set is a CPU DoS (SEC5). At\n// the default of 5000 the worst case is ~12.5M cosine comparisons; callers with\n// a trusted, larger set can raise the cap explicitly.\nexport const DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS = 5000\n\nexport function findAiwgStaticDuplicatePairs(\n index: AiwgFortemiIndexExport,\n embeddingSet: AiwgStaticEmbeddingSet,\n threshold = 0.9,\n options?: { maxEmbeddings?: number },\n): AiwgStaticDuplicatePair[] {\n assertAiwgStaticEmbeddingSet(embeddingSet)\n const maxEmbeddings = options?.maxEmbeddings ?? DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS\n if (embeddingSet.embeddings.length > maxEmbeddings) {\n throw new Error(\n 'Embedding set too large for duplicate scan: ' + embeddingSet.embeddings.length +\n ' > ' + maxEmbeddings + ' (raise options.maxEmbeddings to override for trusted input)',\n )\n }\n const byId = new Map(index.items.map((item) => [item.id, item]))\n const pairs: AiwgStaticDuplicatePair[] = []\n for (let leftIndex = 0; leftIndex < embeddingSet.embeddings.length; leftIndex += 1) {\n for (let rightIndex = leftIndex + 1; rightIndex < embeddingSet.embeddings.length; rightIndex += 1) {\n const leftEmbedding = embeddingSet.embeddings[leftIndex]\n const rightEmbedding = embeddingSet.embeddings[rightIndex]\n const left = byId.get(leftEmbedding.record_id)\n const right = byId.get(rightEmbedding.record_id)\n if (!left || !right) continue\n const score = cosineSimilarity(leftEmbedding.embedding, rightEmbedding.embedding)\n if (score >= threshold) pairs.push({ left, right, score })\n }\n }\n return pairs.sort((left, right) => right.score - left.score || left.left.id.localeCompare(right.left.id))\n}\n\ninterface AiwgChunkedIndexRuntime {\n manifest: AiwgFortemiChunkManifest\n loader: AiwgChunkedIndexLoader\n maxCachedParts: number\n partCache: Map<string, AiwgFortemiChunkPart>\n detailLoader?: AiwgChunkedIndexDetailLoader\n maxCachedDetails: number\n detailCache: Map<string, AiwgFortemiRecord>\n maxCachedMatches: number\n // query+filter+weights key -> the full filtered/ranked entry set for that\n // query (offset/limit/sort/snippets independent). LRU-ordered; bounded by\n // maxCachedMatches (total entries). Lets pagination reuse a single scan.\n matchCache: Map<string, AiwgRankedEntry[]>\n}\n\nfunction chunkPartCacheKey(part: AiwgFortemiChunkPartRef): string {\n return `${part.offset}:${part.href}`\n}\n\nfunction clampMaxCachedParts(value: number | undefined): number {\n if (!hasPositiveInteger(value)) return 3\n return value\n}\n\nfunction clampMaxCachedDetails(value: number | undefined): number {\n if (!hasPositiveInteger(value)) return 32\n return value\n}\n\nfunction clampMaxCachedMatches(value: number | undefined): number {\n if (!hasPositiveInteger(value)) return 5000\n return value\n}\n\n// Stable key over the inputs that determine the filtered/ranked entry SET and\n// each entry's rank value — but not offset/limit/sort/snippets, which only shape\n// the page projected from a cached set. Caller-stable option objects (same field\n// order each page) hit the cache; a reordered object simply misses (still correct).\nfunction matchSetCacheKey(q: string, options: AiwgIndexQueryOptions): string {\n return JSON.stringify({\n q,\n types: options.types ?? null,\n facets: options.facets ?? null,\n tags: options.tags ?? null,\n concepts: options.concepts ?? null,\n privacy: options.privacy ?? null,\n rel: options.relationshipTargetId ?? null,\n searchProfile: options.searchProfile ?? 'default',\n weights: { ...DEFAULT_QUERY_WEIGHTS, ...options.weights },\n })\n}\n\nfunction cacheMatchEntries(runtime: AiwgChunkedIndexRuntime, key: string, entries: AiwgRankedEntry[]): void {\n runtime.matchCache.delete(key)\n runtime.matchCache.set(key, entries)\n let total = 0\n for (const set of runtime.matchCache.values()) total += set.length\n // Evict oldest sets until within budget, but always keep the just-inserted set\n // so paging a large result still benefits from the single scan.\n while (total > runtime.maxCachedMatches && runtime.matchCache.size > 1) {\n const oldest = runtime.matchCache.keys().next().value\n if (oldest === undefined || oldest === key) break\n total -= runtime.matchCache.get(oldest)?.length ?? 0\n runtime.matchCache.delete(oldest)\n }\n}\n\nfunction isDirectChunkBrowse(query: string, options: AiwgIndexQueryOptions): boolean {\n return query.trim() === ''\n && !options.rank\n && !options.snippets\n && !options.includeMatches\n && !options.types\n && !options.facets\n && !options.tags\n && !options.concepts\n && !options.privacy\n && !options.relationshipTargetId\n}\n\nfunction getPartsForRange(\n manifest: AiwgFortemiChunkManifest,\n offset: number,\n limit: number,\n): AiwgFortemiChunkPartRef[] {\n const end = offset + limit\n return manifest.parts.filter((part) => part.count > 0 && part.offset < end && part.offset + part.count > offset)\n}\n\nasync function loadChunkPart(\n runtime: AiwgChunkedIndexRuntime,\n part: AiwgFortemiChunkPartRef,\n): Promise<{ part: AiwgFortemiChunkPart; fetched: boolean }> {\n const key = chunkPartCacheKey(part)\n const cached = runtime.partCache.get(key)\n if (cached) {\n runtime.partCache.delete(key)\n runtime.partCache.set(key, cached)\n return { part: cached, fetched: false }\n }\n\n const parsed = assertAiwgFortemiChunkPart(await runtime.loader(part, runtime.manifest), part, runtime.manifest)\n runtime.partCache.set(key, parsed)\n while (runtime.partCache.size > runtime.maxCachedParts) {\n const oldest = runtime.partCache.keys().next().value\n if (oldest === undefined) break\n runtime.partCache.delete(oldest)\n }\n return { part: parsed, fetched: true }\n}\n\nasync function getChunkRecord(runtime: AiwgChunkedIndexRuntime, id: string): Promise<AiwgFortemiRecord> {\n const cached = runtime.detailCache.get(id)\n if (cached) {\n runtime.detailCache.delete(id)\n runtime.detailCache.set(id, cached)\n return cached\n }\n // Whole-record parts already in cache: serve without a detail fetch.\n if (!runtime.manifest.projection) {\n for (const part of runtime.partCache.values()) {\n const found = part.items.find((item) => item.id === id)\n if (found) return found\n }\n }\n if (!runtime.detailLoader) {\n throw new Error('No detailLoader configured to resolve record ' + id)\n }\n const raw = await runtime.detailLoader(id, runtime.manifest)\n const record = assertAiwgFortemiIndexExport({\n schema_version: 'aiwg.fortemi.index.export.v1',\n generated_at: runtime.manifest.generated_at,\n source: runtime.manifest.source,\n items: [raw],\n }).items[0]\n if (record.id !== id) {\n throw new Error('Detail record id mismatch: expected ' + id + ', got ' + record.id)\n }\n runtime.detailCache.set(id, record)\n while (runtime.detailCache.size > runtime.maxCachedDetails) {\n const oldest = runtime.detailCache.keys().next().value\n if (oldest === undefined) break\n runtime.detailCache.delete(oldest)\n }\n return record\n}\n\nfunction relationshipTypeFilter(options?: AiwgRelationshipQueryOptions): string | undefined {\n return options?.relationshipType ?? options?.type\n}\n\nfunction edgeFromRelationship(sourceId: string, relationship: AiwgFortemiRelationship): AiwgRelationshipEdgeSummary {\n return {\n source_id: sourceId,\n target_id: relationship.target_id,\n type: relationship.type,\n ...(relationship.source_path ? { source_path: relationship.source_path } : {}),\n ...(relationship.target_path ? { target_path: relationship.target_path } : {}),\n ...(relationship.direction ? { direction: relationship.direction } : {}),\n }\n}\n\nfunction relationshipMatches(edge: AiwgRelationshipEdgeSummary, options: AiwgRelationshipQueryOptions = {}): boolean {\n const type = relationshipTypeFilter(options)\n if (type && edge.type !== type) return false\n if (options.relationshipDirection && edge.direction !== options.relationshipDirection) return false\n if (options.sourceId && edge.source_id !== options.sourceId) return false\n if (options.targetId && edge.target_id !== options.targetId) return false\n if (options.endpointId && edge.source_id !== options.endpointId && edge.target_id !== options.endpointId) return false\n return true\n}\n\nfunction assertRelationshipDirectionAnchor(options: AiwgRelationshipQueryOptions): void {\n if (options.direction === 'out' && !options.sourceId) {\n throw new Error(\"relationship direction 'out' requires sourceId\")\n }\n if (options.direction === 'in' && !options.targetId) {\n throw new Error(\"relationship direction 'in' requires targetId\")\n }\n}\n\nfunction nodeSummary(item: AiwgFortemiProjectedRecord): AiwgRelationshipNodeSummary {\n return { id: item.id, type: item.type, title: recordTitle(item) }\n}\n\nfunction addNode(nodes: Map<string, AiwgRelationshipNodeSummary>, item: AiwgFortemiProjectedRecord | undefined) {\n if (item) nodes.set(item.id, nodeSummary(item))\n}\n\nfunction relationshipResultFromRecords(\n records: AiwgFortemiProjectedRecord[],\n options: AiwgRelationshipQueryOptions = {},\n): AiwgRelationshipTraversalResult {\n assertRelationshipDirectionAnchor(options)\n const byId = new Map(records.map((record) => [record.id, record]))\n const edges: AiwgRelationshipEdgeSummary[] = []\n for (const record of records) {\n for (const relationship of record.relationships ?? []) {\n const edge = edgeFromRelationship(record.id, relationship)\n if (!relationshipMatches(edge, options)) continue\n edges.push(edge)\n }\n }\n const sortedEdges = edges.sort((left, right) => (\n left.source_id.localeCompare(right.source_id)\n || left.target_id.localeCompare(right.target_id)\n || left.type.localeCompare(right.type)\n ))\n const limitedEdges = options.limit ? sortedEdges.slice(0, options.limit) : sortedEdges\n const nodes = new Map<string, AiwgRelationshipNodeSummary>()\n for (const edge of limitedEdges) {\n addNode(nodes, byId.get(edge.source_id))\n addNode(nodes, byId.get(edge.target_id))\n }\n return {\n nodes: [...nodes.values()].sort((left, right) => left.id.localeCompare(right.id)),\n edges: limitedEdges,\n complete: true,\n }\n}\n\nfunction neighborQueryOptions(id: string, options: AiwgRelationshipTraversalOptions = {}): AiwgRelationshipQueryOptions {\n const direction = options.direction ?? 'both'\n return {\n ...options,\n ...(direction === 'out' ? { sourceId: id } : {}),\n ...(direction === 'in' ? { targetId: id } : {}),\n ...(direction === 'both' ? { endpointId: id } : {}),\n }\n}\n\nfunction filterNeighborResult(id: string, result: AiwgRelationshipTraversalResult, options: AiwgRelationshipTraversalOptions = {}): AiwgRelationshipTraversalResult {\n const direction = options.direction ?? 'both'\n const edges = result.edges.filter((edge) => {\n if (direction === 'out') return edge.source_id === id\n if (direction === 'in') return edge.target_id === id\n return edge.source_id === id || edge.target_id === id\n })\n const ids = new Set<string>()\n for (const edge of edges) {\n ids.add(edge.source_id)\n ids.add(edge.target_id)\n }\n return {\n ...result,\n edges,\n nodes: result.nodes.filter((node) => ids.has(node.id)),\n }\n}\n\nasync function recordsFromChunkedRuntime(\n runtime: AiwgChunkedIndexRuntime,\n onProgress?: (progress: AiwgChunkedIndexProgress) => void,\n): Promise<{ records: AiwgFortemiRecord[]; scannedParts: number; fetchedParts: number }> {\n let scannedParts = 0\n let fetchedParts = 0\n const records: AiwgFortemiRecord[] = []\n for (const partRef of runtime.manifest.parts) {\n const loaded = await loadChunkPart(runtime, partRef)\n if (loaded.fetched) fetchedParts += 1\n scannedParts += 1\n onProgress?.({ phase: 'part', done: scannedParts, total: runtime.manifest.parts.length, href: partRef.href })\n for (const item of loaded.part.items) {\n records.push(item.relationships ? item : await getChunkRecord(runtime, item.id))\n }\n }\n return { records, scannedParts, fetchedParts }\n}\n\nasync function relationshipResultFromChunkedRuntime(\n runtime: AiwgChunkedIndexRuntime,\n options: AiwgRelationshipQueryOptions = {},\n): Promise<AiwgRelationshipTraversalResult> {\n const loaded = await recordsFromChunkedRuntime(runtime)\n return {\n ...relationshipResultFromRecords(loaded.records, options),\n scannedParts: loaded.scannedParts,\n fetchedParts: loaded.fetchedParts,\n }\n}\n\nasync function queryChunkedAiwgFortemiIndex(\n runtime: AiwgChunkedIndexRuntime,\n query = '',\n options: AiwgChunkedIndexQueryOptions = {},\n): Promise<AiwgChunkedIndexQueryResult> {\n const q = query.trim().toLowerCase()\n let scannedParts = 0\n let fetchedParts = 0\n\n if (isDirectChunkBrowse(query, options)) {\n const offset = options.offset ?? 0\n const limit = options.limit ?? runtime.manifest.total\n const parts = getPartsForRange(runtime.manifest, offset, limit)\n const items: AiwgFortemiRecord[] = []\n for (const partRef of parts) {\n const loaded = await loadChunkPart(runtime, partRef)\n if (loaded.fetched) fetchedParts += 1\n scannedParts += 1\n options.onProgress?.({ phase: 'part', done: scannedParts, total: parts.length, href: partRef.href })\n const start = Math.max(0, offset - partRef.offset)\n const end = Math.min(loaded.part.items.length, offset + limit - partRef.offset)\n items.push(...loaded.part.items.slice(start, end))\n }\n return {\n items,\n total: runtime.manifest.total,\n facets: runtime.manifest.facets ?? {},\n manifestTotal: runtime.manifest.total,\n scannedParts,\n fetchedParts,\n complete: true,\n }\n }\n\n // Reuse the filtered/ranked entry set across pages of the same query: the\n // expensive part scan is offset/limit/sort/snippet independent. A hit projects\n // a new page from cached entries without touching parts (scanned/fetched = 0).\n const matchKey = matchSetCacheKey(q, options)\n const cached = runtime.matchCache.get(matchKey)\n if (cached) {\n runtime.matchCache.delete(matchKey)\n runtime.matchCache.set(matchKey, cached)\n return {\n ...createQueryResultFromRankedEntries(cached, q, options),\n manifestTotal: runtime.manifest.total,\n scannedParts: 0,\n fetchedParts: 0,\n complete: true,\n }\n }\n\n const entries: AiwgRankedEntry[] = []\n for (const partRef of runtime.manifest.parts) {\n const loaded = await loadChunkPart(runtime, partRef)\n if (loaded.fetched) fetchedParts += 1\n scannedParts += 1\n options.onProgress?.({ phase: 'part', done: scannedParts, total: runtime.manifest.parts.length, href: partRef.href })\n entries.push(...createRankedEntries(loaded.part.items, q, options, partRef.offset))\n options.onProgress?.({ phase: 'query', done: scannedParts, total: runtime.manifest.parts.length, href: partRef.href })\n }\n cacheMatchEntries(runtime, matchKey, entries)\n\n return {\n ...createQueryResultFromRankedEntries(entries, q, options),\n manifestTotal: runtime.manifest.total,\n scannedParts,\n fetchedParts,\n complete: true,\n }\n}\n\nexport function createAiwgReviewDecisionExport(\n // Only the export schema_version is needed — so this works in chunked mode\n // (where no whole index is loaded) by passing a minimal source. See #178.\n source: Pick<AiwgFortemiIndexExport, 'schema_version'>,\n decisions: AiwgReviewDecision[],\n generatedAt = new Date().toISOString(),\n): AiwgReviewDecisionExport {\n return {\n schema_version: 'aiwg.fortemi.review-decisions.v1',\n generated_at: generatedAt,\n source_export_schema_version: source.schema_version,\n decisions: [...decisions].sort((left, right) => left.item_id.localeCompare(right.item_id)),\n }\n}\n\nexport function createAiwgIndexController(initialIndex?: AiwgFortemiIndexExport): AiwgIndexController {\n let index: AiwgFortemiIndexExport | null = initialIndex ?? null\n let chunked: AiwgChunkedIndexRuntime | null = null\n let data: AiwgIndexQueryResult | null = null\n let error: Error | null = null\n let reviewDecisions: AiwgReviewDecision[] = []\n const listeners = new Set<AiwgIndexControllerListener>()\n\n const snapshot = (): AiwgIndexControllerSnapshot => ({\n index,\n chunked: chunked\n ? {\n manifest: chunked.manifest,\n cachedParts: chunked.partCache.size,\n maxCachedParts: chunked.maxCachedParts,\n }\n : null,\n data,\n error,\n reviewDecisions: [...reviewDecisions],\n })\n const notify = () => {\n const current = snapshot()\n for (const listener of listeners) listener(current)\n }\n const requireIndex = (): AiwgFortemiIndexExport => {\n if (!index) throw new Error('No AIWG index export loaded')\n return index\n }\n\n return {\n loadIndex(value: unknown): AiwgFortemiIndexExport {\n try {\n const parsed = assertAiwgFortemiIndexExport(value)\n index = parsed\n chunked = null\n data = null\n reviewDecisions = []\n error = null\n notify()\n return parsed\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n loadChunkedIndex(\n manifest: unknown,\n loader: AiwgChunkedIndexLoader,\n options: AiwgChunkedIndexLoadOptions = {},\n ): AiwgFortemiChunkManifest {\n try {\n const parsed = assertAiwgFortemiChunkManifest(manifest)\n index = null\n chunked = {\n manifest: parsed,\n loader,\n maxCachedParts: clampMaxCachedParts(options.maxCachedParts),\n partCache: new Map(),\n detailLoader: options.detailLoader,\n maxCachedDetails: clampMaxCachedDetails(options.maxCachedDetails),\n detailCache: new Map(),\n maxCachedMatches: clampMaxCachedMatches(options.maxCachedMatches),\n matchCache: new Map(),\n }\n data = null\n reviewDecisions = []\n error = null\n notify()\n return parsed\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n getIndex(): AiwgFortemiIndexExport | null {\n return index\n },\n getChunkedManifest(): AiwgFortemiChunkManifest | null {\n return chunked?.manifest ?? null\n },\n getSnapshot(): AiwgIndexControllerSnapshot {\n return snapshot()\n },\n query(query = '', options?: AiwgIndexQueryOptions): AiwgIndexQueryResult {\n const result = queryAiwgFortemiIndex(requireIndex(), query, options)\n data = result\n error = null\n notify()\n return result\n },\n async queryChunked(query = '', options?: AiwgChunkedIndexQueryOptions): Promise<AiwgChunkedIndexQueryResult> {\n if (!chunked) throw new Error('No AIWG chunked index manifest loaded')\n try {\n const result = await queryChunkedAiwgFortemiIndex(chunked, query, options)\n data = result\n error = null\n notify()\n return result\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n async getRecord(id: string): Promise<AiwgFortemiRecord> {\n if (chunked) {\n try {\n return await getChunkRecord(chunked, id)\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n }\n const found = requireIndex().items.find((item) => item.id === id)\n if (!found) throw new Error('Record not found: ' + id)\n return found\n },\n async neighbors(id: string, options?: AiwgRelationshipTraversalOptions): Promise<AiwgRelationshipTraversalResult> {\n try {\n const queryOptions = neighborQueryOptions(id, options)\n const result = chunked\n ? await relationshipResultFromChunkedRuntime(chunked, queryOptions)\n : relationshipResultFromRecords(requireIndex().items, queryOptions)\n return filterNeighborResult(id, result, options)\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n async relationshipQuery(options?: AiwgRelationshipQueryOptions): Promise<AiwgRelationshipTraversalResult> {\n try {\n return chunked\n ? await relationshipResultFromChunkedRuntime(chunked, options)\n : relationshipResultFromRecords(requireIndex().items, options)\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n async relationshipSet(options: AiwgRelationshipSetOptions): Promise<AiwgRelationshipSetResult> {\n const [left, right] = await Promise.all([\n this.neighbors(options.a, options),\n this.neighbors(options.b, options),\n ])\n const leftIds = new Set(left.nodes.map((node) => node.id).filter((id) => id !== options.a))\n const rightIds = new Set(right.nodes.map((node) => node.id).filter((id) => id !== options.b))\n let ids: string[]\n if (options.op === 'intersection') ids = [...leftIds].filter((id) => rightIds.has(id))\n else if (options.op === 'difference') ids = [...leftIds].filter((id) => !rightIds.has(id))\n else ids = [...new Set([...leftIds, ...rightIds])]\n return { op: options.op, ids: ids.sort() }\n },\n clearChunkCache(): void {\n chunked?.partCache.clear()\n chunked?.detailCache.clear()\n chunked?.matchCache.clear()\n error = null\n notify()\n },\n toCommunityGraph(options?: AiwgIndexGraphOptions) {\n return aiwgFortemiIndexToCommunityGraph(requireIndex(), options)\n },\n async toCommunityGraphChunked(options?: AiwgIndexGraphOptions & { onProgress?: (progress: AiwgChunkedIndexProgress) => void }) {\n if (!chunked) return aiwgFortemiIndexToCommunityGraph(requireIndex(), options)\n const loaded = await recordsFromChunkedRuntime(chunked, options?.onProgress)\n return aiwgFortemiIndexToCommunityGraph({\n schema_version: 'aiwg.fortemi.index.export.v1',\n generated_at: chunked.manifest.generated_at,\n source: chunked.manifest.source,\n items: loaded.records,\n }, options)\n },\n setReviewDecision(input: AiwgReviewInput): AiwgReviewDecision {\n const decision: AiwgReviewDecision = {\n ...input,\n updated_at: new Date().toISOString(),\n }\n reviewDecisions = [\n ...reviewDecisions.filter((item) => item.item_id !== decision.item_id),\n decision,\n ].sort((left, right) => left.item_id.localeCompare(right.item_id))\n error = null\n notify()\n return decision\n },\n clearReviewDecision(itemId: string): void {\n reviewDecisions = reviewDecisions.filter((item) => item.item_id !== itemId)\n error = null\n notify()\n },\n createReviewDecisionExport(generatedAt?: string): AiwgReviewDecisionExport {\n // The review-decisions export only needs the export schema_version, not the\n // items — so it works in chunked mode by synthesizing a minimal source (#178).\n const source: Pick<AiwgFortemiIndexExport, 'schema_version'> | null =\n index ??\n (chunked\n ? { schema_version: chunked.manifest.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1' }\n : null)\n if (!source) throw new Error('No AIWG index export or chunked manifest loaded')\n return createAiwgReviewDecisionExport(source, reviewDecisions, generatedAt)\n },\n subscribe(listener: AiwgIndexControllerListener): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n }\n}\n\nexport function aiwgFortemiIndexToCommunityGraph(\n index: AiwgFortemiIndexExport,\n options: AiwgIndexGraphOptions = {},\n) {\n const ids = new Set(index.items.map((item) => item.id))\n const relationshipWeights = options.relationshipWeights ?? Object.create(null)\n const edgeCounts = new Map<string, { source: string; target: string; kind: string; weight: number }>()\n\n for (const item of index.items) {\n for (const relationship of item.relationships) {\n if (!ids.has(relationship.target_id) && !options.includeDanglingRelationships) continue\n const kind = relationship.type\n const configuredWeight = Object.prototype.hasOwnProperty.call(relationshipWeights, kind)\n ? relationshipWeights[kind]\n : undefined\n const baseWeight = typeof configuredWeight === 'number' && Number.isFinite(configuredWeight)\n ? configuredWeight\n : 1\n const key = `${item.id}\\u0000${relationship.target_id}\\u0000${kind}`\n const existing = edgeCounts.get(key)\n if (existing) existing.weight += baseWeight\n else edgeCounts.set(key, { source: item.id, target: relationship.target_id, kind, weight: baseWeight })\n }\n }\n\n const communities = new Map<string, string[]>()\n for (const item of index.items) {\n const communityIds = communityIdsFor(item, options)\n for (const communityId of communityIds) {\n const nodes = communities.get(communityId) ?? []\n nodes.push(item.id)\n communities.set(communityId, nodes)\n }\n }\n\n return {\n nodes: index.items.map((item) => ({ id: item.id })),\n edges: Array.from(edgeCounts.values()).sort((left, right) => (\n left.source.localeCompare(right.source)\n || left.target.localeCompare(right.target)\n || left.kind.localeCompare(right.kind)\n )),\n communities: Array.from(communities.entries())\n .map(([id, nodes]) => ({ id, nodes: [...new Set(nodes)].sort() }))\n .sort((left, right) => left.id.localeCompare(right.id)),\n }\n}\n\nfunction communityIdsFor(item: AiwgFortemiRecord, options: AiwgIndexGraphOptions): string[] {\n if (options.communityFacet) {\n const values = item.facets[options.communityFacet] ?? []\n if (values.length > 0) return values.map((value) => `${options.communityFacet}:${value}`)\n }\n if (options.communityTagPrefix) {\n const prefix = options.communityTagPrefix\n const tags = item.tags.filter((tag) => tag.startsWith(prefix))\n if (tags.length > 0) return tags\n }\n if (item.concepts.length > 0) return item.concepts.map((concept) => `concept:${concept}`)\n return [`type:${item.type}`]\n}\n\nconst AIWG_SHARD_UUID_NAMESPACE = '7ab5d1f8-29d2-5e35-9e2f-3a45de171a9e'\nconst shardEncoder = new TextEncoder()\nconst shardDecoder = new TextDecoder()\n\nfunction aiwgShardUuid(kind: string, id: string): string {\n return uuidv5(`${kind}:${id}`, AIWG_SHARD_UUID_NAMESPACE)\n}\n\nfunction aiwgShardTimestamp(value: string | undefined, fallback: string): string {\n if (!value || Number.isNaN(Date.parse(value))) return fallback\n return new Date(value).toISOString()\n}\n\nfunction aiwgRecordTitle(record: AiwgFortemiRecord): string {\n return record.title ?? record.search?.title ?? record.search?.name ?? record.id\n}\n\nfunction aiwgRecordContent(record: AiwgFortemiRecord): string {\n if (record.text) return record.text\n if (record.search?.body) return record.search.body\n const chunks = record.chunks\n ?.map((chunk) => chunk.text ?? chunk.body ?? chunk.summary ?? '')\n .filter(Boolean)\n if (chunks?.length) return chunks.join('\\n\\n')\n return record.search?.summary ?? ''\n}\n\nfunction aiwgShardMetadata(\n index: AiwgFortemiIndexExport,\n record: AiwgFortemiRecord,\n): Record<string, unknown> {\n return {\n aiwg_fortemi_index: {\n envelope: {\n schema_version: index.schema_version,\n generated_at: index.generated_at,\n source: index.source,\n ...(index.compatibility ? { compatibility: index.compatibility } : {}),\n },\n record,\n },\n }\n}\n\nfunction encodeJsonLines(values: unknown[]): Uint8Array {\n return shardEncoder.encode(values.map((value) => JSON.stringify(value)).join('\\n'))\n}\n\n/**\n * Convert the static AIWG/Fortemi v2 index contract into a portable Knowledge\n * Shard. Every note retains the complete source envelope and record in metadata,\n * so the native note/link/SKOS/provenance projections are reversible.\n */\nexport async function aiwgFortemiIndexToKnowledgeShard(\n index: AiwgFortemiIndexExport,\n options: AiwgKnowledgeShardOptions = {},\n): Promise<Uint8Array> {\n const validation = validateAiwgFortemiIndexExport(index)\n if (!validation.valid) {\n throw new Error(`Invalid AIWG Fortemi index export:\\n${validation.errors.join('\\n')}`)\n }\n if (index.schema_version !== 'aiwg.fortemi.index.export.v2') {\n throw new Error('Knowledge Shard conversion requires aiwg.fortemi.index.export.v2')\n }\n\n const createdAt = aiwgShardTimestamp(options.createdAt ?? index.generated_at, new Date().toISOString())\n const noteIds = new Map(index.items.map((record) => [record.id, aiwgShardUuid('record', record.id)]))\n const notes: ShardNote[] = index.items.map((record) => ({\n id: noteIds.get(record.id)!,\n title: aiwgRecordTitle(record),\n original_content: aiwgRecordContent(record),\n revised_content: null,\n metadata: aiwgShardMetadata(index, record),\n format: 'markdown',\n source: 'aiwg-index',\n starred: false,\n archived: false,\n tags: [...new Set(record.tags)].sort(),\n created_at: aiwgShardTimestamp(record.source.updated_at ?? record.updated_at, createdAt),\n updated_at: aiwgShardTimestamp(record.updated_at, createdAt),\n deleted_at: null,\n }))\n\n const links: ShardLink[] = []\n for (const record of index.items) {\n for (const [position, relationship] of record.relationships.entries()) {\n const targetNoteId = noteIds.get(relationship.target_id) ?? null\n links.push({\n id: aiwgShardUuid(\n 'relationship',\n `${record.id}\\u0000${position}\\u0000${relationship.type}\\u0000${relationship.target_id}`,\n ),\n from_note_id: noteIds.get(record.id)!,\n to_note_id: targetNoteId,\n to_url: targetNoteId ? null : `aiwg://record/${encodeURIComponent(relationship.target_id)}`,\n kind: relationship.type,\n score: relationship.confidence ?? null,\n created_at: aiwgShardTimestamp(record.updated_at, createdAt),\n metadata: {\n aiwg_fortemi_index: {\n source_record_id: record.id,\n target_record_id: relationship.target_id,\n relationship,\n },\n },\n })\n }\n }\n\n const defaultScheme = index.source.graph ?? index.source.repo\n const concepts = new Map<string, { concept: AiwgFortemiSkosConcept; scheme: string }>()\n for (const record of index.items) {\n for (const conceptId of record.concepts) {\n concepts.set(conceptId, {\n concept: { id: conceptId, prefLabel: conceptId },\n scheme: defaultScheme,\n })\n }\n for (const concept of record.skos_concepts ?? []) {\n concepts.set(concept.id, { concept, scheme: concept.scheme ?? defaultScheme })\n }\n for (const relation of record.skos_relations ?? []) {\n if (!concepts.has(relation.source_id)) {\n concepts.set(relation.source_id, {\n concept: { id: relation.source_id, prefLabel: relation.source_id },\n scheme: defaultScheme,\n })\n }\n if (!concepts.has(relation.target_id)) {\n concepts.set(relation.target_id, {\n concept: { id: relation.target_id, prefLabel: relation.target_id },\n scheme: defaultScheme,\n })\n }\n }\n }\n\n const schemeNames = [...new Set([...concepts.values()].map(({ scheme }) => scheme))].sort()\n const schemes: ShardSkosScheme[] = schemeNames.map((scheme) => ({\n id: aiwgShardUuid('skos-scheme', scheme),\n title: scheme,\n description: `SKOS scheme projected from ${index.source.repo}`,\n created_at: createdAt,\n updated_at: createdAt,\n }))\n const shardConcepts: ShardSkosConcept[] = [...concepts.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([id, { concept, scheme }]) => ({\n id: aiwgShardUuid('skos-concept', id),\n scheme_id: aiwgShardUuid('skos-scheme', scheme),\n pref_label: concept.prefLabel,\n alt_labels: concept.altLabels ?? [],\n definition: concept.definition ?? null,\n created_at: createdAt,\n updated_at: createdAt,\n }))\n\n const noteSkosTags: ShardNoteSkosTag[] = []\n const skosRelations: ShardSkosRelation[] = []\n const provenanceEdges: ShardProvenanceEdge[] = []\n for (const record of index.items) {\n const recordConceptIds = new Set([\n ...record.concepts,\n ...(record.skos_concepts ?? []).map((concept) => concept.id),\n ])\n for (const conceptId of [...recordConceptIds].sort()) {\n noteSkosTags.push({\n id: aiwgShardUuid('note-skos-tag', `${record.id}\\u0000${conceptId}`),\n note_id: noteIds.get(record.id)!,\n concept_id: aiwgShardUuid('skos-concept', conceptId),\n created_at: createdAt,\n })\n }\n for (const [position, relation] of (record.skos_relations ?? []).entries()) {\n const relationType = relation.type === 'broader' || relation.type === 'narrower'\n ? relation.type\n : 'related'\n skosRelations.push({\n id: aiwgShardUuid(\n 'skos-relation',\n `${record.id}\\u0000${position}\\u0000${relation.source_id}\\u0000${relation.type}\\u0000${relation.target_id}`,\n ),\n source_concept_id: aiwgShardUuid('skos-concept', relation.source_id),\n target_concept_id: aiwgShardUuid('skos-concept', relation.target_id),\n relation_type: relationType,\n created_at: createdAt,\n })\n }\n for (const [position, provenance] of record.provenance.entries()) {\n provenanceEdges.push({\n id: aiwgShardUuid('provenance', `${record.id}\\u0000field\\u0000${position}`),\n entity_type: 'note',\n entity_id: noteIds.get(record.id)!,\n activity: 'source',\n agent: provenance.source,\n started_at: aiwgShardTimestamp(record.updated_at, createdAt),\n ended_at: null,\n attributes: { aiwg_fortemi_index: { provenance } },\n })\n }\n for (const [position, event] of (record.provenance_events ?? []).entries()) {\n provenanceEdges.push({\n id: aiwgShardUuid('provenance', event.id ?? `${record.id}\\u0000event\\u0000${position}`),\n entity_type: 'note',\n entity_id: noteIds.get(record.id)!,\n activity: event.activity,\n agent: event.agent ?? 'aiwg-index',\n started_at: aiwgShardTimestamp(event.started_at, createdAt),\n ended_at: event.ended_at ? aiwgShardTimestamp(event.ended_at, createdAt) : null,\n attributes: { aiwg_fortemi_index: { event } },\n })\n }\n }\n\n const files = new Map<string, Uint8Array>()\n const components: ShardComponent[] = ['notes', 'tags']\n const counts: ShardManifest['counts'] = {\n notes: notes.length,\n tags: [...new Set(notes.flatMap((note) => note.tags))].length,\n }\n files.set('notes.jsonl', encodeJsonLines(notes))\n files.set('tags.json', shardEncoder.encode(JSON.stringify(\n [...new Set(notes.flatMap((note) => note.tags))]\n .sort()\n .map((name) => ({ name, created_at: createdAt })),\n )))\n\n const addComponent = (\n component: ShardComponent,\n filename: string,\n values: unknown[],\n jsonLines = true,\n ) => {\n if (values.length === 0) return\n components.push(component)\n counts[component] = values.length\n files.set(filename, jsonLines ? encodeJsonLines(values) : shardEncoder.encode(JSON.stringify(values)))\n }\n addComponent('links', 'links.jsonl', links)\n if (options.includeNativeRichComponents) {\n addComponent('skos_schemes', 'skos_schemes.json', schemes, false)\n addComponent('skos_concepts', 'skos_concepts.json', shardConcepts, false)\n addComponent('skos_relations', 'skos_relations.jsonl', skosRelations)\n addComponent('note_skos_tags', 'note_skos_tags.jsonl', noteSkosTags)\n addComponent('provenance_edges', 'provenance_edges.jsonl', provenanceEdges)\n }\n\n const checksums: Record<string, string> = {}\n for (const [filename, bytes] of files) checksums[filename] = await shardSha256Hex(bytes)\n const manifest: ShardManifest = {\n version: CURRENT_SHARD_VERSION,\n matric_version: options.matricVersion ?? 'fortemi-core-aiwg-index',\n format: SHARD_FORMAT,\n created_at: createdAt,\n components,\n counts,\n checksums,\n min_reader_version: CURRENT_SHARD_VERSION,\n migrated_from: null,\n migration_history: [],\n }\n files.set('manifest.json', shardEncoder.encode(JSON.stringify(manifest, null, 2)))\n return packTarGz(files)\n}\n\n/**\n * Recover the exact AIWG index envelope and records embedded by\n * {@link aiwgFortemiIndexToKnowledgeShard}.\n */\nexport function aiwgFortemiIndexFromKnowledgeShard(bytes: Uint8Array): AiwgFortemiIndexExport {\n const files = unpackTarGz(bytes)\n const noteBytes = files.get('notes.jsonl')\n const notes = (noteBytes ? shardDecoder.decode(noteBytes) : '')\n .split('\\n')\n .filter(Boolean)\n .map((line) => JSON.parse(line) as ShardNote)\n if (notes.length === 0) throw new Error('Knowledge Shard contains no AIWG index notes')\n\n let envelope: Record<string, unknown> | undefined\n const items: AiwgFortemiRecord[] = []\n for (const note of notes) {\n const metadata = note.metadata?.aiwg_fortemi_index\n if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n throw new Error(`Knowledge Shard note ${note.id} has no AIWG index metadata`)\n }\n const value = metadata as Record<string, unknown>\n envelope ??= value.envelope as Record<string, unknown>\n items.push(value.record as AiwgFortemiRecord)\n }\n const restored = {\n ...envelope,\n items: items.sort((left, right) => left.id.localeCompare(right.id)),\n } as unknown as AiwgFortemiIndexExport\n const validation = validateAiwgFortemiIndexExport(restored)\n if (!validation.valid) {\n throw new Error(`Knowledge Shard contains invalid AIWG index metadata:\\n${validation.errors.join('\\n')}`)\n }\n return restored\n}\n"]}
1
+ {"version":3,"sources":["../src/shard/types.ts","../src/shard/checksum.ts","../schemas/knowledge-shard/1.0.0/core-v1/manifest.schema.json","../schemas/knowledge-shard/1.0.0/core-v1/note.schema.json","../schemas/knowledge-shard/1.0.0/core-v1/collection.schema.json","../schemas/knowledge-shard/1.0.0/core-v1/tag.schema.json","../schemas/knowledge-shard/1.0.0/core-v1/template.schema.json","../schemas/knowledge-shard/1.0.0/core-v1/link.schema.json","../schemas/knowledge-shard/1.1.0/core-v1/manifest.schema.json","../schemas/knowledge-shard/1.2.0/core-v1/manifest.schema.json","../schemas/knowledge-shard/1.2.0/core-v1/note.schema.json","../schemas/knowledge-shard/1.2.0/core-v1/collection.schema.json","../schemas/knowledge-shard/1.2.0/core-v1/tag.schema.json","../schemas/knowledge-shard/1.2.0/core-v1/template.schema.json","../schemas/knowledge-shard/1.2.0/core-v1/link.schema.json","../src/shard/shard-tar.ts","../src/shard/schema-validator.ts","../src/aiwg-index.ts"],"names":["CURRENT_SHARD_VERSION","SHARD_FORMAT","sha256Hex","data","buf","hashBuffer","hashArray","b","validateChecksums","checksums","files","failures","filename","expectedHash","fileData","manifest_schema_default","note_schema_default","collection_schema_default","tag_schema_default","template_schema_default","link_schema_default","BLOCK_SIZE","USTAR_MAGIC","writeString","offset","str","len","writeOctal","value","computeHeaderChecksum","header","sum","i","createTarHeader","size","csStr","encodeTar","blocks","remainder","totalLen","result","readString","end","limit","readOctal","isZeroBlock","decodeTar","tarData","name","typeflag","dataBlocks","packTarGz","opts","cap","DEFAULT_MAX_DECOMPRESSED_BYTES","gzipSync","unpackTarGz","declaredSize","gunzipSync","decoder","CORE_V1_COMPONENT_FILES","CORE_V1_SCHEMAS","coreAjvInstance","coreValidators","addCanonicalFormats","ajv","getCoreAjv","Ajv2020","registered","bundle","schema","coreSchemaVersion","coreValidatorFor","version","key","cached","validator","formatErrors","errors","error","parseJsonArray","bytes","path","parseJsonl","text","records","index","line","unpackShardFiles","input","parseRecords","encoding","coreReferenceErrors","notes","collections","tags","templates","links","noteIds","record","collectionIds","tagNames","collection","note","tag","template","link","validateCoreV1Structure","manifest","schemaVersion","manifestValidator","components","expectedFiles","component","spec","parsed","expectedCount","validateCoreV1ShardArchive","manifestBytes","checksumResult","AIWG_SCAN_REQUIRED_FIELDS","isPrivacyExcluded","options","privacy","isPrivacyClassification","filterAiwgRecordsByPrivacy","REQUIRED_RECORD_FIELDS","DEFAULT_QUERY_WEIGHTS","hasString","pushFacet","counts","bucket","hasNonNegativeInteger","hasPositiveInteger","isFacetCounts","count","isPlainRecord","isOptionalStringArray","item","isSupportedIndexSchemaVersion","isSupportedRecordSchemaVersion","validateOptionalRichMetadata","conceptIndex","concept","relationIndex","relation","eventIndex","event","relationshipIndex","relationship","chunkIndex","chunk","embeddingIndex","embedding","vector","entry","isProvenanceConfidence","validateProvenanceItems","provIndex","prov","at","V2_ONLY_RECORD_FIELDS","V2_ONLY_SOURCE_FIELDS","V2_ONLY_RELATIONSHIP_FIELDS","forbidV2FieldsOnV1Record","bag","v2msg","field","src","relIndex","rel","relBag","validateAiwgFortemiIndexExport","ids","previousId","items","assertAiwgFortemiIndexExport","validateAiwgFortemiChunkManifest","present","expectedOffset","parts","part","assertAiwgFortemiChunkManifest","validateProjectedRecordShape","validateProjectedRecords","sourceSchemaVersion","expectedRecordVersion","validateAiwgFortemiChunkPart","partRef","validation","assertAiwgFortemiChunkPart","ALLOWED_AIWG_FETCH_SCHEMES","tryParseUrl","resolveAiwgFetchUrl","href","baseUrl","absolute","base","resolved","createAiwgFetchChunkLoader","response","encodeAiwgDetailId","id","binary","byte","aiwgDetailHrefForId","detail","createAiwgFetchDetailLoader","relative","getAiwgFortemiFacets","values","recordTitle","recordText","extractedText","binarySourceText","source","defaultEmbeddingInput","granularity","title","generatedAtString","SHA256_K","rotr","bits","bitLength","padded","view","h0","h1","h2","h3","h4","h5","h6","h7","w","s0","s1","a","c","d","e","f","g","h","ch","temp1","maj","temp2","computeAiwgIndexHash","buildAiwgStaticEmbeddingSet","embeddings","embeddingSet","assertAiwgStaticEmbeddingSet","recordSearchValues","search","buildAiwgChunkedIndex","partSize","projection","idEncoding","detailHref","pad","project","slim","partRefs","partIndex","slice","includesAll","actual","expected","actualSet","matchesFacetFilters","filters","queryMatches","q","matches","DISCOVERY_STOPWORDS","normalizeDiscoveryName","discoveryTokens","token","facetValues","names","addDiscoveryMatch","match","existing","damerauLevenshteinAtMostOne","left","right","firstDiff","diffCount","shorter","longer","shorterIndex","longerIndex","edits","nearDiscoveryNameMatch","query","queryParts","nameParts","target","lowerValues","discoveryMatches","tokens","lower","rawLower","idParts","triggers","capabilities","sourceValues","summary","type","useMultiToken","minHits","overlapOK","hits","addInfo","addScore","score","scoreText","reason","exactScore","overlapScore","weight","exactBonus","normalized","trigger","capability","rankMatches","weights","total","clipSnippet","maxLength","normalizedLength","context","start","prefix","suffix","createSnippet","textMatch","titleMatch","firstMatch","createRankedEntries","ordinalBase","discoveryOptions","profile","ordinal","sortRankedEntries","entries","rank","createQueryResultFromRankedEntries","ranked","page","snippetLength","queryAiwgFortemiIndex","cosineSimilarity","dot","leftMag","rightMag","l","r","validateAiwgStaticEmbeddingSet","number","queryAiwgSemanticIndex","queryEmbedding","byId","queryAiwgHybridIndex","lexicalOptions","lexical","semantic","lexicalWeight","semanticWeight","lexicalScores","maxLexical","embeddingById","semanticScores","candidate","DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS","findAiwgStaticDuplicatePairs","threshold","maxEmbeddings","pairs","leftIndex","rightIndex","leftEmbedding","rightEmbedding","chunkPartCacheKey","clampMaxCachedParts","clampMaxCachedDetails","clampMaxCachedMatches","matchSetCacheKey","cacheMatchEntries","runtime","set","oldest","isDirectChunkBrowse","getPartsForRange","loadChunkPart","getChunkRecord","found","raw","relationshipTypeFilter","edgeFromRelationship","sourceId","relationshipMatches","edge","assertRelationshipDirectionAnchor","nodeSummary","addNode","nodes","relationshipResultFromRecords","edges","sortedEdges","limitedEdges","neighborQueryOptions","direction","filterNeighborResult","node","recordsFromChunkedRuntime","onProgress","scannedParts","fetchedParts","loaded","relationshipResultFromChunkedRuntime","queryChunkedAiwgFortemiIndex","matchKey","createAiwgReviewDecisionExport","decisions","generatedAt","createAiwgIndexController","initialIndex","chunked","reviewDecisions","listeners","snapshot","notify","current","listener","requireIndex","err","loader","queryOptions","leftIds","rightIds","aiwgFortemiIndexToCommunityGraph","decision","itemId","relationshipWeights","edgeCounts","kind","configuredWeight","baseWeight","communities","communityIds","communityIdsFor","communityId","AIWG_SHARD_UUID_NAMESPACE","shardEncoder","shardDecoder","aiwgShardUuid","uuidv5","aiwgShardTimestamp","fallback","aiwgRecordTitle","aiwgRecordContent","chunks","aiwgShardMetadata","encodeJsonLines","aiwgFortemiIndexToKnowledgeShard","createdAt","content","position","targetNoteId","jsonLines","contractValidation","aiwgFortemiIndexFromKnowledgeShard","noteBytes","envelope","metadata","restored"],"mappings":"gGAeO,IAAMA,CAAAA,CAAwB,OAAA,CACxBC,EAAAA,CAAe,cAAA,CCP5B,eAAsBC,EAAAA,CAAUC,CAAAA,CAAmC,CACjE,IAAMC,EAAM,I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AC9C,CACA,IAAMic,CAAAA,CAAW,CACf,GAAGF,CAAAA,CACH,KAAA,CAAO5S,EAAM,IAAA,CAAK,CAAC8G,EAAMC,CAAAA,GAAUD,CAAAA,CAAK,GAAG,aAAA,CAAcC,CAAAA,CAAM,EAAE,CAAC,CACpE,EACMjG,CAAAA,CAAajB,CAAAA,CAA+BiT,CAAQ,CAAA,CAC1D,GAAI,CAAChS,CAAAA,CAAW,KAAA,CACd,MAAM,IAAI,KAAA,CAAM,CAAA;AAAA,EAA0DA,CAAAA,CAAW,OAAO,IAAA,CAAK;AAAA,CAAI,CAAC,CAAA,CAAE,CAAA,CAE1G,OAAOgS,CACT","file":"aiwg-index.js","sourcesContent":["/**\n * Shard format types — matches the fortemi server matric-shard specification.\n *\n * A shard is a gzip-compressed tar archive (.shard) containing serialized\n * knowledge data with a manifest for integrity verification.\n *\n * @implements @.aiwg/adrs/ADR-011-shard-server-conformance-and-version-negotiation.md\n * @schema @packages/core/schemas/knowledge-shard.schema.receipt.json\n * @created 2026-07-17\n * @agent Codex\n */\n\nimport type { BlobStore } from '../blob-store.js'\nimport type { ShardTrustStore } from './shard-signature.js'\n\nexport const CURRENT_SHARD_VERSION = '1.2.0'\nexport const SHARD_FORMAT = 'matric-shard'\n\nfunction parseVersion(value: string): number[] {\n return value.split('.').map((segment) => {\n const match = segment.match(/^\\d+/)\n return match ? Number.parseInt(match[0], 10) : 0\n })\n}\n\nexport function compareShardVersions(left: string, right: string): number {\n const leftParts = parseVersion(left)\n const rightParts = parseVersion(right)\n const length = Math.max(leftParts.length, rightParts.length)\n for (let index = 0; index < length; index += 1) {\n const leftValue = leftParts[index] ?? 0\n const rightValue = rightParts[index] ?? 0\n if (leftValue !== rightValue) return leftValue > rightValue ? 1 : -1\n }\n return 0\n}\n\n/** Components that can appear in a shard archive. */\nexport type ShardComponent =\n | 'notes'\n | 'collections'\n | 'tags'\n | 'templates'\n | 'links'\n | 'note_originals'\n | 'note_original_history'\n | 'note_revised_current'\n | 'note_revisions'\n | 'embedding_sets'\n | 'embedding_configs'\n | 'embedding_set_members'\n | 'embeddings'\n | 'provenance_activities'\n | 'named_locations'\n | 'provenance_locations'\n | 'provenance_devices'\n | 'provenance_records'\n | 'skos_schemes'\n | 'skos_concepts'\n | 'skos_labels'\n | 'skos_notes'\n | 'skos_relations'\n | 'skos_mapping_relations'\n | 'skos_scheme_memberships'\n | 'note_skos_tags'\n | 'skos_collections'\n | 'skos_collection_members'\n | 'provenance_edges'\n | 'community_assignments'\n | 'communities'\n | 'graph_edges'\n | 'graph_sources'\n\nexport type KnowledgeShardProfile = 'core-v1' | 'full-v1' | 'record-v1'\nexport type ShardBackend = 'pglite' | 'record-store'\nexport type ShardOperation = 'export' | 'import'\nexport type ShardAuthorityStatus =\n | 'supported'\n | 'candidate'\n | 'reserved'\n | 'unknown'\n | 'unprofiled'\n\nexport interface ShardProfileRegistryEntry {\n profile: KnowledgeShardProfile\n authority_status: 'supported' | 'candidate' | 'reserved'\n components: ShardComponent[]\n}\n\nexport interface ShardLossEntry {\n code: string\n message: string\n component?: ShardComponent\n count?: number\n}\n\nexport interface ShardCapabilityReport {\n schema_version: 'fortemi.shard.capability-report.v1'\n backend: ShardBackend\n operation: ShardOperation\n requested_profile: string | null\n authority_status: ShardAuthorityStatus\n backend_supported: boolean\n portable: boolean\n authority: {\n repository: string\n commit: string\n contract_sha256: string\n contract_revision: string\n schema_version: string\n schema_bundle_sha256: string\n }\n advertised_profiles: KnowledgeShardProfile[]\n supported_components: ShardComponent[]\n declared_components: ShardComponent[]\n unsupported_components: ShardComponent[]\n omitted_components: ShardComponent[]\n losses: ShardLossEntry[]\n}\n\nexport interface ShardAttachmentReference {\n id: string\n path: string\n mime: string | null\n checksum: string\n bytes: number\n}\n\nexport interface ShardAttachmentProjection {\n extracted_text: string | null\n /** Legacy unprofiled relationship timestamp; outside core-v1. */\n created_at?: string\n /** Legacy unprofiled attachment tombstone; outside core-v1. */\n deleted_at?: string | null\n extraction_status?: 'extracted' | 'pending' | 'failed' | 'blocked' | 'deferred'\n reason?:\n | null\n | 'extraction_pending'\n | 'extractor_failed'\n | 'quarantined'\n | 'large_binary'\n | 'unsupported_mime'\n | 'no_extracted_text'\n attachment: ShardAttachmentReference\n}\n\n/** @deprecated Legacy React shard field name. Server shards use `attachments`. */\nexport type ShardBinarySource = ShardAttachmentProjection\n\n/**\n * Reference to one cluster file of a component split across addressable files\n * (`notes/000.jsonl`, `notes/001.jsonl`, …). `offset` preserves deterministic\n * component order; readers discover each cluster's size from its contents.\n */\nexport interface ShardClusterRef {\n href: string // path within the shard, relative to manifest base\n offset: number // index of the first record in this cluster\n}\n\n/**\n * Optional clustered layout (additive — absent on monolithic shards). When a\n * component is present here, its records live in the listed cluster files instead\n * of (or in addition to) the single `<component>.jsonl`. Both `importShard` and\n * the in-place reader consume it; a monolithic shard omits `layout` entirely.\n */\nexport interface ShardLayout {\n clusters?: Partial<Record<ShardComponent, ShardClusterRef[]>>\n}\n\nexport interface ShardMigrationHistoryEntry {\n from_version: string\n to_version: string\n migrated_at: string\n migrated_by: string\n changes: string[]\n}\n\n/** Manifest included in every shard as manifest.json. */\nexport interface ShardProducer {\n name: string\n version: string\n revision?: string\n}\n\nexport interface ShardManifest {\n version: string\n /** Named server-owned portability profile. Required for canonical interchange. */\n profile?: string\n /** Structured producer identity used by canonical profiles. */\n producer?: ShardProducer\n /** @deprecated Legacy producer release field. */\n matric_version?: string\n format: typeof SHARD_FORMAT\n created_at: string // ISO 8601\n components: ShardComponent[]\n counts: Partial<Record<ShardComponent | 'community_sets', number>>\n checksums: Record<string, string> // filename → sha256 hex\n min_reader_version: string\n migrated_from?: string | null\n migration_history?: ShardMigrationHistoryEntry[]\n /** Clustered component layout for partial fetch (issue #189). Absent → monolithic. */\n layout?: ShardLayout\n}\n\n/** Options for shard export. */\nexport interface ExportOptions {\n /**\n * Explicit portability profile. Only profiles advertised by the selected\n * producer are accepted. Omit to retain the legacy unprofiled React archive.\n */\n profile?: string\n includeEmbeddings?: boolean\n /** Filter to specific collection (export only notes in this collection). */\n collectionId?: string\n /** Filter to notes with this tag (e.g. 'app:research' for app-scoped export). */\n tag?: string\n /** Export only these embedding sets and their member/vector rows. */\n embeddingSetIds?: string[]\n /** Preserve virtual selector materialization metadata and virtual member rows. */\n includeMaterializedSelectors?: boolean\n /**\n * When set to a positive integer, emit notes as clustered files\n * (`notes/000.jsonl`, …) of this many records each, and record the layout in\n * the manifest, so an in-place reader can fetch only the clusters it needs\n * (issue #189). Absent → a single monolithic `notes.jsonl` (unchanged).\n */\n clusterNotesSize?: number\n /**\n * Pack attachment bytes into a portable content-addressed `blobs/<hex>`\n * sidecar (Fortemi/fortemi#1046), producing a self-contained shard whose\n * attachments survive a round-trip (`getBlob()` returns real bytes on the\n * importing host). Requires {@link blobStore}. Absent/false → reference-only\n * (server default), which remains a valid shard.\n */\n includeBlobs?: boolean\n /**\n * Byte source for the sidecar. Required when `includeBlobs` is set; attachment\n * bytes are read by their `content_hash`. A blob the store cannot return is\n * skipped (its attachment stays reference-only) rather than failing export.\n */\n blobStore?: BlobStore\n}\n\n/** Conflict resolution strategy for shard import. */\nexport type ConflictStrategy = 'skip' | 'replace' | 'error'\n\n/** Options for shard import. */\nexport interface ImportOptions {\n conflictStrategy?: ConflictStrategy\n /** Rows processed between cooperative yields. Defaults to 250. */\n batchSize?: number\n /** Progress callback for long-running import phases. */\n onProgress?: (progress: ImportProgress) => void\n /**\n * Destination for hydrating attachment bytes from a portable `blobs/<hex>`\n * sidecar (Fortemi/fortemi#1046). When provided, sidecar entries whose bare\n * hex matches an imported attachment's `content_hash` are promoted before\n * the logical transaction. A transaction failure removes only bytes that\n * were absent before promotion. Stores without the optional `delete`\n * capability fail before promotion. Absent → reference-only metadata.\n */\n blobStore?: BlobStore\n /**\n * Publisher-provenance policy for signed shards (#324, ADR-014):\n * - `require` — reject unsigned or bad-signature shards (default when a\n * `trustStore` is supplied);\n * - `prefer` — verify signed shards; import unsigned ones with a warning;\n * still reject a present-but-invalid signature;\n * - `trusted-local-only` — ignore signatures (own-export import).\n * When both `trustStore` and this are omitted, verification is skipped\n * entirely (checksum-only, unchanged behavior).\n */\n verifySignature?: 'require' | 'prefer' | 'trusted-local-only'\n /** Trust store resolving signer key_id → public key (required for `require`/`prefer`). */\n trustStore?: ShardTrustStore\n}\n\nexport type ImportProgressPhase =\n | 'unpack'\n | 'validate'\n | 'collections'\n | 'notes'\n | 'skos'\n | 'templates'\n | 'links'\n | 'provenance'\n | 'embedding_sets'\n | 'embedding_configs'\n | 'embeddings'\n | 'embedding_set_members'\n | 'graph'\n | 'communities'\n | 'index'\n\nexport interface ImportProgress {\n phase: ImportProgressPhase\n done: number\n total: number\n}\n\n/** Per-entity import counts. */\nexport interface ImportCounts {\n notes: number\n collections: number\n templates: number\n tags: number\n links: number\n embedding_sets: number\n embedding_configs: number\n embedding_set_members: number\n embeddings: number\n skos_schemes: number\n skos_concepts: number\n skos_relations: number\n note_skos_tags: number\n provenance_edges: number\n graph_sources: number\n graph_edges: number\n community_sets: number\n communities: number\n community_assignments: number\n}\n\n/** Result of a shard import operation. */\nexport interface ImportResult {\n success: boolean\n counts: ImportCounts\n skipped: Partial<ImportCounts>\n warnings: string[]\n errors: string[]\n duration_ms: number\n capability_report: ShardCapabilityReport\n}\n\nexport interface ShardExportResult {\n success: boolean\n archive: Uint8Array | null\n errors: string[]\n capability_report: ShardCapabilityReport\n}\n\n// ── Shard-format entity shapes (server-compatible) ──────────────────────\n\n/** Note as serialized in the shard JSONL. */\nexport interface ShardNote {\n id: string\n title: string | null\n original_content: string\n revised_content: string | null\n metadata?: Record<string, unknown> | null\n collection_id?: string | null\n attachments?: ShardAttachmentProjection[]\n /** @deprecated Legacy React shard field name. Use `attachments`. */\n binary_sources?: ShardBinarySource[]\n format: string\n source: string\n starred: boolean\n archived: boolean\n tags: string[]\n created_at: string\n updated_at: string\n /** Schema 1.1 core-v1 tombstone; legacy unprofiled archives also carry it. */\n deleted_at?: string | null\n}\n\n/** Collection as serialized in the shard JSON array. */\nexport interface ShardCollection {\n id: string\n name: string\n description: string | null\n parent_id: string | null\n created_at: string\n /** Legacy unprofiled fields; outside core-v1. */\n updated_at?: string\n deleted_at?: string | null\n note_count?: number\n}\n\n/** Tag as serialized in the shard JSON array. */\nexport interface ShardTag {\n name: string\n created_at: string\n}\n\n/** Template as serialized in the shard JSON array. */\nexport interface ShardTemplate {\n id: string\n name: string\n description: string | null\n content: string\n format: string\n default_tags: string[]\n collection_id: string | null\n created_at: string\n updated_at: string\n}\n\n/** Link as serialized in the shard JSONL. */\nexport interface ShardLink {\n id: string\n from_note_id: string\n to_note_id: string | null\n /** Optional for legacy React shards exported before URL links existed. */\n to_url?: string | null\n kind: string\n score: number | null\n created_at: string\n /** Optional for legacy React shards exported before link metadata existed. */\n metadata?: Record<string, unknown> | null\n}\n\n/**\n * Embedding set as serialized in the shard JSON array.\n *\n * Fields beyond id/model/dimension are optional for backward compatibility:\n * legacy React shards omit them and import falls back to the same defaults\n * `embeddingSetFromShard` applies (name → model, is_system → false, …).\n */\nexport interface ShardEmbeddingSet {\n id: string\n name?: string\n slug?: string | null\n description?: string | null\n purpose?: string | null\n document_count?: number\n embedding_count?: number\n is_system?: boolean\n keywords?: string[]\n model: string\n dimension: number\n kind?: 'physical' | 'filter' | 'virtual'\n mode?: 'auto' | 'manual' | 'mixed' | null\n truncate_dimension?: number | null\n criteria?: Record<string, unknown> | null\n source?: Record<string, unknown> | null\n compatibility?: Record<string, unknown> | null\n materialization?: Record<string, unknown> | null\n freshness?: ShardArtifactFreshness | null\n created_at?: string\n updated_at?: string\n}\n\n/** Embedding set member as serialized in the shard JSONL. */\nexport interface ShardEmbeddingSetMember {\n embedding_set_id: string\n note_id: string\n /** Legacy React shard field; new exports use server membership metadata instead. */\n embedding_id?: string\n /** Optional for legacy React shards; import defaults to 'materialized'. */\n membership_type?: string\n /** Optional for legacy React shards; import falls back to the manifest timestamp. */\n added_at?: string\n /** Optional for legacy React shards; import defaults to NULL. */\n added_by?: string | null\n}\n\n/** Embedding config as serialized in the shard JSON array. */\nexport interface ShardEmbeddingConfig {\n id: string\n name: string\n description: string | null\n model: string\n dimension: number\n chunk_size: number\n chunk_overlap: number\n is_default: boolean\n}\n\n/**\n * Embedding as serialized in the shard JSONL.\n *\n * Server metadata fields (`chunk_index`, `text`, `model`) are optional for\n * backward compatibility: legacy React shards exported before migration 0016\n * carry only `id`, `note_id`, `embedding_set_id`, `vector`, `created_at`.\n * Import normalizes absent metadata to schema defaults (0, '', NULL).\n */\nexport interface ShardEmbedding {\n id: string\n note_id: string\n chunk_index?: number\n text?: string\n vector: number[]\n model?: string\n /** React shard extension used to preserve local embedding-set scoping. */\n embedding_set_id?: string\n /** React shard extension used to preserve local creation ordering. */\n created_at?: string\n}\n\n\n/** SKOS scheme as serialized in the shard JSON array. */\nexport interface ShardSkosScheme {\n id: string\n title: string\n description: string | null\n created_at: string\n updated_at: string\n}\n\n/** SKOS concept as serialized in the shard JSON array. */\nexport interface ShardSkosConcept {\n id: string\n scheme_id: string\n pref_label: string\n alt_labels: string[]\n definition: string | null\n created_at: string\n updated_at: string\n}\n\n/** SKOS concept relation as serialized in the shard JSONL. */\nexport interface ShardSkosRelation {\n id: string\n source_concept_id: string\n target_concept_id: string\n relation_type: 'broader' | 'narrower' | 'related'\n created_at: string\n}\n\n/** Note-to-SKOS-concept assignment as serialized in the shard JSONL. */\nexport interface ShardNoteSkosTag {\n id: string\n note_id: string\n concept_id: string\n created_at: string\n}\n\n/** Provenance edge as serialized in the shard JSONL. */\nexport interface ShardProvenanceEdge {\n id: string\n entity_type: string\n entity_id: string\n activity: string\n agent: string\n started_at: string\n ended_at: string | null\n attributes: Record<string, unknown> | null\n}\n\n\n// - Graph/community derived artifacts ---------------------------------------\n\nexport interface ShardArtifactFreshness {\n status: 'fresh' | 'stale' | 'unknown'\n checked_at?: string\n stale_reason?: string\n source_hashes?: {\n notes?: string\n links?: string\n embeddings?: string\n embedding_set_members?: string\n virtual_set_definition?: string\n parameters?: string\n }\n}\n\nexport interface ShardGraphSource {\n id: string\n name: string\n kind: 'link' | 'similarity' | 'search' | 'manual' | 'imported'\n source_table?: 'link' | 'embedding' | 'manual' | null\n embedding_set_id?: string | null\n virtual_set_id?: string | null\n model?: string | null\n dimension?: number | null\n truncate_dimension?: number | null\n metric?: 'cosine' | 'inner_product' | 'l2' | null\n algorithm?: string | null\n parameters?: Record<string, unknown>\n input_hash: string\n freshness: ShardArtifactFreshness\n created_at: string\n}\n\nexport interface ShardGraphEdge {\n graph_source_id: string\n from_note_id: string\n to_note_id: string\n weight: number\n kind: 'link' | 'similarity' | 'manual'\n rank?: number | null\n metadata?: Record<string, unknown>\n}\n\nexport interface ShardCommunitySet {\n id: string\n graph_source_id: string\n name: string\n source_type: 'precomputed' | 'dynamic-snapshot' | 'user-authored' | 'imported'\n algorithm?: string | null\n parameters?: Record<string, unknown>\n input_hash: string\n freshness: ShardArtifactFreshness\n communities: ShardCommunity[]\n created_at: string\n}\n\nexport interface ShardCommunity {\n id: string\n label?: string | null\n rank?: number | null\n size?: number | null\n confidence?: number | null\n representative_note_ids?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface ShardCommunityAssignment {\n community_set_id: string\n community_id: string\n note_id: string\n confidence?: number | null\n source_type: 'precomputed' | 'dynamic-snapshot' | 'user-authored' | 'imported'\n metadata?: Record<string, unknown>\n}\n","/**\n * SHA-256 checksum utilities for shard integrity verification.\n * Uses the Web Crypto API (browser-native, no extra dependencies).\n */\n\n/**\n * Compute SHA-256 hex digest of a Uint8Array.\n * Returns lowercase hex string (64 characters).\n */\nexport async function sha256Hex(data: Uint8Array): Promise<string> {\n const buf = new ArrayBuffer(data.byteLength)\n new Uint8Array(buf).set(data)\n const hashBuffer = await crypto.subtle.digest('SHA-256', buf)\n const hashArray = new Uint8Array(hashBuffer)\n return Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Validate checksums listed in a shard manifest against actual file contents.\n *\n * SECURITY (SEC7 — trust model): these checksums live *inside* the same archive\n * as the files they hash, so they detect **transport corruption**, not\n * **tampering**. An attacker who controls the archive controls both the file\n * bytes and the manifest hashes, so a passing result proves the archive is\n * internally consistent — nothing more. For provenance-sensitive imports, verify\n * integrity out-of-band: a signed manifest, or a caller-supplied expected digest\n * checked against the whole archive (see `prefetchShard`'s `expectedSha256`,\n * which is real integrity because the hash arrives on a separate channel).\n *\n * The signed-manifest path is now implemented: `verifyShardSignature`\n * (`shard-signature.ts`, #324/ADR-014) authenticates publisher provenance via\n * an Ed25519 signature over the manifest digest + blob-digest set, and\n * `importShard` runs it BEFORE any record or blob mutation. These in-archive\n * checksums remain the consistency layer *inside* that verified boundary.\n *\n * @returns Object with `valid` flag and list of failed filenames.\n */\nexport async function validateChecksums(\n checksums: Record<string, string>,\n files: Map<string, Uint8Array>,\n): Promise<{ valid: boolean; failures: string[] }> {\n const failures: string[] = []\n\n for (const [filename, expectedHash] of Object.entries(checksums)) {\n const fileData = files.get(filename)\n if (!fileData) {\n failures.push(filename)\n continue\n }\n const actualHash = await sha256Hex(fileData)\n if (actualHash !== expectedHash) {\n failures.push(filename)\n }\n }\n\n return { valid: failures.length === 0, failures }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/manifest.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 manifest\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"version\",\n \"profile\",\n \"producer\",\n \"format\",\n \"created_at\",\n \"components\",\n \"counts\",\n \"checksums\",\n \"min_reader_version\"\n ],\n \"properties\": {\n \"version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"profile\": {\n \"const\": \"core-v1\"\n },\n \"producer\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"name\", \"version\"],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"revision\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n },\n \"matric_version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"deprecated\": true\n },\n \"format\": {\n \"const\": \"matric-shard\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"components\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"uniqueItems\": true,\n \"items\": {\n \"enum\": [\"notes\", \"collections\", \"tags\", \"templates\", \"links\"]\n }\n },\n \"counts\": {\n \"$ref\": \"#/$defs/counts\"\n },\n \"checksums\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"enum\": [\n \"notes.jsonl\",\n \"collections.json\",\n \"tags.json\",\n \"templates.json\",\n \"links.jsonl\"\n ]\n },\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/sha256\"\n }\n },\n \"min_reader_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migrated_from\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migration_history\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"from_version\",\n \"to_version\",\n \"migrated_at\",\n \"migrated_by\",\n \"changes\"\n ],\n \"properties\": {\n \"from_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"to_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migrated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"migrated_by\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"changes\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n }\n }\n }\n },\n \"$defs\": {\n \"strictSemVer\": {\n \"type\": \"string\",\n \"pattern\": \"^(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)$\"\n },\n \"sha256\": {\n \"type\": \"string\",\n \"pattern\": \"^[0-9a-f]{64}$\"\n },\n \"count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"counts\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"notes\",\n \"collections\",\n \"tags\",\n \"templates\",\n \"links\",\n \"embedding_sets\",\n \"embedding_set_members\",\n \"embeddings\",\n \"embedding_configs\"\n ],\n \"properties\": {\n \"notes\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"collections\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"tags\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"templates\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"links\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"embedding_sets\": {\n \"const\": 0\n },\n \"embedding_set_members\": {\n \"const\": 0\n },\n \"embeddings\": {\n \"const\": 0\n },\n \"embedding_configs\": {\n \"const\": 0\n }\n }\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/note.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 note record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"id\",\n \"title\",\n \"original_content\",\n \"revised_content\",\n \"metadata\",\n \"format\",\n \"source\",\n \"starred\",\n \"archived\",\n \"collection_id\",\n \"created_at\",\n \"updated_at\",\n \"tags\",\n \"attachments\"\n ],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"title\": {\n \"type\": [\"string\", \"null\"]\n },\n \"original_content\": {\n \"type\": \"string\"\n },\n \"revised_content\": {\n \"type\": \"string\"\n },\n \"metadata\": true,\n \"format\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"source\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"starred\": {\n \"type\": \"boolean\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"collection_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"created_at\": {\n \"$ref\": \"#/$defs/dateTime\"\n },\n \"updated_at\": {\n \"$ref\": \"#/$defs/dateTime\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"uniqueItems\": true,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n },\n \"attachments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/attachmentProjection\"\n }\n }\n },\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"dateTime\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"sha256\": {\n \"type\": \"string\",\n \"pattern\": \"^blake3:[0-9a-f]{64}$\"\n },\n \"attachmentProjection\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"extracted_text\",\n \"extraction_status\",\n \"reason\",\n \"attachment\"\n ],\n \"properties\": {\n \"extracted_text\": {\n \"type\": [\"string\", \"null\"]\n },\n \"extraction_status\": {\n \"enum\": [\"extracted\", \"pending\", \"failed\", \"blocked\", \"deferred\"]\n },\n \"reason\": {\n \"enum\": [\n null,\n \"extraction_pending\",\n \"extractor_failed\",\n \"quarantined\",\n \"large_binary\",\n \"unsupported_mime\",\n \"no_extracted_text\"\n ]\n },\n \"attachment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"path\", \"mime\", \"checksum\", \"bytes\"],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"path\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"mime\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"checksum\": {\n \"$ref\": \"#/$defs/sha256\"\n },\n \"bytes\": {\n \"type\": \"integer\",\n \"minimum\": 0\n }\n }\n }\n }\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/collection.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 collection record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"name\", \"description\", \"parent_id\", \"created_at\", \"note_count\"],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"description\": {\n \"type\": [\"string\", \"null\"]\n },\n \"parent_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"note_count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n }\n },\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/tag.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 tag record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"name\", \"created_at\"],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/template.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 template record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"id\",\n \"name\",\n \"description\",\n \"content\",\n \"format\",\n \"default_tags\",\n \"collection_id\",\n \"created_at\",\n \"updated_at\"\n ],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"description\": {\n \"type\": [\"string\", \"null\"]\n },\n \"content\": {\n \"type\": \"string\"\n },\n \"format\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"default_tags\": {\n \"type\": \"array\",\n \"uniqueItems\": true,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n },\n \"collection_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"updated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n },\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.0.0/core-v1/link.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 link record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"id\",\n \"from_note_id\",\n \"to_note_id\",\n \"to_url\",\n \"kind\",\n \"score\",\n \"created_at\",\n \"metadata\"\n ],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"from_note_id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"to_note_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"to_url\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"uri\"\n },\n \"kind\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"score\": {\n \"type\": \"number\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"metadata\": true\n },\n \"oneOf\": [\n {\n \"properties\": {\n \"to_note_id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"to_url\": {\n \"type\": \"null\"\n }\n }\n },\n {\n \"properties\": {\n \"to_note_id\": {\n \"type\": \"null\"\n },\n \"to_url\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n }\n }\n }\n ],\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.1.0/core-v1/manifest.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 manifest\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"version\",\n \"profile\",\n \"producer\",\n \"format\",\n \"created_at\",\n \"components\",\n \"counts\",\n \"checksums\",\n \"min_reader_version\"\n ],\n \"properties\": {\n \"version\": {\n \"const\": \"1.1.0\"\n },\n \"profile\": {\n \"const\": \"core-v1\"\n },\n \"producer\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"name\", \"version\"],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"revision\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n },\n \"matric_version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"deprecated\": true\n },\n \"format\": {\n \"const\": \"matric-shard\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"components\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"uniqueItems\": true,\n \"items\": {\n \"enum\": [\"notes\", \"collections\", \"tags\", \"templates\", \"links\"]\n }\n },\n \"counts\": {\n \"$ref\": \"#/$defs/counts\"\n },\n \"checksums\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"enum\": [\n \"notes.jsonl\",\n \"collections.json\",\n \"tags.json\",\n \"templates.json\",\n \"links.jsonl\"\n ]\n },\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/sha256\"\n }\n },\n \"min_reader_version\": {\n \"const\": \"1.1.0\"\n },\n \"migrated_from\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migration_history\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"from_version\",\n \"to_version\",\n \"migrated_at\",\n \"migrated_by\",\n \"changes\"\n ],\n \"properties\": {\n \"from_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"to_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migrated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"migrated_by\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"changes\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n }\n }\n }\n },\n \"$defs\": {\n \"strictSemVer\": {\n \"type\": \"string\",\n \"pattern\": \"^(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)$\"\n },\n \"sha256\": {\n \"type\": \"string\",\n \"pattern\": \"^[0-9a-f]{64}$\"\n },\n \"count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"counts\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"notes\",\n \"collections\",\n \"tags\",\n \"templates\",\n \"links\",\n \"embedding_sets\",\n \"embedding_set_members\",\n \"embeddings\",\n \"embedding_configs\"\n ],\n \"properties\": {\n \"notes\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"collections\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"tags\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"templates\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"links\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"embedding_sets\": {\n \"const\": 0\n },\n \"embedding_set_members\": {\n \"const\": 0\n },\n \"embeddings\": {\n \"const\": 0\n },\n \"embedding_configs\": {\n \"const\": 0\n }\n }\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/manifest.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 manifest\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"version\",\n \"profile\",\n \"producer\",\n \"format\",\n \"created_at\",\n \"components\",\n \"counts\",\n \"checksums\",\n \"min_reader_version\"\n ],\n \"properties\": {\n \"version\": {\n \"const\": \"1.2.0\"\n },\n \"profile\": {\n \"const\": \"core-v1\"\n },\n \"producer\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"name\", \"version\"],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"revision\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n },\n \"matric_version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"deprecated\": true\n },\n \"format\": {\n \"const\": \"matric-shard\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"components\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"uniqueItems\": true,\n \"items\": {\n \"enum\": [\"notes\", \"collections\", \"tags\", \"templates\", \"links\"]\n }\n },\n \"counts\": {\n \"$ref\": \"#/$defs/counts\"\n },\n \"checksums\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"enum\": [\n \"notes.jsonl\",\n \"collections.json\",\n \"tags.json\",\n \"templates.json\",\n \"links.jsonl\"\n ]\n },\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/sha256\"\n }\n },\n \"min_reader_version\": {\n \"const\": \"1.2.0\"\n },\n \"migrated_from\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migration_history\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"from_version\",\n \"to_version\",\n \"migrated_at\",\n \"migrated_by\",\n \"changes\"\n ],\n \"properties\": {\n \"from_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"to_version\": {\n \"$ref\": \"#/$defs/strictSemVer\"\n },\n \"migrated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"migrated_by\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"changes\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n }\n }\n }\n },\n \"$defs\": {\n \"strictSemVer\": {\n \"type\": \"string\",\n \"pattern\": \"^(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)$\"\n },\n \"sha256\": {\n \"type\": \"string\",\n \"pattern\": \"^[0-9a-f]{64}$\"\n },\n \"count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"counts\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"notes\",\n \"collections\",\n \"tags\",\n \"templates\",\n \"links\",\n \"embedding_sets\",\n \"embedding_set_members\",\n \"embeddings\",\n \"embedding_configs\"\n ],\n \"properties\": {\n \"notes\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"collections\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"tags\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"templates\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"links\": {\n \"$ref\": \"#/$defs/count\"\n },\n \"embedding_sets\": {\n \"const\": 0\n },\n \"embedding_set_members\": {\n \"const\": 0\n },\n \"embeddings\": {\n \"const\": 0\n },\n \"embedding_configs\": {\n \"const\": 0\n }\n }\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/note.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 note record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"id\",\n \"title\",\n \"original_content\",\n \"revised_content\",\n \"metadata\",\n \"format\",\n \"source\",\n \"starred\",\n \"archived\",\n \"collection_id\",\n \"created_at\",\n \"updated_at\",\n \"tags\",\n \"attachments\"\n ],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"title\": {\n \"type\": [\"string\", \"null\"]\n },\n \"original_content\": {\n \"type\": \"string\"\n },\n \"revised_content\": {\n \"type\": \"string\"\n },\n \"metadata\": true,\n \"format\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"source\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"starred\": {\n \"type\": \"boolean\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"collection_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"created_at\": {\n \"$ref\": \"#/$defs/dateTime\"\n },\n \"updated_at\": {\n \"$ref\": \"#/$defs/dateTime\"\n },\n \"deleted_at\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/dateTime\"\n },\n {\n \"type\": \"null\"\n }\n ],\n \"default\": null\n },\n \"tags\": {\n \"type\": \"array\",\n \"uniqueItems\": true,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n },\n \"attachments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/attachmentProjection\"\n }\n }\n },\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"dateTime\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"sha256\": {\n \"type\": \"string\",\n \"pattern\": \"^blake3:[0-9a-f]{64}$\"\n },\n \"attachmentProjection\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"extracted_text\",\n \"extraction_status\",\n \"reason\",\n \"attachment\"\n ],\n \"properties\": {\n \"extracted_text\": {\n \"type\": [\"string\", \"null\"]\n },\n \"extraction_status\": {\n \"enum\": [\"extracted\", \"pending\", \"failed\", \"blocked\", \"deferred\"]\n },\n \"reason\": {\n \"enum\": [\n null,\n \"extraction_pending\",\n \"extractor_failed\",\n \"quarantined\",\n \"large_binary\",\n \"unsupported_mime\",\n \"no_extracted_text\"\n ]\n },\n \"attachment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"path\", \"mime\", \"checksum\", \"bytes\"],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"path\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"mime\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"checksum\": {\n \"$ref\": \"#/$defs/sha256\"\n },\n \"bytes\": {\n \"type\": \"integer\",\n \"minimum\": 0\n }\n }\n }\n }\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/collection.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 collection record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"name\", \"description\", \"parent_id\", \"created_at\", \"note_count\"],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"description\": {\n \"type\": [\"string\", \"null\"]\n },\n \"parent_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"note_count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n }\n },\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/tag.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 tag record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"name\", \"created_at\"],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/template.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 template record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"id\",\n \"name\",\n \"description\",\n \"content\",\n \"format\",\n \"default_tags\",\n \"collection_id\",\n \"created_at\",\n \"updated_at\"\n ],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"description\": {\n \"type\": [\"string\", \"null\"]\n },\n \"content\": {\n \"type\": \"string\"\n },\n \"format\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"default_tags\": {\n \"type\": \"array\",\n \"uniqueItems\": true,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n },\n \"collection_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"updated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n },\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.fortemi.dev/knowledge-shard/1.2.0/core-v1/link.schema.json\",\n \"title\": \"Fortemi Knowledge Shard core-v1 link record\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"id\",\n \"from_note_id\",\n \"to_note_id\",\n \"to_url\",\n \"kind\",\n \"score\",\n \"created_at\",\n \"metadata\"\n ],\n \"properties\": {\n \"id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"from_note_id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"to_note_id\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/uuid\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"to_url\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"uri\"\n },\n \"kind\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"score\": {\n \"type\": \"number\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"metadata\": true\n },\n \"oneOf\": [\n {\n \"properties\": {\n \"to_note_id\": {\n \"$ref\": \"#/$defs/uuid\"\n },\n \"to_url\": {\n \"type\": \"null\"\n }\n }\n },\n {\n \"properties\": {\n \"to_note_id\": {\n \"type\": \"null\"\n },\n \"to_url\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n }\n }\n }\n ],\n \"$defs\": {\n \"uuid\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n}\n","/**\n * Minimal tar + gzip packing/unpacking for shard archives.\n *\n * Uses fflate for gzip compression and implements a lightweight POSIX tar\n * encoder/decoder (512-byte block headers, ustar format).\n */\n\nimport { gzipSync, gunzipSync } from 'fflate'\n\n// ── Tar constants ────────────────────────────────────────────────────────\n\nconst BLOCK_SIZE = 512\nconst USTAR_MAGIC = 'ustar\\x0000'\n\n// ── Tar encoder ──────────────────────────────────────────────────────────\n\nfunction writeString(buf: Uint8Array, offset: number, str: string, len: number) {\n for (let i = 0; i < Math.min(str.length, len); i++) {\n buf[offset + i] = str.charCodeAt(i)\n }\n}\n\nfunction writeOctal(buf: Uint8Array, offset: number, value: number, len: number) {\n const str = value.toString(8).padStart(len - 1, '0')\n writeString(buf, offset, str, len - 1)\n}\n\nfunction computeHeaderChecksum(header: Uint8Array): number {\n // For checksum computation, treat the checksum field (offset 148, 8 bytes) as spaces\n let sum = 0\n for (let i = 0; i < BLOCK_SIZE; i++) {\n sum += i >= 148 && i < 156 ? 32 : header[i]\n }\n return sum\n}\n\nfunction createTarHeader(filename: string, size: number): Uint8Array {\n const header = new Uint8Array(BLOCK_SIZE)\n\n // name (0, 100)\n writeString(header, 0, filename, 100)\n // mode (100, 8) — 0644\n writeOctal(header, 100, 0o644, 8)\n // uid (108, 8)\n writeOctal(header, 108, 0, 8)\n // gid (116, 8)\n writeOctal(header, 116, 0, 8)\n // size (124, 12)\n writeOctal(header, 124, size, 12)\n // mtime (136, 12)\n writeOctal(header, 136, Math.floor(Date.now() / 1000), 12)\n // typeflag (156) — '0' for regular file\n header[156] = 48 // ASCII '0'\n // magic (257, 8) — ustar\\000\n writeString(header, 257, USTAR_MAGIC, 8)\n\n // compute and write checksum (148, 8)\n const checksum = computeHeaderChecksum(header)\n const csStr = checksum.toString(8).padStart(6, '0')\n writeString(header, 148, csStr, 6)\n header[154] = 0 // null terminator\n header[155] = 32 // space\n\n return header\n}\n\nfunction encodeTar(files: Map<string, Uint8Array>): Uint8Array {\n const blocks: Uint8Array[] = []\n\n for (const [filename, data] of files) {\n blocks.push(createTarHeader(filename, data.byteLength))\n blocks.push(data)\n\n // Pad to 512-byte boundary\n const remainder = data.byteLength % BLOCK_SIZE\n if (remainder > 0) {\n blocks.push(new Uint8Array(BLOCK_SIZE - remainder))\n }\n }\n\n // Two zero blocks mark end of archive\n blocks.push(new Uint8Array(BLOCK_SIZE * 2))\n\n // Concatenate\n let totalLen = 0\n for (const b of blocks) totalLen += b.byteLength\n const result = new Uint8Array(totalLen)\n let offset = 0\n for (const b of blocks) {\n result.set(b, offset)\n offset += b.byteLength\n }\n return result\n}\n\n// ── Tar decoder ──────────────────────────────────────────────────────────\n\nfunction readString(buf: Uint8Array, offset: number, len: number): string {\n let end = offset\n const limit = offset + len\n while (end < limit && buf[end] !== 0) end++\n return String.fromCharCode(...buf.slice(offset, end))\n}\n\nfunction readOctal(buf: Uint8Array, offset: number, len: number): number {\n const str = readString(buf, offset, len).trim()\n return str.length > 0 ? parseInt(str, 8) : 0\n}\n\nfunction isZeroBlock(buf: Uint8Array, offset: number): boolean {\n for (let i = 0; i < BLOCK_SIZE; i++) {\n if (buf[offset + i] !== 0) return false\n }\n return true\n}\n\nfunction decodeTar(tarData: Uint8Array): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>()\n let offset = 0\n\n while (offset + BLOCK_SIZE <= tarData.byteLength) {\n // Check for end-of-archive (two zero blocks)\n if (isZeroBlock(tarData, offset)) break\n\n const name = readString(tarData, offset, 100)\n const size = readOctal(tarData, offset + 124, 12)\n const typeflag = tarData[offset + 156]\n\n offset += BLOCK_SIZE // skip header\n\n // Only extract regular files (typeflag '0' or NUL)\n if (typeflag === 48 || typeflag === 0) {\n files.set(name, tarData.slice(offset, offset + size))\n }\n\n // Advance past data blocks (padded to 512-byte boundary)\n const dataBlocks = Math.ceil(size / BLOCK_SIZE)\n offset += dataBlocks * BLOCK_SIZE\n }\n\n return files\n}\n\n// ── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Pack files into a gzip-compressed tar archive.\n *\n * @param files Map of filename → file contents\n * @returns Compressed archive bytes (suitable for .shard file)\n */\nexport function packTarGz(\n files: Map<string, Uint8Array>,\n opts?: { maxDecompressedBytes?: number },\n): Uint8Array {\n const tarData = encodeTar(files)\n const cap = opts?.maxDecompressedBytes ?? DEFAULT_MAX_DECOMPRESSED_BYTES\n if (tarData.byteLength > cap) {\n throw new Error(\n 'Refusing to create archive: uncompressed size ' + tarData.byteLength +\n ' exceeds cap ' + cap + ' bytes',\n )\n }\n return gzipSync(tarData)\n}\n\n/**\n * Default cap on decompressed archive size (256 MiB). A gzip \"bomb\" is a tiny\n * compressed payload that expands to gigabytes; without a cap `gunzipSync`\n * allocates the whole thing before any checksum check runs (SEC3). Callers that\n * genuinely need larger archives can raise the cap explicitly.\n */\nexport const DEFAULT_MAX_DECOMPRESSED_BYTES = 256 * 1024 * 1024\n\n/**\n * Unpack a gzip-compressed tar archive.\n *\n * Before decompressing, the gzip ISIZE footer (declared uncompressed size) is\n * checked against `maxDecompressedBytes` and rejected if it exceeds the cap.\n * fflate independently verifies the actual output length against ISIZE, so a\n * lying footer fails during decompression — together this bounds the memory a\n * malicious archive can force us to allocate.\n *\n * @param data Compressed archive bytes\n * @param opts.maxDecompressedBytes Cap on decompressed size (default 256 MiB)\n * @returns Map of filename → file contents\n */\nexport function unpackTarGz(\n data: Uint8Array,\n opts?: { maxDecompressedBytes?: number },\n): Map<string, Uint8Array> {\n const cap = opts?.maxDecompressedBytes ?? DEFAULT_MAX_DECOMPRESSED_BYTES\n // gzip footer: last 4 bytes are ISIZE (uncompressed size mod 2^32, LE).\n if (data.byteLength < 18) {\n throw new Error('Invalid gzip archive: too short')\n }\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength)\n const declaredSize = view.getUint32(data.byteLength - 4, true)\n if (declaredSize > cap) {\n throw new Error(\n 'Refusing to decompress archive: declared size ' + declaredSize +\n ' exceeds cap ' + cap + ' bytes',\n )\n }\n const tarData = gunzipSync(data)\n if (tarData.byteLength > cap) {\n // Defense against a footer that wrapped past 2^32; fflate would normally\n // have thrown on the ISIZE mismatch, but guard the boundary explicitly.\n throw new Error(\n 'Refusing to decompress archive: decompressed size ' + tarData.byteLength +\n ' exceeds cap ' + cap + ' bytes',\n )\n }\n return decodeTar(tarData)\n}\n","/**\n * Canonical and transitional Knowledge Shard validation.\n *\n * @implements @.aiwg/adrs/ADR-010-portable-schema-topology-and-source-of-truth.md\n * @implements @.aiwg/adrs/ADR-011-shard-server-conformance-and-version-negotiation.md\n * @schema @packages/core/schemas/knowledge-shard.schema.receipt.json\n * @created 2026-07-17\n * @agent Codex\n */\nimport Ajv2020 from 'ajv/dist/2020.js'\nimport type { ErrorObject, ValidateFunction } from 'ajv'\nimport legacySchema from '../../schemas/knowledge-shard.schema.json' with { type: 'json' }\nimport authorityReceipt from '../../schemas/knowledge-shard.schema.receipt.json' with { type: 'json' }\nimport legacyManifestSchema from '../../schemas/knowledge-shard/1.0.0/core-v1/manifest.schema.json' with { type: 'json' }\nimport legacyNoteSchema from '../../schemas/knowledge-shard/1.0.0/core-v1/note.schema.json' with { type: 'json' }\nimport legacyCollectionSchema from '../../schemas/knowledge-shard/1.0.0/core-v1/collection.schema.json' with { type: 'json' }\nimport legacyTagSchema from '../../schemas/knowledge-shard/1.0.0/core-v1/tag.schema.json' with { type: 'json' }\nimport legacyTemplateSchema from '../../schemas/knowledge-shard/1.0.0/core-v1/template.schema.json' with { type: 'json' }\nimport legacyLinkSchema from '../../schemas/knowledge-shard/1.0.0/core-v1/link.schema.json' with { type: 'json' }\nimport v1_1CoreManifestSchema from '../../schemas/knowledge-shard/1.1.0/core-v1/manifest.schema.json' with { type: 'json' }\nimport v1_1RecordManifestSchema from '../../schemas/knowledge-shard/1.1.0/record-v1/manifest.schema.json' with { type: 'json' }\nimport v1_1FullManifestSchema from '../../schemas/knowledge-shard/1.1.0/full-v1/manifest.schema.json' with { type: 'json' }\nimport v1_1FullEmbeddingSchema from '../../schemas/knowledge-shard/1.1.0/full-v1/embedding.schema.json' with { type: 'json' }\nimport manifestSchema from '../../schemas/knowledge-shard/1.2.0/core-v1/manifest.schema.json' with { type: 'json' }\nimport noteSchema from '../../schemas/knowledge-shard/1.2.0/core-v1/note.schema.json' with { type: 'json' }\nimport collectionSchema from '../../schemas/knowledge-shard/1.2.0/core-v1/collection.schema.json' with { type: 'json' }\nimport tagSchema from '../../schemas/knowledge-shard/1.2.0/core-v1/tag.schema.json' with { type: 'json' }\nimport templateSchema from '../../schemas/knowledge-shard/1.2.0/core-v1/template.schema.json' with { type: 'json' }\nimport linkSchema from '../../schemas/knowledge-shard/1.2.0/core-v1/link.schema.json' with { type: 'json' }\nimport recordManifestSchema from '../../schemas/knowledge-shard/1.2.0/record-v1/manifest.schema.json' with { type: 'json' }\nimport recordNoteSchema from '../../schemas/knowledge-shard/1.2.0/record-v1/note.schema.json' with { type: 'json' }\nimport recordCollectionSchema from '../../schemas/knowledge-shard/1.2.0/record-v1/collection.schema.json' with { type: 'json' }\nimport recordTagSchema from '../../schemas/knowledge-shard/1.2.0/record-v1/tag.schema.json' with { type: 'json' }\nimport recordLinkSchema from '../../schemas/knowledge-shard/1.2.0/record-v1/link.schema.json' with { type: 'json' }\nimport fullManifestSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/manifest.schema.json' with { type: 'json' }\nimport fullNoteOriginalSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/note-original.schema.json' with { type: 'json' }\nimport fullNoteOriginalHistorySchema from '../../schemas/knowledge-shard/1.2.0/full-v1/note-original-history.schema.json' with { type: 'json' }\nimport fullNoteRevisedCurrentSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/note-revised-current.schema.json' with { type: 'json' }\nimport fullNoteRevisionSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/note-revision.schema.json' with { type: 'json' }\nimport fullEmbeddingConfigSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/embedding-config.schema.json' with { type: 'json' }\nimport fullEmbeddingSetSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/embedding-set.schema.json' with { type: 'json' }\nimport fullEmbeddingSetMemberSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/embedding-set-member.schema.json' with { type: 'json' }\nimport fullEmbeddingSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/embedding.schema.json' with { type: 'json' }\nimport fullProvenanceEdgeSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/provenance-edge.schema.json' with { type: 'json' }\nimport fullProvenanceActivitySchema from '../../schemas/knowledge-shard/1.2.0/full-v1/provenance-activity.schema.json' with { type: 'json' }\nimport fullNamedLocationSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/named-location.schema.json' with { type: 'json' }\nimport fullProvenanceLocationSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/provenance-location.schema.json' with { type: 'json' }\nimport fullProvenanceDeviceSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/provenance-device.schema.json' with { type: 'json' }\nimport fullProvenanceRecordSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/provenance-record.schema.json' with { type: 'json' }\nimport fullSkosSchemeSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-scheme.schema.json' with { type: 'json' }\nimport fullSkosConceptSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-concept.schema.json' with { type: 'json' }\nimport fullSkosLabelSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-label.schema.json' with { type: 'json' }\nimport fullSkosNoteSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-note.schema.json' with { type: 'json' }\nimport fullSkosRelationSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-relation.schema.json' with { type: 'json' }\nimport fullSkosMappingRelationSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-mapping-relation.schema.json' with { type: 'json' }\nimport fullSkosSchemeMembershipSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-scheme-membership.schema.json' with { type: 'json' }\nimport fullNoteSkosTagSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/note-skos-tag.schema.json' with { type: 'json' }\nimport fullSkosCollectionSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-collection.schema.json' with { type: 'json' }\nimport fullSkosCollectionMemberSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/skos-collection-member.schema.json' with { type: 'json' }\nimport fullGraphSourceSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/graph-source.schema.json' with { type: 'json' }\nimport fullGraphEdgeSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/graph-edge.schema.json' with { type: 'json' }\nimport fullCommunitySetSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/community-set.schema.json' with { type: 'json' }\nimport fullCommunityAssignmentSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/community-assignment.schema.json' with { type: 'json' }\nimport fullSignatureSchema from '../../schemas/knowledge-shard/1.2.0/full-v1/signature.schema.json' with { type: 'json' }\nimport { validateChecksums } from './checksum.js'\nimport { unpackTarGz } from './shard-tar.js'\nimport { CURRENT_SHARD_VERSION } from './types.js'\nimport type { ShardComponent, ShardManifest } from './types.js'\nimport { computeBlobHash } from '../hash.js'\nimport { isSidecarEntry, sidecarEntryName } from './blob-sidecar.js'\n\nexport interface ShardSchemaValidationResult {\n valid: boolean\n errors: string[]\n}\n\ntype ShardFiles = Map<string, Uint8Array>\ntype CoreV1Component = 'notes' | 'collections' | 'tags' | 'templates' | 'links'\ntype RecordV1Component = 'notes' | 'collections' | 'tags' | 'links'\ntype FullV1Component = ShardComponent\nexport type CoreV1SchemaVersion = '1.0.0' | '1.1.0' | '1.2.0'\ntype CurrentCanonicalSchemaVersion = '1.1.0' | '1.2.0'\ntype RecordEncoding = 'json-array' | 'jsonl'\ntype IdentifiedSchema = object & { $id: string }\n\nconst decoder = new TextDecoder()\n\ntype LegacySchemaDefName =\n | 'manifest'\n | 'note'\n | 'collection'\n | 'tag'\n | 'template'\n | 'link'\n | 'embeddingSet'\n | 'embeddingSetMember'\n | 'embeddingConfig'\n | 'embedding'\n | 'skosScheme'\n | 'skosConcept'\n | 'skosRelation'\n | 'noteSkosTag'\n | 'provenanceEdge'\n | 'graphSource'\n | 'graphEdge'\n | 'communitySet'\n | 'communityAssignment'\n\nconst LEGACY_COMPONENT_SCHEMA_DEFS: Partial<\n Record<ShardComponent | 'templates', LegacySchemaDefName>\n> = {\n notes: 'note',\n collections: 'collection',\n tags: 'tag',\n templates: 'template',\n links: 'link',\n embedding_sets: 'embeddingSet',\n embedding_set_members: 'embeddingSetMember',\n embedding_configs: 'embeddingConfig',\n embeddings: 'embedding',\n skos_schemes: 'skosScheme',\n skos_concepts: 'skosConcept',\n skos_relations: 'skosRelation',\n note_skos_tags: 'noteSkosTag',\n provenance_edges: 'provenanceEdge',\n graph_sources: 'graphSource',\n graph_edges: 'graphEdge',\n communities: 'communitySet',\n community_assignments: 'communityAssignment',\n}\n\nconst LEGACY_COMPONENT_FILES: Partial<\n Record<ShardComponent, { file: string; encoding: RecordEncoding }>\n> = {\n notes: { file: 'notes.jsonl', encoding: 'jsonl' },\n collections: { file: 'collections.json', encoding: 'json-array' },\n tags: { file: 'tags.json', encoding: 'json-array' },\n templates: { file: 'templates.json', encoding: 'json-array' },\n links: { file: 'links.jsonl', encoding: 'jsonl' },\n embedding_sets: { file: 'embedding_sets.json', encoding: 'json-array' },\n embedding_set_members: { file: 'embedding_set_members.jsonl', encoding: 'jsonl' },\n embedding_configs: { file: 'embedding_configs.json', encoding: 'json-array' },\n embeddings: { file: 'embeddings.jsonl', encoding: 'jsonl' },\n skos_schemes: { file: 'skos_schemes.json', encoding: 'json-array' },\n skos_concepts: { file: 'skos_concepts.json', encoding: 'json-array' },\n skos_relations: { file: 'skos_relations.jsonl', encoding: 'jsonl' },\n note_skos_tags: { file: 'note_skos_tags.jsonl', encoding: 'jsonl' },\n provenance_edges: { file: 'provenance_edges.jsonl', encoding: 'jsonl' },\n graph_sources: { file: 'graph_sources.json', encoding: 'json-array' },\n graph_edges: { file: 'graph_edges.jsonl', encoding: 'jsonl' },\n communities: { file: 'communities.json', encoding: 'json-array' },\n community_assignments: { file: 'community_assignments.jsonl', encoding: 'jsonl' },\n}\n\nconst CORE_V1_COMPONENT_FILES: Record<\n CoreV1Component,\n { file: string; encoding: RecordEncoding }\n> = {\n notes: { file: 'notes.jsonl', encoding: 'jsonl' },\n collections: { file: 'collections.json', encoding: 'json-array' },\n tags: { file: 'tags.json', encoding: 'json-array' },\n templates: { file: 'templates.json', encoding: 'json-array' },\n links: { file: 'links.jsonl', encoding: 'jsonl' },\n}\n\nconst RECORD_V1_COMPONENT_FILES: Record<\n RecordV1Component,\n { file: string; encoding: RecordEncoding }\n> = {\n notes: { file: 'notes.jsonl', encoding: 'jsonl' },\n collections: { file: 'collections.json', encoding: 'json-array' },\n tags: { file: 'tags.json', encoding: 'json-array' },\n links: { file: 'links.jsonl', encoding: 'jsonl' },\n}\n\nconst FULL_V1_COMPONENT_FILES: Record<\n FullV1Component,\n { file: string; encoding: RecordEncoding }\n> = {\n notes: { file: 'notes.jsonl', encoding: 'jsonl' },\n collections: { file: 'collections.json', encoding: 'json-array' },\n tags: { file: 'tags.json', encoding: 'json-array' },\n templates: { file: 'templates.json', encoding: 'json-array' },\n links: { file: 'links.jsonl', encoding: 'jsonl' },\n note_originals: { file: 'note_originals.jsonl', encoding: 'jsonl' },\n note_original_history: { file: 'note_original_history.jsonl', encoding: 'jsonl' },\n note_revised_current: { file: 'note_revised_current.jsonl', encoding: 'jsonl' },\n note_revisions: { file: 'note_revisions.jsonl', encoding: 'jsonl' },\n embedding_configs: { file: 'embedding_configs.json', encoding: 'json-array' },\n embedding_sets: { file: 'embedding_sets.json', encoding: 'json-array' },\n embedding_set_members: { file: 'embedding_set_members.jsonl', encoding: 'jsonl' },\n embeddings: { file: 'embeddings.jsonl', encoding: 'jsonl' },\n provenance_edges: { file: 'provenance_edges.jsonl', encoding: 'jsonl' },\n provenance_activities: { file: 'provenance_activities.jsonl', encoding: 'jsonl' },\n named_locations: { file: 'named_locations.jsonl', encoding: 'jsonl' },\n provenance_locations: { file: 'provenance_locations.jsonl', encoding: 'jsonl' },\n provenance_devices: { file: 'provenance_devices.jsonl', encoding: 'jsonl' },\n provenance_records: { file: 'provenance_records.jsonl', encoding: 'jsonl' },\n skos_schemes: { file: 'skos_schemes.json', encoding: 'json-array' },\n skos_concepts: { file: 'skos_concepts.json', encoding: 'json-array' },\n skos_labels: { file: 'skos_labels.jsonl', encoding: 'jsonl' },\n skos_notes: { file: 'skos_notes.jsonl', encoding: 'jsonl' },\n skos_relations: { file: 'skos_relations.jsonl', encoding: 'jsonl' },\n skos_mapping_relations: { file: 'skos_mapping_relations.jsonl', encoding: 'jsonl' },\n skos_scheme_memberships: { file: 'skos_scheme_memberships.jsonl', encoding: 'jsonl' },\n note_skos_tags: { file: 'note_skos_tags.jsonl', encoding: 'jsonl' },\n skos_collections: { file: 'skos_collections.json', encoding: 'json-array' },\n skos_collection_members: { file: 'skos_collection_members.jsonl', encoding: 'jsonl' },\n graph_sources: { file: 'graph_sources.json', encoding: 'json-array' },\n graph_edges: { file: 'graph_edges.jsonl', encoding: 'jsonl' },\n communities: { file: 'communities.json', encoding: 'json-array' },\n community_assignments: { file: 'community_assignments.jsonl', encoding: 'jsonl' },\n}\n\nconst CORE_V1_SCHEMAS: Record<\n CoreV1SchemaVersion,\n Record<CoreV1Component | 'manifest', IdentifiedSchema>\n> = {\n '1.0.0': {\n manifest: legacyManifestSchema,\n notes: legacyNoteSchema,\n collections: legacyCollectionSchema,\n tags: legacyTagSchema,\n templates: legacyTemplateSchema,\n links: legacyLinkSchema,\n },\n '1.1.0': {\n manifest: v1_1CoreManifestSchema,\n notes: noteSchema,\n collections: collectionSchema,\n tags: tagSchema,\n templates: templateSchema,\n links: linkSchema,\n },\n '1.2.0': {\n manifest: manifestSchema,\n notes: noteSchema,\n collections: collectionSchema,\n tags: tagSchema,\n templates: templateSchema,\n links: linkSchema,\n },\n}\n\nconst RECORD_V1_CURRENT_SCHEMAS: Record<\n RecordV1Component | 'manifest',\n IdentifiedSchema\n> = {\n manifest: recordManifestSchema,\n notes: recordNoteSchema,\n collections: recordCollectionSchema,\n tags: recordTagSchema,\n links: recordLinkSchema,\n}\n\nconst RECORD_V1_SCHEMAS: Record<\n CurrentCanonicalSchemaVersion,\n Record<RecordV1Component | 'manifest', IdentifiedSchema>\n> = {\n '1.1.0': {\n ...RECORD_V1_CURRENT_SCHEMAS,\n manifest: v1_1RecordManifestSchema,\n },\n '1.2.0': RECORD_V1_CURRENT_SCHEMAS,\n}\n\nconst FULL_V1_CURRENT_SCHEMAS: Record<\n FullV1Component | 'manifest' | 'signature',\n IdentifiedSchema\n> = {\n manifest: fullManifestSchema,\n notes: noteSchema,\n collections: collectionSchema,\n tags: tagSchema,\n templates: templateSchema,\n links: linkSchema,\n note_originals: fullNoteOriginalSchema,\n note_original_history: fullNoteOriginalHistorySchema,\n note_revised_current: fullNoteRevisedCurrentSchema,\n note_revisions: fullNoteRevisionSchema,\n embedding_configs: fullEmbeddingConfigSchema,\n embedding_sets: fullEmbeddingSetSchema,\n embedding_set_members: fullEmbeddingSetMemberSchema,\n embeddings: fullEmbeddingSchema,\n provenance_edges: fullProvenanceEdgeSchema,\n provenance_activities: fullProvenanceActivitySchema,\n named_locations: fullNamedLocationSchema,\n provenance_locations: fullProvenanceLocationSchema,\n provenance_devices: fullProvenanceDeviceSchema,\n provenance_records: fullProvenanceRecordSchema,\n skos_schemes: fullSkosSchemeSchema,\n skos_concepts: fullSkosConceptSchema,\n skos_labels: fullSkosLabelSchema,\n skos_notes: fullSkosNoteSchema,\n skos_relations: fullSkosRelationSchema,\n skos_mapping_relations: fullSkosMappingRelationSchema,\n skos_scheme_memberships: fullSkosSchemeMembershipSchema,\n note_skos_tags: fullNoteSkosTagSchema,\n skos_collections: fullSkosCollectionSchema,\n skos_collection_members: fullSkosCollectionMemberSchema,\n graph_sources: fullGraphSourceSchema,\n graph_edges: fullGraphEdgeSchema,\n communities: fullCommunitySetSchema,\n community_assignments: fullCommunityAssignmentSchema,\n signature: fullSignatureSchema,\n}\n\nconst FULL_V1_SCHEMAS: Record<\n CurrentCanonicalSchemaVersion,\n Record<FullV1Component | 'manifest' | 'signature', IdentifiedSchema>\n> = {\n '1.1.0': {\n ...FULL_V1_CURRENT_SCHEMAS,\n manifest: v1_1FullManifestSchema,\n embeddings: v1_1FullEmbeddingSchema,\n },\n '1.2.0': FULL_V1_CURRENT_SCHEMAS,\n}\n\nlet legacyAjvInstance: Ajv2020 | undefined\nlet coreAjvInstance: Ajv2020 | undefined\nlet recordAjvInstance: Ajv2020 | undefined\nlet fullAjvInstance: Ajv2020 | undefined\nconst legacyValidators = new Map<LegacySchemaDefName, ValidateFunction>()\nconst coreValidators = new Map<string, ValidateFunction>()\nconst recordValidators = new Map<string, ValidateFunction>()\nconst fullValidators = new Map<string, ValidateFunction>()\n\nexport function getKnowledgeShardSchema(): unknown {\n return {\n manifest: manifestSchema,\n notes: noteSchema,\n collections: collectionSchema,\n tags: tagSchema,\n templates: templateSchema,\n links: linkSchema,\n recordV1: {\n manifest: recordManifestSchema,\n notes: recordNoteSchema,\n collections: recordCollectionSchema,\n tags: recordTagSchema,\n links: recordLinkSchema,\n },\n fullV1: FULL_V1_CURRENT_SCHEMAS,\n }\n}\n\nexport function getKnowledgeShardContractReceipt(): unknown {\n return authorityReceipt\n}\n\nfunction addCanonicalFormats(ajv: Ajv2020): void {\n ajv.addFormat('uuid', /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)\n ajv.addFormat('date-time', {\n type: 'string',\n validate: (value: string) =>\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(value)\n && !Number.isNaN(Date.parse(value)),\n })\n ajv.addFormat('uri', {\n type: 'string',\n validate: (value: string) => {\n try {\n return Boolean(new URL(value).protocol)\n } catch {\n return false\n }\n },\n })\n}\n\nfunction getLegacyAjv(): Ajv2020 {\n if (!legacyAjvInstance) {\n legacyAjvInstance = new Ajv2020({\n allErrors: true,\n strict: true,\n validateFormats: false,\n })\n legacyAjvInstance.addSchema(legacySchema)\n }\n return legacyAjvInstance\n}\n\nfunction getCoreAjv(): Ajv2020 {\n if (!coreAjvInstance) {\n coreAjvInstance = new Ajv2020({\n allErrors: true,\n strict: true,\n validateFormats: true,\n })\n addCanonicalFormats(coreAjvInstance)\n const registered = new Set<string>()\n for (const bundle of Object.values(CORE_V1_SCHEMAS)) {\n for (const schema of Object.values(bundle)) {\n if (!registered.has(schema.$id)) {\n coreAjvInstance.addSchema(schema)\n registered.add(schema.$id)\n }\n }\n }\n }\n return coreAjvInstance\n}\n\nfunction getRecordAjv(): Ajv2020 {\n if (!recordAjvInstance) {\n recordAjvInstance = new Ajv2020({\n allErrors: true,\n strict: true,\n validateFormats: true,\n })\n addCanonicalFormats(recordAjvInstance)\n const registered = new Set<string>()\n for (const bundle of Object.values(RECORD_V1_SCHEMAS)) {\n for (const schema of Object.values(bundle)) {\n if (!registered.has(schema.$id)) {\n recordAjvInstance.addSchema(schema)\n registered.add(schema.$id)\n }\n }\n }\n }\n return recordAjvInstance\n}\n\nfunction getFullAjv(): Ajv2020 {\n if (!fullAjvInstance) {\n fullAjvInstance = new Ajv2020({\n allErrors: true,\n strict: true,\n validateFormats: true,\n })\n addCanonicalFormats(fullAjvInstance)\n const registered = new Set<string>()\n for (const bundle of Object.values(FULL_V1_SCHEMAS)) {\n for (const schema of Object.values(bundle)) {\n if (!registered.has(schema.$id)) {\n fullAjvInstance.addSchema(schema)\n registered.add(schema.$id)\n }\n }\n }\n }\n return fullAjvInstance\n}\n\nfunction legacyValidatorFor(defName: LegacySchemaDefName): ValidateFunction {\n const cached = legacyValidators.get(defName)\n if (cached) return cached\n const validator = getLegacyAjv().getSchema(`${legacySchema.$id}#/$defs/${defName}`)\n ?? getLegacyAjv().compile({ $ref: `${legacySchema.$id}#/$defs/${defName}` })\n legacyValidators.set(defName, validator)\n return validator\n}\n\nfunction coreSchemaVersion(value: string): CoreV1SchemaVersion | undefined {\n return value === '1.0.0' || value === '1.1.0' || value === '1.2.0'\n ? value\n : undefined\n}\n\nfunction currentCanonicalSchemaVersion(\n value: string,\n): CurrentCanonicalSchemaVersion | undefined {\n return value === '1.1.0' || value === '1.2.0' ? value : undefined\n}\n\nfunction coreValidatorFor(\n name: CoreV1Component | 'manifest',\n version: CoreV1SchemaVersion = CURRENT_SHARD_VERSION,\n): ValidateFunction {\n const key = `${version}:${name}`\n const cached = coreValidators.get(key)\n if (cached) return cached\n const schema = CORE_V1_SCHEMAS[version][name]\n const validator = getCoreAjv().getSchema(schema.$id) ?? getCoreAjv().compile(schema)\n coreValidators.set(key, validator)\n return validator\n}\n\nfunction recordValidatorFor(\n name: RecordV1Component | 'manifest',\n version: CurrentCanonicalSchemaVersion = CURRENT_SHARD_VERSION,\n): ValidateFunction {\n const key = `${version}:${name}`\n const cached = recordValidators.get(key)\n if (cached) return cached\n const schema = RECORD_V1_SCHEMAS[version][name]\n const validator = getRecordAjv().getSchema(schema.$id) ?? getRecordAjv().compile(schema)\n recordValidators.set(key, validator)\n return validator\n}\n\nfunction fullValidatorFor(\n name: FullV1Component | 'manifest' | 'signature',\n version: CurrentCanonicalSchemaVersion = CURRENT_SHARD_VERSION,\n): ValidateFunction {\n const key = `${version}:${name}`\n const cached = fullValidators.get(key)\n if (cached) return cached\n const schema = FULL_V1_SCHEMAS[version][name]\n const validator = getFullAjv().getSchema(schema.$id) ?? getFullAjv().compile(schema)\n fullValidators.set(key, validator)\n return validator\n}\n\nfunction formatErrors(errors: ErrorObject[] | null | undefined): string[] {\n return (errors ?? []).map((error) => {\n const path = error.instancePath || '(root)'\n return `${path} ${error.message ?? 'is invalid'}`\n })\n}\n\nfunction profileOf(value: unknown): string | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const profile = (value as Record<string, unknown>).profile\n return typeof profile === 'string' ? profile : undefined\n}\n\nexport function validateShardManifest(value: unknown): ShardSchemaValidationResult {\n let validate: ValidateFunction\n const profile = profileOf(value)\n if (profile === 'core-v1') {\n const version = value && typeof value === 'object' && !Array.isArray(value)\n ? coreSchemaVersion(String((value as Record<string, unknown>).version ?? ''))\n : undefined\n if (!version) {\n return {\n valid: false,\n errors: ['(root) uses an unsupported canonical core-v1 schema version'],\n }\n }\n validate = coreValidatorFor('manifest', version)\n } else if (profile === 'record-v1') {\n const version = value && typeof value === 'object' && !Array.isArray(value)\n ? currentCanonicalSchemaVersion(String((value as Record<string, unknown>).version ?? ''))\n : undefined\n if (!version) {\n return {\n valid: false,\n errors: ['(root) uses an unsupported canonical record-v1 schema version'],\n }\n }\n validate = recordValidatorFor('manifest', version)\n } else if (profile === 'full-v1') {\n const version = value && typeof value === 'object' && !Array.isArray(value)\n ? currentCanonicalSchemaVersion(String((value as Record<string, unknown>).version ?? ''))\n : undefined\n if (!version) {\n return {\n valid: false,\n errors: ['(root) uses an unsupported canonical full-v1 schema version'],\n }\n }\n validate = fullValidatorFor('manifest', version)\n } else {\n validate = legacyValidatorFor('manifest')\n }\n const valid = validate(value)\n return { valid, errors: formatErrors(validate.errors) }\n}\n\nfunction parseJsonArray(\n bytes: Uint8Array | undefined,\n path: string,\n): { records: unknown[]; errors: string[] } {\n if (!bytes) return { records: [], errors: [] }\n try {\n const value = JSON.parse(decoder.decode(bytes)) as unknown\n if (!Array.isArray(value)) return { records: [], errors: [`${path} must be a JSON array`] }\n return { records: value, errors: [] }\n } catch {\n return { records: [], errors: [`${path} failed to parse as JSON`] }\n }\n}\n\nfunction parseJsonl(\n bytes: Uint8Array | undefined,\n path: string,\n): { records: unknown[]; errors: string[] } {\n if (!bytes) return { records: [], errors: [] }\n const text = decoder.decode(bytes).trim()\n if (!text) return { records: [], errors: [] }\n const records: unknown[] = []\n const errors: string[] = []\n for (const [index, line] of text.split('\\n').entries()) {\n try {\n records.push(JSON.parse(line) as unknown)\n } catch {\n errors.push(`${path}:${index + 1} failed to parse as JSON`)\n }\n }\n return { records, errors }\n}\n\nfunction unpackShardFiles(input: Uint8Array | ArrayBuffer | ShardFiles): ShardFiles {\n if (input instanceof Map) return input\n return unpackTarGz(input instanceof ArrayBuffer ? new Uint8Array(input) : input)\n}\n\nfunction parseRecords(\n bytes: Uint8Array | undefined,\n path: string,\n encoding: RecordEncoding,\n): { records: unknown[]; errors: string[] } {\n return encoding === 'json-array' ? parseJsonArray(bytes, path) : parseJsonl(bytes, path)\n}\n\nfunction validateLegacyComponentRecords(\n component: ShardComponent,\n records: unknown[],\n path: string,\n): string[] {\n const errors: string[] = []\n for (const [index, record] of records.entries()) {\n const result = validateShardComponentRecord(component, record)\n if (!result.valid) {\n errors.push(...result.errors.map((error) => `${path}[${index}] ${error}`))\n }\n }\n return errors\n}\n\nfunction validateLegacyArchive(files: ShardFiles, manifest: ShardManifest): string[] {\n const errors: string[] = []\n const manifestResult = validateShardManifest(manifest)\n if (!manifestResult.valid) {\n errors.push(...manifestResult.errors.map((error) => `manifest.json ${error}`))\n }\n\n const componentsToValidate = new Set<ShardComponent>(manifest.components)\n for (const [component, spec] of Object.entries(LEGACY_COMPONENT_FILES) as Array<\n [ShardComponent, { file: string; encoding: RecordEncoding }]\n >) {\n if (files.has(spec.file)) componentsToValidate.add(component)\n }\n\n for (const component of componentsToValidate) {\n const spec = LEGACY_COMPONENT_FILES[component]\n if (!spec) continue\n if (component === 'notes' && manifest.layout?.clusters?.notes?.length) {\n for (const cluster of manifest.layout.clusters.notes) {\n const parsed = parseJsonl(files.get(cluster.href), cluster.href)\n errors.push(...parsed.errors)\n errors.push(...validateLegacyComponentRecords('notes', parsed.records, cluster.href))\n }\n continue\n }\n const parsed = parseRecords(files.get(spec.file), spec.file, spec.encoding)\n errors.push(...parsed.errors)\n errors.push(...validateLegacyComponentRecords(component, parsed.records, spec.file))\n }\n return errors\n}\n\nfunction coreReferenceErrors(records: Map<CoreV1Component, unknown[]>): string[] {\n const errors: string[] = []\n const notes = records.get('notes') as Array<Record<string, unknown>>\n const collections = records.get('collections') as Array<Record<string, unknown>>\n const tags = records.get('tags') as Array<Record<string, unknown>>\n const templates = records.get('templates') as Array<Record<string, unknown>>\n const links = records.get('links') as Array<Record<string, unknown>>\n const noteIds = new Set(notes.map((record) => record.id))\n const collectionIds = new Set(collections.map((record) => record.id))\n const tagNames = new Set(tags.map((record) => record.name))\n\n for (const [index, collection] of collections.entries()) {\n if (collection.parent_id !== null && !collectionIds.has(collection.parent_id)) {\n errors.push(`collections.json[${index}] parent_id does not reference a declared collection`)\n }\n }\n for (const [index, note] of notes.entries()) {\n if (note.collection_id !== null && !collectionIds.has(note.collection_id)) {\n errors.push(`notes.jsonl[${index}] collection_id does not reference a declared collection`)\n }\n for (const tag of note.tags as string[]) {\n if (!tagNames.has(tag)) {\n errors.push(`notes.jsonl[${index}] tag does not reference a declared tag`)\n }\n }\n }\n for (const [index, template] of templates.entries()) {\n if (template.collection_id !== null && !collectionIds.has(template.collection_id)) {\n errors.push(`templates.json[${index}] collection_id does not reference a declared collection`)\n }\n for (const tag of template.default_tags as string[]) {\n if (!tagNames.has(tag)) {\n errors.push(`templates.json[${index}] default tag does not reference a declared tag`)\n }\n }\n }\n for (const [index, link] of links.entries()) {\n if (!noteIds.has(link.from_note_id)) {\n errors.push(`links.jsonl[${index}] from_note_id does not reference a declared note`)\n }\n if (link.to_note_id !== null && !noteIds.has(link.to_note_id)) {\n errors.push(`links.jsonl[${index}] to_note_id does not reference a declared note`)\n }\n }\n return errors\n}\n\nfunction validateCoreV1Structure(files: ShardFiles, manifest: ShardManifest): string[] {\n const errors: string[] = []\n const schemaVersion = coreSchemaVersion(manifest.version)\n if (!schemaVersion) {\n return ['manifest.json uses an unsupported canonical core-v1 schema version']\n }\n const manifestValidator = coreValidatorFor('manifest', schemaVersion)\n if (!manifestValidator(manifest)) {\n return formatErrors(manifestValidator.errors).map((error) => `manifest.json ${error}`)\n }\n\n const components = manifest.components as CoreV1Component[]\n const expectedFiles = new Set(components.map((component) => CORE_V1_COMPONENT_FILES[component].file))\n for (const filename of expectedFiles) {\n if (!files.has(filename)) errors.push(`${filename} is declared but missing`)\n if (!(filename in manifest.checksums)) errors.push(`${filename} is missing its declared checksum`)\n }\n for (const filename of Object.keys(manifest.checksums)) {\n if (!expectedFiles.has(filename)) {\n errors.push(`manifest checksum references undeclared file ${filename}`)\n }\n }\n for (const filename of files.keys()) {\n if (filename !== 'manifest.json' && !expectedFiles.has(filename)) {\n errors.push(`archive contains undeclared file ${filename}`)\n }\n }\n\n const records = new Map<CoreV1Component, unknown[]>()\n for (const component of components) {\n const spec = CORE_V1_COMPONENT_FILES[component]\n const parsed = parseRecords(files.get(spec.file), spec.file, spec.encoding)\n errors.push(...parsed.errors)\n const validator = coreValidatorFor(component, schemaVersion)\n for (const [index, record] of parsed.records.entries()) {\n if (!validator(record)) {\n errors.push(\n ...formatErrors(validator.errors).map((error) => `${spec.file}[${index}] ${error}`),\n )\n }\n }\n const expectedCount = manifest.counts[component]\n if (expectedCount !== parsed.records.length) {\n errors.push(\n `${spec.file} count mismatch: manifest=${String(expectedCount)} actual=${parsed.records.length}`,\n )\n }\n records.set(component, parsed.records)\n }\n for (const component of Object.keys(CORE_V1_COMPONENT_FILES) as CoreV1Component[]) {\n if (!records.has(component)) records.set(component, [])\n }\n\n if (errors.length === 0) errors.push(...coreReferenceErrors(records))\n return errors\n}\n\nfunction validateFullV1Structure(files: ShardFiles, manifest: ShardManifest): string[] {\n const errors: string[] = []\n const schemaVersion = currentCanonicalSchemaVersion(manifest.version)\n if (!schemaVersion) {\n return ['manifest.json uses an unsupported canonical full-v1 schema version']\n }\n const manifestValidator = fullValidatorFor('manifest', schemaVersion)\n if (!manifestValidator(manifest)) {\n return formatErrors(manifestValidator.errors).map((error) => `manifest.json ${error}`)\n }\n\n const components = manifest.components as FullV1Component[]\n const expectedFiles = new Set(\n components.map((component) => FULL_V1_COMPONENT_FILES[component].file),\n )\n for (const filename of expectedFiles) {\n if (!files.has(filename)) errors.push(`${filename} is declared but missing`)\n if (!(filename in manifest.checksums)) errors.push(`${filename} is missing its declared checksum`)\n }\n for (const filename of Object.keys(manifest.checksums)) {\n if (!expectedFiles.has(filename)) {\n errors.push(`manifest checksum references undeclared file ${filename}`)\n }\n }\n for (const filename of files.keys()) {\n if (\n filename !== 'manifest.json'\n && filename !== 'signature.json'\n && !isSidecarEntry(filename)\n && !expectedFiles.has(filename)\n ) {\n errors.push(`archive contains undeclared file ${filename}`)\n }\n }\n\n const records = new Map<FullV1Component, unknown[]>()\n for (const component of components) {\n const spec = FULL_V1_COMPONENT_FILES[component]\n const parsed = parseRecords(files.get(spec.file), spec.file, spec.encoding)\n errors.push(...parsed.errors)\n const validator = fullValidatorFor(component, schemaVersion)\n for (const [index, record] of parsed.records.entries()) {\n if (!validator(record)) {\n errors.push(\n ...formatErrors(validator.errors).map((error) => `${spec.file}[${index}] ${error}`),\n )\n }\n }\n if (component !== 'communities') {\n const expectedCount = manifest.counts[component]\n if (expectedCount !== parsed.records.length) {\n errors.push(\n `${spec.file} count mismatch: manifest=${String(expectedCount)} actual=${parsed.records.length}`,\n )\n }\n }\n records.set(component, parsed.records)\n }\n\n const communitySets = records.get('communities') as Array<Record<string, unknown>>\n const communityCount = communitySets.reduce((total, set) => {\n const communities = Array.isArray(set.communities) ? set.communities : []\n return total + communities.length\n }, 0)\n if (manifest.counts.community_sets !== communitySets.length) {\n errors.push(\n `communities.json set count mismatch: manifest=${String(manifest.counts.community_sets)} actual=${communitySets.length}`,\n )\n }\n if (manifest.counts.communities !== communityCount) {\n errors.push(\n `communities.json community count mismatch: manifest=${String(manifest.counts.communities)} actual=${communityCount}`,\n )\n }\n\n const signatureBytes = files.get('signature.json')\n if (signatureBytes) {\n try {\n const signature = JSON.parse(decoder.decode(signatureBytes)) as unknown\n const signatureValidator = fullValidatorFor('signature', schemaVersion)\n if (!signatureValidator(signature)) {\n errors.push(\n ...formatErrors(signatureValidator.errors).map(\n (error) => `signature.json ${error}`,\n ),\n )\n }\n } catch {\n errors.push('signature.json failed to parse as JSON')\n }\n }\n\n const notes = records.get('notes') as Array<Record<string, unknown>>\n for (const [noteIndex, note] of notes.entries()) {\n const attachments = Array.isArray(note.attachments) ? note.attachments : []\n for (const [attachmentIndex, projection] of attachments.entries()) {\n const attachment = (\n projection as { attachment?: { checksum?: unknown } }\n ).attachment\n if (typeof attachment?.checksum !== 'string') continue\n const sidecar = sidecarEntryName(attachment.checksum)\n if (!files.has(sidecar)) {\n errors.push(\n `notes.jsonl[${noteIndex}].attachments[${attachmentIndex}] is missing mandatory sidecar ${sidecar}`,\n )\n }\n }\n }\n return errors\n}\n\nfunction validateRecordV1Structure(files: ShardFiles, manifest: ShardManifest): string[] {\n const errors: string[] = []\n const schemaVersion = currentCanonicalSchemaVersion(manifest.version)\n if (!schemaVersion) {\n return ['manifest.json uses an unsupported canonical record-v1 schema version']\n }\n const manifestValidator = recordValidatorFor('manifest', schemaVersion)\n if (!manifestValidator(manifest)) {\n return formatErrors(manifestValidator.errors).map((error) => `manifest.json ${error}`)\n }\n\n const components = manifest.components as RecordV1Component[]\n const expectedFiles = new Set(\n components.map((component) => RECORD_V1_COMPONENT_FILES[component].file),\n )\n for (const filename of expectedFiles) {\n if (!files.has(filename)) errors.push(`${filename} is declared but missing`)\n if (!(filename in manifest.checksums)) errors.push(`${filename} is missing its declared checksum`)\n }\n for (const filename of Object.keys(manifest.checksums)) {\n if (!expectedFiles.has(filename)) {\n errors.push(`manifest checksum references undeclared file ${filename}`)\n }\n }\n for (const filename of files.keys()) {\n if (filename !== 'manifest.json' && !expectedFiles.has(filename)) {\n errors.push(`archive contains undeclared file ${filename}`)\n }\n }\n\n const records = new Map<CoreV1Component, unknown[]>()\n for (const component of components) {\n const spec = RECORD_V1_COMPONENT_FILES[component]\n const parsed = parseRecords(files.get(spec.file), spec.file, spec.encoding)\n errors.push(...parsed.errors)\n const validator = recordValidatorFor(component, schemaVersion)\n for (const [index, record] of parsed.records.entries()) {\n if (!validator(record)) {\n errors.push(\n ...formatErrors(validator.errors).map((error) => `${spec.file}[${index}] ${error}`),\n )\n }\n }\n const expectedCount = manifest.counts[component]\n if (expectedCount !== parsed.records.length) {\n errors.push(\n `${spec.file} count mismatch: manifest=${String(expectedCount)} actual=${parsed.records.length}`,\n )\n }\n records.set(component, parsed.records)\n }\n for (const component of Object.keys(CORE_V1_COMPONENT_FILES) as CoreV1Component[]) {\n if (!records.has(component)) records.set(component, [])\n }\n\n if (errors.length === 0) errors.push(...coreReferenceErrors(records))\n return errors\n}\n\nexport function validateShardArchive(\n input: Uint8Array | ArrayBuffer | ShardFiles,\n): ShardSchemaValidationResult {\n let files: ShardFiles\n try {\n files = unpackShardFiles(input)\n } catch {\n return { valid: false, errors: ['archive failed to unpack'] }\n }\n\n const manifestBytes = files.get('manifest.json')\n if (!manifestBytes) return { valid: false, errors: ['manifest.json is missing'] }\n\n let manifest: ShardManifest\n try {\n manifest = JSON.parse(decoder.decode(manifestBytes)) as ShardManifest\n } catch {\n return { valid: false, errors: ['manifest.json failed to parse as JSON'] }\n }\n\n const profile = profileOf(manifest)\n const errors = profile === 'core-v1'\n ? validateCoreV1Structure(files, manifest)\n : profile === 'record-v1'\n ? validateRecordV1Structure(files, manifest)\n : profile === 'full-v1'\n ? validateFullV1Structure(files, manifest)\n : validateLegacyArchive(files, manifest)\n return { valid: errors.length === 0, errors }\n}\n\nexport async function validateCoreV1ShardArchive(\n input: Uint8Array | ArrayBuffer | ShardFiles,\n): Promise<ShardSchemaValidationResult> {\n let files: ShardFiles\n try {\n files = unpackShardFiles(input)\n } catch {\n return { valid: false, errors: ['archive failed to unpack'] }\n }\n const manifestBytes = files.get('manifest.json')\n if (!manifestBytes) return { valid: false, errors: ['manifest.json is missing'] }\n\n let manifest: ShardManifest\n try {\n manifest = JSON.parse(decoder.decode(manifestBytes)) as ShardManifest\n } catch {\n return { valid: false, errors: ['manifest.json failed to parse as JSON'] }\n }\n\n const errors = validateCoreV1Structure(files, manifest)\n if (errors.length > 0) return { valid: false, errors }\n\n const checksumResult = await validateChecksums(manifest.checksums, files)\n if (!checksumResult.valid) {\n errors.push(...checksumResult.failures.map((filename) => `${filename} checksum mismatch`))\n }\n return { valid: errors.length === 0, errors }\n}\n\nexport async function validateRecordV1ShardArchive(\n input: Uint8Array | ArrayBuffer | ShardFiles,\n): Promise<ShardSchemaValidationResult> {\n let files: ShardFiles\n try {\n files = unpackShardFiles(input)\n } catch {\n return { valid: false, errors: ['archive failed to unpack'] }\n }\n const manifestBytes = files.get('manifest.json')\n if (!manifestBytes) return { valid: false, errors: ['manifest.json is missing'] }\n\n let manifest: ShardManifest\n try {\n manifest = JSON.parse(decoder.decode(manifestBytes)) as ShardManifest\n } catch {\n return { valid: false, errors: ['manifest.json failed to parse as JSON'] }\n }\n\n const errors = validateRecordV1Structure(files, manifest)\n if (errors.length > 0) return { valid: false, errors }\n\n const checksumResult = await validateChecksums(manifest.checksums, files)\n if (!checksumResult.valid) {\n errors.push(...checksumResult.failures.map((filename) => `${filename} checksum mismatch`))\n }\n return { valid: errors.length === 0, errors }\n}\n\nexport async function validateFullV1ShardArchive(\n input: Uint8Array | ArrayBuffer | ShardFiles,\n): Promise<ShardSchemaValidationResult> {\n let files: ShardFiles\n try {\n files = unpackShardFiles(input)\n } catch {\n return { valid: false, errors: ['archive failed to unpack'] }\n }\n const manifestBytes = files.get('manifest.json')\n if (!manifestBytes) return { valid: false, errors: ['manifest.json is missing'] }\n\n let manifest: ShardManifest\n try {\n manifest = JSON.parse(decoder.decode(manifestBytes)) as ShardManifest\n } catch {\n return { valid: false, errors: ['manifest.json failed to parse as JSON'] }\n }\n\n const errors = validateFullV1Structure(files, manifest)\n if (errors.length > 0) return { valid: false, errors }\n\n const checksumResult = await validateChecksums(manifest.checksums, files)\n if (!checksumResult.valid) {\n errors.push(...checksumResult.failures.map((filename) => `${filename} checksum mismatch`))\n }\n\n const notesSpec = FULL_V1_COMPONENT_FILES.notes\n const parsedNotes = parseRecords(files.get(notesSpec.file), notesSpec.file, notesSpec.encoding)\n for (const [noteIndex, note] of (\n parsedNotes.records as Array<Record<string, unknown>>\n ).entries()) {\n const attachments = Array.isArray(note.attachments) ? note.attachments : []\n for (const [attachmentIndex, projection] of attachments.entries()) {\n const attachment = (\n projection as { attachment?: { checksum?: unknown } }\n ).attachment\n if (typeof attachment?.checksum !== 'string') continue\n const sidecar = sidecarEntryName(attachment.checksum)\n const bytes = files.get(sidecar)\n if (bytes && computeBlobHash(bytes) !== attachment.checksum) {\n errors.push(\n `notes.jsonl[${noteIndex}].attachments[${attachmentIndex}] sidecar checksum mismatch`,\n )\n }\n }\n }\n return { valid: errors.length === 0, errors }\n}\n\nexport function validateShardComponentRecord(\n component: ShardComponent | 'templates',\n value: unknown,\n profile?: 'core-v1' | 'record-v1' | 'full-v1',\n version: CoreV1SchemaVersion = CURRENT_SHARD_VERSION,\n): ShardSchemaValidationResult {\n let validate: ValidateFunction\n if (profile === 'core-v1' && component in CORE_V1_COMPONENT_FILES) {\n validate = coreValidatorFor(component as CoreV1Component, version)\n } else if (profile === 'record-v1' && component in RECORD_V1_COMPONENT_FILES) {\n const canonicalVersion = currentCanonicalSchemaVersion(version)\n if (!canonicalVersion) {\n return {\n valid: false,\n errors: [`(root) uses an unsupported canonical record-v1 schema version ${version}`],\n }\n }\n validate = recordValidatorFor(component as RecordV1Component, canonicalVersion)\n } else if (profile === 'full-v1' && component in FULL_V1_COMPONENT_FILES) {\n const canonicalVersion = currentCanonicalSchemaVersion(version)\n if (!canonicalVersion) {\n return {\n valid: false,\n errors: [`(root) uses an unsupported canonical full-v1 schema version ${version}`],\n }\n }\n validate = fullValidatorFor(component as FullV1Component, canonicalVersion)\n } else {\n const legacyDef = LEGACY_COMPONENT_SCHEMA_DEFS[component]\n if (!legacyDef) {\n return {\n valid: false,\n errors: [`(root) component '${component}' requires an explicit full-v1 profile`],\n }\n }\n validate = legacyValidatorFor(legacyDef)\n }\n const valid = validate(value)\n return { valid, errors: formatErrors(validate.errors) }\n}\n\nexport function assertShardComponentRecord(\n component: ShardComponent | 'templates',\n value: unknown,\n profile?: 'core-v1' | 'record-v1' | 'full-v1',\n version: CoreV1SchemaVersion = CURRENT_SHARD_VERSION,\n): void {\n const result = validateShardComponentRecord(component, value, profile, version)\n if (!result.valid) {\n throw new Error(`Invalid shard ${component} record:\\n${result.errors.join('\\n')}`)\n }\n}\n","import type { ShardAttachmentReference, ShardBinarySource } from './shard/types.js'\nimport {\n CURRENT_SHARD_VERSION,\n SHARD_FORMAT,\n type ShardComponent,\n type ShardLink,\n type ShardManifest,\n type ShardNote,\n} from './shard/types.js'\nimport { sha256Hex as shardSha256Hex } from './shard/checksum.js'\nimport { validateCoreV1ShardArchive } from './shard/schema-validator.js'\nimport { packTarGz, unpackTarGz } from './shard/shard-tar.js'\nimport { v5 as uuidv5 } from 'uuid'\n\nexport type AiwgFortemiRecordType = string\n\nexport type AiwgFortemiRecordSchemaVersion = 'aiwg.fortemi.index.record.v1' | 'aiwg.fortemi.index.record.v2'\nexport type AiwgFortemiIndexExportSchemaVersion = 'aiwg.fortemi.index.export.v1' | 'aiwg.fortemi.index.export.v2'\nexport type AiwgPrivacyClassification = 'private' | 'sanitized' | 'public'\nexport type AiwgProvenanceConfidence = 'source' | 'candidate' | 'reviewed' | 'rejected'\nexport type AiwgReviewAction = 'accept' | 'reject' | 'defer'\nexport type AiwgFortemiRelationshipDirection = 'upstream' | 'downstream' | 'related'\n\nexport interface AiwgFortemiRecordSource {\n path: string\n repo_relative_path: string\n locator: string\n origin?: string\n generated?: boolean\n checksum?: string\n updated_at?: string\n}\n\nexport interface AiwgFortemiRelationship {\n type: string\n target_id: string\n source_path?: string\n target_path?: string\n direction?: AiwgFortemiRelationshipDirection\n label?: string\n confidence?: number\n privacy?: AiwgPrivacyClassification\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiProvenance {\n field: string\n source: string\n path: string\n confidence: AiwgProvenanceConfidence\n privacy: AiwgPrivacyClassification\n}\n\nexport type AiwgFortemiSkosRelationType = 'broader' | 'narrower' | 'related' | string\n\nexport interface AiwgFortemiSkosConcept {\n id: string\n prefLabel: string\n definition?: string\n scheme?: string\n notation?: string\n uri?: string\n altLabels?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiSkosRelation {\n type: AiwgFortemiSkosRelationType\n source_id: string\n target_id: string\n source_path?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiProvenanceEvent {\n id?: string\n activity: string\n agent?: string\n started_at?: string\n ended_at?: string\n source?: string\n path?: string\n confidence?: AiwgProvenanceConfidence\n privacy?: AiwgPrivacyClassification\n attributes?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiSearchProjection {\n title?: string\n name?: string\n summary?: string\n body?: string\n triggers?: string[]\n aliases?: string[]\n capability?: string\n tags?: string[]\n phase?: string\n type?: string\n frontmatter?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiChunk {\n id?: string\n text?: string\n body?: string\n summary?: string\n source_path?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface AiwgFortemiRecordEmbedding {\n id?: string\n embedding?: number[]\n vector?: number[]\n model?: string\n granularity?: string\n input_hash?: string\n source_path?: string\n metadata?: Record<string, unknown>\n}\n\nexport type AiwgFortemiAttachmentReference = ShardAttachmentReference\nexport type AiwgFortemiBinarySource = ShardBinarySource\n\nexport interface AiwgFortemiRecord {\n schema_version: AiwgFortemiRecordSchemaVersion\n id: string\n type: AiwgFortemiRecordType\n source: AiwgFortemiRecordSource\n title?: string\n text?: string\n facets: Record<string, string[]>\n tags: string[]\n concepts: string[]\n relationships: AiwgFortemiRelationship[]\n provenance: AiwgFortemiProvenance[]\n search?: AiwgFortemiSearchProjection\n chunks?: AiwgFortemiChunk[]\n binary_sources?: AiwgFortemiBinarySource[]\n embeddings?: AiwgFortemiRecordEmbedding[]\n compatibility?: Record<string, unknown>\n /** Optional rich SKOS metadata for static consumers that need labels/definitions without opening a shard. */\n skos_concepts?: AiwgFortemiSkosConcept[]\n /** Optional SKOS relationship edges among concepts referenced by this record. */\n skos_relations?: AiwgFortemiSkosRelation[]\n /** Optional W3C PROV-style activity chain for this record. */\n provenance_events?: AiwgFortemiProvenanceEvent[]\n privacy: {\n classification: AiwgPrivacyClassification\n pii: boolean\n locality?: string\n }\n updated_at: string\n}\n\nexport interface AiwgFortemiIndexExport {\n schema_version: AiwgFortemiIndexExportSchemaVersion\n generated_at: string\n source: {\n repo: string\n privacy: AiwgPrivacyClassification\n // v2-only upstream graph name; the vendored schema is authoritative.\n graph?: string\n }\n items: AiwgFortemiRecord[]\n // v2-only compatibility declaration defined by the vendored upstream schema.\n compatibility?: {\n previous_schema_version: 'aiwg.fortemi.index.export.v1'\n strategy: 'supported'\n }\n}\n\nexport interface AiwgFortemiChunkPartRef {\n href: string\n offset: number\n count: number\n}\n\n// Fields a scan part must retain for query/browse/rank/facet to work. The rest\n// (source, provenance, relationships, updated_at) are detail-only and may be\n// dropped from scan parts via `projection`, then resolved on demand by id.\nexport const AIWG_SCAN_REQUIRED_FIELDS: Array<keyof AiwgFortemiRecord> = [\n 'schema_version',\n 'id',\n 'type',\n 'title',\n 'text',\n 'facets',\n 'tags',\n 'concepts',\n 'privacy',\n]\n\n// A record as it appears in a scan part. With no manifest `projection`, this is a\n// full AiwgFortemiRecord. With a projection, detail-only fields are absent — read\n// them via the controller's getRecord(). Typed as the full record for ergonomics;\n// query/browse code guards the projectable fields.\nexport type AiwgFortemiProjectedRecord =\n Pick<AiwgFortemiRecord, 'schema_version' | 'id' | 'type' | 'title' | 'text' | 'facets' | 'tags' | 'concepts' | 'privacy'>\n & Partial<AiwgFortemiRecord>\n\n// How a record id is encoded into a detail filename/path segment.\n// - 'base64url': path-safe, single segment, no '%' — works on every static host,\n// including ids containing '/' (default for new builds; see #177).\n// - 'uri': encodeURIComponent — legacy. Breaks for ids containing '/' on static\n// servers that reject %2F (path-traversal protection → 404).\nexport type AiwgDetailIdEncoding = 'uri' | 'base64url'\n\n// How the controller resolves a full record by id when scan parts are projected.\nexport interface AiwgFortemiChunkDetailRef {\n // href template containing `{id}`, relative to the manifest base — e.g.\n // \"detail/{id}.json\". The `{id}` is encoded per `encoding` at substitution.\n href: string\n // id→segment encoding. Absent is treated as 'uri' for backward compatibility\n // with manifests built before #177; new builds default to 'base64url'.\n encoding?: AiwgDetailIdEncoding\n}\n\nexport interface AiwgFortemiChunkManifest {\n schema_version: 'aiwg.fortemi.index.chunk-manifest.v1'\n generated_at: string\n source: AiwgFortemiIndexExport['source']\n // The schema_version of the source index export this manifest was built from,\n // so chunked consumers (e.g. review-decision export) can report the true source\n // version rather than assuming v1 (#239 E8). Optional for backward compatibility.\n source_export_schema_version?: AiwgFortemiIndexExportSchemaVersion\n total: number\n part_size: number\n facets?: Record<string, Record<string, number>>\n // Field names present in scan-part items. Absent → scan parts carry whole records.\n // When set, must include AIWG_SCAN_REQUIRED_FIELDS.\n projection?: Array<keyof AiwgFortemiRecord>\n // Resolver for full records by id (used with `projection` to lazy-load detail).\n detail?: AiwgFortemiChunkDetailRef\n parts: AiwgFortemiChunkPartRef[]\n}\n\nexport interface AiwgFortemiChunkPart {\n schema_version: 'aiwg.fortemi.index.chunk.v1'\n manifest_schema_version: 'aiwg.fortemi.index.chunk-manifest.v1'\n offset: number\n items: AiwgFortemiRecord[]\n}\n\nexport interface AiwgIndexValidationResult {\n valid: boolean\n errors: string[]\n counts: Partial<Record<string, number>>\n}\n\nexport interface AiwgKnowledgeShardOptions {\n createdAt?: string\n matricVersion?: string\n /**\n * Reserved for a future full-v1 converter. Passing true currently fails\n * closed because a partial rich-component inventory is not a valid profile.\n */\n includeNativeRichComponents?: boolean\n}\n\nexport interface AiwgChunkedIndexValidationResult {\n valid: boolean\n errors: string[]\n}\n\nexport interface AiwgIndexQueryOptions {\n types?: AiwgFortemiRecordType[]\n facets?: Record<string, string[]>\n tags?: string[]\n concepts?: string[]\n privacy?: AiwgPrivacyClassification[]\n relationshipTargetId?: string\n limit?: number\n offset?: number\n rank?: boolean\n snippets?: boolean\n snippetLength?: number\n weights?: Partial<AiwgIndexQueryWeights>\n includeMatches?: boolean\n searchProfile?: 'default' | 'aiwg-discovery'\n}\n\nexport interface AiwgIndexQueryWeights {\n title: number\n text: number\n tag: number\n concept: number\n facet: number\n id: number\n source: number\n}\n\nexport interface AiwgIndexQueryMatch {\n field: 'title' | 'text' | 'tag' | 'concept' | 'facet' | 'id' | 'source'\n value: string\n score?: number\n reason?: string\n}\n\nexport interface AiwgIndexQueryRankedItem {\n item: AiwgFortemiRecord\n rank: number\n snippet?: string\n matches?: AiwgIndexQueryMatch[]\n}\n\nexport interface AiwgIndexQueryResult {\n items: AiwgFortemiRecord[]\n total: number\n facets: Record<string, Record<string, number>>\n rankedItems?: AiwgIndexQueryRankedItem[]\n}\n\nexport type AiwgChunkedIndexLoader = (\n part: AiwgFortemiChunkPartRef,\n manifest: AiwgFortemiChunkManifest,\n) => Promise<unknown>\n\n// Resolves a full record by id (used with projected scan parts). Returns the\n// parsed record JSON; validated by the controller before use.\nexport type AiwgChunkedIndexDetailLoader = (\n id: string,\n manifest: AiwgFortemiChunkManifest,\n) => Promise<unknown>\n\nexport interface AiwgChunkedIndexLoadOptions {\n maxCachedParts?: number\n // Required to resolve detail for projected indexes via getRecord(); ignored otherwise.\n detailLoader?: AiwgChunkedIndexDetailLoader\n maxCachedDetails?: number\n // Bounds the filtered/ranked match-set cache used to page a query without\n // re-scanning every part. Counts total cached entries across all queries\n // (LRU-evicted). Defaults to 5000. The cache is keyed on query + filters +\n // weights, so paging the same query (varying only offset/limit/sort/snippets)\n // reuses the scan; see queryChunked.\n maxCachedMatches?: number\n}\n\nexport type AiwgChunkedIndexProgressPhase = 'part' | 'query'\n\nexport interface AiwgChunkedIndexProgress {\n phase: AiwgChunkedIndexProgressPhase\n done: number\n total: number\n href?: string\n}\n\nexport interface AiwgChunkedIndexQueryOptions extends AiwgIndexQueryOptions {\n onProgress?: (progress: AiwgChunkedIndexProgress) => void\n}\n\nexport interface AiwgChunkedIndexQueryResult extends AiwgIndexQueryResult {\n manifestTotal: number\n scannedParts: number\n fetchedParts: number\n complete: boolean\n}\n\nexport interface AiwgReviewDecision {\n item_id: string\n action: AiwgReviewAction\n reason?: string\n updated_at: string\n}\n\nexport interface AiwgReviewDecisionExport {\n schema_version: 'aiwg.fortemi.review-decisions.v1'\n generated_at: string\n source_export_schema_version: AiwgFortemiIndexExportSchemaVersion\n decisions: AiwgReviewDecision[]\n}\n\nexport interface AiwgIndexGraphOptions {\n communityFacet?: string\n communityTagPrefix?: string\n relationshipWeights?: Record<string, number>\n includeDanglingRelationships?: boolean\n}\n\nexport type AiwgRelationshipDirection = 'in' | 'out' | 'both'\nexport type AiwgRelationshipSetOperation = 'intersection' | 'union' | 'difference'\n\nexport interface AiwgRelationshipTraversalOptions {\n direction?: AiwgRelationshipDirection\n relationshipType?: string\n relationshipDirection?: AiwgFortemiRelationshipDirection\n limit?: number\n}\n\nexport interface AiwgRelationshipQueryOptions extends AiwgRelationshipTraversalOptions {\n sourceId?: string\n targetId?: string\n endpointId?: string\n type?: string\n}\n\nexport interface AiwgRelationshipEdgeSummary {\n source_id: string\n target_id: string\n type: string\n source_path?: string\n target_path?: string\n direction?: AiwgFortemiRelationshipDirection\n}\n\nexport interface AiwgRelationshipNodeSummary {\n id: string\n type: AiwgFortemiRecordType\n title: string\n}\n\nexport interface AiwgRelationshipTraversalResult {\n nodes: AiwgRelationshipNodeSummary[]\n edges: AiwgRelationshipEdgeSummary[]\n complete: boolean\n scannedParts?: number\n fetchedParts?: number\n}\n\nexport interface AiwgRelationshipSetOptions extends AiwgRelationshipTraversalOptions {\n op: AiwgRelationshipSetOperation\n a: string\n b: string\n}\n\nexport interface AiwgRelationshipSetResult {\n ids: string[]\n op: AiwgRelationshipSetOperation\n}\n\nexport interface AiwgStaticEmbeddingRecord {\n record_id: string\n embedding: number[]\n embedding_id?: string\n granularity?: string\n input_hash: string\n source_path?: string\n}\n\nexport interface AiwgStaticEmbeddingSet {\n schema_version: 'aiwg.fortemi.embedding.set.v1'\n id: string\n model: string\n dimensions: number\n generated_at: string\n granularity: 'title-summary' | 'body' | 'chunked-body' | string\n metric?: 'cosine' | 'dot' | 'euclidean'\n input_hash_algorithm?: string\n embeddings: AiwgStaticEmbeddingRecord[]\n}\n\nexport interface AiwgHeadlessEmbeddingBackend {\n model: string\n dimensions: number\n embed(input: string, record: AiwgFortemiRecord): number[] | Promise<number[]>\n}\n\n// Privacy filtering for generated index/embedding artifacts (SEC6). Generation\n// is default-safe: records classified `private`, or flagged `pii`, are excluded\n// unless the caller explicitly opts them in. This keeps the query-time privacy\n// gate from being the *only* enforcement point — a leaked embedding set or scan\n// part can no longer carry private/PII-derived vectors by default.\nexport interface AiwgPrivacyFilterOptions {\n /** Include records classified `private` (default false). */\n includePrivate?: boolean\n /** Include records flagged `pii` (default false). */\n includePii?: boolean\n}\n\nfunction isPrivacyExcluded(record: AiwgFortemiRecord, options?: AiwgPrivacyFilterOptions): boolean {\n const privacy = record.privacy\n if (!privacy || !isPrivacyClassification(privacy.classification) || typeof privacy.pii !== 'boolean') return true\n if (privacy.classification === 'private' && !options?.includePrivate) return true\n if (privacy.pii && !options?.includePii) return true\n return false\n}\n\n/** Drop `private`/`pii` records unless explicitly opted in (SEC6, default-safe). */\nexport function filterAiwgRecordsByPrivacy(\n records: AiwgFortemiRecord[],\n options?: AiwgPrivacyFilterOptions,\n): AiwgFortemiRecord[] {\n return records.filter((record) => !isPrivacyExcluded(record, options))\n}\n\nexport interface BuildAiwgStaticEmbeddingSetOptions {\n id: string\n backend: AiwgHeadlessEmbeddingBackend\n records?: AiwgFortemiRecord[]\n generatedAt?: string | Date\n granularity?: AiwgStaticEmbeddingSet['granularity']\n metric?: AiwgStaticEmbeddingSet['metric']\n textForRecord?: (record: AiwgFortemiRecord) => string\n /** Privacy filtering (SEC6). Default-safe: excludes `private`/`pii` records. */\n privacy?: AiwgPrivacyFilterOptions\n}\n\nexport interface AiwgStaticSemanticQueryOptions {\n limit?: number\n offset?: number\n minScore?: number\n}\n\nexport interface AiwgStaticSemanticResult {\n item: AiwgFortemiRecord\n score: number\n embedding?: AiwgStaticEmbeddingRecord\n}\n\nexport interface AiwgStaticHybridQueryOptions extends AiwgStaticSemanticQueryOptions, AiwgIndexQueryOptions {\n lexicalWeight?: number\n semanticWeight?: number\n}\n\nexport interface AiwgStaticDuplicatePair {\n left: AiwgFortemiRecord\n right: AiwgFortemiRecord\n score: number\n}\n\nexport interface AiwgReviewInput {\n item_id: string\n action: AiwgReviewAction\n reason?: string\n}\n\nexport interface AiwgIndexControllerSnapshot {\n index: AiwgFortemiIndexExport | null\n chunked: {\n manifest: AiwgFortemiChunkManifest\n cachedParts: number\n maxCachedParts: number\n } | null\n data: AiwgIndexQueryResult | null\n error: Error | null\n reviewDecisions: AiwgReviewDecision[]\n}\n\nexport type AiwgIndexControllerListener = (snapshot: AiwgIndexControllerSnapshot) => void\n\nexport interface AiwgIndexController {\n loadIndex(value: unknown): AiwgFortemiIndexExport\n loadChunkedIndex(\n manifest: unknown,\n loader: AiwgChunkedIndexLoader,\n options?: AiwgChunkedIndexLoadOptions,\n ): AiwgFortemiChunkManifest\n getIndex(): AiwgFortemiIndexExport | null\n getChunkedManifest(): AiwgFortemiChunkManifest | null\n getSnapshot(): AiwgIndexControllerSnapshot\n query(query?: string, options?: AiwgIndexQueryOptions): AiwgIndexQueryResult\n queryChunked(query?: string, options?: AiwgChunkedIndexQueryOptions): Promise<AiwgChunkedIndexQueryResult>\n // Resolve a full record by id. For a projected chunked index, fetches detail via\n // the detailLoader (bounded cache); for a whole-record index/parts, returns the\n // record from loaded data. Rejects if detail is unavailable.\n getRecord(id: string): Promise<AiwgFortemiRecord>\n neighbors(id: string, options?: AiwgRelationshipTraversalOptions): Promise<AiwgRelationshipTraversalResult>\n relationshipQuery(options?: AiwgRelationshipQueryOptions): Promise<AiwgRelationshipTraversalResult>\n relationshipSet(options: AiwgRelationshipSetOptions): Promise<AiwgRelationshipSetResult>\n clearChunkCache(): void\n toCommunityGraph(options?: AiwgIndexGraphOptions): ReturnType<typeof aiwgFortemiIndexToCommunityGraph>\n toCommunityGraphChunked(options?: AiwgIndexGraphOptions & { onProgress?: (progress: AiwgChunkedIndexProgress) => void }): Promise<ReturnType<typeof aiwgFortemiIndexToCommunityGraph>>\n setReviewDecision(input: AiwgReviewInput): AiwgReviewDecision\n clearReviewDecision(itemId: string): void\n createReviewDecisionExport(generatedAt?: string): AiwgReviewDecisionExport\n subscribe(listener: AiwgIndexControllerListener): () => void\n}\n\nconst REQUIRED_RECORD_FIELDS: Array<keyof AiwgFortemiRecord> = [\n 'schema_version',\n 'id',\n 'type',\n 'source',\n 'facets',\n 'tags',\n 'concepts',\n 'relationships',\n 'provenance',\n 'privacy',\n 'updated_at',\n]\n\nconst DEFAULT_QUERY_WEIGHTS: AiwgIndexQueryWeights = {\n title: 4,\n tag: 3,\n concept: 2,\n text: 1,\n facet: 2,\n id: 1,\n source: 0.25,\n}\n\nfunction hasString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0\n}\n\nfunction pushFacet(counts: Record<string, Record<string, number>>, name: string, value: string) {\n // `name`/`value` come from untrusted index records (item.facets). Using a\n // prototype-bearing accumulator would let a key such as `__proto__` (or any\n // inherited name like `toString`) read through the prototype chain and mutate\n // shared built-ins. Null-prototype buckets make every access own-property\n // only, so exotic keys are counted as plain data. See SEC1 / #236.\n let bucket = counts[name]\n if (bucket === undefined) {\n bucket = Object.create(null) as Record<string, number>\n counts[name] = bucket\n }\n bucket[value] = (bucket[value] ?? 0) + 1\n}\n\nfunction hasNonNegativeInteger(value: unknown): value is number {\n return Number.isInteger(value) && typeof value === 'number' && value >= 0\n}\n\nfunction hasPositiveInteger(value: unknown): value is number {\n return Number.isInteger(value) && typeof value === 'number' && value > 0\n}\n\nfunction isFacetCounts(value: unknown): value is Record<string, Record<string, number>> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n return Object.values(value).every((counts) => (\n !!counts\n && typeof counts === 'object'\n && !Array.isArray(counts)\n && Object.values(counts).every((count) => hasNonNegativeInteger(count))\n ))\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isOptionalStringArray(value: unknown): boolean {\n return value === undefined || (Array.isArray(value) && value.every((item) => typeof item === 'string'))\n}\n\nfunction isSupportedIndexSchemaVersion(value: unknown): value is AiwgFortemiIndexExportSchemaVersion {\n return value === 'aiwg.fortemi.index.export.v1' || value === 'aiwg.fortemi.index.export.v2'\n}\n\nfunction isSupportedRecordSchemaVersion(value: unknown): value is AiwgFortemiRecordSchemaVersion {\n return value === 'aiwg.fortemi.index.record.v1' || value === 'aiwg.fortemi.index.record.v2'\n}\n\nfunction validateOptionalRichMetadata(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n if (item.skos_concepts !== undefined) {\n if (!Array.isArray(item.skos_concepts)) {\n errors.push('items[' + index + '].skos_concepts must be an array when present')\n } else {\n for (const [conceptIndex, concept] of item.skos_concepts.entries()) {\n if (!isPlainRecord(concept)) {\n errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '] must be an object')\n continue\n }\n if (!hasString(concept.id)) errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].id is required')\n if (!hasString(concept.prefLabel)) errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].prefLabel is required')\n if (!isOptionalStringArray(concept.altLabels)) errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].altLabels must be a string array')\n if (concept.metadata !== undefined && !isPlainRecord(concept.metadata)) {\n errors.push('items[' + index + '].skos_concepts[' + conceptIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.skos_relations !== undefined) {\n if (!Array.isArray(item.skos_relations)) {\n errors.push('items[' + index + '].skos_relations must be an array when present')\n } else {\n for (const [relationIndex, relation] of item.skos_relations.entries()) {\n if (!isPlainRecord(relation)) {\n errors.push('items[' + index + '].skos_relations[' + relationIndex + '] must be an object')\n continue\n }\n if (!hasString(relation.type)) errors.push('items[' + index + '].skos_relations[' + relationIndex + '].type is required')\n if (!hasString(relation.source_id)) errors.push('items[' + index + '].skos_relations[' + relationIndex + '].source_id is required')\n if (!hasString(relation.target_id)) errors.push('items[' + index + '].skos_relations[' + relationIndex + '].target_id is required')\n if (relation.metadata !== undefined && !isPlainRecord(relation.metadata)) {\n errors.push('items[' + index + '].skos_relations[' + relationIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.provenance_events !== undefined) {\n if (!Array.isArray(item.provenance_events)) {\n errors.push('items[' + index + '].provenance_events must be an array when present')\n } else {\n for (const [eventIndex, event] of item.provenance_events.entries()) {\n if (!isPlainRecord(event)) {\n errors.push('items[' + index + '].provenance_events[' + eventIndex + '] must be an object')\n continue\n }\n if (!hasString(event.activity)) errors.push('items[' + index + '].provenance_events[' + eventIndex + '].activity is required')\n if (event.attributes !== undefined && !isPlainRecord(event.attributes)) {\n errors.push('items[' + index + '].provenance_events[' + eventIndex + '].attributes must be an object')\n }\n }\n }\n }\n if (Array.isArray(item.relationships)) {\n for (const [relationshipIndex, relationship] of item.relationships.entries()) {\n if (!isPlainRecord(relationship)) {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '] must be an object')\n continue\n }\n if (relationship.metadata !== undefined && !isPlainRecord(relationship.metadata)) {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '].metadata must be an object')\n }\n if (\n relationship.direction !== undefined &&\n relationship.direction !== 'upstream' &&\n relationship.direction !== 'downstream' &&\n relationship.direction !== 'related'\n ) {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '].direction must be upstream, downstream, or related')\n }\n if (relationship.target_path !== undefined && typeof relationship.target_path !== 'string') {\n errors.push('items[' + index + '].relationships[' + relationshipIndex + '].target_path must be a string')\n }\n }\n }\n if (item.search !== undefined) {\n if (!isPlainRecord(item.search)) {\n errors.push('items[' + index + '].search must be an object')\n } else {\n if (!isOptionalStringArray(item.search.triggers)) errors.push('items[' + index + '].search.triggers must be a string array')\n if (!isOptionalStringArray(item.search.aliases)) errors.push('items[' + index + '].search.aliases must be a string array')\n if (!isOptionalStringArray(item.search.tags)) errors.push('items[' + index + '].search.tags must be a string array')\n if (item.search.frontmatter !== undefined && !isPlainRecord(item.search.frontmatter)) {\n errors.push('items[' + index + '].search.frontmatter must be an object')\n }\n }\n }\n if (item.chunks !== undefined) {\n if (!Array.isArray(item.chunks)) {\n errors.push('items[' + index + '].chunks must be an array when present')\n } else {\n for (const [chunkIndex, chunk] of item.chunks.entries()) {\n if (!isPlainRecord(chunk)) {\n errors.push('items[' + index + '].chunks[' + chunkIndex + '] must be an object')\n continue\n }\n if (chunk.metadata !== undefined && !isPlainRecord(chunk.metadata)) {\n errors.push('items[' + index + '].chunks[' + chunkIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.embeddings !== undefined) {\n if (!Array.isArray(item.embeddings)) {\n errors.push('items[' + index + '].embeddings must be an array when present')\n } else {\n for (const [embeddingIndex, embedding] of item.embeddings.entries()) {\n if (!isPlainRecord(embedding)) {\n errors.push('items[' + index + '].embeddings[' + embeddingIndex + '] must be an object')\n continue\n }\n const vector = embedding.embedding ?? embedding.vector\n if (vector !== undefined && (!Array.isArray(vector) || !vector.every((entry) => typeof entry === 'number'))) {\n errors.push('items[' + index + '].embeddings[' + embeddingIndex + '].embedding/vector must be a number array')\n }\n if (embedding.metadata !== undefined && !isPlainRecord(embedding.metadata)) {\n errors.push('items[' + index + '].embeddings[' + embeddingIndex + '].metadata must be an object')\n }\n }\n }\n }\n if (item.compatibility !== undefined && !isPlainRecord(item.compatibility)) {\n errors.push('items[' + index + '].compatibility must be an object')\n }\n}\n\nfunction isPrivacyClassification(value: unknown): value is AiwgPrivacyClassification {\n return value === 'private' || value === 'sanitized' || value === 'public'\n}\n\nfunction isProvenanceConfidence(value: unknown): value is AiwgProvenanceConfidence {\n return value === 'source' || value === 'candidate' || value === 'reviewed' || value === 'rejected'\n}\n\n// Provenance item shape + enum validation (#239 A4). Each item requires\n// field/source/path and enum-valid confidence/privacy — the schema marks all five\n// required, but the parser previously only checked \"non-empty array\".\nfunction validateProvenanceItems(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n if (!Array.isArray(item.provenance)) return\n for (const [provIndex, prov] of item.provenance.entries()) {\n const at = 'items[' + index + '].provenance[' + provIndex + ']'\n if (!isPlainRecord(prov)) {\n errors.push(at + ' must be an object')\n continue\n }\n if (!hasString(prov.field)) errors.push(at + '.field is required')\n if (!hasString(prov.source)) errors.push(at + '.source is required')\n if (!hasString(prov.path)) errors.push(at + '.path is required')\n if (!isProvenanceConfidence(prov.confidence)) errors.push(at + '.confidence must be one of source, candidate, reviewed, rejected')\n if (!isPrivacyClassification(prov.privacy)) errors.push(at + '.privacy must be one of private, sanitized, public')\n }\n}\n\n// v1/v2 field forbiddance (#239 A2): a record.v1 record must not carry fields the\n// schema defines only for record.v2. Keeps the parser as strict as the schema, so\n// a too-loose generator output is rejected rather than silently accepted.\nconst V2_ONLY_RECORD_FIELDS = [\n 'search',\n 'chunks',\n 'embeddings',\n 'skos_concepts',\n 'skos_relations',\n 'provenance_events',\n 'compatibility',\n] as const\nconst V2_ONLY_SOURCE_FIELDS = ['origin', 'generated', 'checksum', 'updated_at'] as const\nconst V2_ONLY_RELATIONSHIP_FIELDS = ['target_path', 'direction', 'metadata'] as const\n\nfunction forbidV2FieldsOnV1Record(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n if (item.schema_version !== 'aiwg.fortemi.index.record.v1') return\n const at = 'items[' + index + ']'\n const bag = item as Record<string, unknown>\n const v2msg = ' is a v2-only field and must be absent on a record.v1 record'\n for (const field of V2_ONLY_RECORD_FIELDS) {\n if (bag[field] !== undefined) errors.push(at + '.' + field + v2msg)\n }\n if (isPlainRecord(item.source)) {\n const src = item.source as Record<string, unknown>\n for (const field of V2_ONLY_SOURCE_FIELDS) {\n if (src[field] !== undefined) errors.push(at + '.source.' + field + v2msg)\n }\n }\n if (isPlainRecord(item.privacy) && (item.privacy as Record<string, unknown>).locality !== undefined) {\n errors.push(at + '.privacy.locality' + v2msg)\n }\n if (Array.isArray(item.relationships)) {\n for (const [relIndex, rel] of item.relationships.entries()) {\n if (!isPlainRecord(rel)) continue\n const relBag = rel as Record<string, unknown>\n for (const field of V2_ONLY_RELATIONSHIP_FIELDS) {\n if (relBag[field] !== undefined) errors.push(at + '.relationships[' + relIndex + '].' + field + v2msg)\n }\n }\n }\n}\n\nexport function validateAiwgFortemiIndexExport(value: unknown): AiwgIndexValidationResult {\n const errors: string[] = []\n const counts: Partial<Record<string, number>> = Object.create(null)\n const data = isPlainRecord(value) ? value as Partial<AiwgFortemiIndexExport> : {}\n if (!isPlainRecord(value)) errors.push('index export must be an object')\n\n if (!isSupportedIndexSchemaVersion(data?.schema_version)) {\n errors.push('schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2')\n }\n if (!hasString(data?.generated_at)) errors.push('generated_at is required')\n if (!hasString(data?.source?.repo)) errors.push('source.repo is required')\n if (!hasString(data?.source?.privacy)) errors.push('source.privacy is required')\n else if (!isPrivacyClassification(data?.source?.privacy)) {\n errors.push('source.privacy must be one of private, sanitized, public')\n }\n if (!Array.isArray(data?.items)) errors.push('items must be an array')\n if (data.compatibility !== undefined && !isPlainRecord(data.compatibility)) {\n errors.push('compatibility must be an object')\n }\n // A5: export-level v1/v2 gating — source.graph and compatibility are v2-only.\n if (data?.schema_version === 'aiwg.fortemi.index.export.v1') {\n if (isPlainRecord(data.source) && (data.source as Record<string, unknown>).graph !== undefined) {\n errors.push('source.graph is a v2-only field and must be absent on an export.v1 export')\n }\n if (data.compatibility !== undefined) {\n errors.push('compatibility is a v2-only field and must be absent on an export.v1 export')\n }\n }\n\n const ids = new Set<string>()\n let previousId = ''\n const items = Array.isArray(data.items) ? data.items : []\n for (const [index, item] of items.entries()) {\n if (!isPlainRecord(item)) {\n errors.push('items[' + index + '] must be an object')\n continue\n }\n for (const field of REQUIRED_RECORD_FIELDS) {\n if (!(field in item)) errors.push('items[' + index + '].' + field + ' is required')\n }\n if (!isSupportedRecordSchemaVersion(item.schema_version)) {\n errors.push('items[' + index + '].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2')\n }\n if (data.schema_version === 'aiwg.fortemi.index.export.v1' && item.schema_version === 'aiwg.fortemi.index.record.v2') {\n errors.push('items[' + index + '].schema_version must match aiwg.fortemi.index.export.v1')\n }\n if (!hasString(item.id)) errors.push('items[' + index + '].id is required')\n if (hasString(item.id) && ids.has(item.id)) errors.push('duplicate id: ' + item.id)\n if (hasString(item.id)) ids.add(item.id)\n if (previousId && hasString(item.id) && previousId > item.id) {\n errors.push('items must be sorted by id: ' + previousId + ' before ' + item.id)\n }\n if (hasString(item.id)) previousId = item.id\n if (!hasString(item.type)) errors.push('items[' + index + '].type must be a non-empty string')\n else counts[item.type] = (counts[item.type] ?? 0) + 1\n if (!hasString(item.source?.path)) errors.push('items[' + index + '].source.path is required')\n if (!hasString(item.source?.repo_relative_path)) errors.push('items[' + index + '].source.repo_relative_path is required')\n if (!hasString(item.source?.locator)) errors.push('items[' + index + '].source.locator is required')\n if (typeof item.title !== 'string' && typeof item.search?.title !== 'string' && typeof item.search?.name !== 'string') {\n errors.push('items[' + index + '].title or search.title/search.name is required')\n }\n if (typeof item.text !== 'string' && typeof item.search?.body !== 'string' && typeof item.search?.summary !== 'string') {\n errors.push('items[' + index + '].text or search.body/search.summary is required')\n }\n if (!Array.isArray(item.tags)) errors.push('items[' + index + '].tags must be an array')\n if (!Array.isArray(item.concepts)) errors.push('items[' + index + '].concepts must be an array')\n if (!Array.isArray(item.relationships)) errors.push('items[' + index + '].relationships must be an array')\n if (!Array.isArray(item.provenance) || item.provenance.length === 0) {\n errors.push('items[' + index + '].provenance must be a non-empty array')\n }\n validateOptionalRichMetadata(item, index, errors)\n validateProvenanceItems(item, index, errors)\n forbidV2FieldsOnV1Record(item, index, errors)\n if (!item.privacy || typeof item.privacy.pii !== 'boolean' || !hasString(item.privacy.classification)) {\n errors.push('items[' + index + '].privacy requires classification and pii')\n } else if (!isPrivacyClassification(item.privacy.classification)) {\n errors.push('items[' + index + '].privacy.classification must be one of private, sanitized, public')\n }\n }\n\n return { valid: errors.length === 0, errors, counts }\n}\n\nexport function assertAiwgFortemiIndexExport(value: unknown): AiwgFortemiIndexExport {\n const result = validateAiwgFortemiIndexExport(value)\n if (!result.valid) {\n throw new Error('Invalid AIWG Fortemi index export:\\n' + result.errors.join('\\n'))\n }\n return value as AiwgFortemiIndexExport\n}\n\nexport function validateAiwgFortemiChunkManifest(value: unknown): AiwgChunkedIndexValidationResult {\n const errors: string[] = []\n const data = isPlainRecord(value) ? value as Partial<AiwgFortemiChunkManifest> : {}\n if (!isPlainRecord(value)) errors.push('chunk manifest must be an object')\n\n if (data?.schema_version !== 'aiwg.fortemi.index.chunk-manifest.v1') {\n errors.push('schema_version must be aiwg.fortemi.index.chunk-manifest.v1')\n }\n if (!hasString(data?.generated_at)) errors.push('generated_at is required')\n if (!hasString(data?.source?.repo)) errors.push('source.repo is required')\n if (!hasString(data?.source?.privacy)) errors.push('source.privacy is required')\n if (data?.source_export_schema_version !== undefined && !isSupportedIndexSchemaVersion(data.source_export_schema_version)) {\n errors.push('source_export_schema_version must be aiwg.fortemi.index.export.v1 or aiwg.fortemi.index.export.v2 when present')\n }\n if (!hasNonNegativeInteger(data?.total)) errors.push('total must be a non-negative integer')\n if (!hasPositiveInteger(data?.part_size)) errors.push('part_size must be a positive integer')\n if (data.facets !== undefined && !isFacetCounts(data.facets)) {\n errors.push('facets must be a nested string-to-number count object')\n }\n if (data.projection !== undefined) {\n if (!Array.isArray(data.projection) || !data.projection.every((field) => typeof field === 'string')) {\n errors.push('projection must be an array of field names')\n } else {\n const present = new Set(data.projection)\n for (const field of AIWG_SCAN_REQUIRED_FIELDS) {\n if (!present.has(field)) errors.push('projection must include scan-required field ' + field)\n }\n }\n }\n if (data.detail !== undefined && !isPlainRecord(data.detail)) {\n errors.push('detail must be an object')\n } else if (data.detail !== undefined) {\n if (!hasString(data.detail.href)) errors.push('detail.href is required')\n else if (!data.detail.href.includes('{id}')) errors.push('detail.href must contain the {id} placeholder')\n if (\n data.detail.encoding !== undefined &&\n data.detail.encoding !== 'uri' &&\n data.detail.encoding !== 'base64url'\n ) {\n errors.push(\"detail.encoding must be 'uri' or 'base64url'\")\n }\n }\n if (!Array.isArray(data?.parts)) errors.push('parts must be an array')\n\n let expectedOffset = 0\n const parts = Array.isArray(data?.parts) ? data.parts : []\n for (const [index, part] of parts.entries()) {\n if (!isPlainRecord(part)) {\n errors.push('parts[' + index + '] must be an object')\n continue\n }\n if (!hasString(part.href)) errors.push('parts[' + index + '].href is required')\n if (!hasNonNegativeInteger(part.offset)) errors.push('parts[' + index + '].offset must be a non-negative integer')\n if (!hasNonNegativeInteger(part.count)) errors.push('parts[' + index + '].count must be a non-negative integer')\n if (hasNonNegativeInteger(part.offset) && part.offset !== expectedOffset) {\n errors.push('parts[' + index + '].offset must be ' + expectedOffset)\n }\n if (hasNonNegativeInteger(part.count)) expectedOffset += part.count\n }\n if (hasNonNegativeInteger(data?.total) && expectedOffset !== data.total) {\n errors.push('parts counts must add up to total')\n }\n\n return { valid: errors.length === 0, errors }\n}\n\nexport function assertAiwgFortemiChunkManifest(value: unknown): AiwgFortemiChunkManifest {\n const result = validateAiwgFortemiChunkManifest(value)\n if (!result.valid) {\n throw new Error('Invalid AIWG Fortemi chunk manifest:\\n' + result.errors.join('\\n'))\n }\n return value as AiwgFortemiChunkManifest\n}\n\nfunction validateProjectedRecordShape(item: Partial<AiwgFortemiRecord>, index: number, errors: string[]): void {\n const at = 'items[' + index + ']'\n if (!item.privacy || !isPlainRecord(item.privacy)) {\n errors.push(at + '/privacy requires classification and pii')\n } else {\n if (!isPrivacyClassification(item.privacy.classification)) {\n errors.push(at + '/privacy/classification must be one of private, sanitized, public')\n }\n if (typeof item.privacy.pii !== 'boolean') {\n errors.push(at + '/privacy/pii must be boolean')\n }\n }\n if (Array.isArray(item.provenance)) {\n for (const [provIndex, prov] of item.provenance.entries()) {\n if (!isPlainRecord(prov)) {\n errors.push(at + '/provenance/' + provIndex + ' must be an object')\n continue\n }\n if (!isProvenanceConfidence(prov.confidence)) {\n errors.push(at + '/provenance/' + provIndex + '/confidence must be one of source, candidate, reviewed, rejected')\n }\n if (!isPrivacyClassification(prov.privacy)) {\n errors.push(at + '/provenance/' + provIndex + '/privacy must be one of private, sanitized, public')\n }\n }\n }\n}\n\n// Validate projected (slim) scan-part items: scan-required fields only, ids unique + sorted.\nfunction validateProjectedRecords(\n items: Array<Partial<AiwgFortemiRecord>>,\n sourceSchemaVersion: AiwgFortemiIndexExportSchemaVersion,\n): string[] {\n const errors: string[] = []\n const ids = new Set<string>()\n let previousId = ''\n for (const [index, item] of items.entries()) {\n if (!isPlainRecord(item)) {\n errors.push('items[' + index + '] must be an object')\n continue\n }\n validateProjectedRecordShape(item, index, errors)\n const expectedRecordVersion = sourceSchemaVersion === 'aiwg.fortemi.index.export.v2'\n ? 'aiwg.fortemi.index.record.v2'\n : 'aiwg.fortemi.index.record.v1'\n if (item.schema_version !== expectedRecordVersion) {\n errors.push(`items[${index}].schema_version must match ${sourceSchemaVersion}`)\n }\n if (!isSupportedRecordSchemaVersion(item.schema_version)) {\n errors.push('items[' + index + '].schema_version must be aiwg.fortemi.index.record.v1 or aiwg.fortemi.index.record.v2')\n }\n if (!hasString(item.id)) errors.push('items[' + index + '].id is required')\n if (hasString(item.id) && ids.has(item.id)) errors.push('duplicate id: ' + item.id)\n if (hasString(item.id)) ids.add(item.id)\n if (previousId && hasString(item.id) && previousId > item.id) {\n errors.push('items must be sorted by id: ' + previousId + ' before ' + item.id)\n }\n if (hasString(item.id)) previousId = item.id\n if (!hasString(item.type)) errors.push('items[' + index + '].type must be a non-empty string')\n if (typeof item.title !== 'string' && typeof item.search?.title !== 'string' && typeof item.search?.name !== 'string') {\n errors.push('items[' + index + '].title or search.title/search.name is required')\n }\n if (typeof item.text !== 'string' && typeof item.search?.body !== 'string' && typeof item.search?.summary !== 'string') {\n errors.push('items[' + index + '].text or search.body/search.summary is required')\n }\n if (!item.facets || typeof item.facets !== 'object' || Array.isArray(item.facets)) {\n errors.push('items[' + index + '].facets must be an object')\n }\n if (!Array.isArray(item.tags)) errors.push('items[' + index + '].tags must be an array')\n if (!Array.isArray(item.concepts)) errors.push('items[' + index + '].concepts must be an array')\n }\n return errors\n}\n\nexport function validateAiwgFortemiChunkPart(\n value: unknown,\n partRef?: AiwgFortemiChunkPartRef,\n manifest?: AiwgFortemiChunkManifest,\n): AiwgChunkedIndexValidationResult {\n const errors: string[] = []\n const data = isPlainRecord(value) ? value as Partial<AiwgFortemiChunkPart> : {}\n if (!isPlainRecord(value)) errors.push('chunk part must be an object')\n\n if (data?.schema_version !== 'aiwg.fortemi.index.chunk.v1') {\n errors.push('schema_version must be aiwg.fortemi.index.chunk.v1')\n }\n if (data?.manifest_schema_version !== 'aiwg.fortemi.index.chunk-manifest.v1') {\n errors.push('manifest_schema_version must be aiwg.fortemi.index.chunk-manifest.v1')\n }\n if (!hasNonNegativeInteger(data?.offset)) errors.push('offset must be a non-negative integer')\n if (!Array.isArray(data?.items)) errors.push('items must be an array')\n\n if (partRef && hasNonNegativeInteger(data?.offset) && data.offset !== partRef.offset) {\n errors.push('offset must match manifest part offset ' + partRef.offset)\n }\n if (partRef && Array.isArray(data?.items) && data.items.length !== partRef.count) {\n errors.push('items length must match manifest part count ' + partRef.count)\n }\n\n if (Array.isArray(data?.items)) {\n if (manifest?.projection) {\n errors.push(...validateProjectedRecords(\n data.items,\n manifest.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1',\n ).map((error) => 'items.' + error))\n } else {\n const validation = validateAiwgFortemiIndexExport({\n schema_version: manifest?.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1',\n generated_at: manifest?.generated_at ?? '1970-01-01T00:00:00.000Z',\n source: manifest?.source ?? { repo: 'chunk', privacy: 'public' },\n ...((manifest?.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1') === 'aiwg.fortemi.index.export.v2'\n ? { compatibility: { previous_schema_version: 'aiwg.fortemi.index.export.v1', strategy: 'supported' } }\n : {}),\n items: data.items,\n })\n errors.push(...validation.errors.map((error) => 'items.' + error))\n }\n }\n\n return { valid: errors.length === 0, errors }\n}\n\nexport function assertAiwgFortemiChunkPart(\n value: unknown,\n partRef?: AiwgFortemiChunkPartRef,\n manifest?: AiwgFortemiChunkManifest,\n): AiwgFortemiChunkPart {\n const result = validateAiwgFortemiChunkPart(value, partRef, manifest)\n if (!result.valid) {\n throw new Error('Invalid AIWG Fortemi chunk part:\\n' + result.errors.join('\\n'))\n }\n return value as AiwgFortemiChunkPart\n}\n\n// Schemes an index fetch may target. Blocks file:, ftp:, ws:, etc. so a\n// manifest-controlled href cannot pivot the browser into a non-web protocol.\nconst ALLOWED_AIWG_FETCH_SCHEMES = new Set(['http:', 'https:', 'blob:', 'data:'])\n\nfunction tryParseUrl(value: string): URL | null {\n try {\n return new URL(value)\n } catch {\n return null\n }\n}\n\n// Resolve and vet a manifest-controlled fetch target (SEC2 — SSRF).\n// - With a baseUrl: the href is resolved against it and MUST stay same-origin,\n// so an absolute `href` (which `new URL` would otherwise honor, ignoring the\n// base) cannot redirect the fetch to an attacker origin.\n// - Without a baseUrl: the caller opted into a bare href; only the scheme is\n// vetted (relative hrefs are passed through unchanged).\nexport function resolveAiwgFetchUrl(href: string, baseUrl?: string | URL): string {\n if (baseUrl === undefined) {\n const absolute = tryParseUrl(href)\n if (absolute && !ALLOWED_AIWG_FETCH_SCHEMES.has(absolute.protocol)) {\n throw new Error('Refusing AIWG index fetch with disallowed scheme: ' + absolute.protocol)\n }\n return href\n }\n const base = new URL(baseUrl)\n const resolved = new URL(href, base)\n if (!ALLOWED_AIWG_FETCH_SCHEMES.has(resolved.protocol)) {\n throw new Error('Refusing AIWG index fetch with disallowed scheme: ' + resolved.protocol)\n }\n if (resolved.origin !== base.origin) {\n throw new Error('Refusing cross-origin AIWG index fetch: ' + resolved.origin + ' != ' + base.origin)\n }\n return resolved.toString()\n}\n\nexport function createAiwgFetchChunkLoader(baseUrl?: string | URL): AiwgChunkedIndexLoader {\n return async (part) => {\n const href = resolveAiwgFetchUrl(part.href, baseUrl)\n const response = await fetch(href)\n if (!response.ok) throw new Error('Failed to fetch AIWG index chunk ' + href + ': ' + response.status)\n return response.json()\n }\n}\n\n// Encode a record id into a single, path-safe detail filename segment.\n// - 'base64url' (default): UTF-8 → base64url (no '+', '/', '=', '%'). Safe for ids\n// containing '/' on static hosts that reject %2F (#177).\n// - 'uri': encodeURIComponent (legacy).\nexport function encodeAiwgDetailId(id: string, encoding: AiwgDetailIdEncoding = 'base64url'): string {\n if (encoding === 'uri') return encodeURIComponent(id)\n const bytes = new TextEncoder().encode(id)\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n // btoa is available in browsers and Node ≥16.\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// Resolve a manifest detail.href template for a given id, honoring detail.encoding\n// (absent → 'uri' for backward compatibility). The writer and the loader both go\n// through this so emitted filenames and fetched paths always agree.\nexport function aiwgDetailHrefForId(detail: AiwgFortemiChunkDetailRef, id: string): string {\n return detail.href.replace('{id}', encodeAiwgDetailId(id, detail.encoding ?? 'uri'))\n}\n\n// Detail loader for projected indexes: resolves the manifest's detail.href {id}\n// template (encoded per detail.encoding) against baseUrl and fetches the full record.\nexport function createAiwgFetchDetailLoader(baseUrl?: string | URL): AiwgChunkedIndexDetailLoader {\n return async (id, manifest) => {\n if (!manifest.detail?.href) throw new Error('Manifest has no detail.href for record resolution')\n const relative = aiwgDetailHrefForId(manifest.detail, id)\n const href = resolveAiwgFetchUrl(relative, baseUrl)\n const response = await fetch(href)\n if (!response.ok) throw new Error('Failed to fetch AIWG index detail ' + href + ': ' + response.status)\n return response.json()\n }\n}\n\nexport function getAiwgFortemiFacets(items: AiwgFortemiRecord[]): Record<string, Record<string, number>> {\n // Null-prototype accumulator: untrusted facet names must never resolve to an\n // inherited property (see pushFacet / SEC1 / #236). Round-trips to a plain\n // object through JSON serialization, so no downstream consumer is affected.\n const result: Record<string, Record<string, number>> = Object.create(null)\n for (const item of items) {\n pushFacet(result, 'type', item.type)\n pushFacet(result, 'privacy', item.privacy.classification)\n for (const tag of item.tags) pushFacet(result, 'tag', tag)\n for (const concept of item.concepts) pushFacet(result, 'concept', concept)\n for (const [name, values] of Object.entries(item.facets)) {\n for (const value of values) pushFacet(result, name, value)\n }\n }\n return result\n}\n\nfunction recordTitle(item: AiwgFortemiProjectedRecord): string {\n return item.title ?? item.search?.title ?? item.search?.name ?? item.id\n}\n\nfunction recordText(item: AiwgFortemiProjectedRecord): string {\n const base = item.text\n ?? item.search?.body\n ?? item.search?.summary\n ?? item.chunks?.map((chunk) => chunk.text ?? chunk.body ?? chunk.summary ?? '').filter(Boolean).join('\\n')\n ?? ''\n const extractedText = binarySourceText(item)\n return [base, extractedText].filter(Boolean).join('\\n')\n}\n\nfunction binarySourceText(item: AiwgFortemiProjectedRecord): string {\n return 'binary_sources' in item\n ? item.binary_sources?.map((source) => source.extracted_text).filter(Boolean).join('\\n') ?? ''\n : ''\n}\n\nfunction defaultEmbeddingInput(record: AiwgFortemiRecord, granularity: AiwgStaticEmbeddingSet['granularity']): string {\n const title = recordTitle(record)\n const text = recordText(record)\n if (granularity === 'title-summary') {\n // Attachment text remains part of title-summary embeddings so binary-only\n // knowledge is searchable even when the record has no authored summary.\n return [title, record.search?.summary ?? '', binarySourceText(record)].filter(Boolean).join('\\n')\n }\n return [title, text].filter(Boolean).join('\\n')\n}\n\nfunction generatedAtString(value: string | Date | undefined): string {\n if (value instanceof Date) return value.toISOString()\n return value ?? new Date().toISOString()\n}\n\nconst SHA256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n] as const\n\nfunction rotr(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits))\n}\n\nfunction sha256Hex(data: Uint8Array): string {\n const bitLength = data.length * 8\n const padded = new Uint8Array((((data.length + 9 + 63) >> 6) << 6))\n padded.set(data)\n padded[data.length] = 0x80\n const view = new DataView(padded.buffer)\n view.setUint32(padded.length - 4, bitLength >>> 0)\n view.setUint32(padded.length - 8, Math.floor(bitLength / 0x100000000))\n let h0 = 0x6a09e667\n let h1 = 0xbb67ae85\n let h2 = 0x3c6ef372\n let h3 = 0xa54ff53a\n let h4 = 0x510e527f\n let h5 = 0x9b05688c\n let h6 = 0x1f83d9ab\n let h7 = 0x5be0cd19\n const w = new Uint32Array(64)\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4)\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3)\n const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10)\n w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0\n }\n let a = h0\n let b = h1\n let c = h2\n let d = h3\n let e = h4\n let f = h5\n let g = h6\n let h = h7\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)\n const ch = (e & f) ^ (~e & g)\n const temp1 = (h + s1 + ch + SHA256_K[i] + w[i]) >>> 0\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)\n const maj = (a & b) ^ (a & c) ^ (b & c)\n const temp2 = (s0 + maj) >>> 0\n h = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n h0 = (h0 + a) >>> 0\n h1 = (h1 + b) >>> 0\n h2 = (h2 + c) >>> 0\n h3 = (h3 + d) >>> 0\n h4 = (h4 + e) >>> 0\n h5 = (h5 + f) >>> 0\n h6 = (h6 + g) >>> 0\n h7 = (h7 + h) >>> 0\n }\n return [h0, h1, h2, h3, h4, h5, h6, h7].map((part) => part.toString(16).padStart(8, '0')).join('')\n}\n\nfunction computeAiwgIndexHash(data: Uint8Array): string {\n return `sha256:${sha256Hex(data)}`\n}\n\nexport async function buildAiwgStaticEmbeddingSet(\n index: AiwgFortemiIndexExport,\n options: BuildAiwgStaticEmbeddingSetOptions,\n): Promise<AiwgStaticEmbeddingSet> {\n assertAiwgFortemiIndexExport(index)\n const granularity = options.granularity ?? 'body'\n // SEC6: default-safe privacy filter over the source records.\n const records = filterAiwgRecordsByPrivacy(options.records ?? index.items, options.privacy)\n const embeddings: AiwgStaticEmbeddingRecord[] = []\n\n for (const record of records) {\n const input = options.textForRecord?.(record) ?? defaultEmbeddingInput(record, granularity)\n const embedding = await options.backend.embed(input, record)\n if (embedding.length !== options.backend.dimensions) {\n throw new Error(`Embedding for ${record.id} has ${embedding.length} dimensions; expected ${options.backend.dimensions}`)\n }\n embeddings.push({\n record_id: record.id,\n embedding,\n granularity,\n input_hash: computeAiwgIndexHash(new TextEncoder().encode(input)),\n source_path: record.source.path,\n })\n }\n\n const embeddingSet: AiwgStaticEmbeddingSet = {\n schema_version: 'aiwg.fortemi.embedding.set.v1',\n id: options.id,\n model: options.backend.model,\n dimensions: options.backend.dimensions,\n generated_at: generatedAtString(options.generatedAt),\n granularity,\n ...(options.metric ? { metric: options.metric } : {}),\n input_hash_algorithm: 'sha256',\n embeddings,\n }\n assertAiwgStaticEmbeddingSet(embeddingSet)\n return embeddingSet\n}\n\nfunction recordSearchValues(item: AiwgFortemiProjectedRecord): string[] {\n const search = item.search\n const values = [\n item.id,\n recordTitle(item),\n recordText(item),\n search?.title,\n search?.name,\n search?.summary,\n search?.body,\n search?.capability,\n search?.phase,\n search?.type,\n ...(search?.triggers ?? []),\n ...(search?.aliases ?? []),\n ...(search?.tags ?? []),\n ...(item.chunks ?? []).flatMap((chunk) => [chunk.text, chunk.body, chunk.summary, chunk.source_path]),\n ]\n if (search?.frontmatter) {\n for (const value of Object.values(search.frontmatter)) {\n if (typeof value === 'string') values.push(value)\n else if (Array.isArray(value)) values.push(...value.filter((entry): entry is string => typeof entry === 'string'))\n }\n }\n return values.filter((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\nexport interface AiwgChunkedIndexBuildOptions {\n partSize?: number\n // When set, scan parts carry only these fields; full records go to `details`.\n projection?: Array<keyof AiwgFortemiRecord>\n // Detail href template (with {id}); defaults to \"detail/{id}.json\" when projecting.\n detailHref?: string\n // id→filename encoding for detail files; defaults to 'base64url' (path-safe,\n // works for ids containing '/'; see #177).\n idEncoding?: AiwgDetailIdEncoding\n generatedAt?: string\n /** Privacy filtering (SEC6). Default-safe: excludes `private`/`pii` records. */\n privacy?: AiwgPrivacyFilterOptions\n}\n\nexport interface AiwgChunkedIndexBuildResult {\n manifest: AiwgFortemiChunkManifest\n parts: Array<{ href: string; part: AiwgFortemiChunkPart }>\n // Empty unless projecting. Each entry carries the full record plus the resolved,\n // encoding-correct `href` to host it at — write the record to that path so the\n // detail loader (which uses the same encoding) can fetch it back.\n details: Array<{ id: string; href: string; record: AiwgFortemiRecord }>\n}\n\n// Pure builder (no I/O): project an index export into the chunked manifest + parts\n// (+ detail records when projecting). The caller writes the returned objects to disk.\n// Manifest facets are computed from the full records, so global counts are exact even\n// when scan parts are slim.\nexport function buildAiwgChunkedIndex(\n index: AiwgFortemiIndexExport,\n options: AiwgChunkedIndexBuildOptions = {},\n): AiwgChunkedIndexBuildResult {\n assertAiwgFortemiIndexExport(index)\n const partSize = hasPositiveInteger(options.partSize) ? options.partSize : 500\n const projection = options.projection\n const idEncoding = options.idEncoding ?? 'base64url'\n const detailHref = options.detailHref ?? 'detail/{id}.json'\n // SEC6: default-safe privacy filter — `private`/`pii` records never enter the\n // generated scan parts, detail files, or manifest facet counts.\n const items = filterAiwgRecordsByPrivacy(index.items, options.privacy)\n const pad = (value: number): string => String(value).padStart(4, '0')\n const project = (record: AiwgFortemiRecord): AiwgFortemiRecord => {\n if (!projection) return record\n const slim: Record<string, unknown> = {}\n for (const field of projection) slim[field] = record[field]\n return slim as unknown as AiwgFortemiRecord\n }\n\n const parts: Array<{ href: string; part: AiwgFortemiChunkPart }> = []\n const partRefs: AiwgFortemiChunkPartRef[] = []\n for (let offset = 0, partIndex = 0; offset < items.length; offset += partSize, partIndex += 1) {\n const slice = items.slice(offset, offset + partSize)\n const href = 'part-' + pad(partIndex) + '.json'\n parts.push({\n href,\n part: {\n schema_version: 'aiwg.fortemi.index.chunk.v1',\n manifest_schema_version: 'aiwg.fortemi.index.chunk-manifest.v1',\n offset,\n items: slice.map(project),\n },\n })\n partRefs.push({ href, offset, count: slice.length })\n }\n\n const manifest: AiwgFortemiChunkManifest = {\n schema_version: 'aiwg.fortemi.index.chunk-manifest.v1',\n generated_at: options.generatedAt ?? index.generated_at,\n source: index.source,\n source_export_schema_version: index.schema_version,\n total: items.length,\n part_size: partSize,\n facets: getAiwgFortemiFacets(items),\n parts: partRefs,\n ...(projection ? { projection, detail: { href: detailHref, encoding: idEncoding } } : {}),\n }\n\n return {\n manifest,\n parts,\n details: projection\n ? items.map((record) => ({\n id: record.id,\n href: aiwgDetailHrefForId({ href: detailHref, encoding: idEncoding }, record.id),\n record,\n }))\n : [],\n }\n}\n\nfunction includesAll(actual: string[], expected: string[] | undefined): boolean {\n if (!expected || expected.length === 0) return true\n const actualSet = new Set(actual)\n return expected.every((value) => actualSet.has(value))\n}\n\nfunction matchesFacetFilters(item: AiwgFortemiRecord, filters: Record<string, string[]> | undefined): boolean {\n if (!filters) return true\n return Object.entries(filters).every(([name, expected]) => includesAll(item.facets[name] ?? [], expected))\n}\n\nfunction queryMatches(item: AiwgFortemiRecord, q: string): AiwgIndexQueryMatch[] {\n if (!q) return []\n const matches: AiwgIndexQueryMatch[] = []\n const title = recordTitle(item)\n const text = recordText(item)\n if (title.toLowerCase().includes(q)) matches.push({ field: 'title', value: title })\n if (text.toLowerCase().includes(q)) matches.push({ field: 'text', value: text })\n for (const tag of item.tags) {\n if (tag.toLowerCase().includes(q)) matches.push({ field: 'tag', value: tag })\n }\n for (const concept of item.concepts) {\n if (concept.toLowerCase().includes(q)) matches.push({ field: 'concept', value: concept })\n }\n for (const value of recordSearchValues(item)) {\n if (value !== title && value !== text && value.toLowerCase().includes(q)) {\n matches.push({ field: 'text', value, score: DEFAULT_QUERY_WEIGHTS.text })\n }\n }\n return matches\n}\n\nconst DISCOVERY_STOPWORDS = new Set([\n 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'in', 'on',\n 'with', 'into', 'from', 'is', 'are', 'be', 'i', 'we', 'my',\n 'it', 'you', 'me', 'us', 'your', 'our', 'this', 'that', 'these', 'those',\n 'there', 'here', 'some', 'any', 'all', 'also', 'please', 'about',\n 'how', 'what', 'which', 'where', 'when', 'who', 'why',\n 'find', 'give', 'show', 'need', 'want', 'looking', 'look', 'help',\n 'do', 'does', 'did', 'can', 'could', 'should', 'would', 'will',\n 'handle', 'handles', 'handling',\n 'aiwg', 'skill', 'skills', 'agent', 'agents', 'command', 'commands',\n 'rule', 'rules', 'flow', 'flows', 'workflow', 'workflows',\n])\n\nfunction normalizeDiscoveryName(value: string): string {\n return value.toLowerCase().replace(/[-_\\s]+/g, ' ').trim()\n}\n\nfunction discoveryTokens(value: string): string[] {\n return value\n .toLowerCase()\n .split(/[^a-z0-9-]+/)\n .filter((token) => token.length > 1 && !DISCOVERY_STOPWORDS.has(token))\n}\n\nfunction facetValues(item: AiwgFortemiRecord, names: string[]): string[] {\n return names.flatMap((name) => item.facets[name] ?? [])\n}\n\nfunction addDiscoveryMatch(matches: AiwgIndexQueryMatch[], match: AiwgIndexQueryMatch) {\n if (!matches.some((existing) => existing.field === match.field && existing.value === match.value && existing.reason === match.reason)) {\n matches.push(match)\n }\n}\n\nfunction damerauLevenshteinAtMostOne(left: string, right: string): boolean {\n if (left === right) return true\n if (Math.abs(left.length - right.length) > 1) return false\n\n if (left.length === right.length) {\n let firstDiff = -1\n let diffCount = 0\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n if (firstDiff < 0) firstDiff = index\n diffCount += 1\n }\n }\n if (diffCount === 1) return true\n return diffCount === 2\n && firstDiff + 1 < left.length\n && left[firstDiff] === right[firstDiff + 1]\n && left[firstDiff + 1] === right[firstDiff]\n }\n\n const shorter = left.length < right.length ? left : right\n const longer = left.length < right.length ? right : left\n let shorterIndex = 0\n let longerIndex = 0\n let edits = 0\n while (shorterIndex < shorter.length && longerIndex < longer.length) {\n if (shorter[shorterIndex] === longer[longerIndex]) {\n shorterIndex += 1\n longerIndex += 1\n } else {\n edits += 1\n if (edits > 1) return false\n longerIndex += 1\n }\n }\n return true\n}\n\nfunction nearDiscoveryNameMatch(query: string, name: string): boolean {\n const queryParts = normalizeDiscoveryName(query).split(/\\s+/).filter(Boolean)\n const nameParts = normalizeDiscoveryName(name).split(/\\s+/).filter(Boolean)\n if (queryParts.length !== nameParts.length) return false\n\n return queryParts.every((part, index) => {\n const target = nameParts[index]\n if (part === target) return true\n if (part.length < 5 || target.length < 5) return false\n return damerauLevenshteinAtMostOne(part, target)\n })\n}\n\nfunction lowerValues(values: string[]): string[] {\n return values.map((value) => value.toLowerCase())\n}\n\ninterface DiscoveryScoringOptions {\n relaxOverlap?: boolean\n}\n\nfunction discoveryMatches(item: AiwgFortemiRecord, query: string, options: DiscoveryScoringOptions = {}): AiwgIndexQueryMatch[] {\n if (!query) return []\n const matches: AiwgIndexQueryMatch[] = []\n const tokens = discoveryTokens(query)\n const lower = tokens.length > 0 ? tokens.join(' ') : query.toLowerCase().trim()\n const rawLower = query.toLowerCase().trim()\n const idParts = item.id.split(/[:/]/)\n const names = [\n item.id,\n recordTitle(item),\n item.search?.name,\n item.search?.title,\n ...(item.search?.aliases ?? []),\n ...idParts,\n ...facetValues(item, ['name', 'canonical_name', 'command', 'skill', 'agent', 'rule']),\n ].filter((value): value is string => hasString(value))\n const triggers = [\n ...facetValues(item, ['trigger', 'triggers', 'trigger_phrase', 'trigger_phrases']),\n ...(item.search?.triggers ?? []),\n ]\n const capabilities = [\n ...facetValues(item, ['capability', 'capabilities', 'summary', 'description']),\n item.search?.capability,\n item.search?.summary,\n item.search?.phase,\n item.search?.type,\n ...(item.search?.tags ?? []),\n ...item.concepts,\n ...item.tags,\n ].filter((value): value is string => hasString(value))\n const sourceValues = [item.source?.path, item.source?.repo_relative_path, item.source?.locator].filter((value): value is string => hasString(value))\n const title = recordTitle(item)\n const summary = [item.search?.summary, recordText(item)].filter((value): value is string => hasString(value)).join('\\n')\n const type = item.search?.type ?? item.type\n const tags = [...(item.search?.tags ?? []), ...item.tags]\n const useMultiToken = tokens.length > 1\n const minHits = useMultiToken ? (options.relaxOverlap ? 1 : Math.ceil(tokens.length / 2)) : 1\n const overlapOK = (hits: number): boolean => useMultiToken && hits >= minHits\n\n const addInfo = (match: AiwgIndexQueryMatch) => addDiscoveryMatch(matches, { ...match, score: 0 })\n const addScore = (score: number) => {\n if (score > 0) addDiscoveryMatch(matches, { field: 'id', value: item.id, score, reason: 'aiwg discovery score' })\n }\n\n for (const name of names) {\n if (normalizeDiscoveryName(query) === normalizeDiscoveryName(name)) {\n addInfo({ field: 'id', value: name, reason: 'exact canonical name' })\n addScore(1.001)\n return matches\n }\n if (nearDiscoveryNameMatch(query, name)) {\n addInfo({ field: 'id', value: name, reason: 'near canonical name' })\n addScore(0.951)\n return matches\n }\n }\n\n let score = 0\n const scoreText = (\n field: AiwgIndexQueryMatch['field'],\n value: string,\n reason: string,\n exactScore: number,\n overlapScore: number,\n weight: number,\n exactBonus = 0,\n ) => {\n const normalized = value.toLowerCase()\n if (normalized.includes(lower)) {\n score += exactScore * weight\n if (normalized === lower) score += exactBonus\n addInfo({ field, value, reason })\n } else if (useMultiToken) {\n const hits = tokens.filter((token) => normalized.includes(token)).length\n if (overlapOK(hits)) {\n score += overlapScore * weight * (hits / tokens.length)\n addInfo({ field, value, reason })\n }\n }\n }\n\n for (const trigger of lowerValues(triggers)) {\n if (trigger === lower || trigger === rawLower) {\n addInfo({ field: 'facet', value: trigger, reason: 'trigger phrase' })\n addScore(1.0008)\n return matches\n }\n }\n for (const trigger of triggers) {\n scoreText('facet', trigger, 'trigger phrase', 0.25, 0.06, 4)\n }\n for (const capability of capabilities) scoreText('concept', capability, 'capability overlap', 0.2, 0.1, 2)\n scoreText('title', title, 'title token overlap', 0.3, 0.08, 3, 0.2)\n for (const tag of tags) scoreText('tag', tag, 'tag token overlap', 0.2, 0.05, 2)\n if (summary) scoreText('text', summary, 'body token overlap', 0.15, 0.04, 1)\n for (const source of sourceValues) {\n scoreText('source', source, 'path overlap', 0.1, 0.03, 1)\n }\n if (type.toLowerCase().includes(lower)) {\n score += 0.1\n addInfo({ field: 'facet', value: type, reason: 'type overlap' })\n }\n addScore(Math.min(score, 1.0))\n\n return matches\n}\n\nfunction rankMatches(matches: AiwgIndexQueryMatch[], weights: AiwgIndexQueryWeights): number {\n return matches.reduce((total, match) => total + (match.score ?? weights[match.field]), 0)\n}\n\nfunction clipSnippet(value: string, q: string, maxLength: number): string {\n const normalizedLength = Math.max(20, maxLength)\n if (!value) return ''\n if (!q) return value.length > normalizedLength ? `${value.slice(0, normalizedLength).trimEnd()}...` : value\n\n const lower = value.toLowerCase()\n const index = lower.indexOf(q)\n if (index < 0) return value.length > normalizedLength ? `${value.slice(0, normalizedLength).trimEnd()}...` : value\n\n const context = Math.max(0, Math.floor((normalizedLength - q.length) / 2))\n const start = Math.max(0, index - context)\n const end = Math.min(value.length, start + normalizedLength)\n const prefix = start > 0 ? '...' : ''\n const suffix = end < value.length ? '...' : ''\n return `${prefix}${value.slice(start, end).trim()}${suffix}`\n}\n\nfunction createSnippet(item: AiwgFortemiRecord, matches: AiwgIndexQueryMatch[], q: string, maxLength: number): string {\n const textMatch = matches.find((match) => match.field === 'text')\n const titleMatch = matches.find((match) => match.field === 'title')\n const firstMatch = textMatch ?? titleMatch ?? matches[0]\n return clipSnippet(firstMatch?.value ?? recordText(item), q, maxLength)\n}\n\ninterface AiwgRankedEntry {\n item: AiwgFortemiRecord\n ordinal: number\n rank: number\n matches: AiwgIndexQueryMatch[]\n}\n\nfunction createRankedEntries(\n items: AiwgFortemiRecord[],\n q: string,\n options: AiwgIndexQueryOptions,\n ordinalBase = 0,\n discoveryOptions: DiscoveryScoringOptions = {},\n): AiwgRankedEntry[] {\n const weights = { ...DEFAULT_QUERY_WEIGHTS, ...options.weights }\n const profile = options.searchProfile ?? 'default'\n return items.map((item, ordinal) => ({\n item,\n ordinal: ordinalBase + ordinal,\n matches: profile === 'aiwg-discovery' ? discoveryMatches(item, q, discoveryOptions) : queryMatches(item, q),\n }))\n .filter(({ item, matches }) => {\n if (q && matches.length === 0) return false\n if (options.types && !options.types.includes(item.type)) return false\n if (options.privacy && !options.privacy.includes(item.privacy.classification)) return false\n if (!includesAll(item.tags, options.tags)) return false\n if (!includesAll(item.concepts, options.concepts)) return false\n if (!matchesFacetFilters(item, options.facets)) return false\n if (options.relationshipTargetId && !(item.relationships ?? []).some((rel) => rel.target_id === options.relationshipTargetId)) {\n return false\n }\n return true\n })\n .map(({ item, ordinal, matches }) => ({\n item,\n ordinal,\n rank: rankMatches(matches, weights),\n matches,\n }))\n}\n\nfunction sortRankedEntries(entries: AiwgRankedEntry[], rank?: boolean): AiwgRankedEntry[] {\n return [...entries].sort((left, right) => {\n if (rank) return right.rank - left.rank || left.ordinal - right.ordinal\n return left.ordinal - right.ordinal\n })\n}\n\nfunction createQueryResultFromRankedEntries(\n entries: AiwgRankedEntry[],\n query: string,\n options: AiwgIndexQueryOptions,\n): AiwgIndexQueryResult {\n const ranked = sortRankedEntries(entries, options.rank)\n const offset = options.offset ?? 0\n const limit = options.limit ?? ranked.length\n const page = ranked.slice(offset, offset + limit)\n const result: AiwgIndexQueryResult = {\n items: page.map((entry) => entry.item),\n total: ranked.length,\n facets: getAiwgFortemiFacets(ranked.map((entry) => entry.item)),\n }\n if (options.rank || options.snippets || options.includeMatches) {\n const snippetLength = options.snippetLength ?? 160\n result.rankedItems = page.map((entry) => ({\n item: entry.item,\n rank: entry.rank,\n ...(options.snippets ? { snippet: createSnippet(entry.item, entry.matches, query, snippetLength) } : {}),\n ...(options.includeMatches ? { matches: entry.matches } : {}),\n }))\n }\n return result\n}\n\nexport function queryAiwgFortemiIndex(\n index: AiwgFortemiIndexExport,\n query = '',\n options: AiwgIndexQueryOptions = {},\n): AiwgIndexQueryResult {\n const q = query.trim().toLowerCase()\n const entries = createRankedEntries(index.items, q, options)\n if (entries.length === 0 && q && options.searchProfile === 'aiwg-discovery') {\n return createQueryResultFromRankedEntries(createRankedEntries(index.items, q, options, 0, { relaxOverlap: true }), q, options)\n }\n return createQueryResultFromRankedEntries(entries, q, options)\n}\n\nfunction cosineSimilarity(left: number[], right: number[]): number {\n if (left.length !== right.length || left.length === 0) return 0\n let dot = 0\n let leftMag = 0\n let rightMag = 0\n for (let i = 0; i < left.length; i += 1) {\n const l = left[i]\n const r = right[i]\n dot += l * r\n leftMag += l * l\n rightMag += r * r\n }\n if (leftMag === 0 || rightMag === 0) return 0\n return dot / (Math.sqrt(leftMag) * Math.sqrt(rightMag))\n}\n\nexport function validateAiwgStaticEmbeddingSet(value: unknown): AiwgChunkedIndexValidationResult {\n const errors: string[] = []\n const data = isPlainRecord(value) ? value as Partial<AiwgStaticEmbeddingSet> : {}\n if (!isPlainRecord(value)) errors.push('embedding set must be an object')\n if (data?.schema_version !== 'aiwg.fortemi.embedding.set.v1') errors.push('schema_version must be aiwg.fortemi.embedding.set.v1')\n if (!hasString(data?.id)) errors.push('id is required')\n if (!hasString(data?.model)) errors.push('model is required')\n if (!hasPositiveInteger(data?.dimensions)) errors.push('dimensions must be a positive integer')\n if (!hasString(data?.generated_at)) errors.push('generated_at is required')\n if (!hasString(data?.granularity)) errors.push('granularity is required')\n if (!Array.isArray(data?.embeddings)) errors.push('embeddings must be an array')\n const embeddings = Array.isArray(data.embeddings) ? data.embeddings : []\n for (const [index, embedding] of embeddings.entries()) {\n if (!isPlainRecord(embedding)) {\n errors.push('embeddings[' + index + '] must be an object')\n continue\n }\n if (!hasString(embedding.record_id)) errors.push('embeddings[' + index + '].record_id is required')\n if (!hasString(embedding.input_hash)) errors.push('embeddings[' + index + '].input_hash is required')\n if (!Array.isArray(embedding.embedding)) errors.push('embeddings[' + index + '].embedding must be an array')\n else if (hasPositiveInteger(data?.dimensions) && embedding.embedding.length !== data.dimensions) {\n errors.push('embeddings[' + index + '].embedding length must match dimensions')\n } else if (!embedding.embedding.every((number) => typeof number === 'number' && Number.isFinite(number))) {\n errors.push('embeddings[' + index + '].embedding must contain finite numbers')\n }\n }\n return { valid: errors.length === 0, errors }\n}\n\nexport function assertAiwgStaticEmbeddingSet(value: unknown): AiwgStaticEmbeddingSet {\n const result = validateAiwgStaticEmbeddingSet(value)\n if (!result.valid) throw new Error('Invalid AIWG Fortemi embedding set:\\n' + result.errors.join('\\n'))\n return value as AiwgStaticEmbeddingSet\n}\n\nexport function queryAiwgSemanticIndex(\n index: AiwgFortemiIndexExport,\n embeddingSet: AiwgStaticEmbeddingSet,\n queryEmbedding: number[],\n options: AiwgStaticSemanticQueryOptions = {},\n): AiwgStaticSemanticResult[] {\n assertAiwgStaticEmbeddingSet(embeddingSet)\n if (queryEmbedding.length !== embeddingSet.dimensions) throw new Error('query embedding length must match embedding set dimensions')\n const byId = new Map(index.items.map((item) => [item.id, item]))\n const offset = options.offset ?? 0\n const limit = options.limit ?? 20\n return embeddingSet.embeddings\n .map((embedding): AiwgStaticSemanticResult | null => {\n const item = byId.get(embedding.record_id)\n if (!item) return null\n return { item, embedding, score: cosineSimilarity(queryEmbedding, embedding.embedding) }\n })\n .filter((result): result is AiwgStaticSemanticResult => result !== null && result.score >= (options.minScore ?? -1))\n .sort((left, right) => right.score - left.score || left.item.id.localeCompare(right.item.id))\n .slice(offset, offset + limit)\n}\n\nexport function queryAiwgHybridIndex(\n index: AiwgFortemiIndexExport,\n embeddingSet: AiwgStaticEmbeddingSet,\n query: string,\n queryEmbedding: number[],\n options: AiwgStaticHybridQueryOptions = {},\n): AiwgStaticSemanticResult[] {\n const lexicalOptions: AiwgStaticHybridQueryOptions = { ...options }\n delete lexicalOptions.limit\n delete lexicalOptions.offset\n const lexical = queryAiwgFortemiIndex(index, query, { ...lexicalOptions, rank: true })\n const semantic = queryAiwgSemanticIndex(index, embeddingSet, queryEmbedding, { limit: index.items.length })\n const lexicalWeight = options.lexicalWeight ?? 0.5\n const semanticWeight = options.semanticWeight ?? 0.5\n const lexicalScores = new Map(lexical.rankedItems?.map((entry) => [entry.item.id, entry.rank]) ?? [])\n const maxLexical = Math.max(1, ...lexicalScores.values())\n const embeddingById = new Map(semantic.flatMap((entry) => entry.embedding ? [[entry.item.id, entry.embedding] as const] : []))\n const semanticScores = new Map(semantic.map((entry) => [entry.item.id, entry.score]))\n const ids = new Set([...lexicalScores.keys(), ...semanticScores.keys()])\n const offset = options.offset ?? 0\n const limit = options.limit ?? 20\n return [...ids]\n .map((id) => {\n const item = index.items.find((candidate) => candidate.id === id)\n const embedding = embeddingById.get(id)\n if (!item) return null\n return {\n item,\n ...(embedding ? { embedding } : {}),\n score: ((lexicalScores.get(id) ?? 0) / maxLexical) * lexicalWeight + (semanticScores.get(id) ?? 0) * semanticWeight,\n }\n })\n .filter((result): result is AiwgStaticSemanticResult => result !== null && result.score >= (options.minScore ?? -1))\n .sort((left, right) => right.score - left.score || left.item.id.localeCompare(right.item.id))\n .slice(offset, offset + limit)\n}\n\n// Default cap for the pairwise duplicate scan. The scan is O(n²) in the number\n// of embeddings, so an unbounded attacker-supplied set is a CPU DoS (SEC5). At\n// the default of 5000 the worst case is ~12.5M cosine comparisons; callers with\n// a trusted, larger set can raise the cap explicitly.\nexport const DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS = 5000\n\nexport function findAiwgStaticDuplicatePairs(\n index: AiwgFortemiIndexExport,\n embeddingSet: AiwgStaticEmbeddingSet,\n threshold = 0.9,\n options?: { maxEmbeddings?: number },\n): AiwgStaticDuplicatePair[] {\n assertAiwgStaticEmbeddingSet(embeddingSet)\n const maxEmbeddings = options?.maxEmbeddings ?? DEFAULT_AIWG_DUPLICATE_SCAN_MAX_EMBEDDINGS\n if (embeddingSet.embeddings.length > maxEmbeddings) {\n throw new Error(\n 'Embedding set too large for duplicate scan: ' + embeddingSet.embeddings.length +\n ' > ' + maxEmbeddings + ' (raise options.maxEmbeddings to override for trusted input)',\n )\n }\n const byId = new Map(index.items.map((item) => [item.id, item]))\n const pairs: AiwgStaticDuplicatePair[] = []\n for (let leftIndex = 0; leftIndex < embeddingSet.embeddings.length; leftIndex += 1) {\n for (let rightIndex = leftIndex + 1; rightIndex < embeddingSet.embeddings.length; rightIndex += 1) {\n const leftEmbedding = embeddingSet.embeddings[leftIndex]\n const rightEmbedding = embeddingSet.embeddings[rightIndex]\n const left = byId.get(leftEmbedding.record_id)\n const right = byId.get(rightEmbedding.record_id)\n if (!left || !right) continue\n const score = cosineSimilarity(leftEmbedding.embedding, rightEmbedding.embedding)\n if (score >= threshold) pairs.push({ left, right, score })\n }\n }\n return pairs.sort((left, right) => right.score - left.score || left.left.id.localeCompare(right.left.id))\n}\n\ninterface AiwgChunkedIndexRuntime {\n manifest: AiwgFortemiChunkManifest\n loader: AiwgChunkedIndexLoader\n maxCachedParts: number\n partCache: Map<string, AiwgFortemiChunkPart>\n detailLoader?: AiwgChunkedIndexDetailLoader\n maxCachedDetails: number\n detailCache: Map<string, AiwgFortemiRecord>\n maxCachedMatches: number\n // query+filter+weights key -> the full filtered/ranked entry set for that\n // query (offset/limit/sort/snippets independent). LRU-ordered; bounded by\n // maxCachedMatches (total entries). Lets pagination reuse a single scan.\n matchCache: Map<string, AiwgRankedEntry[]>\n}\n\nfunction chunkPartCacheKey(part: AiwgFortemiChunkPartRef): string {\n return `${part.offset}:${part.href}`\n}\n\nfunction clampMaxCachedParts(value: number | undefined): number {\n if (!hasPositiveInteger(value)) return 3\n return value\n}\n\nfunction clampMaxCachedDetails(value: number | undefined): number {\n if (!hasPositiveInteger(value)) return 32\n return value\n}\n\nfunction clampMaxCachedMatches(value: number | undefined): number {\n if (!hasPositiveInteger(value)) return 5000\n return value\n}\n\n// Stable key over the inputs that determine the filtered/ranked entry SET and\n// each entry's rank value — but not offset/limit/sort/snippets, which only shape\n// the page projected from a cached set. Caller-stable option objects (same field\n// order each page) hit the cache; a reordered object simply misses (still correct).\nfunction matchSetCacheKey(q: string, options: AiwgIndexQueryOptions): string {\n return JSON.stringify({\n q,\n types: options.types ?? null,\n facets: options.facets ?? null,\n tags: options.tags ?? null,\n concepts: options.concepts ?? null,\n privacy: options.privacy ?? null,\n rel: options.relationshipTargetId ?? null,\n searchProfile: options.searchProfile ?? 'default',\n weights: { ...DEFAULT_QUERY_WEIGHTS, ...options.weights },\n })\n}\n\nfunction cacheMatchEntries(runtime: AiwgChunkedIndexRuntime, key: string, entries: AiwgRankedEntry[]): void {\n runtime.matchCache.delete(key)\n runtime.matchCache.set(key, entries)\n let total = 0\n for (const set of runtime.matchCache.values()) total += set.length\n // Evict oldest sets until within budget, but always keep the just-inserted set\n // so paging a large result still benefits from the single scan.\n while (total > runtime.maxCachedMatches && runtime.matchCache.size > 1) {\n const oldest = runtime.matchCache.keys().next().value\n if (oldest === undefined || oldest === key) break\n total -= runtime.matchCache.get(oldest)?.length ?? 0\n runtime.matchCache.delete(oldest)\n }\n}\n\nfunction isDirectChunkBrowse(query: string, options: AiwgIndexQueryOptions): boolean {\n return query.trim() === ''\n && !options.rank\n && !options.snippets\n && !options.includeMatches\n && !options.types\n && !options.facets\n && !options.tags\n && !options.concepts\n && !options.privacy\n && !options.relationshipTargetId\n}\n\nfunction getPartsForRange(\n manifest: AiwgFortemiChunkManifest,\n offset: number,\n limit: number,\n): AiwgFortemiChunkPartRef[] {\n const end = offset + limit\n return manifest.parts.filter((part) => part.count > 0 && part.offset < end && part.offset + part.count > offset)\n}\n\nasync function loadChunkPart(\n runtime: AiwgChunkedIndexRuntime,\n part: AiwgFortemiChunkPartRef,\n): Promise<{ part: AiwgFortemiChunkPart; fetched: boolean }> {\n const key = chunkPartCacheKey(part)\n const cached = runtime.partCache.get(key)\n if (cached) {\n runtime.partCache.delete(key)\n runtime.partCache.set(key, cached)\n return { part: cached, fetched: false }\n }\n\n const parsed = assertAiwgFortemiChunkPart(await runtime.loader(part, runtime.manifest), part, runtime.manifest)\n runtime.partCache.set(key, parsed)\n while (runtime.partCache.size > runtime.maxCachedParts) {\n const oldest = runtime.partCache.keys().next().value\n if (oldest === undefined) break\n runtime.partCache.delete(oldest)\n }\n return { part: parsed, fetched: true }\n}\n\nasync function getChunkRecord(runtime: AiwgChunkedIndexRuntime, id: string): Promise<AiwgFortemiRecord> {\n const cached = runtime.detailCache.get(id)\n if (cached) {\n runtime.detailCache.delete(id)\n runtime.detailCache.set(id, cached)\n return cached\n }\n // Whole-record parts already in cache: serve without a detail fetch.\n if (!runtime.manifest.projection) {\n for (const part of runtime.partCache.values()) {\n const found = part.items.find((item) => item.id === id)\n if (found) return found\n }\n }\n if (!runtime.detailLoader) {\n throw new Error('No detailLoader configured to resolve record ' + id)\n }\n const raw = await runtime.detailLoader(id, runtime.manifest)\n const record = assertAiwgFortemiIndexExport({\n schema_version: 'aiwg.fortemi.index.export.v1',\n generated_at: runtime.manifest.generated_at,\n source: runtime.manifest.source,\n items: [raw],\n }).items[0]\n if (record.id !== id) {\n throw new Error('Detail record id mismatch: expected ' + id + ', got ' + record.id)\n }\n runtime.detailCache.set(id, record)\n while (runtime.detailCache.size > runtime.maxCachedDetails) {\n const oldest = runtime.detailCache.keys().next().value\n if (oldest === undefined) break\n runtime.detailCache.delete(oldest)\n }\n return record\n}\n\nfunction relationshipTypeFilter(options?: AiwgRelationshipQueryOptions): string | undefined {\n return options?.relationshipType ?? options?.type\n}\n\nfunction edgeFromRelationship(sourceId: string, relationship: AiwgFortemiRelationship): AiwgRelationshipEdgeSummary {\n return {\n source_id: sourceId,\n target_id: relationship.target_id,\n type: relationship.type,\n ...(relationship.source_path ? { source_path: relationship.source_path } : {}),\n ...(relationship.target_path ? { target_path: relationship.target_path } : {}),\n ...(relationship.direction ? { direction: relationship.direction } : {}),\n }\n}\n\nfunction relationshipMatches(edge: AiwgRelationshipEdgeSummary, options: AiwgRelationshipQueryOptions = {}): boolean {\n const type = relationshipTypeFilter(options)\n if (type && edge.type !== type) return false\n if (options.relationshipDirection && edge.direction !== options.relationshipDirection) return false\n if (options.sourceId && edge.source_id !== options.sourceId) return false\n if (options.targetId && edge.target_id !== options.targetId) return false\n if (options.endpointId && edge.source_id !== options.endpointId && edge.target_id !== options.endpointId) return false\n return true\n}\n\nfunction assertRelationshipDirectionAnchor(options: AiwgRelationshipQueryOptions): void {\n if (options.direction === 'out' && !options.sourceId) {\n throw new Error(\"relationship direction 'out' requires sourceId\")\n }\n if (options.direction === 'in' && !options.targetId) {\n throw new Error(\"relationship direction 'in' requires targetId\")\n }\n}\n\nfunction nodeSummary(item: AiwgFortemiProjectedRecord): AiwgRelationshipNodeSummary {\n return { id: item.id, type: item.type, title: recordTitle(item) }\n}\n\nfunction addNode(nodes: Map<string, AiwgRelationshipNodeSummary>, item: AiwgFortemiProjectedRecord | undefined) {\n if (item) nodes.set(item.id, nodeSummary(item))\n}\n\nfunction relationshipResultFromRecords(\n records: AiwgFortemiProjectedRecord[],\n options: AiwgRelationshipQueryOptions = {},\n): AiwgRelationshipTraversalResult {\n assertRelationshipDirectionAnchor(options)\n const byId = new Map(records.map((record) => [record.id, record]))\n const edges: AiwgRelationshipEdgeSummary[] = []\n for (const record of records) {\n for (const relationship of record.relationships ?? []) {\n const edge = edgeFromRelationship(record.id, relationship)\n if (!relationshipMatches(edge, options)) continue\n edges.push(edge)\n }\n }\n const sortedEdges = edges.sort((left, right) => (\n left.source_id.localeCompare(right.source_id)\n || left.target_id.localeCompare(right.target_id)\n || left.type.localeCompare(right.type)\n ))\n const limitedEdges = options.limit ? sortedEdges.slice(0, options.limit) : sortedEdges\n const nodes = new Map<string, AiwgRelationshipNodeSummary>()\n for (const edge of limitedEdges) {\n addNode(nodes, byId.get(edge.source_id))\n addNode(nodes, byId.get(edge.target_id))\n }\n return {\n nodes: [...nodes.values()].sort((left, right) => left.id.localeCompare(right.id)),\n edges: limitedEdges,\n complete: true,\n }\n}\n\nfunction neighborQueryOptions(id: string, options: AiwgRelationshipTraversalOptions = {}): AiwgRelationshipQueryOptions {\n const direction = options.direction ?? 'both'\n return {\n ...options,\n ...(direction === 'out' ? { sourceId: id } : {}),\n ...(direction === 'in' ? { targetId: id } : {}),\n ...(direction === 'both' ? { endpointId: id } : {}),\n }\n}\n\nfunction filterNeighborResult(id: string, result: AiwgRelationshipTraversalResult, options: AiwgRelationshipTraversalOptions = {}): AiwgRelationshipTraversalResult {\n const direction = options.direction ?? 'both'\n const edges = result.edges.filter((edge) => {\n if (direction === 'out') return edge.source_id === id\n if (direction === 'in') return edge.target_id === id\n return edge.source_id === id || edge.target_id === id\n })\n const ids = new Set<string>()\n for (const edge of edges) {\n ids.add(edge.source_id)\n ids.add(edge.target_id)\n }\n return {\n ...result,\n edges,\n nodes: result.nodes.filter((node) => ids.has(node.id)),\n }\n}\n\nasync function recordsFromChunkedRuntime(\n runtime: AiwgChunkedIndexRuntime,\n onProgress?: (progress: AiwgChunkedIndexProgress) => void,\n): Promise<{ records: AiwgFortemiRecord[]; scannedParts: number; fetchedParts: number }> {\n let scannedParts = 0\n let fetchedParts = 0\n const records: AiwgFortemiRecord[] = []\n for (const partRef of runtime.manifest.parts) {\n const loaded = await loadChunkPart(runtime, partRef)\n if (loaded.fetched) fetchedParts += 1\n scannedParts += 1\n onProgress?.({ phase: 'part', done: scannedParts, total: runtime.manifest.parts.length, href: partRef.href })\n for (const item of loaded.part.items) {\n records.push(item.relationships ? item : await getChunkRecord(runtime, item.id))\n }\n }\n return { records, scannedParts, fetchedParts }\n}\n\nasync function relationshipResultFromChunkedRuntime(\n runtime: AiwgChunkedIndexRuntime,\n options: AiwgRelationshipQueryOptions = {},\n): Promise<AiwgRelationshipTraversalResult> {\n const loaded = await recordsFromChunkedRuntime(runtime)\n return {\n ...relationshipResultFromRecords(loaded.records, options),\n scannedParts: loaded.scannedParts,\n fetchedParts: loaded.fetchedParts,\n }\n}\n\nasync function queryChunkedAiwgFortemiIndex(\n runtime: AiwgChunkedIndexRuntime,\n query = '',\n options: AiwgChunkedIndexQueryOptions = {},\n): Promise<AiwgChunkedIndexQueryResult> {\n const q = query.trim().toLowerCase()\n let scannedParts = 0\n let fetchedParts = 0\n\n if (isDirectChunkBrowse(query, options)) {\n const offset = options.offset ?? 0\n const limit = options.limit ?? runtime.manifest.total\n const parts = getPartsForRange(runtime.manifest, offset, limit)\n const items: AiwgFortemiRecord[] = []\n for (const partRef of parts) {\n const loaded = await loadChunkPart(runtime, partRef)\n if (loaded.fetched) fetchedParts += 1\n scannedParts += 1\n options.onProgress?.({ phase: 'part', done: scannedParts, total: parts.length, href: partRef.href })\n const start = Math.max(0, offset - partRef.offset)\n const end = Math.min(loaded.part.items.length, offset + limit - partRef.offset)\n items.push(...loaded.part.items.slice(start, end))\n }\n return {\n items,\n total: runtime.manifest.total,\n facets: runtime.manifest.facets ?? {},\n manifestTotal: runtime.manifest.total,\n scannedParts,\n fetchedParts,\n complete: true,\n }\n }\n\n // Reuse the filtered/ranked entry set across pages of the same query: the\n // expensive part scan is offset/limit/sort/snippet independent. A hit projects\n // a new page from cached entries without touching parts (scanned/fetched = 0).\n const matchKey = matchSetCacheKey(q, options)\n const cached = runtime.matchCache.get(matchKey)\n if (cached) {\n runtime.matchCache.delete(matchKey)\n runtime.matchCache.set(matchKey, cached)\n return {\n ...createQueryResultFromRankedEntries(cached, q, options),\n manifestTotal: runtime.manifest.total,\n scannedParts: 0,\n fetchedParts: 0,\n complete: true,\n }\n }\n\n const entries: AiwgRankedEntry[] = []\n for (const partRef of runtime.manifest.parts) {\n const loaded = await loadChunkPart(runtime, partRef)\n if (loaded.fetched) fetchedParts += 1\n scannedParts += 1\n options.onProgress?.({ phase: 'part', done: scannedParts, total: runtime.manifest.parts.length, href: partRef.href })\n entries.push(...createRankedEntries(loaded.part.items, q, options, partRef.offset))\n options.onProgress?.({ phase: 'query', done: scannedParts, total: runtime.manifest.parts.length, href: partRef.href })\n }\n cacheMatchEntries(runtime, matchKey, entries)\n\n return {\n ...createQueryResultFromRankedEntries(entries, q, options),\n manifestTotal: runtime.manifest.total,\n scannedParts,\n fetchedParts,\n complete: true,\n }\n}\n\nexport function createAiwgReviewDecisionExport(\n // Only the export schema_version is needed — so this works in chunked mode\n // (where no whole index is loaded) by passing a minimal source. See #178.\n source: Pick<AiwgFortemiIndexExport, 'schema_version'>,\n decisions: AiwgReviewDecision[],\n generatedAt = new Date().toISOString(),\n): AiwgReviewDecisionExport {\n return {\n schema_version: 'aiwg.fortemi.review-decisions.v1',\n generated_at: generatedAt,\n source_export_schema_version: source.schema_version,\n decisions: [...decisions].sort((left, right) => left.item_id.localeCompare(right.item_id)),\n }\n}\n\nexport function createAiwgIndexController(initialIndex?: AiwgFortemiIndexExport): AiwgIndexController {\n let index: AiwgFortemiIndexExport | null = initialIndex ?? null\n let chunked: AiwgChunkedIndexRuntime | null = null\n let data: AiwgIndexQueryResult | null = null\n let error: Error | null = null\n let reviewDecisions: AiwgReviewDecision[] = []\n const listeners = new Set<AiwgIndexControllerListener>()\n\n const snapshot = (): AiwgIndexControllerSnapshot => ({\n index,\n chunked: chunked\n ? {\n manifest: chunked.manifest,\n cachedParts: chunked.partCache.size,\n maxCachedParts: chunked.maxCachedParts,\n }\n : null,\n data,\n error,\n reviewDecisions: [...reviewDecisions],\n })\n const notify = () => {\n const current = snapshot()\n for (const listener of listeners) listener(current)\n }\n const requireIndex = (): AiwgFortemiIndexExport => {\n if (!index) throw new Error('No AIWG index export loaded')\n return index\n }\n\n return {\n loadIndex(value: unknown): AiwgFortemiIndexExport {\n try {\n const parsed = assertAiwgFortemiIndexExport(value)\n index = parsed\n chunked = null\n data = null\n reviewDecisions = []\n error = null\n notify()\n return parsed\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n loadChunkedIndex(\n manifest: unknown,\n loader: AiwgChunkedIndexLoader,\n options: AiwgChunkedIndexLoadOptions = {},\n ): AiwgFortemiChunkManifest {\n try {\n const parsed = assertAiwgFortemiChunkManifest(manifest)\n index = null\n chunked = {\n manifest: parsed,\n loader,\n maxCachedParts: clampMaxCachedParts(options.maxCachedParts),\n partCache: new Map(),\n detailLoader: options.detailLoader,\n maxCachedDetails: clampMaxCachedDetails(options.maxCachedDetails),\n detailCache: new Map(),\n maxCachedMatches: clampMaxCachedMatches(options.maxCachedMatches),\n matchCache: new Map(),\n }\n data = null\n reviewDecisions = []\n error = null\n notify()\n return parsed\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n getIndex(): AiwgFortemiIndexExport | null {\n return index\n },\n getChunkedManifest(): AiwgFortemiChunkManifest | null {\n return chunked?.manifest ?? null\n },\n getSnapshot(): AiwgIndexControllerSnapshot {\n return snapshot()\n },\n query(query = '', options?: AiwgIndexQueryOptions): AiwgIndexQueryResult {\n const result = queryAiwgFortemiIndex(requireIndex(), query, options)\n data = result\n error = null\n notify()\n return result\n },\n async queryChunked(query = '', options?: AiwgChunkedIndexQueryOptions): Promise<AiwgChunkedIndexQueryResult> {\n if (!chunked) throw new Error('No AIWG chunked index manifest loaded')\n try {\n const result = await queryChunkedAiwgFortemiIndex(chunked, query, options)\n data = result\n error = null\n notify()\n return result\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n async getRecord(id: string): Promise<AiwgFortemiRecord> {\n if (chunked) {\n try {\n return await getChunkRecord(chunked, id)\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n }\n const found = requireIndex().items.find((item) => item.id === id)\n if (!found) throw new Error('Record not found: ' + id)\n return found\n },\n async neighbors(id: string, options?: AiwgRelationshipTraversalOptions): Promise<AiwgRelationshipTraversalResult> {\n try {\n const queryOptions = neighborQueryOptions(id, options)\n const result = chunked\n ? await relationshipResultFromChunkedRuntime(chunked, queryOptions)\n : relationshipResultFromRecords(requireIndex().items, queryOptions)\n return filterNeighborResult(id, result, options)\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n async relationshipQuery(options?: AiwgRelationshipQueryOptions): Promise<AiwgRelationshipTraversalResult> {\n try {\n return chunked\n ? await relationshipResultFromChunkedRuntime(chunked, options)\n : relationshipResultFromRecords(requireIndex().items, options)\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err))\n notify()\n throw error\n }\n },\n async relationshipSet(options: AiwgRelationshipSetOptions): Promise<AiwgRelationshipSetResult> {\n const [left, right] = await Promise.all([\n this.neighbors(options.a, options),\n this.neighbors(options.b, options),\n ])\n const leftIds = new Set(left.nodes.map((node) => node.id).filter((id) => id !== options.a))\n const rightIds = new Set(right.nodes.map((node) => node.id).filter((id) => id !== options.b))\n let ids: string[]\n if (options.op === 'intersection') ids = [...leftIds].filter((id) => rightIds.has(id))\n else if (options.op === 'difference') ids = [...leftIds].filter((id) => !rightIds.has(id))\n else ids = [...new Set([...leftIds, ...rightIds])]\n return { op: options.op, ids: ids.sort() }\n },\n clearChunkCache(): void {\n chunked?.partCache.clear()\n chunked?.detailCache.clear()\n chunked?.matchCache.clear()\n error = null\n notify()\n },\n toCommunityGraph(options?: AiwgIndexGraphOptions) {\n return aiwgFortemiIndexToCommunityGraph(requireIndex(), options)\n },\n async toCommunityGraphChunked(options?: AiwgIndexGraphOptions & { onProgress?: (progress: AiwgChunkedIndexProgress) => void }) {\n if (!chunked) return aiwgFortemiIndexToCommunityGraph(requireIndex(), options)\n const loaded = await recordsFromChunkedRuntime(chunked, options?.onProgress)\n return aiwgFortemiIndexToCommunityGraph({\n schema_version: 'aiwg.fortemi.index.export.v1',\n generated_at: chunked.manifest.generated_at,\n source: chunked.manifest.source,\n items: loaded.records,\n }, options)\n },\n setReviewDecision(input: AiwgReviewInput): AiwgReviewDecision {\n const decision: AiwgReviewDecision = {\n ...input,\n updated_at: new Date().toISOString(),\n }\n reviewDecisions = [\n ...reviewDecisions.filter((item) => item.item_id !== decision.item_id),\n decision,\n ].sort((left, right) => left.item_id.localeCompare(right.item_id))\n error = null\n notify()\n return decision\n },\n clearReviewDecision(itemId: string): void {\n reviewDecisions = reviewDecisions.filter((item) => item.item_id !== itemId)\n error = null\n notify()\n },\n createReviewDecisionExport(generatedAt?: string): AiwgReviewDecisionExport {\n // The review-decisions export only needs the export schema_version, not the\n // items — so it works in chunked mode by synthesizing a minimal source (#178).\n const source: Pick<AiwgFortemiIndexExport, 'schema_version'> | null =\n index ??\n (chunked\n ? { schema_version: chunked.manifest.source_export_schema_version ?? 'aiwg.fortemi.index.export.v1' }\n : null)\n if (!source) throw new Error('No AIWG index export or chunked manifest loaded')\n return createAiwgReviewDecisionExport(source, reviewDecisions, generatedAt)\n },\n subscribe(listener: AiwgIndexControllerListener): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n }\n}\n\nexport function aiwgFortemiIndexToCommunityGraph(\n index: AiwgFortemiIndexExport,\n options: AiwgIndexGraphOptions = {},\n) {\n const ids = new Set(index.items.map((item) => item.id))\n const relationshipWeights = options.relationshipWeights ?? Object.create(null)\n const edgeCounts = new Map<string, { source: string; target: string; kind: string; weight: number }>()\n\n for (const item of index.items) {\n for (const relationship of item.relationships) {\n if (!ids.has(relationship.target_id) && !options.includeDanglingRelationships) continue\n const kind = relationship.type\n const configuredWeight = Object.prototype.hasOwnProperty.call(relationshipWeights, kind)\n ? relationshipWeights[kind]\n : undefined\n const baseWeight = typeof configuredWeight === 'number' && Number.isFinite(configuredWeight)\n ? configuredWeight\n : 1\n const key = `${item.id}\\u0000${relationship.target_id}\\u0000${kind}`\n const existing = edgeCounts.get(key)\n if (existing) existing.weight += baseWeight\n else edgeCounts.set(key, { source: item.id, target: relationship.target_id, kind, weight: baseWeight })\n }\n }\n\n const communities = new Map<string, string[]>()\n for (const item of index.items) {\n const communityIds = communityIdsFor(item, options)\n for (const communityId of communityIds) {\n const nodes = communities.get(communityId) ?? []\n nodes.push(item.id)\n communities.set(communityId, nodes)\n }\n }\n\n return {\n nodes: index.items.map((item) => ({ id: item.id })),\n edges: Array.from(edgeCounts.values()).sort((left, right) => (\n left.source.localeCompare(right.source)\n || left.target.localeCompare(right.target)\n || left.kind.localeCompare(right.kind)\n )),\n communities: Array.from(communities.entries())\n .map(([id, nodes]) => ({ id, nodes: [...new Set(nodes)].sort() }))\n .sort((left, right) => left.id.localeCompare(right.id)),\n }\n}\n\nfunction communityIdsFor(item: AiwgFortemiRecord, options: AiwgIndexGraphOptions): string[] {\n if (options.communityFacet) {\n const values = item.facets[options.communityFacet] ?? []\n if (values.length > 0) return values.map((value) => `${options.communityFacet}:${value}`)\n }\n if (options.communityTagPrefix) {\n const prefix = options.communityTagPrefix\n const tags = item.tags.filter((tag) => tag.startsWith(prefix))\n if (tags.length > 0) return tags\n }\n if (item.concepts.length > 0) return item.concepts.map((concept) => `concept:${concept}`)\n return [`type:${item.type}`]\n}\n\nconst AIWG_SHARD_UUID_NAMESPACE = '7ab5d1f8-29d2-5e35-9e2f-3a45de171a9e'\nconst shardEncoder = new TextEncoder()\nconst shardDecoder = new TextDecoder()\n\nfunction aiwgShardUuid(kind: string, id: string): string {\n return uuidv5(`${kind}:${id}`, AIWG_SHARD_UUID_NAMESPACE)\n}\n\nfunction aiwgShardTimestamp(value: string | undefined, fallback: string): string {\n if (!value || Number.isNaN(Date.parse(value))) return fallback\n return new Date(value).toISOString()\n}\n\nfunction aiwgRecordTitle(record: AiwgFortemiRecord): string {\n return record.title ?? record.search?.title ?? record.search?.name ?? record.id\n}\n\nfunction aiwgRecordContent(record: AiwgFortemiRecord): string {\n if (record.text) return record.text\n if (record.search?.body) return record.search.body\n const chunks = record.chunks\n ?.map((chunk) => chunk.text ?? chunk.body ?? chunk.summary ?? '')\n .filter(Boolean)\n if (chunks?.length) return chunks.join('\\n\\n')\n return record.search?.summary ?? ''\n}\n\nfunction aiwgShardMetadata(\n index: AiwgFortemiIndexExport,\n record: AiwgFortemiRecord,\n): Record<string, unknown> {\n return {\n aiwg_fortemi_index: {\n envelope: {\n schema_version: index.schema_version,\n generated_at: index.generated_at,\n source: index.source,\n ...(index.compatibility ? { compatibility: index.compatibility } : {}),\n },\n record,\n },\n }\n}\n\nfunction encodeJsonLines(values: unknown[]): Uint8Array {\n return shardEncoder.encode(values.map((value) => JSON.stringify(value)).join('\\n'))\n}\n\n/**\n * Convert the static AIWG/Fortemi v2 index contract into a portable Knowledge\n * Shard. Every note retains the complete source envelope and record in metadata,\n * so the native note/link/SKOS/provenance projections are reversible.\n */\nexport async function aiwgFortemiIndexToKnowledgeShard(\n index: AiwgFortemiIndexExport,\n options: AiwgKnowledgeShardOptions = {},\n): Promise<Uint8Array> {\n if (options.includeNativeRichComponents) {\n throw new Error(\n 'Native AIWG rich components require the complete full-v1 inventory; use core-v1 metadata preservation until full-v1 conversion is available',\n )\n }\n const validation = validateAiwgFortemiIndexExport(index)\n if (!validation.valid) {\n throw new Error(`Invalid AIWG Fortemi index export:\\n${validation.errors.join('\\n')}`)\n }\n if (index.schema_version !== 'aiwg.fortemi.index.export.v2') {\n throw new Error('Knowledge Shard conversion requires aiwg.fortemi.index.export.v2')\n }\n const createdAt = aiwgShardTimestamp(options.createdAt ?? index.generated_at, new Date().toISOString())\n const noteIds = new Map(index.items.map((record) => [record.id, aiwgShardUuid('record', record.id)]))\n const notes: ShardNote[] = index.items.map((record) => {\n const content = aiwgRecordContent(record)\n return {\n id: noteIds.get(record.id)!,\n title: aiwgRecordTitle(record),\n original_content: content,\n revised_content: content,\n metadata: aiwgShardMetadata(index, record),\n collection_id: null,\n attachments: [],\n format: 'markdown',\n source: 'aiwg-index',\n starred: false,\n archived: false,\n tags: [...new Set(record.tags)].sort(),\n created_at: aiwgShardTimestamp(record.source.updated_at ?? record.updated_at, createdAt),\n updated_at: aiwgShardTimestamp(record.updated_at, createdAt),\n deleted_at: null,\n }\n })\n\n const links: ShardLink[] = []\n for (const record of index.items) {\n for (const [position, relationship] of record.relationships.entries()) {\n const targetNoteId = noteIds.get(relationship.target_id) ?? null\n links.push({\n id: aiwgShardUuid(\n 'relationship',\n `${record.id}\\u0000${position}\\u0000${relationship.type}\\u0000${relationship.target_id}`,\n ),\n from_note_id: noteIds.get(record.id)!,\n to_note_id: targetNoteId,\n to_url: targetNoteId ? null : `aiwg://record/${encodeURIComponent(relationship.target_id)}`,\n kind: relationship.type,\n score: relationship.confidence ?? 1,\n created_at: aiwgShardTimestamp(record.updated_at, createdAt),\n metadata: {\n aiwg_fortemi_index: {\n source_record_id: record.id,\n target_record_id: relationship.target_id,\n relationship,\n },\n },\n })\n }\n }\n\n const files = new Map<string, Uint8Array>()\n const components: ShardComponent[] = ['notes', 'tags']\n const counts: ShardManifest['counts'] = {\n notes: notes.length,\n tags: [...new Set(notes.flatMap((note) => note.tags))].length,\n }\n files.set('notes.jsonl', encodeJsonLines(notes))\n files.set('tags.json', shardEncoder.encode(JSON.stringify(\n [...new Set(notes.flatMap((note) => note.tags))]\n .sort()\n .map((name) => ({ name, created_at: createdAt })),\n )))\n\n const addComponent = (\n component: ShardComponent,\n filename: string,\n values: unknown[],\n jsonLines = true,\n ) => {\n if (values.length === 0) return\n components.push(component)\n counts[component] = values.length\n files.set(filename, jsonLines ? encodeJsonLines(values) : shardEncoder.encode(JSON.stringify(values)))\n }\n addComponent('links', 'links.jsonl', links)\n\n const checksums: Record<string, string> = {}\n for (const [filename, bytes] of files) checksums[filename] = await shardSha256Hex(bytes)\n const manifest: ShardManifest = {\n version: CURRENT_SHARD_VERSION,\n profile: 'core-v1',\n producer: {\n name: 'fortemi-core-aiwg-index',\n version: options.matricVersion ?? 'fortemi-core',\n },\n format: SHARD_FORMAT,\n created_at: createdAt,\n components,\n counts: {\n notes: 0,\n collections: 0,\n tags: 0,\n templates: 0,\n links: 0,\n embedding_sets: 0,\n embedding_set_members: 0,\n embeddings: 0,\n embedding_configs: 0,\n ...counts,\n },\n checksums,\n min_reader_version: CURRENT_SHARD_VERSION,\n }\n files.set('manifest.json', shardEncoder.encode(JSON.stringify(manifest, null, 2)))\n const contractValidation = await validateCoreV1ShardArchive(files)\n if (!contractValidation.valid) {\n throw new Error(\n `Generated AIWG core-v1 shard failed canonical validation: ${contractValidation.errors.join('; ')}`,\n )\n }\n return packTarGz(files)\n}\n\n/**\n * Recover the exact AIWG index envelope and records embedded by\n * {@link aiwgFortemiIndexToKnowledgeShard}.\n */\nexport function aiwgFortemiIndexFromKnowledgeShard(bytes: Uint8Array): AiwgFortemiIndexExport {\n const files = unpackTarGz(bytes)\n const noteBytes = files.get('notes.jsonl')\n const notes = (noteBytes ? shardDecoder.decode(noteBytes) : '')\n .split('\\n')\n .filter(Boolean)\n .map((line) => JSON.parse(line) as ShardNote)\n if (notes.length === 0) throw new Error('Knowledge Shard contains no AIWG index notes')\n\n let envelope: Record<string, unknown> | undefined\n const items: AiwgFortemiRecord[] = []\n for (const note of notes) {\n const metadata = note.metadata?.aiwg_fortemi_index\n if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n throw new Error(`Knowledge Shard note ${note.id} has no AIWG index metadata`)\n }\n const value = metadata as Record<string, unknown>\n envelope ??= value.envelope as Record<string, unknown>\n items.push(value.record as AiwgFortemiRecord)\n }\n const restored = {\n ...envelope,\n items: items.sort((left, right) => left.id.localeCompare(right.id)),\n } as unknown as AiwgFortemiIndexExport\n const validation = validateAiwgFortemiIndexExport(restored)\n if (!validation.valid) {\n throw new Error(`Knowledge Shard contains invalid AIWG index metadata:\\n${validation.errors.join('\\n')}`)\n }\n return restored\n}\n"]}