@semiont/make-meaning 0.2.30-build.60 → 0.2.30-build.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -583
- package/dist/index.d.ts +175 -7
- package/dist/index.js +1410 -54
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/resource-context.ts","../src/annotation-context.ts","../src/graph-context.ts","../src/annotation-detection.ts","../src/index.ts"],"sourcesContent":["/**\n * Resource Context\n *\n * Assembles resource context from view storage and content store\n * Does NOT touch the graph - graph queries go through GraphContext\n */\n\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport type { components } from '@semiont/api-client';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface ListResourcesFilters {\n search?: string;\n archived?: boolean;\n}\n\nexport class ResourceContext {\n /**\n * Get resource metadata from view storage\n */\n static async getResourceMetadata(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceDescriptor | null> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const view = await viewStorage.get(resourceId);\n if (!view) {\n return null;\n }\n\n return view.resource;\n }\n\n /**\n * List all resources by scanning view storage\n */\n static async listResources(filters: ListResourcesFilters | undefined, config: EnvironmentConfig): Promise<ResourceDescriptor[]> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const allViews = await viewStorage.getAll();\n const resources: ResourceDescriptor[] = [];\n\n for (const view of allViews) {\n const doc = view.resource;\n\n // Apply filters\n if (filters?.archived !== undefined && doc.archived !== filters.archived) {\n continue;\n }\n\n if (filters?.search) {\n const searchLower = filters.search.toLowerCase();\n if (!doc.name.toLowerCase().includes(searchLower)) {\n continue;\n }\n }\n\n resources.push(doc);\n }\n\n // Sort by creation date (newest first)\n resources.sort((a, b) => {\n const aTime = a.dateCreated ? new Date(a.dateCreated).getTime() : 0;\n const bTime = b.dateCreated ? new Date(b.dateCreated).getTime() : 0;\n return bTime - aTime;\n });\n\n return resources;\n }\n\n /**\n * Add content previews to resources (for search results)\n * Retrieves and decodes the first 200 characters of each resource's primary representation\n */\n static async addContentPreviews(\n resources: ResourceDescriptor[],\n config: EnvironmentConfig\n ): Promise<Array<ResourceDescriptor & { content: string }>> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n return await Promise.all(\n resources.map(async (doc) => {\n try {\n const primaryRep = getPrimaryRepresentation(doc);\n if (primaryRep?.checksum && primaryRep?.mediaType) {\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentPreview = decodeRepresentation(contentBuffer, primaryRep.mediaType).slice(0, 200);\n return { ...doc, content: contentPreview };\n }\n return { ...doc, content: '' };\n } catch {\n return { ...doc, content: '' };\n }\n })\n );\n }\n}\n","/**\n * Annotation Context\n *\n * Assembles annotation context from view storage and content store.\n * Provides methods for:\n * - Getting resource annotations\n * - Building LLM context for annotations\n * - Extracting annotation text context\n * - Generating AI summaries\n */\n\nimport { generateResourceSummary, generateText } from '@semiont/inference';\nimport {\n getBodySource,\n getTargetSource,\n getTargetSelector,\n getResourceEntityTypes,\n getTextPositionSelector,\n getPrimaryRepresentation,\n decodeRepresentation,\n} from '@semiont/api-client';\nimport type { components, AnnotationUri, GenerationContext } from '@semiont/api-client';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport type {\n EnvironmentConfig,\n ResourceId,\n ResourceAnnotations,\n AnnotationId,\n AnnotationCategory,\n} from '@semiont/core';\nimport { resourceId as createResourceId, uriToResourceId } from '@semiont/core';\nimport { getEntityTypes } from '@semiont/ontology';\nimport { ResourceContext } from './resource-context';\n\ntype AnnotationLLMContextResponse = components['schemas']['AnnotationLLMContextResponse'];\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype AnnotationContextResponse = components['schemas']['AnnotationContextResponse'];\ntype ContextualSummaryResponse = components['schemas']['ContextualSummaryResponse'];\n\nexport interface BuildContextOptions {\n includeSourceContext?: boolean;\n includeTargetContext?: boolean;\n contextWindow?: number;\n}\n\ninterface AnnotationTextContext {\n before: string;\n selected: string;\n after: string;\n}\n\nexport class AnnotationContext {\n /**\n * Build LLM context for an annotation\n *\n * @param annotationUri - Full annotation URI (e.g., http://localhost:4000/annotations/abc123)\n * @param resourceId - Source resource ID\n * @param config - Application configuration\n * @param options - Context building options\n * @returns Rich context for LLM processing\n * @throws Error if annotation or resource not found\n */\n static async buildLLMContext(\n annotationUri: AnnotationUri,\n resourceId: ResourceId,\n config: EnvironmentConfig,\n options: BuildContextOptions = {}\n ): Promise<AnnotationLLMContextResponse> {\n const {\n includeSourceContext = true,\n includeTargetContext = true,\n contextWindow = 1000\n } = options;\n\n // Validate contextWindow range\n if (contextWindow < 100 || contextWindow > 5000) {\n throw new Error('contextWindow must be between 100 and 5000');\n }\n\n console.log(`[AnnotationContext] buildLLMContext called with annotationUri=${annotationUri}, resourceId=${resourceId}`);\n\n const basePath = config.services.filesystem!.path;\n console.log(`[AnnotationContext] basePath=${basePath}`);\n\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get source resource view\n console.log(`[AnnotationContext] Getting view for resourceId=${resourceId}`);\n let sourceView;\n try {\n sourceView = await viewStorage.get(resourceId);\n console.log(`[AnnotationContext] Got view:`, !!sourceView);\n\n if (!sourceView) {\n throw new Error('Source resource not found');\n }\n } catch (error) {\n console.error(`[AnnotationContext] Error getting view:`, error);\n throw error;\n }\n\n console.log(`[AnnotationContext] Looking for annotation ${annotationUri} in resource ${resourceId}`);\n console.log(`[AnnotationContext] View has ${sourceView.annotations.annotations.length} annotations`);\n console.log(`[AnnotationContext] First 5 annotation IDs:`, sourceView.annotations.annotations.slice(0, 5).map((a: Annotation) => a.id));\n\n // Find the annotation in the view (annotations have full URIs as their id)\n const annotation = sourceView.annotations.annotations.find((a: Annotation) => a.id === annotationUri);\n console.log(`[AnnotationContext] Found annotation:`, !!annotation);\n\n if (!annotation) {\n throw new Error('Annotation not found in view');\n }\n\n const targetSource = getTargetSource(annotation.target);\n // Extract resource ID from the target source URI (format: http://host/resources/{id})\n const targetResourceId = targetSource.split('/').pop();\n console.log(`[AnnotationContext] Target source: ${targetSource}, Expected resource ID: ${resourceId}, Extracted ID: ${targetResourceId}`);\n\n if (targetResourceId !== resourceId) {\n throw new Error(`Annotation target resource ID (${targetResourceId}) does not match expected resource ID (${resourceId})`);\n }\n\n const sourceDoc = sourceView.resource;\n\n // Get target resource if annotation is a reference (has resolved body source)\n const bodySource = getBodySource(annotation.body);\n\n // Extract target document from body source URI if present\n let targetDoc = null;\n if (bodySource) {\n // Inline extraction: \"http://localhost:4000/resources/abc123\" → \"abc123\"\n const parts = (bodySource as string).split('/');\n const lastPart = parts[parts.length - 1];\n if (!lastPart) {\n throw new Error(`Invalid body source URI: ${bodySource}`);\n }\n const targetResourceId = createResourceId(lastPart);\n const targetView = await viewStorage.get(targetResourceId);\n targetDoc = targetView?.resource || null;\n }\n\n // Build source context if requested\n let sourceContext;\n if (includeSourceContext) {\n const primaryRep = getPrimaryRepresentation(sourceDoc);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Source content not found');\n }\n const sourceContent = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentStr = decodeRepresentation(sourceContent, primaryRep.mediaType);\n\n const targetSelectorRaw = getTargetSelector(annotation.target);\n\n // Handle array of selectors - take the first one\n const targetSelector = Array.isArray(targetSelectorRaw) ? targetSelectorRaw[0] : targetSelectorRaw;\n\n console.log(`[AnnotationContext] Target selector type:`, targetSelector?.type);\n\n if (!targetSelector) {\n console.warn(`[AnnotationContext] No target selector found`);\n } else if (targetSelector.type === 'TextPositionSelector') {\n // TypeScript now knows this is TextPositionSelector with required start/end\n const selector = targetSelector as TextPositionSelector;\n const start = selector.start;\n const end = selector.end;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = contentStr.slice(start, end);\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n console.log(`[AnnotationContext] Built source context using TextPositionSelector (${start}-${end})`);\n } else if (targetSelector.type === 'TextQuoteSelector') {\n // TypeScript now knows this is TextQuoteSelector with required exact\n const selector = targetSelector as TextQuoteSelector;\n const exact = selector.exact;\n const index = contentStr.indexOf(exact);\n\n if (index !== -1) {\n const start = index;\n const end = index + exact.length;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = exact;\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n console.log(`[AnnotationContext] Built source context using TextQuoteSelector (found at ${index})`);\n } else {\n console.warn(`[AnnotationContext] TextQuoteSelector exact text not found in content: \"${exact.substring(0, 50)}...\"`);\n }\n } else {\n console.warn(`[AnnotationContext] Unknown selector type: ${(targetSelector as any).type}`);\n }\n }\n\n // Build target context if requested and available\n let targetContext;\n if (includeTargetContext && targetDoc) {\n const targetRep = getPrimaryRepresentation(targetDoc);\n if (targetRep?.checksum && targetRep?.mediaType) {\n const targetContent = await repStore.retrieve(targetRep.checksum, targetRep.mediaType);\n const contentStr = decodeRepresentation(targetContent, targetRep.mediaType);\n\n targetContext = {\n content: contentStr.slice(0, contextWindow * 2),\n summary: await generateResourceSummary(targetDoc.name, contentStr, getResourceEntityTypes(targetDoc), config),\n };\n }\n }\n\n // TODO: Generate suggested resolution using AI\n const suggestedResolution = undefined;\n\n // Build GenerationContext structure\n const generationContext: GenerationContext | undefined = sourceContext ? {\n sourceContext: {\n before: sourceContext.before || '',\n selected: sourceContext.selected,\n after: sourceContext.after || '',\n },\n metadata: {\n resourceType: 'document',\n language: sourceDoc.language as string | undefined,\n entityTypes: getEntityTypes(annotation),\n },\n } : undefined;\n\n const response: AnnotationLLMContextResponse = {\n annotation,\n sourceResource: sourceDoc,\n targetResource: targetDoc,\n ...(generationContext ? { context: generationContext } : {}),\n ...(sourceContext ? { sourceContext } : {}), // Keep for backward compatibility\n ...(targetContext ? { targetContext } : {}),\n ...(suggestedResolution ? { suggestedResolution } : {}),\n };\n\n return response;\n }\n\n /**\n * Get resource annotations from view storage (fast path)\n * Throws if view missing\n */\n static async getResourceAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceAnnotations> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(resourceId);\n\n if (!view) {\n throw new Error(`Resource ${resourceId} not found in view storage`);\n }\n\n return view.annotations;\n }\n\n /**\n * Get all annotations\n * @returns Array of all annotation objects\n */\n static async getAllAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n\n // Enrich resolved references with document names\n // NOTE: Future optimization - make this optional via query param if performance becomes an issue\n return await this.enrichResolvedReferences(annotations.annotations, config);\n }\n\n /**\n * Enrich reference annotations with resolved document names\n * Adds _resolvedDocumentName property to annotations that link to documents\n * @private\n */\n private static async enrichResolvedReferences(annotations: Annotation[], config: EnvironmentConfig): Promise<Annotation[]> {\n if (!config.services?.filesystem?.path) {\n return annotations;\n }\n\n // Extract unique resolved document URIs from reference annotations\n const resolvedUris = new Set<string>();\n for (const ann of annotations) {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.purpose === 'linking' && item.source) {\n resolvedUris.add(item.source);\n }\n }\n }\n }\n\n if (resolvedUris.size === 0) {\n return annotations;\n }\n\n // Batch fetch all resolved documents in parallel\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const metadataPromises = Array.from(resolvedUris).map(async (uri) => {\n const docId = uri.split('/resources/')[1];\n if (!docId) return null;\n\n try {\n const view = await viewStorage.get(docId as ResourceId);\n if (view?.resource?.name) {\n return {\n uri,\n metadata: {\n name: view.resource.name,\n mediaType: view.resource.mediaType as string | undefined\n }\n };\n }\n } catch (e) {\n // Document might not exist, skip\n }\n return null;\n });\n\n const results = await Promise.all(metadataPromises);\n const uriToMetadata = new Map<string, { name: string; mediaType?: string }>();\n for (const result of results) {\n if (result) {\n uriToMetadata.set(result.uri, result.metadata);\n }\n }\n\n // Add _resolvedDocumentName and _resolvedDocumentMediaType to annotations\n return annotations.map(ann => {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.purpose === 'linking' && item.source) {\n const metadata = uriToMetadata.get(item.source);\n if (metadata) {\n return {\n ...ann,\n _resolvedDocumentName: metadata.name,\n _resolvedDocumentMediaType: metadata.mediaType\n } as Annotation;\n }\n }\n }\n }\n return ann;\n });\n }\n\n /**\n * Get resource stats (version info)\n * @returns Version and timestamp info for the annotations\n */\n static async getResourceStats(resourceId: ResourceId, config: EnvironmentConfig): Promise<{\n resourceId: ResourceId;\n version: number;\n updatedAt: string;\n }> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n return {\n resourceId: annotations.resourceId,\n version: annotations.version,\n updatedAt: annotations.updatedAt,\n };\n }\n\n /**\n * Check if resource exists in view storage\n */\n static async resourceExists(resourceId: ResourceId, config: EnvironmentConfig): Promise<boolean> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n return await viewStorage.exists(resourceId);\n }\n\n /**\n * Get a single annotation by ID\n * O(1) lookup using resource ID to access view storage\n */\n static async getAnnotation(annotationId: AnnotationId, resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation | null> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n // Extract short ID from annotation's full URI for comparison\n return annotations.annotations.find((a: Annotation) => {\n const shortId = a.id.split('/').pop();\n return shortId === annotationId;\n }) || null;\n }\n\n /**\n * List annotations with optional filtering\n * @param filters - Optional filters like resourceId and type\n * @throws Error if resourceId not provided (cross-resource queries not supported in view storage)\n */\n static async listAnnotations(filters: { resourceId?: ResourceId; type?: AnnotationCategory } | undefined, config: EnvironmentConfig): Promise<Annotation[]> {\n if (!filters?.resourceId) {\n throw new Error('resourceId is required for annotation listing - cross-resource queries not supported in view storage');\n }\n\n // Use view storage directly\n return await this.getAllAnnotations(filters.resourceId, config);\n }\n\n /**\n * Get annotation context (selected text with surrounding context)\n */\n static async getAnnotationContext(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n contextBefore: number,\n contextAfter: number,\n config: EnvironmentConfig\n ): Promise<AnnotationContextResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource metadata from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract context based on annotation position\n const context = this.extractAnnotationContext(annotation, contentStr, contextBefore, contextAfter);\n\n return {\n annotation: annotation,\n context,\n resource: {\n '@context': resource['@context'],\n '@id': resource['@id'],\n name: resource.name,\n entityTypes: resource.entityTypes,\n representations: resource.representations,\n archived: resource.archived,\n creationMethod: resource.creationMethod,\n wasAttributedTo: resource.wasAttributedTo,\n dateCreated: resource.dateCreated,\n },\n };\n }\n\n /**\n * Generate AI summary of annotation in context\n */\n static async generateAnnotationSummary(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n config: EnvironmentConfig\n ): Promise<ContextualSummaryResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract annotation text with context (fixed 500 chars for summary)\n const contextSize = 500;\n const context = this.extractAnnotationContext(annotation, contentStr, contextSize, contextSize);\n\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes(annotation);\n\n // Generate summary using LLM\n const summary = await this.generateSummary(resource, context, annotationEntityTypes, config);\n\n return {\n summary,\n relevantFields: {\n resourceId: resource.id,\n resourceName: resource.name,\n entityTypes: annotationEntityTypes,\n },\n context: {\n before: context.before.substring(Math.max(0, context.before.length - 200)), // Last 200 chars\n selected: context.selected,\n after: context.after.substring(0, 200), // First 200 chars\n },\n };\n }\n\n /**\n * Get resource content as string\n */\n private static async getResourceContent(\n resource: ResourceDescriptor,\n repStore: FilesystemRepresentationStore\n ): Promise<string> {\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Resource content not found');\n }\n const content = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(content, primaryRep.mediaType);\n }\n\n /**\n * Extract annotation context from resource content\n */\n private static extractAnnotationContext(\n annotation: Annotation,\n contentStr: string,\n contextBefore: number,\n contextAfter: number\n ): AnnotationTextContext {\n const targetSelector = getTargetSelector(annotation.target);\n const posSelector = targetSelector ? getTextPositionSelector(targetSelector) : null;\n if (!posSelector) {\n throw new Error('TextPositionSelector required for context');\n }\n\n const selStart = posSelector.start;\n const selEnd = posSelector.end;\n const start = Math.max(0, selStart - contextBefore);\n const end = Math.min(contentStr.length, selEnd + contextAfter);\n\n return {\n before: contentStr.substring(start, selStart),\n selected: contentStr.substring(selStart, selEnd),\n after: contentStr.substring(selEnd, end),\n };\n }\n\n /**\n * Generate LLM summary of annotation in context\n */\n private static async generateSummary(\n resource: ResourceDescriptor,\n context: AnnotationTextContext,\n entityTypes: string[],\n config: EnvironmentConfig\n ): Promise<string> {\n const summaryPrompt = `Summarize this text in context:\n\nContext before: \"${context.before.substring(Math.max(0, context.before.length - 200))}\"\nSelected exact: \"${context.selected}\"\nContext after: \"${context.after.substring(0, 200)}\"\n\nResource: ${resource.name}\nEntity types: ${entityTypes.join(', ')}`;\n\n return await generateText(summaryPrompt, config, 500, 0.5);\n }\n}\n","/**\n * Graph Context\n *\n * Provides graph database operations for resources and annotations.\n * All methods require graph traversal - must use graph database.\n */\n\nimport { getGraphDatabase } from '@semiont/graph';\nimport { resourceIdToURI } from '@semiont/core';\nimport type {\n ResourceId,\n EnvironmentConfig,\n GraphConnection,\n GraphPath,\n} from '@semiont/core';\nimport type { components } from '@semiont/api-client';\n\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport class GraphContext {\n /**\n * Get all resources referencing this resource (backlinks)\n * Requires graph traversal - must use graph database\n */\n static async getBacklinks(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const graphDb = await getGraphDatabase(config);\n const resourceUri = resourceIdToURI(resourceId, config.services.backend!.publicURL);\n return await graphDb.getResourceReferencedBy(resourceUri);\n }\n\n /**\n * Find shortest path between two resources\n * Requires graph traversal - must use graph database\n */\n static async findPath(\n fromResourceId: ResourceId,\n toResourceId: ResourceId,\n config: EnvironmentConfig,\n maxDepth?: number\n ): Promise<GraphPath[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.findPath(fromResourceId, toResourceId, maxDepth);\n }\n\n /**\n * Get resource connections (graph edges)\n * Requires graph traversal - must use graph database\n */\n static async getResourceConnections(resourceId: ResourceId, config: EnvironmentConfig): Promise<GraphConnection[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.getResourceConnections(resourceId);\n }\n\n /**\n * Search resources by name (cross-resource query)\n * Requires full-text search - must use graph database\n */\n static async searchResources(query: string, config: EnvironmentConfig, limit?: number): Promise<ResourceDescriptor[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.searchResources(query, limit);\n }\n}\n","/**\n * Annotation Detection\n *\n * Orchestrates the full annotation detection pipeline:\n * 1. Fetch resource metadata and content\n * 2. Build AI prompts using MotivationPrompts\n * 3. Call AI inference\n * 4. Parse and validate results using MotivationParsers\n *\n * This is the high-level API for AI-powered annotation detection.\n * Workers and other consumers should use these methods instead of\n * implementing detection logic directly.\n */\n\nimport { ResourceContext } from './resource-context';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport {\n MotivationPrompts,\n MotivationParsers,\n generateText,\n type CommentMatch,\n type HighlightMatch,\n type AssessmentMatch,\n type TagMatch,\n} from '@semiont/inference';\nimport { getTagSchema, getSchemaCategory } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\nexport class AnnotationDetection {\n /**\n * Detect comments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param instructions - Optional user instructions for comment generation\n * @param tone - Optional tone guidance (e.g., \"academic\", \"conversational\")\n * @param density - Optional target number of comments per 2000 words\n * @returns Array of validated comment matches\n */\n static async detectComments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<CommentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildCommentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 3000, // maxTokens: Higher than highlights/assessments due to comment text\n 0.4 // temperature: Slightly higher to allow creative context\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseComments(response, content);\n }\n\n /**\n * Detect highlights in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param instructions - Optional user instructions for highlight selection\n * @param density - Optional target number of highlights per 2000 words\n * @returns Array of validated highlight matches\n */\n static async detectHighlights(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n instructions?: string,\n density?: number\n ): Promise<HighlightMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildHighlightPrompt(content, instructions, density);\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 2000, // maxTokens: Lower than comments/assessments (no body text)\n 0.3 // temperature: Low for consistent importance judgments\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseHighlights(response, content);\n }\n\n /**\n * Detect assessments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param instructions - Optional user instructions for assessment generation\n * @param tone - Optional tone guidance (e.g., \"critical\", \"supportive\")\n * @param density - Optional target number of assessments per 2000 words\n * @returns Array of validated assessment matches\n */\n static async detectAssessments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<AssessmentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildAssessmentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 3000, // maxTokens: Higher for assessment text\n 0.3 // temperature: Lower for analytical consistency\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseAssessments(response, content);\n }\n\n /**\n * Detect tags in a resource for a specific category\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param schemaId - The tag schema identifier (e.g., \"irac\", \"imrad\")\n * @param category - The specific category to detect\n * @returns Array of validated tag matches\n */\n static async detectTags(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n schemaId: string,\n category: string\n ): Promise<TagMatch[]> {\n // Validate schema and category\n const schema = getTagSchema(schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${schemaId}`);\n }\n\n const categoryInfo = getSchemaCategory(schemaId, category);\n if (!categoryInfo) {\n throw new Error(`Invalid category \"${category}\" for schema ${schemaId}`);\n }\n\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store (FULL content for structural analysis)\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt with schema and category information\n const prompt = MotivationPrompts.buildTagPrompt(\n content,\n category,\n schema.name,\n schema.description,\n schema.domain,\n categoryInfo.description,\n categoryInfo.examples\n );\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 4000, // maxTokens: Higher for full document analysis\n 0.2 // temperature: Lower for structural consistency\n );\n\n // 5. Parse response (without validation)\n const parsedTags = MotivationParsers.parseTags(response);\n\n // 6. Validate offsets and add category\n return MotivationParsers.validateTagOffsets(parsedTags, content, category);\n }\n\n /**\n * Load resource content from representation store\n * Helper method used by all detection methods\n *\n * @param resourceId - The resource ID to load\n * @param config - Environment configuration\n * @returns Resource content as string, or null if not available\n */\n private static async loadResourceContent(\n resourceId: ResourceId,\n config: EnvironmentConfig\n ): Promise<string | null> {\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) return null;\n\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return null;\n\n // Only process text content\n const baseMediaType = primaryRep.mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType !== 'text/plain' && baseMediaType !== 'text/markdown') {\n return null;\n }\n\n if (!primaryRep.checksum || !primaryRep.mediaType) return null;\n\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(contentBuffer, primaryRep.mediaType);\n }\n}\n","// @semiont/make-meaning - Making meaning from resources\n// Transforms raw resources into meaningful, interconnected knowledge\n\n// Context assembly exports\nexport { ResourceContext } from './resource-context';\nexport type { ListResourcesFilters } from './resource-context';\nexport { AnnotationContext } from './annotation-context';\nexport type { BuildContextOptions } from './annotation-context';\nexport { GraphContext } from './graph-context';\n\n// Detection exports\nexport { AnnotationDetection } from './annotation-detection';\n\n// Re-export match types from @semiont/inference for convenience\nexport type {\n CommentMatch,\n HighlightMatch,\n AssessmentMatch,\n TagMatch,\n} from '@semiont/inference';\n\n// Reasoning exports (future)\n// export { ResourceReasoning } from './resource-reasoning';\n\n// Placeholder for initial build\nexport const PACKAGE_NAME = '@semiont/make-meaning';\nexport const VERSION = '0.1.0';\n"],"mappings":";AAOA,SAAS,6BAA6B;AACtC,SAAS,qCAAqC;AAC9C,SAAS,0BAA0B,4BAA4B;AAWxD,IAAM,kBAAN,MAAsB;AAAA;AAAA;AAAA;AAAA,EAI3B,aAAa,oBAAoB,YAAwB,QAA+D;AACtH,UAAM,WAAW,OAAO,SAAS,WAAY;AAC7C,UAAM,cAAc,OAAO,WAAW;AAEtC,UAAM,cAAc,IAAI,sBAAsB,UAAU,WAAW;AAEnE,UAAM,OAAO,MAAM,YAAY,IAAI,UAAU;AAC7C,QAAI,CAAC,MAAM;AACT,aAAO;AAAA,IACT;AAEA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,cAAc,SAA2C,QAA0D;AAC9H,UAAM,WAAW,OAAO,SAAS,WAAY;AAC7C,UAAM,cAAc,OAAO,WAAW;AAEtC,UAAM,cAAc,IAAI,sBAAsB,UAAU,WAAW;AAEnE,UAAM,WAAW,MAAM,YAAY,OAAO;AAC1C,UAAM,YAAkC,CAAC;AAEzC,eAAW,QAAQ,UAAU;AAC3B,YAAM,MAAM,KAAK;AAGjB,UAAI,SAAS,aAAa,UAAa,IAAI,aAAa,QAAQ,UAAU;AACxE;AAAA,MACF;AAEA,UAAI,SAAS,QAAQ;AACnB,cAAM,cAAc,QAAQ,OAAO,YAAY;AAC/C,YAAI,CAAC,IAAI,KAAK,YAAY,EAAE,SAAS,WAAW,GAAG;AACjD;AAAA,QACF;AAAA,MACF;AAEA,gBAAU,KAAK,GAAG;AAAA,IACpB;AAGA,cAAU,KAAK,CAAC,GAAG,MAAM;AACvB,YAAM,QAAQ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GxB,UAAM,gBAAgB,WAAW,WAAW,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AACrE,QAAI,kBAAkB,gBAAgB,kBAAkB,iBAAiB;AACvE,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,WAAW,YAAY,CAAC,WAAW,UAAW,QAAO;AAE1D,UAAM,WAAW,OAAO,SAAS,WAAY;AAC7C,UAAM,cAAc,OAAO,WAAW;AACtC,UAAM,WAAW,IAAID,+BAA8B,EAAE,SAAS,GAAG,WAAW;AAC5E,UAAM,gBAAgB,MAAM,SAAS,SAAS,WAAW,UAAU,WAAW,SAAS;AACvF,WAAOE,sBAAqB,eAAe,WAAW,SAAS;AAAA,EACjE;AACF;;;ACvOO,IAAM,eAAe;AACrB,IAAM,UAAU;","names":["getPrimaryRepresentation","decodeRepresentation","FilesystemRepresentationStore","FilesystemViewStorage","FilesystemViewStorage","FilesystemRepresentationStore","targetResourceId","getPrimaryRepresentation","decodeRepresentation","FilesystemRepresentationStore","getPrimaryRepresentation","decodeRepresentation","generateText"]}
|
|
1
|
+
{"version":3,"sources":["../src/resource-context.ts","../src/annotation-context.ts","../src/graph-context.ts","../src/annotation-detection.ts","../src/jobs/workers/comment-detection-worker.ts","../src/jobs/workers/highlight-detection-worker.ts","../src/jobs/workers/assessment-detection-worker.ts","../src/jobs/workers/tag-detection-worker.ts","../src/jobs/workers/reference-detection-worker.ts","../src/jobs/workers/generation-worker.ts","../src/index.ts"],"sourcesContent":["/**\n * Resource Context\n *\n * Assembles resource context from view storage and content store\n * Does NOT touch the graph - graph queries go through GraphContext\n */\n\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport type { components } from '@semiont/api-client';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface ListResourcesFilters {\n search?: string;\n archived?: boolean;\n}\n\nexport class ResourceContext {\n /**\n * Get resource metadata from view storage\n */\n static async getResourceMetadata(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceDescriptor | null> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const view = await viewStorage.get(resourceId);\n if (!view) {\n return null;\n }\n\n return view.resource;\n }\n\n /**\n * List all resources by scanning view storage\n */\n static async listResources(filters: ListResourcesFilters | undefined, config: EnvironmentConfig): Promise<ResourceDescriptor[]> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const allViews = await viewStorage.getAll();\n const resources: ResourceDescriptor[] = [];\n\n for (const view of allViews) {\n const doc = view.resource;\n\n // Apply filters\n if (filters?.archived !== undefined && doc.archived !== filters.archived) {\n continue;\n }\n\n if (filters?.search) {\n const searchLower = filters.search.toLowerCase();\n if (!doc.name.toLowerCase().includes(searchLower)) {\n continue;\n }\n }\n\n resources.push(doc);\n }\n\n // Sort by creation date (newest first)\n resources.sort((a, b) => {\n const aTime = a.dateCreated ? new Date(a.dateCreated).getTime() : 0;\n const bTime = b.dateCreated ? new Date(b.dateCreated).getTime() : 0;\n return bTime - aTime;\n });\n\n return resources;\n }\n\n /**\n * Add content previews to resources (for search results)\n * Retrieves and decodes the first 200 characters of each resource's primary representation\n */\n static async addContentPreviews(\n resources: ResourceDescriptor[],\n config: EnvironmentConfig\n ): Promise<Array<ResourceDescriptor & { content: string }>> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n return await Promise.all(\n resources.map(async (doc) => {\n try {\n const primaryRep = getPrimaryRepresentation(doc);\n if (primaryRep?.checksum && primaryRep?.mediaType) {\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentPreview = decodeRepresentation(contentBuffer, primaryRep.mediaType).slice(0, 200);\n return { ...doc, content: contentPreview };\n }\n return { ...doc, content: '' };\n } catch {\n return { ...doc, content: '' };\n }\n })\n );\n }\n}\n","/**\n * Annotation Context\n *\n * Assembles annotation context from view storage and content store.\n * Provides methods for:\n * - Getting resource annotations\n * - Building LLM context for annotations\n * - Extracting annotation text context\n * - Generating AI summaries\n */\n\nimport { generateResourceSummary, generateText } from '@semiont/inference';\nimport {\n getBodySource,\n getTargetSource,\n getTargetSelector,\n getResourceEntityTypes,\n getTextPositionSelector,\n getPrimaryRepresentation,\n decodeRepresentation,\n} from '@semiont/api-client';\nimport type { components, AnnotationUri, GenerationContext } from '@semiont/api-client';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport type {\n EnvironmentConfig,\n ResourceId,\n ResourceAnnotations,\n AnnotationId,\n AnnotationCategory,\n} from '@semiont/core';\nimport { resourceId as createResourceId, uriToResourceId } from '@semiont/core';\nimport { getEntityTypes } from '@semiont/ontology';\nimport { ResourceContext } from './resource-context';\n\ntype AnnotationLLMContextResponse = components['schemas']['AnnotationLLMContextResponse'];\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype AnnotationContextResponse = components['schemas']['AnnotationContextResponse'];\ntype ContextualSummaryResponse = components['schemas']['ContextualSummaryResponse'];\n\nexport interface BuildContextOptions {\n includeSourceContext?: boolean;\n includeTargetContext?: boolean;\n contextWindow?: number;\n}\n\ninterface AnnotationTextContext {\n before: string;\n selected: string;\n after: string;\n}\n\nexport class AnnotationContext {\n /**\n * Build LLM context for an annotation\n *\n * @param annotationUri - Full annotation URI (e.g., http://localhost:4000/annotations/abc123)\n * @param resourceId - Source resource ID\n * @param config - Application configuration\n * @param options - Context building options\n * @returns Rich context for LLM processing\n * @throws Error if annotation or resource not found\n */\n static async buildLLMContext(\n annotationUri: AnnotationUri,\n resourceId: ResourceId,\n config: EnvironmentConfig,\n options: BuildContextOptions = {}\n ): Promise<AnnotationLLMContextResponse> {\n const {\n includeSourceContext = true,\n includeTargetContext = true,\n contextWindow = 1000\n } = options;\n\n // Validate contextWindow range\n if (contextWindow < 100 || contextWindow > 5000) {\n throw new Error('contextWindow must be between 100 and 5000');\n }\n\n console.log(`[AnnotationContext] buildLLMContext called with annotationUri=${annotationUri}, resourceId=${resourceId}`);\n\n const basePath = config.services.filesystem!.path;\n console.log(`[AnnotationContext] basePath=${basePath}`);\n\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get source resource view\n console.log(`[AnnotationContext] Getting view for resourceId=${resourceId}`);\n let sourceView;\n try {\n sourceView = await viewStorage.get(resourceId);\n console.log(`[AnnotationContext] Got view:`, !!sourceView);\n\n if (!sourceView) {\n throw new Error('Source resource not found');\n }\n } catch (error) {\n console.error(`[AnnotationContext] Error getting view:`, error);\n throw error;\n }\n\n console.log(`[AnnotationContext] Looking for annotation ${annotationUri} in resource ${resourceId}`);\n console.log(`[AnnotationContext] View has ${sourceView.annotations.annotations.length} annotations`);\n console.log(`[AnnotationContext] First 5 annotation IDs:`, sourceView.annotations.annotations.slice(0, 5).map((a: Annotation) => a.id));\n\n // Find the annotation in the view (annotations have full URIs as their id)\n const annotation = sourceView.annotations.annotations.find((a: Annotation) => a.id === annotationUri);\n console.log(`[AnnotationContext] Found annotation:`, !!annotation);\n\n if (!annotation) {\n throw new Error('Annotation not found in view');\n }\n\n const targetSource = getTargetSource(annotation.target);\n // Extract resource ID from the target source URI (format: http://host/resources/{id})\n const targetResourceId = targetSource.split('/').pop();\n console.log(`[AnnotationContext] Target source: ${targetSource}, Expected resource ID: ${resourceId}, Extracted ID: ${targetResourceId}`);\n\n if (targetResourceId !== resourceId) {\n throw new Error(`Annotation target resource ID (${targetResourceId}) does not match expected resource ID (${resourceId})`);\n }\n\n const sourceDoc = sourceView.resource;\n\n // Get target resource if annotation is a reference (has resolved body source)\n const bodySource = getBodySource(annotation.body);\n\n // Extract target document from body source URI if present\n let targetDoc = null;\n if (bodySource) {\n // Inline extraction: \"http://localhost:4000/resources/abc123\" → \"abc123\"\n const parts = (bodySource as string).split('/');\n const lastPart = parts[parts.length - 1];\n if (!lastPart) {\n throw new Error(`Invalid body source URI: ${bodySource}`);\n }\n const targetResourceId = createResourceId(lastPart);\n const targetView = await viewStorage.get(targetResourceId);\n targetDoc = targetView?.resource || null;\n }\n\n // Build source context if requested\n let sourceContext;\n if (includeSourceContext) {\n const primaryRep = getPrimaryRepresentation(sourceDoc);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Source content not found');\n }\n const sourceContent = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentStr = decodeRepresentation(sourceContent, primaryRep.mediaType);\n\n const targetSelectorRaw = getTargetSelector(annotation.target);\n\n // Handle array of selectors - take the first one\n const targetSelector = Array.isArray(targetSelectorRaw) ? targetSelectorRaw[0] : targetSelectorRaw;\n\n console.log(`[AnnotationContext] Target selector type:`, targetSelector?.type);\n\n if (!targetSelector) {\n console.warn(`[AnnotationContext] No target selector found`);\n } else if (targetSelector.type === 'TextPositionSelector') {\n // TypeScript now knows this is TextPositionSelector with required start/end\n const selector = targetSelector as TextPositionSelector;\n const start = selector.start;\n const end = selector.end;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = contentStr.slice(start, end);\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n console.log(`[AnnotationContext] Built source context using TextPositionSelector (${start}-${end})`);\n } else if (targetSelector.type === 'TextQuoteSelector') {\n // TypeScript now knows this is TextQuoteSelector with required exact\n const selector = targetSelector as TextQuoteSelector;\n const exact = selector.exact;\n const index = contentStr.indexOf(exact);\n\n if (index !== -1) {\n const start = index;\n const end = index + exact.length;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = exact;\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n console.log(`[AnnotationContext] Built source context using TextQuoteSelector (found at ${index})`);\n } else {\n console.warn(`[AnnotationContext] TextQuoteSelector exact text not found in content: \"${exact.substring(0, 50)}...\"`);\n }\n } else {\n console.warn(`[AnnotationContext] Unknown selector type: ${(targetSelector as any).type}`);\n }\n }\n\n // Build target context if requested and available\n let targetContext;\n if (includeTargetContext && targetDoc) {\n const targetRep = getPrimaryRepresentation(targetDoc);\n if (targetRep?.checksum && targetRep?.mediaType) {\n const targetContent = await repStore.retrieve(targetRep.checksum, targetRep.mediaType);\n const contentStr = decodeRepresentation(targetContent, targetRep.mediaType);\n\n targetContext = {\n content: contentStr.slice(0, contextWindow * 2),\n summary: await generateResourceSummary(targetDoc.name, contentStr, getResourceEntityTypes(targetDoc), config),\n };\n }\n }\n\n // TODO: Generate suggested resolution using AI\n const suggestedResolution = undefined;\n\n // Build GenerationContext structure\n const generationContext: GenerationContext | undefined = sourceContext ? {\n sourceContext: {\n before: sourceContext.before || '',\n selected: sourceContext.selected,\n after: sourceContext.after || '',\n },\n metadata: {\n resourceType: 'document',\n language: sourceDoc.language as string | undefined,\n entityTypes: getEntityTypes(annotation),\n },\n } : undefined;\n\n const response: AnnotationLLMContextResponse = {\n annotation,\n sourceResource: sourceDoc,\n targetResource: targetDoc,\n ...(generationContext ? { context: generationContext } : {}),\n ...(sourceContext ? { sourceContext } : {}), // Keep for backward compatibility\n ...(targetContext ? { targetContext } : {}),\n ...(suggestedResolution ? { suggestedResolution } : {}),\n };\n\n return response;\n }\n\n /**\n * Get resource annotations from view storage (fast path)\n * Throws if view missing\n */\n static async getResourceAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceAnnotations> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(resourceId);\n\n if (!view) {\n throw new Error(`Resource ${resourceId} not found in view storage`);\n }\n\n return view.annotations;\n }\n\n /**\n * Get all annotations\n * @returns Array of all annotation objects\n */\n static async getAllAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n\n // Enrich resolved references with document names\n // NOTE: Future optimization - make this optional via query param if performance becomes an issue\n return await this.enrichResolvedReferences(annotations.annotations, config);\n }\n\n /**\n * Enrich reference annotations with resolved document names\n * Adds _resolvedDocumentName property to annotations that link to documents\n * @private\n */\n private static async enrichResolvedReferences(annotations: Annotation[], config: EnvironmentConfig): Promise<Annotation[]> {\n if (!config.services?.filesystem?.path) {\n return annotations;\n }\n\n // Extract unique resolved document URIs from reference annotations\n const resolvedUris = new Set<string>();\n for (const ann of annotations) {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.purpose === 'linking' && item.source) {\n resolvedUris.add(item.source);\n }\n }\n }\n }\n\n if (resolvedUris.size === 0) {\n return annotations;\n }\n\n // Batch fetch all resolved documents in parallel\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const metadataPromises = Array.from(resolvedUris).map(async (uri) => {\n const docId = uri.split('/resources/')[1];\n if (!docId) return null;\n\n try {\n const view = await viewStorage.get(docId as ResourceId);\n if (view?.resource?.name) {\n return {\n uri,\n metadata: {\n name: view.resource.name,\n mediaType: view.resource.mediaType as string | undefined\n }\n };\n }\n } catch (e) {\n // Document might not exist, skip\n }\n return null;\n });\n\n const results = await Promise.all(metadataPromises);\n const uriToMetadata = new Map<string, { name: string; mediaType?: string }>();\n for (const result of results) {\n if (result) {\n uriToMetadata.set(result.uri, result.metadata);\n }\n }\n\n // Add _resolvedDocumentName and _resolvedDocumentMediaType to annotations\n return annotations.map(ann => {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.purpose === 'linking' && item.source) {\n const metadata = uriToMetadata.get(item.source);\n if (metadata) {\n return {\n ...ann,\n _resolvedDocumentName: metadata.name,\n _resolvedDocumentMediaType: metadata.mediaType\n } as Annotation;\n }\n }\n }\n }\n return ann;\n });\n }\n\n /**\n * Get resource stats (version info)\n * @returns Version and timestamp info for the annotations\n */\n static async getResourceStats(resourceId: ResourceId, config: EnvironmentConfig): Promise<{\n resourceId: ResourceId;\n version: number;\n updatedAt: string;\n }> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n return {\n resourceId: annotations.resourceId,\n version: annotations.version,\n updatedAt: annotations.updatedAt,\n };\n }\n\n /**\n * Check if resource exists in view storage\n */\n static async resourceExists(resourceId: ResourceId, config: EnvironmentConfig): Promise<boolean> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n return await viewStorage.exists(resourceId);\n }\n\n /**\n * Get a single annotation by ID\n * O(1) lookup using resource ID to access view storage\n */\n static async getAnnotation(annotationId: AnnotationId, resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation | null> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n // Extract short ID from annotation's full URI for comparison\n return annotations.annotations.find((a: Annotation) => {\n const shortId = a.id.split('/').pop();\n return shortId === annotationId;\n }) || null;\n }\n\n /**\n * List annotations with optional filtering\n * @param filters - Optional filters like resourceId and type\n * @throws Error if resourceId not provided (cross-resource queries not supported in view storage)\n */\n static async listAnnotations(filters: { resourceId?: ResourceId; type?: AnnotationCategory } | undefined, config: EnvironmentConfig): Promise<Annotation[]> {\n if (!filters?.resourceId) {\n throw new Error('resourceId is required for annotation listing - cross-resource queries not supported in view storage');\n }\n\n // Use view storage directly\n return await this.getAllAnnotations(filters.resourceId, config);\n }\n\n /**\n * Get annotation context (selected text with surrounding context)\n */\n static async getAnnotationContext(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n contextBefore: number,\n contextAfter: number,\n config: EnvironmentConfig\n ): Promise<AnnotationContextResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource metadata from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract context based on annotation position\n const context = this.extractAnnotationContext(annotation, contentStr, contextBefore, contextAfter);\n\n return {\n annotation: annotation,\n context,\n resource: {\n '@context': resource['@context'],\n '@id': resource['@id'],\n name: resource.name,\n entityTypes: resource.entityTypes,\n representations: resource.representations,\n archived: resource.archived,\n creationMethod: resource.creationMethod,\n wasAttributedTo: resource.wasAttributedTo,\n dateCreated: resource.dateCreated,\n },\n };\n }\n\n /**\n * Generate AI summary of annotation in context\n */\n static async generateAnnotationSummary(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n config: EnvironmentConfig\n ): Promise<ContextualSummaryResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract annotation text with context (fixed 500 chars for summary)\n const contextSize = 500;\n const context = this.extractAnnotationContext(annotation, contentStr, contextSize, contextSize);\n\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes(annotation);\n\n // Generate summary using LLM\n const summary = await this.generateSummary(resource, context, annotationEntityTypes, config);\n\n return {\n summary,\n relevantFields: {\n resourceId: resource.id,\n resourceName: resource.name,\n entityTypes: annotationEntityTypes,\n },\n context: {\n before: context.before.substring(Math.max(0, context.before.length - 200)), // Last 200 chars\n selected: context.selected,\n after: context.after.substring(0, 200), // First 200 chars\n },\n };\n }\n\n /**\n * Get resource content as string\n */\n private static async getResourceContent(\n resource: ResourceDescriptor,\n repStore: FilesystemRepresentationStore\n ): Promise<string> {\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Resource content not found');\n }\n const content = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(content, primaryRep.mediaType);\n }\n\n /**\n * Extract annotation context from resource content\n */\n private static extractAnnotationContext(\n annotation: Annotation,\n contentStr: string,\n contextBefore: number,\n contextAfter: number\n ): AnnotationTextContext {\n const targetSelector = getTargetSelector(annotation.target);\n const posSelector = targetSelector ? getTextPositionSelector(targetSelector) : null;\n if (!posSelector) {\n throw new Error('TextPositionSelector required for context');\n }\n\n const selStart = posSelector.start;\n const selEnd = posSelector.end;\n const start = Math.max(0, selStart - contextBefore);\n const end = Math.min(contentStr.length, selEnd + contextAfter);\n\n return {\n before: contentStr.substring(start, selStart),\n selected: contentStr.substring(selStart, selEnd),\n after: contentStr.substring(selEnd, end),\n };\n }\n\n /**\n * Generate LLM summary of annotation in context\n */\n private static async generateSummary(\n resource: ResourceDescriptor,\n context: AnnotationTextContext,\n entityTypes: string[],\n config: EnvironmentConfig\n ): Promise<string> {\n const summaryPrompt = `Summarize this text in context:\n\nContext before: \"${context.before.substring(Math.max(0, context.before.length - 200))}\"\nSelected exact: \"${context.selected}\"\nContext after: \"${context.after.substring(0, 200)}\"\n\nResource: ${resource.name}\nEntity types: ${entityTypes.join(', ')}`;\n\n return await generateText(summaryPrompt, config, 500, 0.5);\n }\n}\n","/**\n * Graph Context\n *\n * Provides graph database operations for resources and annotations.\n * All methods require graph traversal - must use graph database.\n */\n\nimport { getGraphDatabase } from '@semiont/graph';\nimport { resourceIdToURI } from '@semiont/core';\nimport type {\n ResourceId,\n EnvironmentConfig,\n GraphConnection,\n GraphPath,\n} from '@semiont/core';\nimport type { components } from '@semiont/api-client';\n\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport class GraphContext {\n /**\n * Get all resources referencing this resource (backlinks)\n * Requires graph traversal - must use graph database\n */\n static async getBacklinks(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const graphDb = await getGraphDatabase(config);\n const resourceUri = resourceIdToURI(resourceId, config.services.backend!.publicURL);\n return await graphDb.getResourceReferencedBy(resourceUri);\n }\n\n /**\n * Find shortest path between two resources\n * Requires graph traversal - must use graph database\n */\n static async findPath(\n fromResourceId: ResourceId,\n toResourceId: ResourceId,\n config: EnvironmentConfig,\n maxDepth?: number\n ): Promise<GraphPath[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.findPath(fromResourceId, toResourceId, maxDepth);\n }\n\n /**\n * Get resource connections (graph edges)\n * Requires graph traversal - must use graph database\n */\n static async getResourceConnections(resourceId: ResourceId, config: EnvironmentConfig): Promise<GraphConnection[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.getResourceConnections(resourceId);\n }\n\n /**\n * Search resources by name (cross-resource query)\n * Requires full-text search - must use graph database\n */\n static async searchResources(query: string, config: EnvironmentConfig, limit?: number): Promise<ResourceDescriptor[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.searchResources(query, limit);\n }\n}\n","/**\n * Annotation Detection\n *\n * Orchestrates the full annotation detection pipeline:\n * 1. Fetch resource metadata and content\n * 2. Build AI prompts using MotivationPrompts\n * 3. Call AI inference\n * 4. Parse and validate results using MotivationParsers\n *\n * This is the high-level API for AI-powered annotation detection.\n * Workers and other consumers should use these methods instead of\n * implementing detection logic directly.\n */\n\nimport { ResourceContext } from './resource-context';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport {\n MotivationPrompts,\n MotivationParsers,\n generateText,\n type CommentMatch,\n type HighlightMatch,\n type AssessmentMatch,\n type TagMatch,\n} from '@semiont/inference';\nimport { getTagSchema, getSchemaCategory } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\nexport class AnnotationDetection {\n /**\n * Detect comments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param instructions - Optional user instructions for comment generation\n * @param tone - Optional tone guidance (e.g., \"academic\", \"conversational\")\n * @param density - Optional target number of comments per 2000 words\n * @returns Array of validated comment matches\n */\n static async detectComments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<CommentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildCommentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 3000, // maxTokens: Higher than highlights/assessments due to comment text\n 0.4 // temperature: Slightly higher to allow creative context\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseComments(response, content);\n }\n\n /**\n * Detect highlights in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param instructions - Optional user instructions for highlight selection\n * @param density - Optional target number of highlights per 2000 words\n * @returns Array of validated highlight matches\n */\n static async detectHighlights(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n instructions?: string,\n density?: number\n ): Promise<HighlightMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildHighlightPrompt(content, instructions, density);\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 2000, // maxTokens: Lower than comments/assessments (no body text)\n 0.3 // temperature: Low for consistent importance judgments\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseHighlights(response, content);\n }\n\n /**\n * Detect assessments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param instructions - Optional user instructions for assessment generation\n * @param tone - Optional tone guidance (e.g., \"critical\", \"supportive\")\n * @param density - Optional target number of assessments per 2000 words\n * @returns Array of validated assessment matches\n */\n static async detectAssessments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<AssessmentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildAssessmentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 3000, // maxTokens: Higher for assessment text\n 0.3 // temperature: Lower for analytical consistency\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseAssessments(response, content);\n }\n\n /**\n * Detect tags in a resource for a specific category\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param schemaId - The tag schema identifier (e.g., \"irac\", \"imrad\")\n * @param category - The specific category to detect\n * @returns Array of validated tag matches\n */\n static async detectTags(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n schemaId: string,\n category: string\n ): Promise<TagMatch[]> {\n // Validate schema and category\n const schema = getTagSchema(schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${schemaId}`);\n }\n\n const categoryInfo = getSchemaCategory(schemaId, category);\n if (!categoryInfo) {\n throw new Error(`Invalid category \"${category}\" for schema ${schemaId}`);\n }\n\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store (FULL content for structural analysis)\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt with schema and category information\n const prompt = MotivationPrompts.buildTagPrompt(\n content,\n category,\n schema.name,\n schema.description,\n schema.domain,\n categoryInfo.description,\n categoryInfo.examples\n );\n\n // 4. Call AI inference\n const response = await generateText(\n prompt,\n config,\n 4000, // maxTokens: Higher for full document analysis\n 0.2 // temperature: Lower for structural consistency\n );\n\n // 5. Parse response (without validation)\n const parsedTags = MotivationParsers.parseTags(response);\n\n // 6. Validate offsets and add category\n return MotivationParsers.validateTagOffsets(parsedTags, content, category);\n }\n\n /**\n * Load resource content from representation store\n * Helper method used by all detection methods\n *\n * @param resourceId - The resource ID to load\n * @param config - Environment configuration\n * @returns Resource content as string, or null if not available\n */\n private static async loadResourceContent(\n resourceId: ResourceId,\n config: EnvironmentConfig\n ): Promise<string | null> {\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) return null;\n\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return null;\n\n // Only process text content\n const baseMediaType = primaryRep.mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType !== 'text/plain' && baseMediaType !== 'text/markdown') {\n return null;\n }\n\n if (!primaryRep.checksum || !primaryRep.mediaType) return null;\n\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(contentBuffer, primaryRep.mediaType);\n }\n}\n","/**\n * Comment Detection Worker\n *\n * Processes comment-detection jobs: runs AI inference to identify passages\n * that would benefit from explanatory comments and creates comment annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, CommentDetectionJob, JobQueue, RunningJob, CommentDetectionParams, CommentDetectionProgress } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '../..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { CommentMatch } from '@semiont/inference';\n\nexport class CommentDetectionWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore\n ) {\n super(jobQueue);\n }\n\n protected getWorkerName(): string {\n return 'CommentDetectionWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'comment-detection';\n }\n\n protected async executeJob(job: AnyJob): Promise<void> {\n if (job.metadata.type !== 'comment-detection') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n await this.processCommentDetectionJob(job as RunningJob<CommentDetectionParams, CommentDetectionProgress>);\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'comment-detection') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const cdJob = job as RunningJob<CommentDetectionParams, CommentDetectionProgress>;\n\n const baseEvent = {\n resourceId: cdJob.params.resourceId,\n userId: cdJob.metadata.userId,\n version: 1,\n };\n\n // Determine if this is completion (100% and has result)\n const isComplete = cdJob.progress.percentage === 100;\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n },\n });\n } else if (isComplete) {\n // Final update - emit job.completed\n await this.eventStore.appendEvent({\n type: 'job.completed',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n // Note: result would come from job.result, but that's handled by base class\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n progress: cdJob.progress,\n },\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'comment-detection') {\n const cdJob = job as CommentDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: cdJob.params.resourceId,\n userId: cdJob.metadata.userId,\n version: 1,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n error: 'Comment detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processCommentDetectionJob(job: RunningJob<CommentDetectionParams, CommentDetectionProgress>): Promise<void> {\n console.log(`[CommentDetectionWorker] Processing comment detection for resource ${job.params.resourceId} (job: ${job.metadata.id})`);\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<CommentDetectionParams, CommentDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text and generating comments...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect passages needing comments\n const comments = await AnnotationDetection.detectComments(\n job.params.resourceId,\n this.config,\n job.params.instructions,\n job.params.tone,\n job.params.density\n );\n\n console.log(`[CommentDetectionWorker] Found ${comments.length} comments to create`);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${comments.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each comment\n let created = 0;\n for (const comment of comments) {\n try {\n await this.createCommentAnnotation(job.params.resourceId, job.metadata.userId, comment);\n created++;\n } catch (error) {\n console.error(`[CommentDetectionWorker] Failed to create comment:`, error);\n }\n }\n\n // Note: JobWorker base class will create the CompleteJob with result\n // We don't set job.result here - that's handled by the base class\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} comments`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n console.log(`[CommentDetectionWorker] ✅ Created ${created}/${comments.length} comments`);\n }\n\n private async createCommentAnnotation(\n resourceId: ResourceId,\n userId_: string,\n comment: CommentMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n const annotationId = generateAnnotationId(backendUrl);\n\n // Create W3C-compliant annotation with motivation: \"commenting\"\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n type: 'Annotation' as const,\n id: annotationId,\n motivation: 'commenting' as const,\n target: {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: comment.start,\n end: comment.end\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: comment.exact,\n prefix: comment.prefix || '',\n suffix: comment.suffix || ''\n }\n ]\n },\n body: [\n {\n type: 'TextualBody' as const,\n value: comment.comment,\n purpose: 'commenting' as const,\n format: 'text/plain',\n language: 'en'\n }\n ]\n };\n\n // Append annotation.added event to Event Store\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(userId_),\n version: 1,\n payload: {\n annotation\n }\n });\n\n console.log(`[CommentDetectionWorker] Created comment annotation ${annotationId} for \"${comment.exact.substring(0, 50)}...\"`);\n }\n}\n","/**\n * Highlight Detection Worker\n *\n * Processes highlight-detection jobs: runs AI inference to find passages\n * that should be highlighted and creates highlight annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, HighlightDetectionJob, JobQueue, RunningJob, HighlightDetectionParams, HighlightDetectionProgress } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '../..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { HighlightMatch } from '@semiont/inference';\n\nexport class HighlightDetectionWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore\n ) {\n super(jobQueue);\n }\n\n protected getWorkerName(): string {\n return 'HighlightDetectionWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'highlight-detection';\n }\n\n protected async executeJob(job: AnyJob): Promise<void> {\n if (job.metadata.type !== 'highlight-detection') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n await this.processHighlightDetectionJob(job as RunningJob<HighlightDetectionParams, HighlightDetectionProgress>);\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'highlight-detection') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const hlJob = job as RunningJob<HighlightDetectionParams, HighlightDetectionProgress>;\n\n const baseEvent = {\n resourceId: hlJob.params.resourceId,\n userId: hlJob.metadata.userId,\n version: 1,\n };\n\n // Determine if this is completion (100% and has result)\n const isComplete = hlJob.progress.percentage === 100;\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n },\n });\n } else if (isComplete) {\n // Final update - emit job.completed\n await this.eventStore.appendEvent({\n type: 'job.completed',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n // Note: result would come from job.result, but that's handled by base class\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n progress: hlJob.progress,\n },\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'highlight-detection') {\n const hlJob = job as HighlightDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: hlJob.params.resourceId,\n userId: hlJob.metadata.userId,\n version: 1,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n error: 'Highlight detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processHighlightDetectionJob(job: RunningJob<HighlightDetectionParams, HighlightDetectionProgress>): Promise<void> {\n console.log(`[HighlightDetectionWorker] Processing highlight detection for resource ${job.params.resourceId} (job: ${job.metadata.id})`);\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<HighlightDetectionParams, HighlightDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect highlights\n const highlights = await AnnotationDetection.detectHighlights(\n job.params.resourceId,\n this.config,\n job.params.instructions,\n job.params.density\n );\n\n console.log(`[HighlightDetectionWorker] Found ${highlights.length} highlights to create`);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${highlights.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each highlight\n let created = 0;\n for (const highlight of highlights) {\n try {\n await this.createHighlightAnnotation(job.params.resourceId, job.metadata.userId, highlight);\n created++;\n } catch (error) {\n console.error(`[HighlightDetectionWorker] Failed to create highlight:`, error);\n }\n }\n\n // Note: JobWorker base class will create the CompleteJob with result\n // We don't set job.result here - that's handled by the base class\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} highlights`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n console.log(`[HighlightDetectionWorker] ✅ Created ${created}/${highlights.length} highlights`);\n }\n\n private async createHighlightAnnotation(\n resourceId: ResourceId,\n creatorUserId: string,\n highlight: HighlightMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) throw new Error('Backend publicURL not configured');\n\n const annotationId = generateAnnotationId(backendUrl);\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n\n // Create W3C annotation with motivation: highlighting\n // Use both TextPositionSelector and TextQuoteSelector (with prefix/suffix for fuzzy anchoring)\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationId,\n 'motivation': 'highlighting' as const,\n 'creator': userId(creatorUserId),\n 'created': new Date().toISOString(),\n 'target': {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: highlight.start,\n end: highlight.end,\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: highlight.exact,\n ...(highlight.prefix && { prefix: highlight.prefix }),\n ...(highlight.suffix && { suffix: highlight.suffix }),\n },\n ]\n },\n 'body': [] // Empty body for highlights\n };\n\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(creatorUserId),\n version: 1,\n payload: { annotation }\n });\n }\n}\n","/**\n * Assessment Detection Worker\n *\n * Processes assessment-detection jobs: runs AI inference to assess/evaluate\n * passages in the text and creates assessment annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, AssessmentDetectionJob, JobQueue, RunningJob, AssessmentDetectionParams, AssessmentDetectionProgress } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '../..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { AssessmentMatch } from '@semiont/inference';\n\nexport class AssessmentDetectionWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore\n ) {\n super(jobQueue);\n }\n\n protected getWorkerName(): string {\n return 'AssessmentDetectionWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'assessment-detection';\n }\n\n protected async executeJob(job: AnyJob): Promise<void> {\n if (job.metadata.type !== 'assessment-detection') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n await this.processAssessmentDetectionJob(job as RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>);\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'assessment-detection') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const assJob = job as RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>;\n\n const baseEvent = {\n resourceId: assJob.params.resourceId,\n userId: assJob.metadata.userId,\n version: 1,\n };\n\n // Determine if this is completion (100% and has result)\n const isComplete = assJob.progress.percentage === 100;\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n },\n });\n } else if (isComplete) {\n // Final update - emit job.completed\n await this.eventStore.appendEvent({\n type: 'job.completed',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n // Note: result would come from job.result, but that's handled by base class\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n progress: assJob.progress,\n },\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'assessment-detection') {\n const aJob = job as AssessmentDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: aJob.params.resourceId,\n userId: aJob.metadata.userId,\n version: 1,\n payload: {\n jobId: aJob.metadata.id,\n jobType: aJob.metadata.type,\n error: 'Assessment detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processAssessmentDetectionJob(job: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>): Promise<void> {\n console.log(`[AssessmentDetectionWorker] Processing assessment detection for resource ${job.params.resourceId} (job: ${job.metadata.id})`);\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect assessments\n const assessments = await AnnotationDetection.detectAssessments(\n job.params.resourceId,\n this.config,\n job.params.instructions,\n job.params.tone,\n job.params.density\n );\n\n console.log(`[AssessmentDetectionWorker] Found ${assessments.length} assessments to create`);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${assessments.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each assessment\n let created = 0;\n for (const assessment of assessments) {\n try {\n await this.createAssessmentAnnotation(job.params.resourceId, job.metadata.userId, assessment);\n created++;\n } catch (error) {\n console.error(`[AssessmentDetectionWorker] Failed to create assessment:`, error);\n }\n }\n\n // Note: JobWorker base class will create the CompleteJob with result\n // We don't set job.result here - that's handled by the base class\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} assessments`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n console.log(`[AssessmentDetectionWorker] ✅ Created ${created}/${assessments.length} assessments`);\n }\n\n private async createAssessmentAnnotation(\n resourceId: ResourceId,\n creatorUserId: string,\n assessment: AssessmentMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) throw new Error('Backend publicURL not configured');\n\n const annotationId = generateAnnotationId(backendUrl);\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n\n // Create W3C annotation with motivation: assessing\n // Use both TextPositionSelector and TextQuoteSelector (with prefix/suffix for fuzzy anchoring)\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationId,\n 'motivation': 'assessing' as const,\n 'creator': userId(creatorUserId),\n 'created': new Date().toISOString(),\n 'target': {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: assessment.start,\n end: assessment.end,\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: assessment.exact,\n ...(assessment.prefix && { prefix: assessment.prefix }),\n ...(assessment.suffix && { suffix: assessment.suffix }),\n },\n ]\n },\n 'body': {\n type: 'TextualBody' as const,\n value: assessment.assessment,\n format: 'text/plain'\n }\n };\n\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(creatorUserId),\n version: 1,\n payload: { annotation }\n });\n }\n}\n","/**\n * Tag Detection Worker\n *\n * Processes tag-detection jobs: runs AI inference to identify passages\n * serving specific structural roles (IRAC, IMRAD, Toulmin, etc.) and\n * creates tag annotations with dual-body structure.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, TagDetectionJob, JobQueue, RunningJob, TagDetectionParams, TagDetectionProgress } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '../..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI } from '@semiont/core';\nimport { getTagSchema } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { TagMatch } from '@semiont/inference';\n\nexport class TagDetectionWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore\n ) {\n super(jobQueue);\n }\n\n protected getWorkerName(): string {\n return 'TagDetectionWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'tag-detection';\n }\n\n protected async executeJob(job: AnyJob): Promise<void> {\n if (job.metadata.type !== 'tag-detection') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n await this.processTagDetectionJob(job as RunningJob<TagDetectionParams, TagDetectionProgress>);\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'tag-detection') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const tdJob = job as RunningJob<TagDetectionParams, TagDetectionProgress>;\n\n const baseEvent = {\n resourceId: tdJob.params.resourceId,\n userId: tdJob.metadata.userId,\n version: 1,\n };\n\n // Determine if this is completion (100% and has result)\n const isComplete = tdJob.progress.percentage === 100;\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n },\n });\n } else if (isComplete) {\n // Final update - emit job.completed\n await this.eventStore.appendEvent({\n type: 'job.completed',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n // Note: result would come from job.result, but that's handled by base class\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n progress: tdJob.progress,\n },\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'tag-detection') {\n const tdJob = job as TagDetectionJob;\n\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: tdJob.params.resourceId,\n userId: tdJob.metadata.userId,\n version: 1,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n error: 'Tag detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processTagDetectionJob(job: RunningJob<TagDetectionParams, TagDetectionProgress>): Promise<void> {\n console.log(`[TagDetectionWorker] Processing tag detection for resource ${job.params.resourceId} (job: ${job.metadata.id})`);\n\n // Validate schema\n const schema = getTagSchema(job.params.schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${job.params.schemaId}`);\n }\n\n // Validate categories\n for (const category of job.params.categories) {\n if (!schema.tags.some(t => t.name === category)) {\n throw new Error(`Invalid category \"${category}\" for schema ${job.params.schemaId}`);\n }\n }\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started\n let updatedJob: RunningJob<TagDetectionParams, TagDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n processedCategories: 0,\n totalCategories: job.params.categories.length,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Process each category separately\n const allTags: TagMatch[] = [];\n const byCategory: Record<string, number> = {};\n\n for (let i = 0; i < job.params.categories.length; i++) {\n const category = job.params.categories[i]!; // Safe: i < length check guarantees element exists\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 10 + Math.floor((i / job.params.categories.length) * 50),\n currentCategory: category,\n processedCategories: i + 1,\n totalCategories: job.params.categories.length,\n message: `Analyzing ${category}...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Detect tags for this category\n const tags = await AnnotationDetection.detectTags(\n job.params.resourceId,\n this.config,\n job.params.schemaId,\n category\n );\n console.log(`[TagDetectionWorker] Found ${tags.length} tags for category \"${category}\"`);\n\n allTags.push(...tags);\n byCategory[category] = tags.length;\n }\n\n // Create annotations\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n processedCategories: job.params.categories.length,\n totalCategories: job.params.categories.length,\n message: `Creating ${allTags.length} tag annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n let created = 0;\n for (const tag of allTags) {\n try {\n await this.createTagAnnotation(job.params.resourceId, job.metadata.userId, job.params.schemaId, tag);\n created++;\n } catch (error) {\n console.error(`[TagDetectionWorker] Failed to create tag:`, error);\n }\n }\n\n // Note: JobWorker base class will create the CompleteJob with result\n // We don't set job.result here - that's handled by the base class\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n processedCategories: job.params.categories.length,\n totalCategories: job.params.categories.length,\n message: `Complete! Created ${created} tags`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n console.log(`[TagDetectionWorker] ✅ Created ${created}/${allTags.length} tags across ${job.params.categories.length} categories`);\n }\n\n private async createTagAnnotation(\n resourceId: ResourceId,\n userId_: string,\n schemaId: string,\n tag: TagMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n const annotationId = generateAnnotationId(backendUrl);\n\n // Create W3C-compliant annotation with dual-body structure:\n // 1. purpose: \"tagging\" with category value\n // 2. purpose: \"classifying\" with schema ID\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n type: 'Annotation' as const,\n id: annotationId,\n motivation: 'tagging' as const,\n target: {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: tag.start,\n end: tag.end\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: tag.exact,\n prefix: tag.prefix || '',\n suffix: tag.suffix || ''\n }\n ]\n },\n body: [\n {\n type: 'TextualBody' as const,\n value: tag.category,\n purpose: 'tagging' as const,\n format: 'text/plain',\n language: 'en'\n },\n {\n type: 'TextualBody' as const,\n value: schemaId,\n purpose: 'classifying' as const,\n format: 'text/plain'\n }\n ]\n };\n\n // Append annotation.added event to Event Store\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(userId_),\n version: 1,\n payload: {\n annotation\n }\n });\n\n console.log(`[TagDetectionWorker] Created tag annotation ${annotationId} for \"${tag.category}\": \"${tag.exact.substring(0, 50)}...\"`);\n }\n}\n","/**\n * Reference Detection Worker\n *\n * Processes detection jobs: runs AI inference to find entities in resources\n * and emits reference.created events for each detected entity.\n *\n * This worker is INDEPENDENT of HTTP clients - it just processes jobs and emits events.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, DetectionJob, JobQueue, RunningJob, DetectionParams, DetectionProgress } from '@semiont/jobs';\nimport { ResourceContext } from '../..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI } from '@semiont/core';\nimport type { EnvironmentConfig } from '@semiont/core';\nimport {\n type components,\n getPrimaryRepresentation,\n decodeRepresentation,\n validateAndCorrectOffsets,\n} from '@semiont/api-client';\nimport { extractEntities } from '@semiont/inference';\nimport { FilesystemRepresentationStore } from '@semiont/content';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface DetectedAnnotation {\n annotation: {\n selector: {\n start: number;\n end: number;\n exact: string;\n prefix?: string;\n suffix?: string;\n };\n entityTypes: string[];\n };\n}\n\nexport class ReferenceDetectionWorker extends JobWorker {\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore\n ) {\n super(jobQueue);\n }\n\n protected getWorkerName(): string {\n return 'ReferenceDetectionWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'detection';\n }\n\n protected async executeJob(job: AnyJob): Promise<void> {\n if (job.metadata.type !== 'detection') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n await this.processDetectionJob(job as RunningJob<DetectionParams, DetectionProgress>);\n }\n\n /**\n * Detect entity references in resource using AI\n * Self-contained implementation for reference detection\n *\n * Public for testing charset handling - see entity-detection-charset.test.ts\n */\n public async detectReferences(\n resource: ResourceDescriptor,\n entityTypes: string[],\n includeDescriptiveReferences: boolean = false\n ): Promise<DetectedAnnotation[]> {\n console.log(`Detecting entities of types: ${entityTypes.join(', ')}${includeDescriptiveReferences ? ' (including descriptive references)' : ''}`);\n\n const detectedAnnotations: DetectedAnnotation[] = [];\n\n // Get primary representation\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return detectedAnnotations;\n\n // Only process text content (check base media type, ignoring charset parameters)\n const mediaType = primaryRep.mediaType;\n const baseMediaType = mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType === 'text/plain' || baseMediaType === 'text/markdown') {\n // Load content from representation store using content-addressed lookup\n if (!primaryRep.checksum || !primaryRep.mediaType) return detectedAnnotations;\n\n const basePath = this.config.services.filesystem!.path;\n const projectRoot = this.config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const content = decodeRepresentation(contentBuffer, primaryRep.mediaType);\n\n // Use AI to extract entities (with optional anaphoric/cataphoric references)\n const extractedEntities = await extractEntities(content, entityTypes, this.config, includeDescriptiveReferences);\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n for (const entity of extractedEntities) {\n try {\n const validated = validateAndCorrectOffsets(\n content,\n entity.startOffset,\n entity.endOffset,\n entity.exact\n );\n\n const annotation: DetectedAnnotation = {\n annotation: {\n selector: {\n start: validated.start,\n end: validated.end,\n exact: validated.exact,\n prefix: validated.prefix,\n suffix: validated.suffix,\n },\n entityTypes: [entity.entityType],\n },\n };\n detectedAnnotations.push(annotation);\n } catch (error) {\n console.warn(`[ReferenceDetectionWorker] Skipping invalid entity \"${entity.exact}\":`, error);\n // Skip this entity - AI hallucinated text that doesn't exist\n }\n }\n }\n\n return detectedAnnotations;\n }\n\n private async processDetectionJob(job: RunningJob<DetectionParams, DetectionProgress>): Promise<void> {\n console.log(`[ReferenceDetectionWorker] Processing detection for resource ${job.params.resourceId} (job: ${job.metadata.id})`);\n console.log(`[ReferenceDetectionWorker] 🔍 Entity types: ${job.params.entityTypes.join(', ')}`);\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n let totalFound = 0;\n let totalEmitted = 0;\n let totalErrors = 0;\n\n // Create updated job with initial progress\n let updatedJob: RunningJob<DetectionParams, DetectionProgress> = {\n ...job,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: 0,\n entitiesFound: 0,\n entitiesEmitted: 0\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Process each entity type\n for (let i = 0; i < job.params.entityTypes.length; i++) {\n const entityType = job.params.entityTypes[i];\n\n if (!entityType) continue;\n\n console.log(`[ReferenceDetectionWorker] 🤖 [${i + 1}/${job.params.entityTypes.length}] Detecting ${entityType}...`);\n\n // Detect entities using AI (loads content from filesystem internally)\n const detectedAnnotations = await this.detectReferences(resource, [entityType], job.params.includeDescriptiveReferences);\n\n totalFound += detectedAnnotations.length;\n console.log(`[ReferenceDetectionWorker] ✅ Found ${detectedAnnotations.length} ${entityType} entities`);\n\n // Emit events for each detected entity\n // This happens INDEPENDENT of any HTTP client!\n for (let idx = 0; idx < detectedAnnotations.length; idx++) {\n const detected = detectedAnnotations[idx];\n\n if (!detected) {\n console.warn(`[ReferenceDetectionWorker] Skipping undefined entity at index ${idx}`);\n continue;\n }\n\n let referenceId: string;\n try {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n referenceId = generateAnnotationId(backendUrl);\n } catch (error) {\n console.error(`[ReferenceDetectionWorker] Failed to generate annotation ID:`, error);\n throw new Error('Configuration error: Backend publicURL not set');\n }\n\n try {\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n annotation: {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n id: referenceId,\n motivation: 'linking' as const,\n target: {\n source: resourceIdToURI(job.params.resourceId, this.config.services.backend!.publicURL), // Convert to full URI\n selector: [\n {\n type: 'TextPositionSelector',\n start: detected.annotation.selector.start,\n end: detected.annotation.selector.end,\n },\n {\n type: 'TextQuoteSelector',\n exact: detected.annotation.selector.exact,\n ...(detected.annotation.selector.prefix && { prefix: detected.annotation.selector.prefix }),\n ...(detected.annotation.selector.suffix && { suffix: detected.annotation.selector.suffix }),\n },\n ],\n },\n body: (detected.annotation.entityTypes || []).map(et => ({\n type: 'TextualBody' as const,\n value: et,\n purpose: 'tagging' as const,\n })),\n modified: new Date().toISOString(),\n },\n },\n });\n\n totalEmitted++;\n\n if ((idx + 1) % 10 === 0 || idx === detectedAnnotations.length - 1) {\n console.log(`[ReferenceDetectionWorker] 📤 Emitted ${idx + 1}/${detectedAnnotations.length} events for ${entityType}`);\n }\n\n } catch (error) {\n totalErrors++;\n console.error(`[ReferenceDetectionWorker] ❌ Failed to emit event for ${referenceId}:`, error);\n // Continue processing other entities even if one fails\n }\n }\n\n console.log(`[ReferenceDetectionWorker] ✅ Completed ${entityType}: ${detectedAnnotations.length} found, ${detectedAnnotations.length - (totalErrors - (totalFound - totalEmitted))} emitted`);\n\n // Update progress after processing this entity type\n updatedJob = {\n ...updatedJob,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: i + 1,\n currentEntityType: entityType,\n entitiesFound: totalFound,\n entitiesEmitted: totalEmitted\n }\n };\n await this.updateJobProgress(updatedJob);\n }\n\n console.log(`[ReferenceDetectionWorker] ✅ Detection complete: ${totalFound} entities found, ${totalEmitted} events emitted, ${totalErrors} errors`);\n\n // Note: JobWorker base class will create the CompleteJob with result\n // We don't set job.result here - that's handled by the base class\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'detection') {\n // Type narrowing: job is FailedJob<DetectionParams>\n const detJob = job as DetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: detJob.params.resourceId,\n userId: detJob.metadata.userId,\n version: 1,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n error: 'Entity detection failed. Please try again later.',\n },\n });\n }\n }\n\n /**\n * Update job progress and emit events to Event Store\n * Overrides base class to also emit job progress events\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update job queue\n await super.updateJobProgress(job);\n\n // Emit events for detection jobs\n if (job.metadata.type !== 'detection') {\n return;\n }\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const detJob = job as RunningJob<DetectionParams, DetectionProgress>;\n\n const baseEvent = {\n resourceId: detJob.params.resourceId,\n userId: detJob.metadata.userId,\n version: 1,\n };\n\n // Determine if this is the first progress update (job.started)\n const isFirstUpdate = detJob.progress.processedEntityTypes === 0;\n\n // Determine if this is the final update (job.completed)\n const isFinalUpdate =\n detJob.progress.processedEntityTypes === detJob.progress.totalEntityTypes &&\n detJob.progress.totalEntityTypes > 0;\n\n if (isFirstUpdate) {\n // First progress update - emit job.started\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n totalSteps: detJob.params.entityTypes.length,\n },\n });\n } else if (isFinalUpdate) {\n // Final progress update - emit job.completed\n await this.eventStore.appendEvent({\n type: 'job.completed',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n foundCount: detJob.progress.entitiesFound,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n const percentage = Math.round((detJob.progress.processedEntityTypes / detJob.progress.totalEntityTypes) * 100);\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n percentage,\n currentStep: detJob.progress.currentEntityType,\n processedSteps: detJob.progress.processedEntityTypes,\n totalSteps: detJob.progress.totalEntityTypes,\n foundCount: detJob.progress.entitiesFound,\n },\n });\n }\n }\n}\n","/**\n * Generation Worker\n *\n * Processes generation jobs: runs AI inference to generate new resources\n * and emits resource.created and annotation.body.updated events.\n *\n * This worker is INDEPENDENT of HTTP clients - it just processes jobs and emits events.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, JobQueue, RunningJob, GenerationParams, GenerationProgress } from '@semiont/jobs';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { ResourceContext } from '../..';\nimport { generateResourceFromTopic } from '@semiont/inference';\nimport {\n getTargetSelector,\n getExactText,\n resourceUri,\n annotationUri,\n} from '@semiont/api-client';\nimport { getEntityTypes } from '@semiont/ontology';\nimport {\n CREATION_METHODS,\n generateUuid,\n type BodyOperation,\n resourceId,\n annotationId,\n} from '@semiont/core';\nimport { EventStore } from '@semiont/event-sourcing';\nimport type { EnvironmentConfig } from '@semiont/core';\n\nexport class GenerationWorker extends JobWorker {\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore\n ) {\n super(jobQueue);\n }\n\n protected getWorkerName(): string {\n return 'GenerationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'generation';\n }\n\n protected async executeJob(job: AnyJob): Promise<void> {\n if (job.metadata.type !== 'generation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n await this.processGenerationJob(job as RunningJob<GenerationParams, GenerationProgress>);\n }\n\n private async processGenerationJob(job: RunningJob<GenerationParams, GenerationProgress>): Promise<void> {\n console.log(`[GenerationWorker] Processing generation for reference ${job.params.referenceId} (job: ${job.metadata.id})`);\n\n const basePath = this.config.services.filesystem!.path;\n const projectRoot = this.config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Update progress: fetching\n let updatedJob: RunningJob<GenerationParams, GenerationProgress> = {\n ...job,\n progress: {\n stage: 'fetching',\n percentage: 20,\n message: 'Fetching source resource...'\n }\n };\n console.log(`[GenerationWorker] 📥 ${updatedJob.progress.message}`);\n await this.updateJobProgress(updatedJob);\n\n // Fetch annotation from view storage\n // TODO: Once AnnotationContext is consolidated, use it here\n const { FilesystemViewStorage } = await import('@semiont/event-sourcing');\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(job.params.sourceResourceId);\n if (!view) {\n throw new Error(`Resource ${job.params.sourceResourceId} not found`);\n }\n const projection = view.annotations;\n\n // Construct full annotation URI for comparison\n const expectedAnnotationUri = `${this.config.services.backend!.publicURL}/annotations/${job.params.referenceId}`;\n const annotation = projection.annotations.find((a: any) =>\n a.id === expectedAnnotationUri && a.motivation === 'linking'\n );\n\n if (!annotation) {\n throw new Error(`Annotation ${job.params.referenceId} not found in resource ${job.params.sourceResourceId}`);\n }\n\n const sourceResource = await ResourceContext.getResourceMetadata(job.params.sourceResourceId, this.config);\n if (!sourceResource) {\n throw new Error(`Source resource ${job.params.sourceResourceId} not found`);\n }\n\n // Determine resource name\n const targetSelector = getTargetSelector(annotation.target);\n const resourceName = job.params.title || (targetSelector ? getExactText(targetSelector) : '') || 'New Resource';\n console.log(`[GenerationWorker] Generating resource: \"${resourceName}\"`);\n\n // Verify context is provided (required for generation)\n if (!job.params.context) {\n throw new Error('Generation context is required but was not provided in job');\n }\n console.log(`[GenerationWorker] Using pre-fetched context: ${job.params.context.sourceContext?.before?.length || 0} chars before, ${job.params.context.sourceContext?.selected?.length || 0} chars selected, ${job.params.context.sourceContext?.after?.length || 0} chars after`);\n\n // Update progress: generating (skip fetching context since it's already in job)\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'generating',\n percentage: 40,\n message: 'Creating content with AI...'\n }\n };\n console.log(`[GenerationWorker] 🤖 ${updatedJob.progress.message}`);\n await this.updateJobProgress(updatedJob);\n\n // Generate content using AI with context from job\n const prompt = job.params.prompt || `Create a comprehensive resource about \"${resourceName}\"`;\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes({ body: annotation.body });\n\n const generatedContent = await generateResourceFromTopic(\n resourceName,\n job.params.entityTypes || annotationEntityTypes,\n this.config,\n prompt,\n job.params.language,\n job.params.context, // NEW - context from job (passed from modal)\n job.params.temperature, // NEW - from job\n job.params.maxTokens // NEW - from job\n );\n\n console.log(`[GenerationWorker] ✅ Generated ${generatedContent.content.length} bytes of content`);\n\n // Update progress: creating\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'generating',\n percentage: 70,\n message: 'Content ready, creating resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Generate resource ID\n const rId = resourceId(generateUuid());\n\n // Update progress: creating\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 85,\n message: 'Saving resource...'\n }\n };\n console.log(`[GenerationWorker] 💾 ${updatedJob.progress.message}`);\n await this.updateJobProgress(updatedJob);\n\n // Save content to RepresentationStore\n const storedRep = await repStore.store(Buffer.from(generatedContent.content), {\n mediaType: 'text/markdown',\n rel: 'original',\n });\n console.log(`[GenerationWorker] ✅ Saved resource representation to filesystem: ${rId}`);\n\n // Emit resource.created event\n await this.eventStore.appendEvent({\n type: 'resource.created',\n resourceId: rId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n name: resourceName,\n format: 'text/markdown',\n contentChecksum: storedRep.checksum,\n creationMethod: CREATION_METHODS.GENERATED,\n entityTypes: job.params.entityTypes || annotationEntityTypes,\n language: job.params.language,\n isDraft: true,\n generatedFrom: job.params.referenceId,\n generationPrompt: undefined, // Could be added if we track the prompt\n },\n });\n console.log(`[GenerationWorker] Emitted resource.created event for ${rId}`);\n\n // Update progress: linking\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'linking',\n percentage: 95,\n message: 'Linking reference...',\n resultResourceId: rId // Store for job.completed event\n }\n };\n console.log(`[GenerationWorker] 🔗 ${updatedJob.progress.message}`);\n await this.updateJobProgress(updatedJob);\n\n // Emit annotation.body.updated event to link the annotation to the new resource\n // Build full resource URI for the annotation body\n const newResourceUri = resourceUri(`${this.config.services.backend!.publicURL}/resources/${rId}`);\n\n const operations: BodyOperation[] = [{\n op: 'add',\n item: {\n type: 'SpecificResource',\n source: newResourceUri,\n purpose: 'linking',\n },\n }];\n\n // Extract annotation ID from full URI (format: http://host/annotations/{id})\n const annotationIdSegment = job.params.referenceId.split('/').pop()!;\n\n await this.eventStore.appendEvent({\n type: 'annotation.body.updated',\n resourceId: job.params.sourceResourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n annotationId: annotationId(annotationIdSegment),\n operations,\n },\n });\n console.log(`[GenerationWorker] ✅ Emitted annotation.body.updated event linking ${job.params.referenceId} → ${rId}`);\n\n // Note: JobWorker base class will create the CompleteJob with result\n // We don't set job.result here - that's handled by the base class\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'linking',\n percentage: 100,\n message: 'Complete!',\n resultResourceId: rId // Store for job.completed event\n }\n };\n await this.updateJobProgress(updatedJob);\n\n console.log(`[GenerationWorker] ✅ Generation complete: created resource ${rId}`);\n }\n\n /**\n * Update job progress and emit events to Event Store\n * Overrides base class to also emit job progress events\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update job queue\n await super.updateJobProgress(job);\n\n // Emit events for generation jobs\n if (job.metadata.type !== 'generation') {\n return;\n }\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const genJob = job as RunningJob<GenerationParams, GenerationProgress>;\n\n const baseEvent = {\n resourceId: genJob.params.sourceResourceId,\n userId: genJob.metadata.userId,\n version: 1,\n };\n\n // Emit appropriate event based on progress stage\n if (genJob.progress.stage === 'fetching' && genJob.progress.percentage === 20) {\n // First progress update - emit job.started\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n totalSteps: 5, // fetching, generating, creating, linking, complete\n },\n });\n } else if (genJob.progress.stage === 'linking' && genJob.progress.percentage === 100) {\n // Final progress update - emit job.completed\n await this.eventStore.appendEvent({\n type: 'job.completed',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n resultResourceId: genJob.progress.resultResourceId,\n annotationUri: annotationUri(`${this.config.services.backend!.publicURL}/annotations/${genJob.params.referenceId}`),\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n currentStep: genJob.progress.stage,\n percentage: genJob.progress.percentage,\n message: genJob.progress.message,\n },\n });\n }\n }\n}\n","// @semiont/make-meaning - Making meaning from resources\n// Transforms raw resources into meaningful, interconnected knowledge\n\n// Context assembly exports\nexport { ResourceContext } from './resource-context';\nexport type { ListResourcesFilters } from './resource-context';\nexport { AnnotationContext } from './annotation-context';\nexport type { BuildContextOptions } from './annotation-context';\nexport { GraphContext } from './graph-context';\n\n// Detection exports\nexport { AnnotationDetection } from './annotation-detection';\n\n// Re-export match types from @semiont/inference for convenience\nexport type {\n CommentMatch,\n HighlightMatch,\n AssessmentMatch,\n TagMatch,\n} from '@semiont/inference';\n\n// Job workers\nexport { CommentDetectionWorker } from './jobs/workers/comment-detection-worker';\nexport { HighlightDetectionWorker } from './jobs/workers/highlight-detection-worker';\nexport { AssessmentDetectionWorker } from './jobs/workers/assessment-detection-worker';\nexport { TagDetectionWorker } from './jobs/workers/tag-detection-worker';\nexport { ReferenceDetectionWorker } from './jobs/workers/reference-detection-worker';\nexport { GenerationWorker } from './jobs/workers/generation-worker';\n\n// Reasoning exports (future)\n// export { ResourceReasoning } from './resource-reasoning';\n\n// Placeholder for initial build\nexport const PACKAGE_NAME = '@semiont/make-meaning';\nexport const VERSION = '0.1.0';\n"],"mappings":";AAOA,SAAS,6BAA6B;AACtC,SAAS,qCAAqC;AAC9C,SAAS,0BAA0B,4BAA4B;AAWxD,IAAM,kBAAN,MAAsB;AAAA;AAAA;AAAA;AAAA,EAI3B,aAAa,oBAAoBA,aAAwB,QAA+D;AACtH,UAAM,WAAW,OAAO,SAAS,WAAY;AAC7C,UAAM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AAO,SAAS;AAAA,UACvB,SAAS,OAAO,SAAS;AAAA,UACzB,aAAa,OAAO,SAAS;AAAA,UAC7B,YAAY,OAAO,SAAS;AAAA,UAC5B,SAAS,OAAO,SAAS;AAAA,QAC3B;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;;;ACjSO,IAAM,eAAe;AACrB,IAAM,UAAU;","names":["resourceId","getPrimaryRepresentation","decodeRepresentation","FilesystemRepresentationStore","FilesystemViewStorage","annotationUri","resourceId","FilesystemViewStorage","FilesystemRepresentationStore","targetResourceId","getPrimaryRepresentation","decodeRepresentation","annotationId","resourceId","resourceUri","FilesystemRepresentationStore","getPrimaryRepresentation","decodeRepresentation","generateText","resourceId","resourceIdToURI","resourceId","resourceUri","annotationId","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","resourceId","annotationId","resourceUri","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","resourceId","annotationId","resourceUri","JobWorker","generateAnnotationId","resourceIdToURI","getTagSchema","userId","JobWorker","resourceId","resourceUri","annotationId","JobWorker","generateAnnotationId","resourceIdToURI","getPrimaryRepresentation","decodeRepresentation","FilesystemRepresentationStore","JobWorker","JobWorker","FilesystemRepresentationStore","getTargetSelector","getEntityTypes","JobWorker","FilesystemRepresentationStore","FilesystemViewStorage"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@semiont/make-meaning",
|
|
3
|
-
"version": "0.2.30-build.
|
|
3
|
+
"version": "0.2.30-build.62",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Making meaning from resources through context assembly, pattern detection, and relationship reasoning",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
"@semiont/content": "*",
|
|
31
31
|
"@semiont/graph": "*",
|
|
32
32
|
"@semiont/ontology": "*",
|
|
33
|
-
"@semiont/inference": "*"
|
|
33
|
+
"@semiont/inference": "*",
|
|
34
|
+
"@semiont/jobs": "*"
|
|
34
35
|
},
|
|
35
36
|
"devDependencies": {
|
|
36
37
|
"@vitest/coverage-v8": "^2.1.8",
|