@fortemi/core 2026.7.9 → 2026.7.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -5066,6 +5066,8 @@ interface CollectionRecord {
5066
5066
  id: string;
5067
5067
  name: string;
5068
5068
  description: string | null;
5069
+ /** Omitted only by legacy schema-v1 callers; built-in stores normalize it to null. */
5070
+ parent_id?: string | null;
5069
5071
  created_at: string;
5070
5072
  updated_at: string;
5071
5073
  deleted_at: string | null;
@@ -5224,7 +5226,7 @@ declare class MemoryRecordStore implements RecordStore {
5224
5226
  */
5225
5227
 
5226
5228
  /** Logical record-schema version stored in `meta` (independent of DB_VERSION). */
5227
- declare const RECORD_SCHEMA_VERSION = 1;
5229
+ declare const RECORD_SCHEMA_VERSION = 2;
5228
5230
  interface CreateRecordStoreOptions {
5229
5231
  /** Injectable factory for tests (fake-indexeddb). Defaults to the global. */
5230
5232
  indexedDB?: IDBFactory;
@@ -5304,7 +5306,7 @@ declare class CanonicalNotesRepository {
5304
5306
  softDeleteLink(linkId: string): Promise<void>;
5305
5307
  /** Active links touching a note (either direction). */
5306
5308
  linksOf(noteId: string): Promise<LinkRecord0[]>;
5307
- createCollection(name: string, description?: string): Promise<CollectionRecord>;
5309
+ createCollection(name: string, description?: string, parentId?: string | null): Promise<CollectionRecord>;
5308
5310
  addNoteToCollection(collectionId: string, noteId: string): Promise<void>;
5309
5311
  notesInCollection(collectionId: string): Promise<NoteRecord0[]>;
5310
5312
  }
@@ -5520,6 +5522,6 @@ declare function importShardToRecords(store: RecordStore, data: Uint8Array | Arr
5520
5522
  * @created 2026-07-17
5521
5523
  * @agent Codex
5522
5524
  */
5523
- declare const VERSION = "2026.7.9";
5525
+ declare const VERSION = "2026.7.11";
5524
5526
 
5525
5527
  export { AIWG_SCAN_REQUIRED_FIELDS, type AiwgChunkedIndexBuildOptions, type AiwgChunkedIndexBuildResult, type AiwgChunkedIndexDetailLoader, type AiwgChunkedIndexLoadOptions, type AiwgChunkedIndexLoader, type AiwgChunkedIndexProgress, type AiwgChunkedIndexProgressPhase, type AiwgChunkedIndexQueryOptions, type AiwgChunkedIndexQueryResult, type AiwgChunkedIndexValidationResult, type AiwgFortemiAttachmentReference, type AiwgFortemiBinarySource, type AiwgFortemiChunk, type AiwgFortemiChunkDetailRef, type AiwgFortemiChunkManifest, type AiwgFortemiChunkPart, type AiwgFortemiChunkPartRef, type AiwgFortemiIndexExport, type AiwgFortemiIndexExportSchemaVersion, type AiwgFortemiProjectedRecord, type AiwgFortemiProvenance, type AiwgFortemiProvenanceEvent, type AiwgFortemiRecord, type AiwgFortemiRecordEmbedding, type AiwgFortemiRecordSchemaVersion, type AiwgFortemiRecordSource, type AiwgFortemiRecordType, type AiwgFortemiRelationship, type AiwgFortemiRelationshipDirection, type AiwgFortemiSearchProjection, type AiwgFortemiSkosConcept, type AiwgFortemiSkosRelation, type AiwgFortemiSkosRelationType, type AiwgHeadlessEmbeddingBackend, type AiwgIndexController, type AiwgIndexControllerListener, type AiwgIndexControllerSnapshot, type AiwgIndexGraphOptions, type AiwgIndexQueryMatch, type AiwgIndexQueryOptions, type AiwgIndexQueryRankedItem, type AiwgIndexQueryResult, type AiwgIndexQueryWeights, type AiwgIndexValidationResult, type AiwgKnowledgeShardOptions, type AiwgPrivacyClassification, type AiwgPrivacyFilterOptions, type AiwgProvenanceConfidence, type AiwgRelationshipDirection, type AiwgRelationshipEdgeSummary, type AiwgRelationshipNodeSummary, type AiwgRelationshipQueryOptions, type AiwgRelationshipSetOperation, type AiwgRelationshipSetOptions, type AiwgRelationshipSetResult, type AiwgRelationshipTraversalOptions, type AiwgRelationshipTraversalResult, type AiwgReviewAction, type AiwgReviewDecision, type AiwgReviewDecisionExport, type AiwgReviewInput, type AiwgStaticDuplicatePair, type AiwgStaticEmbeddingRecord, type AiwgStaticEmbeddingSet, type AiwgStaticHybridQueryOptions, type AiwgStaticSemanticQueryOptions, type AiwgStaticSemanticResult, AllowlistTrustStore, type ArchiveInfo, ArchiveManager, type AttachInput, type AttachmentBlobRecord, type AttachmentBlobRow, type AttachmentProjectionResult, type AttachmentRecord, type AttachmentRow, AttachmentsRepository, type BackendCandidate, type BackendCapabilities, type BackendConcept, type BackendLink, type BackendListOptions, type BackendNote, type BackendNoteFull, type BackendProvenanceEdge, type BackendRequest, type BackendSearchHit, type BackendSearchQueryOptions, type BackendSearchResult, type BackendSelection, type BackendSemanticTier, type BackendStartupCost, type BlobBackendKind, type BlobGcOptions, type BlobGcResult, type BlobReconcileOptions, type BlobReconcileResult, type BlobStore, type BlobStoreDiagnostics, type BridgeCapability, type BridgeProviderInfo, type BrowserNoteExport, type BuildAiwgStaticEmbeddingSetOptions, CORE_V1_COMPONENTS, CURRENT_MIGRATION_HEAD, CURRENT_SHARD_VERSION, type CanonicalAttachInput, CanonicalAttachmentsRepository, type CanonicalNoteCreateInput, type CanonicalNoteUpdateInput, type CanonicalNoteView, CanonicalNotesRepository, type CapabilityInfo, CapabilityManager, type CapabilityName, type CapabilityState, type CaptureKnowledgeInput, CaptureKnowledgeInputSchema, type CaptureKnowledgeResult, type CollectionCreateInput, type CollectionNoteRecord, type CollectionRecord, type CollectionRow, CollectionsRepository, CommunitiesRepository, type CommunityAssignmentView, type CommunityCreateInput, type CommunityFilterDefinition, type CommunityGraph, type CommunityOptions, type CommunitySourceDescriptor, type CommunitySourceType, type CommunitySummary, type CompletionRequest, type CompletionResponse, type ConditionResult, type ConflictStrategy, type CooldownConfig, type CooldownEvent, type CosineSemanticProviderOptions, type CreateBlobStoreOptions, type CreatePGliteOptions, type CreateRecordStoreOptions, type CspDirectiveName, type CspDirectives, type CspViolationReport, DB_SNAPSHOT_SCHEMA_VERSION, type DataBackend, type DatabaseClient, type DbSnapshot, type DbSnapshotCompat, type DbSnapshotCompression, type DbSnapshotExpectations, type DbSnapshotMeta, type DbSnapshotSource, DbSnapshotVersionError, type DiscoveredProvider, type DiscoveryOptions, type DumpDbSnapshotOptions, type DumpableDb, EMBED_REQUEST_KIND, EMBED_RESPONSE_KIND, type EmbedFunction, type EmbedRequest, type EmbedRequestMessage, type EmbedResponse, type EmbedResponseMessage, type EmbedTransportPort, type EmbedWorkerOptions, type EmbeddingCompatibilityPolicy, type EmbeddingSetCreateInput, type EmbeddingSetCriteria, type EmbeddingSetDescriptor, type EmbeddingSetEmbeddingInput, type EmbeddingSetFreshness, type EmbeddingSetKind, type EmbeddingSetMode, type EmbeddingSetRow, type EmbeddingSetSelector, EmbeddingSetsRepository, type EnqueueJobInput, type ErrorCategory, type EventMap, type ExportOptions, FORTEMI_COMPATIBILITY_PATH, FORTEMI_COMPATIBILITY_STATES, FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES, type FallbackEvent, FallbackRouter, type FallbackRouterConfig, type FetchFortemiCompatibilityOptions, type FortemiBridge, type FortemiBridgeCapabilities, type FortemiBridgeHost, type FortemiCompatibilityCapability, type FortemiCompatibilityResponse, type FortemiCompatibilityState, type FortemiCompatibilityValidationResult, type FortemiConfig, type FortemiCore, type FortemiInferenceRouter, type FortemiRequiredCompatibilityCapability, type FortemiSecretStore, type FortemiToolDefinition, FortemiToolManifest, type GetNoteInput, GetNoteInputSchema, type GpuCapabilities, type GraphCommunity, type GraphEdge, type GraphNode, GraphRepository, type IDisposable, IdbRecordStore, type ImportCounts, type ImportOptions, type ImportProgress, type ImportProgressPhase, type ImportResult, type InferenceCapabilities, type InferenceProvider, JOB_CAPABILITIES, JOB_PRIORITIES, type JobQueueOptions, JobQueueWorker, type JobStatus, type JobType, type JournalEntry, type KnowledgeShardProfile, LOCAL_ENDPOINTS, type LegacyMigrationReport, type LinkRecord0, type LinkRow, LinksRepository, type ListNotesInput, ListNotesInputSchema, type LlmCapabilityOptions, type LlmCompleteFn, type LoadedPluginScript, type LocalEndpoint, type ManageArchiveInput, ManageArchiveInputSchema, type ManageArchiveResult, type ManageAttachmentsInput, ManageAttachmentsInputSchema, type ManageAttachmentsResult, type ManageCapabilitiesInput, ManageCapabilitiesInputSchema, type ManageCapabilitiesResult, type ManageCollectionsInput, ManageCollectionsInputSchema, type ManageCollectionsResult, type ManageLinksInput, ManageLinksInputSchema, type ManageLinksResult, type ManageNoteInput, ManageNoteInputSchema, type ManageNoteResult, type ManageTagsInput, ManageTagsInputSchema, type ManageTagsResult, MemoryBlobStore, MemoryRecordStore, type Migration, MigrationRunner, type ModelCategory, type ModelFitResult, type ModelInfo, type NoteCreateInput, type NoteFull, type NoteListOptions, type NoteOriginalRecord, type NoteProjectionResult, type NoteRecord0, type NoteRevisedCurrentRecord, type NoteRevision, type NoteSkosTag, type NoteSummary, type NoteTagRecord, type NoteUpdateInput, NotesRepository, OpenAICompatibleProvider, type OpenAIProviderConfig, type OpenShardOptions, type PGliteBackendOptions, PGliteStorageBackend, PGliteStorageBackendFactory, PGliteWorkerClient, PGliteWorkerStorageBackend, PGliteWorkerStorageBackendFactory, type PGliteWorkerStorageBackendFactoryOptions, type PaginatedResult, type PersistenceMode, type PluginCspOptions, type PluginScriptDescriptor, type PluginScriptPolicy, type PrefetchOptions, type PrefetchResult, type ProbeResult, type ProbeStatus, type ProvenanceEdge, ProvenanceRepository, type ProviderCapabilities, ProviderRegistry, type ProviderTier, type QueryExecutor, type QueryResult, RECORD_COLLECTIONS, RECORD_SCHEMA_VERSION, RECORD_STORE_CAPABILITIES, type RecommendedTier, type RecordBackendManageNoteResult, type RecordBackendOptions, type RecordCollectionName, type RecordCollections, type RecordListOptions, type RecordMutation, type RecordProjectionResult, type RecordProvenanceInput, type RecordStore, type RecordStoreCapabilities, type RemoteBackendConfig, type RemoteBackendPaths, type ResolvedEmbeddingRow, type ResolvedEmbeddingSet, type RestoreDbSnapshotOptions, type RouteHandler, SHARD_FORMAT, SIGNATURE_ENTRY, SIGNING_ENVELOPE_VERSION, SUPPORTED_PGLITE_VERSION, type SWRegistrationResult, type SearchFacets, type SearchInput, SearchInputSchema, type SearchOptions, SearchRepository, type SearchResponse, type SearchResult, type ShardAuthorityStatus, type ShardBackend, type ShardBackendOptions, type ShardCapabilityReport, type ShardClusterRef, type ShardCollection, type ShardComponent, type ShardComponentStore, type ShardEmbedding, type ShardEmbeddingConfig, type ShardEmbeddingSet, type ShardEmbeddingSetMember, type ShardExportResult, type ShardLayout, type ShardLink, type ShardListOptions, type ShardLossEntry, type ShardManifest, type ShardNote, type ShardNoteFull, type ShardNoteSkosTag, type ShardOperation, type ShardProfileRegistryEntry, type ShardProvenanceEdge, type ShardReader, type ShardReaderNote, type ShardReaderSource, type ShardSchemaValidationResult, type ShardSearchOptions, type ShardSearchRankedNote, type ShardSearchResult, type ShardSearchWeights, type ShardSignatureEnvelope, type ShardSignatureVerdict, type ShardSigner, type ShardSigningPayload, type ShardSkosConcept, type ShardSkosRelation, type ShardSkosScheme, type ShardTag, type ShardTemplate, type ShardTrustStore, type SignShardInput, type SimilarityGraphCacheKey, type SimilarityGraphOptions, type SimilarityGraphRequest, type SimilarityGraphResult, type SkosConcept, type SkosRelation, SkosRepository, type SkosScheme, type StaticSemanticProvider, type StorageBackend, type StorageBackendFactory, type StorageOpenRequest, type StorageTopology, type StreamChunk, TagsRepository, TransactionProxy, type TrustedKey, TypedEventBus, VERSION, type VectorEntry, type VerifyShardSignatureInput, type VirtualEmbeddingSetDefinition, type VirtualEmbeddingSetSource, type VirtualEmbeddingSetValidationError, type VirtualMaterializationPolicy, type VramTier, type WorkerRequest, type WorkerResponse, aiRevisionHandler, aiwgFortemiIndexFromKnowledgeShard, aiwgFortemiIndexToCommunityGraph, aiwgFortemiIndexToKnowledgeShard, allMigrations, appendPluginScript, assertAiwgFortemiChunkManifest, assertAiwgFortemiChunkPart, assertAiwgFortemiIndexExport, assertAiwgStaticEmbeddingSet, assertShardComponentRecord, buildAiwgChunkedIndex, buildAiwgStaticEmbeddingSet, buildNoteConditions, buildPluginCsp, captureKnowledge, chunkText, classifyError, classifyModel, clearPrefetchedShard, collectionFromShard, collectionToShard, computeBlobHash, computeHash, computeSri, conceptTaggingHandler, cosineSimilarity, createAiwgFetchChunkLoader, createAiwgFetchDetailLoader, createAiwgIndexController, createAiwgReviewDecisionExport, createBlobStore, createCosineSemanticProvider, createCspReportHandler, createFortemi, createLazyBlobStore, createLegacyProvider, createPGliteBackend, createPGliteInstance, createRecordBackend, createRecordStore, createRemoteBackend, createRoutes, createShardBackend, createShardCapabilityReport, createWorkerEmbedFunction, defaultStorageBackendFactory, detectCommunities, detectGpuCapabilities, detectInferenceCapabilities, discoverLocalProviders, dropAttachmentProjection, dropNoteProjection, dumpDbSnapshot, embeddingConfigToShard, embeddingFromShard, embeddingGenerationHandler, embeddingSetFromShard, embeddingSetMemberToShard, embeddingSetToShard, embeddingToShard, enqueueFullWorkflow, enqueueJob, enqueueNoteCreationJobs, estimateModelFit, estimateVramMB, estimateVramTier, exportShard, exportShardFromRecords, exportShardFromRecordsWithReport, exportShardWithReport, fetchAndValidateFortemiCompatibility, fetchPluginScript, filterAiwgRecordsByPrivacy, findAiwgStaticDuplicatePairs, formatFortemiCompatibilitySummary, fortemiCompatibilityUrl, fortemiManifest, fromPrefetched, generateId, getAiwgFortemiFacets, getEmbedFunction, getFortemiBridge, getFortemiSecretStore, getJobQueueStatus, getKnowledgeShardContractReceipt, getKnowledgeShardProfileRegistry, getKnowledgeShardSchema, getLlmFunction, getNote, getPrefetchedSha256, handleEmbedRequests, hasFortemiSecureSecrets, importShard, importShardToRecords, isPluginScriptAllowed, isShardPrefetched, isShardSigningSupported, linkFromShard, linkToShard, linkingHandler, listNotes, manageArchive, manageAttachments, manageCapabilities, manageCollections, manageLinks, manageNote, manageTags, matchRoute, migrateLegacyBlobStore, noteFromShard, noteSkosTagToShard, noteToShard, openShard, packTarGz, parseCspReport, prefetchShard, profileSupportError, projectAttachments, projectNotes, projectRecords, provenanceEdgeToShard, queryAiwgFortemiIndex, queryAiwgHybridIndex, queryAiwgSemanticIndex, registerLlmCapability, registerSemanticCapability, registerSemanticCapabilityWorker, registerServiceWorker, restoreDbSnapshot, searchTool, selectBackend, selectLlmModel, setEmbedFunction, setLlmFunction, sha256Hex, sidecarBlobDigests, signShard, skosConceptToShard, skosRelationToShard, skosSchemeToShard, suggestTags, tagsToShard, templateToShard, titleGenerationHandler, unpackTarGz, unregisterLlmCapability, unregisterSemanticCapability, urlLinkToShard, validateAiwgFortemiChunkManifest, validateAiwgFortemiChunkPart, validateAiwgFortemiIndexExport, validateAiwgStaticEmbeddingSet, validateChecksums, validateCoreV1ShardArchive, validateFortemiCompatibilityResponse, validateFullV1ShardArchive, validateRecordV1ShardArchive, validateShardArchive, validateShardComponentRecord, validateShardManifest, verifyDbSnapshotMeta, verifyShardSignature, verifySri };
package/dist/index.js CHANGED
@@ -7664,7 +7664,7 @@ function createTarHeader(filename, size) {
7664
7664
  writeOctal(header, 108, 0, 8);
7665
7665
  writeOctal(header, 116, 0, 8);
7666
7666
  writeOctal(header, 124, size, 12);
7667
- writeOctal(header, 136, Math.floor(Date.now() / 1e3), 12);
7667
+ writeOctal(header, 136, 0, 12);
7668
7668
  header[156] = 48;
7669
7669
  writeString(header, 257, USTAR_MAGIC, 8);
7670
7670
  const checksum = computeHeaderChecksum(header);
@@ -7736,7 +7736,7 @@ function packTarGz(files, opts) {
7736
7736
  "Refusing to create archive: uncompressed size " + tarData.byteLength + " exceeds cap " + cap + " bytes"
7737
7737
  );
7738
7738
  }
7739
- return gzipSync(tarData);
7739
+ return gzipSync(tarData, { mtime: 0 });
7740
7740
  }
7741
7741
  var DEFAULT_MAX_DECOMPRESSED_BYTES = 256 * 1024 * 1024;
7742
7742
  function unpackTarGz(data, opts) {
@@ -7999,10 +7999,11 @@ function noteFromShard(shard) {
7999
7999
  };
8000
8000
  }
8001
8001
  function linkToShard(link) {
8002
- const legacyState = link.deleted_at ? {
8002
+ const legacyState = link.deleted_at || link.confidence === null ? {
8003
8003
  fortemi_legacy_state: {
8004
8004
  updated_at: link.updated_at === null || link.updated_at === void 0 ? null : toISOString(link.updated_at),
8005
- deleted_at: toISOString(link.deleted_at)
8005
+ deleted_at: link.deleted_at ? toISOString(link.deleted_at) : null,
8006
+ ...link.confidence === null ? { confidence: null } : {}
8006
8007
  }
8007
8008
  } : null;
8008
8009
  return {
@@ -8011,17 +8012,18 @@ function linkToShard(link) {
8011
8012
  to_note_id: link.target_note_id,
8012
8013
  to_url: null,
8013
8014
  kind: link.link_type,
8014
- score: link.confidence,
8015
+ score: link.confidence ?? 1,
8015
8016
  created_at: toISOString(link.created_at),
8016
8017
  metadata: legacyState
8017
8018
  };
8018
8019
  }
8019
8020
  function urlLinkToShard(link) {
8020
8021
  const metadata = typeof link.metadata_json === "string" ? JSON.parse(link.metadata_json) : link.metadata_json ?? null;
8021
- const legacyState = link.deleted_at ? {
8022
+ const legacyState = link.deleted_at || link.confidence === null ? {
8022
8023
  fortemi_legacy_state: {
8023
8024
  updated_at: link.updated_at === null || link.updated_at === void 0 ? null : toISOString(link.updated_at),
8024
- deleted_at: toISOString(link.deleted_at)
8025
+ deleted_at: link.deleted_at ? toISOString(link.deleted_at) : null,
8026
+ ...link.confidence === null ? { confidence: null } : {}
8025
8027
  }
8026
8028
  } : null;
8027
8029
  return {
@@ -8030,7 +8032,7 @@ function urlLinkToShard(link) {
8030
8032
  to_note_id: null,
8031
8033
  to_url: link.to_url,
8032
8034
  kind: link.link_type,
8033
- score: link.confidence,
8035
+ score: link.confidence ?? 1,
8034
8036
  created_at: toISOString(link.created_at),
8035
8037
  metadata: metadata || legacyState ? { ...metadata ?? {}, ...legacyState ?? {} } : null
8036
8038
  };
@@ -8046,7 +8048,7 @@ function linkFromShard(shard) {
8046
8048
  target_note_id: shard.to_note_id,
8047
8049
  to_url: shard.to_url ?? null,
8048
8050
  link_type: shard.kind,
8049
- confidence: shard.score,
8051
+ confidence: state?.confidence === null ? null : shard.score,
8050
8052
  created_at: shard.created_at,
8051
8053
  updated_at: typeof state?.updated_at === "string" ? state.updated_at : null,
8052
8054
  deleted_at: typeof state?.deleted_at === "string" ? state.deleted_at : null,
@@ -14514,6 +14516,22 @@ function coreReferenceErrors(records) {
14514
14516
  errors.push(`collections.json[${index}] parent_id does not reference a declared collection`);
14515
14517
  }
14516
14518
  }
14519
+ const collectionById = new Map(collections.map((collection) => [collection.id, collection]));
14520
+ const visiting = /* @__PURE__ */ new Set();
14521
+ const visited = /* @__PURE__ */ new Set();
14522
+ const visitCollection = (collection) => {
14523
+ if (visited.has(collection.id)) return;
14524
+ if (visiting.has(collection.id)) {
14525
+ errors.push(`collection hierarchy contains a cycle at ${String(collection.id)}`);
14526
+ return;
14527
+ }
14528
+ visiting.add(collection.id);
14529
+ const parent = collection.parent_id === null ? void 0 : collectionById.get(collection.parent_id);
14530
+ if (parent) visitCollection(parent);
14531
+ visiting.delete(collection.id);
14532
+ visited.add(collection.id);
14533
+ };
14534
+ for (const collection of collections) visitCollection(collection);
14517
14535
  for (const [index, note] of notes.entries()) {
14518
14536
  if (note.collection_id !== null && !collectionIds.has(note.collection_id)) {
14519
14537
  errors.push(`notes.jsonl[${index}] collection_id does not reference a declared collection`);
@@ -14963,7 +14981,9 @@ function toCoreV1Link(link) {
14963
14981
  const coreLink = { ...link };
14964
14982
  if (coreLink.metadata?.fortemi_legacy_state) {
14965
14983
  const metadata = { ...coreLink.metadata };
14966
- delete metadata.fortemi_legacy_state;
14984
+ const state = metadata.fortemi_legacy_state;
14985
+ metadata.fortemi_legacy_state = state && typeof state === "object" && !Array.isArray(state) && "confidence" in state && state.confidence === null ? { confidence: null } : void 0;
14986
+ if (metadata.fortemi_legacy_state === void 0) delete metadata.fortemi_legacy_state;
14967
14987
  coreLink.metadata = Object.keys(metadata).length > 0 ? metadata : null;
14968
14988
  }
14969
14989
  return coreLink;
@@ -15694,6 +15714,31 @@ function emptyCounts() {
15694
15714
  community_assignments: 0
15695
15715
  };
15696
15716
  }
15717
+ function orderCollectionsParentsFirst(collections) {
15718
+ const byId = new Map(collections.map((collection) => [collection.id, collection]));
15719
+ const visiting = /* @__PURE__ */ new Set();
15720
+ const visited = /* @__PURE__ */ new Set();
15721
+ const ordered = [];
15722
+ const visit = (collection) => {
15723
+ if (visited.has(collection.id)) return;
15724
+ if (visiting.has(collection.id)) {
15725
+ throw new Error(`collection hierarchy contains a cycle at ${collection.id}`);
15726
+ }
15727
+ visiting.add(collection.id);
15728
+ if (collection.parent_id) {
15729
+ const parent = byId.get(collection.parent_id);
15730
+ if (!parent) {
15731
+ throw new Error(`collection ${collection.id} references missing parent ${collection.parent_id}`);
15732
+ }
15733
+ visit(parent);
15734
+ }
15735
+ visiting.delete(collection.id);
15736
+ visited.add(collection.id);
15737
+ ordered.push(collection);
15738
+ };
15739
+ for (const collection of collections) visit(collection);
15740
+ return ordered;
15741
+ }
15697
15742
  async function enforceSignaturePolicy(files, options, warnings) {
15698
15743
  const policy = options?.verifySignature ?? (options?.trustStore ? "require" : void 0);
15699
15744
  if (!policy) return null;
@@ -15911,7 +15956,9 @@ async function importShard(db, data, options) {
15911
15956
  let parsedCommunityAssignments;
15912
15957
  try {
15913
15958
  parsedNotes = parseComponent("notes", () => noteClusters && noteClusters.length > 0 ? [...noteClusters].sort((a, b) => a.offset - b.offset).flatMap((ref) => parseJsonlBytes(files.get(ref.href))) : parseJsonlBytes(files.get("notes.jsonl")));
15914
- parsedCollections = parseComponent("collections.json", () => parseJsonArrayBytes(files.get("collections.json")));
15959
+ parsedCollections = parseComponent("collections.json", () => orderCollectionsParentsFirst(
15960
+ parseJsonArrayBytes(files.get("collections.json"))
15961
+ ));
15915
15962
  parsedTags = parseComponent("tags.json", () => parseJsonArrayBytes(files.get("tags.json")));
15916
15963
  parsedTemplates = parseComponent("templates.json", () => parseJsonArrayBytes(files.get("templates.json")));
15917
15964
  parsedLinks = parseComponent("links.jsonl", () => parseJsonlBytes(files.get("links.jsonl")));
@@ -20169,6 +20216,18 @@ var RECORD_STORE_CAPABILITIES = {
20169
20216
  vectorSearch: false,
20170
20217
  sqlJoins: false
20171
20218
  };
20219
+ function normalizeRecordMutation(mutation) {
20220
+ if (mutation.op === "put" && mutation.collection === "collection") {
20221
+ return {
20222
+ ...mutation,
20223
+ record: {
20224
+ ...mutation.record,
20225
+ parent_id: mutation.record.parent_id ?? null
20226
+ }
20227
+ };
20228
+ }
20229
+ return mutation;
20230
+ }
20172
20231
 
20173
20232
  // src/records/memory-record-store.ts
20174
20233
  var MemoryRecordStore = class {
@@ -20214,7 +20273,8 @@ var MemoryRecordStore = class {
20214
20273
  }
20215
20274
  return records;
20216
20275
  };
20217
- for (const mutation of mutations) {
20276
+ for (const rawMutation of mutations) {
20277
+ const mutation = normalizeRecordMutation(rawMutation);
20218
20278
  const entry = mutation.op === "put" ? {
20219
20279
  seq: ++stagedSeq,
20220
20280
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -20261,7 +20321,7 @@ var MemoryRecordStore = class {
20261
20321
  var DB_VERSION = 1;
20262
20322
  var JOURNAL_STORE = "journal";
20263
20323
  var META_STORE = "meta";
20264
- var RECORD_SCHEMA_VERSION = 1;
20324
+ var RECORD_SCHEMA_VERSION = 2;
20265
20325
  function requestToPromise(request) {
20266
20326
  return new Promise((resolve, reject) => {
20267
20327
  request.onsuccess = () => resolve(request.result);
@@ -20309,16 +20369,25 @@ var IdbRecordStore = class _IdbRecordStore {
20309
20369
  return store;
20310
20370
  }
20311
20371
  async ensureSchemaVersion() {
20312
- const tx = this.db.transaction(META_STORE, "readwrite");
20372
+ const tx = this.db.transaction([META_STORE, "collection"], "readwrite");
20313
20373
  const meta = tx.objectStore(META_STORE);
20314
20374
  const current = await requestToPromise(meta.get("schemaVersion"));
20315
- if (current === void 0) {
20316
- meta.put(RECORD_SCHEMA_VERSION, "schemaVersion");
20317
- } else if (current > RECORD_SCHEMA_VERSION) {
20375
+ if (current !== void 0 && current > RECORD_SCHEMA_VERSION) {
20318
20376
  throw new Error(
20319
20377
  `IdbRecordStore: records were written by a newer schema (v${current} > v${RECORD_SCHEMA_VERSION}); refusing to open`
20320
20378
  );
20321
20379
  }
20380
+ if ((current ?? 0) < 2) {
20381
+ const collections = await requestToPromise(
20382
+ tx.objectStore("collection").getAll()
20383
+ );
20384
+ for (const collection of collections) {
20385
+ if (!Object.hasOwn(collection, "parent_id")) {
20386
+ tx.objectStore("collection").put({ ...collection, parent_id: null });
20387
+ }
20388
+ }
20389
+ }
20390
+ meta.put(RECORD_SCHEMA_VERSION, "schemaVersion");
20322
20391
  await transactionComplete(tx);
20323
20392
  }
20324
20393
  async get(collection, id) {
@@ -20337,12 +20406,13 @@ var IdbRecordStore = class _IdbRecordStore {
20337
20406
  }
20338
20407
  async applyBatch(mutations) {
20339
20408
  if (mutations.length === 0) return [];
20340
- const collections = [...new Set(mutations.map((mutation) => mutation.collection))];
20409
+ const normalizedMutations = mutations.map(normalizeRecordMutation);
20410
+ const collections = [...new Set(normalizedMutations.map((mutation) => mutation.collection))];
20341
20411
  const tx = this.db.transaction([...collections, JOURNAL_STORE], "readwrite");
20342
20412
  const completed = transactionComplete(tx);
20343
20413
  const pendingEntries = [];
20344
20414
  try {
20345
- for (const mutation of mutations) {
20415
+ for (const mutation of normalizedMutations) {
20346
20416
  const records = tx.objectStore(mutation.collection);
20347
20417
  const pending = mutation.op === "put" ? {
20348
20418
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -20589,12 +20659,16 @@ ${revised.get(note.id) ?? ""}`.toLowerCase();
20589
20659
  );
20590
20660
  }
20591
20661
  // ── Collections ───────────────────────────────────────────────────────────
20592
- async createCollection(name, description) {
20662
+ async createCollection(name, description, parentId = null) {
20663
+ if (parentId !== null && !await this.store.get("collection", parentId)) {
20664
+ throw new Error(`Parent collection not found: ${parentId}`);
20665
+ }
20593
20666
  const ts = nowIso();
20594
20667
  const collection = {
20595
20668
  id: generateId(),
20596
20669
  name,
20597
20670
  description: description ?? null,
20671
+ parent_id: parentId,
20598
20672
  created_at: ts,
20599
20673
  updated_at: ts,
20600
20674
  deleted_at: null
@@ -20777,6 +20851,32 @@ async function dropAttachmentProjection(db) {
20777
20851
  }
20778
20852
 
20779
20853
  // src/records/record-projection.ts
20854
+ function collectionsParentFirst(collections) {
20855
+ const byId = new Map(collections.map((collection) => [collection.id, collection]));
20856
+ const ordered = [];
20857
+ const visiting = /* @__PURE__ */ new Set();
20858
+ const visited = /* @__PURE__ */ new Set();
20859
+ const visit = (collection) => {
20860
+ if (visited.has(collection.id)) return;
20861
+ if (visiting.has(collection.id)) {
20862
+ throw new Error(`Collection hierarchy contains a cycle at ${collection.id}`);
20863
+ }
20864
+ visiting.add(collection.id);
20865
+ const parentId = collection.parent_id ?? null;
20866
+ if (parentId !== null) {
20867
+ const parent = byId.get(parentId);
20868
+ if (!parent) {
20869
+ throw new Error(`Collection ${collection.id} references missing parent ${parentId}`);
20870
+ }
20871
+ visit(parent);
20872
+ }
20873
+ visiting.delete(collection.id);
20874
+ visited.add(collection.id);
20875
+ ordered.push(collection);
20876
+ };
20877
+ for (const collection of collections) visit(collection);
20878
+ return ordered;
20879
+ }
20780
20880
  async function projectNotes(db, store) {
20781
20881
  const [noteRows, originals, revised, tags, links, collections, memberships] = await Promise.all([
20782
20882
  store.list("note"),
@@ -20787,16 +20887,25 @@ async function projectNotes(db, store) {
20787
20887
  store.list("collection"),
20788
20888
  store.list("collection_note")
20789
20889
  ]);
20790
- for (const c of collections) {
20890
+ for (const c of collectionsParentFirst(collections)) {
20791
20891
  await db.query(
20792
- `INSERT INTO collection (id, name, description, created_at, updated_at, deleted_at)
20793
- VALUES ($1, $2, $3, $4, $5, $6)
20892
+ `INSERT INTO collection (id, name, description, parent_id, created_at, updated_at, deleted_at)
20893
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
20794
20894
  ON CONFLICT (id) DO UPDATE SET
20795
20895
  name = EXCLUDED.name,
20796
20896
  description = EXCLUDED.description,
20897
+ parent_id = EXCLUDED.parent_id,
20797
20898
  updated_at = EXCLUDED.updated_at,
20798
20899
  deleted_at = EXCLUDED.deleted_at`,
20799
- [c.id, c.name, c.description, c.created_at, c.updated_at, c.deleted_at]
20900
+ [
20901
+ c.id,
20902
+ c.name,
20903
+ c.description,
20904
+ c.parent_id ?? null,
20905
+ c.created_at,
20906
+ c.updated_at,
20907
+ c.deleted_at
20908
+ ]
20800
20909
  );
20801
20910
  }
20802
20911
  for (const n of noteRows) {
@@ -21294,12 +21403,11 @@ async function buildRecordShardArchive(store, options, profile) {
21294
21403
  const orderedCollections = collections.sort((a, b) => a.name.localeCompare(b.name));
21295
21404
  const shardCollections = orderedCollections.map((c) => {
21296
21405
  const mapped = collectionToShard(
21297
- // Canonical collections are flat (no parent hierarchy yet).
21298
21406
  {
21299
21407
  id: c.id,
21300
21408
  name: c.name,
21301
21409
  description: c.description,
21302
- parent_id: null,
21410
+ parent_id: c.parent_id ?? null,
21303
21411
  created_at: c.created_at,
21304
21412
  updated_at: c.updated_at,
21305
21413
  deleted_at: c.deleted_at
@@ -21733,6 +21841,7 @@ async function importShardToRecords(store, data, options) {
21733
21841
  id: col.id,
21734
21842
  name: col.name,
21735
21843
  description: col.description,
21844
+ parent_id: col.parent_id,
21736
21845
  created_at: col.created_at,
21737
21846
  updated_at: col.updated_at,
21738
21847
  deleted_at: col.deleted_at
@@ -22007,7 +22116,7 @@ async function importShardToRecords(store, data, options) {
22007
22116
  }
22008
22117
 
22009
22118
  // src/index.ts
22010
- var VERSION = "2026.7.9";
22119
+ var VERSION = "2026.7.11";
22011
22120
 
22012
22121
  export { AIWG_SCAN_REQUIRED_FIELDS, AllowlistTrustStore, ArchiveManager, AttachmentsRepository, CORE_V1_COMPONENTS, CURRENT_MIGRATION_HEAD, CURRENT_SHARD_VERSION, CanonicalAttachmentsRepository, CanonicalNotesRepository, CapabilityManager, CaptureKnowledgeInputSchema, CollectionsRepository, CommunitiesRepository, DB_SNAPSHOT_SCHEMA_VERSION, DbSnapshotVersionError, EMBED_REQUEST_KIND, EMBED_RESPONSE_KIND, EmbeddingSetsRepository, FORTEMI_COMPATIBILITY_PATH, FORTEMI_COMPATIBILITY_STATES, FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES, FallbackRouter, FortemiToolManifest, GetNoteInputSchema, GraphRepository, IdbRecordStore, JOB_CAPABILITIES, JOB_PRIORITIES, JobQueueWorker, LOCAL_ENDPOINTS, LinksRepository, ListNotesInputSchema, ManageArchiveInputSchema, ManageAttachmentsInputSchema, ManageCapabilitiesInputSchema, ManageCollectionsInputSchema, ManageLinksInputSchema, ManageNoteInputSchema, ManageTagsInputSchema, MemoryBlobStore, MemoryRecordStore, MigrationRunner, NotesRepository, OpenAICompatibleProvider, PGliteStorageBackend, PGliteStorageBackendFactory, PGliteWorkerClient, PGliteWorkerStorageBackend, PGliteWorkerStorageBackendFactory, ProvenanceRepository, ProviderRegistry, RECORD_COLLECTIONS, RECORD_SCHEMA_VERSION, RECORD_STORE_CAPABILITIES, SHARD_FORMAT, SIGNATURE_ENTRY, SIGNING_ENVELOPE_VERSION, SUPPORTED_PGLITE_VERSION, SearchInputSchema, SearchRepository, SkosRepository, TagsRepository, TransactionProxy, TypedEventBus, VERSION, aiRevisionHandler, aiwgFortemiIndexFromKnowledgeShard, aiwgFortemiIndexToCommunityGraph, aiwgFortemiIndexToKnowledgeShard, allMigrations, appendPluginScript, assertAiwgFortemiChunkManifest, assertAiwgFortemiChunkPart, assertAiwgFortemiIndexExport, assertAiwgStaticEmbeddingSet, assertShardComponentRecord, buildAiwgChunkedIndex, buildAiwgStaticEmbeddingSet, buildNoteConditions, buildPluginCsp, captureKnowledge, chunkText, classifyError, classifyModel, clearPrefetchedShard, collectionFromShard, collectionToShard, computeBlobHash, computeHash, computeSri, conceptTaggingHandler, cosineSimilarity, createAiwgFetchChunkLoader, createAiwgFetchDetailLoader, createAiwgIndexController, createAiwgReviewDecisionExport, createBlobStore, createCosineSemanticProvider, createCspReportHandler, createFortemi, createLazyBlobStore, createLegacyProvider, createPGliteBackend, createPGliteInstance, createRecordBackend, createRecordStore, createRemoteBackend, createRoutes, createShardBackend, createShardCapabilityReport, createWorkerEmbedFunction, defaultStorageBackendFactory, detectCommunities, detectGpuCapabilities, detectInferenceCapabilities, discoverLocalProviders, dropAttachmentProjection, dropNoteProjection, dumpDbSnapshot, embeddingConfigToShard, embeddingFromShard, embeddingGenerationHandler, embeddingSetFromShard, embeddingSetMemberToShard, embeddingSetToShard, embeddingToShard, enqueueFullWorkflow, enqueueJob, enqueueNoteCreationJobs, estimateModelFit, estimateVramMB, estimateVramTier, exportShard, exportShardFromRecords, exportShardFromRecordsWithReport, exportShardWithReport, fetchAndValidateFortemiCompatibility, fetchPluginScript, filterAiwgRecordsByPrivacy, findAiwgStaticDuplicatePairs, formatFortemiCompatibilitySummary, fortemiCompatibilityUrl, fortemiManifest, fromPrefetched, generateId, getAiwgFortemiFacets, getAiwgFortemiIndexExportSchema, getEmbedFunction, getFortemiBridge, getFortemiSecretStore, getJobQueueStatus, getKnowledgeShardContractReceipt, getKnowledgeShardProfileRegistry, getKnowledgeShardSchema, getLlmFunction, getNote, getPrefetchedSha256, handleEmbedRequests, hasFortemiSecureSecrets, importShard, importShardToRecords, isPluginScriptAllowed, isShardPrefetched, isShardSigningSupported, linkFromShard, linkToShard, linkingHandler, listNotes, manageArchive, manageAttachments, manageCapabilities, manageCollections, manageLinks, manageNote, manageTags, matchRoute, migrateLegacyBlobStore, noteFromShard, noteSkosTagToShard, noteToShard, openShard, packTarGz, parseCspReport, prefetchShard, profileSupportError, projectAttachments, projectNotes, projectRecords, provenanceEdgeToShard, queryAiwgFortemiIndex, queryAiwgHybridIndex, queryAiwgSemanticIndex, registerLlmCapability, registerSemanticCapability, registerSemanticCapabilityWorker, registerServiceWorker, restoreDbSnapshot, searchTool, selectBackend, selectLlmModel, setEmbedFunction, setLlmFunction, sha256Hex, sidecarBlobDigests, signShard, skosConceptToShard, skosRelationToShard, skosSchemeToShard, suggestTags, tagsToShard, templateToShard, titleGenerationHandler, unpackTarGz, unregisterLlmCapability, unregisterSemanticCapability, urlLinkToShard, validateAiwgFortemiChunkManifest, validateAiwgFortemiChunkPart, validateAiwgFortemiIndexExport, validateAiwgFortemiIndexExportSchema, validateAiwgFortemiProjectedRecordSchema, validateAiwgStaticEmbeddingSet, validateChecksums, validateCoreV1ShardArchive, validateFortemiCompatibilityResponse, validateFullV1ShardArchive, validateRecordV1ShardArchive, validateShardArchive, validateShardComponentRecord, validateShardManifest, verifyDbSnapshotMeta, verifyShardSignature, verifySri };
22013
22122
  //# sourceMappingURL=index.js.map