Skip to main content

API Reference

Cognitive architecture primitives built on flow-state-dev. Provides attention, memory, identity, and metacognition domains for agentic workflows.

Import: Use subpath exports. @thought-fabric/core/attention, @thought-fabric/core/memory, @thought-fabric/core/identity, @thought-fabric/core/metacognition.


attention

Relevance and salience for what the agent attends to.

filterRelevance(config)

Handler block factory. Deterministic keyword-based relevance filtering. No LLM. Fast. Removes or annotates items below a threshold using keyword overlap heuristics.

import { filterRelevance } from "@thought-fabric/core/attention";

const block = filterRelevance({ name: "filter", criteria: { ... } });

Returns a BlockDefinition (handler). Use as a step in a sequencer or as a tool.

scoreSalience(config)

Generator block factory. LLM-based salience scoring along configurable dimensions (goal relevance, recency, novelty, emotional weight).

import { scoreSalience } from "@thought-fabric/core/attention";

const block = scoreSalience({
name: "salience",
dimensions: { ... },
weights: { ... },
model: "preset/fast",
});

Returns a BlockDefinition (generator). Output schema: scores, composite, ranking, itemScores.


memory

Three-tier memory: working (session), episodic (cross-session), and semantic (stable knowledge).

Unified System

FunctionPurpose
system(config)Factory that wires all three tiers. Returns capture, captureFromItems, consolidate, prune, recall, contextFormatter, and per-tier helpers.

Unified System Blocks

FunctionKindPurpose
memorySystemCapture(config)sequencerFull pipeline: observe → reflect → tick (+ consolidation + prune)
memorySystemObserve(config)generatorLLM extraction with durability/category classification
memorySystemReflect(config)handlerRoutes observations to working, episodic, and semantic stores
memorySystemTick(config)handlerAdvances decay clock
memorySystemConsolidate(config)sequencerGuard → generate → persist consolidation pipeline
memorySystemPrune(config)sequencerGuard → generate → persist pruning pipeline
pruneGuard(config)handlerChecks fact count against threshold
pruneGenerate(config)generatorLLM identifies removals and merges
prunePersist(config)handlerApplies removals and merges to semantic store

Working Memory Blocks

FunctionKindPurpose
workingMemoryCapture(config?)sequencerStandalone: observe → remember → tick
workingMemoryObserve(config?)generatorLLM extraction. Output: observations array.
workingMemoryRemember(config?)handlerPersist observations into the resource.
workingMemoryTick(config?)handlerAdvance decay clock, recompute salience.
workingMemorySnapshot()handlerRead current entries and turn counter.
workingMemoryAdd(config?)handlerManual entry. No LLM extraction.

Resources

ExportScopePurpose
workingMemoryResourcesessionWorking memory resource definition
workingMemoryResourcessessionPre-keyed { workingMemory: workingMemoryResource }
memorySystemResourcesessionTracking state (watermark, consolidation counters)
createEpisodicMemoryResource(scope)user/projectEpisodic memory resource factory
createSemanticMemoryResource(scope)user/projectSemantic memory resource factory

Context

  • workingMemoryContextFormatter — Context slot for generators (working memory only).
  • system().contextFormatter — Cross-store context formatter (all tiers).

Working Memory Helpers

FunctionPurpose
addWorkingMemoryAdd entry with auto-eviction at capacity
evictWorkingMemoryRemove entry by ID
pinWorkingMemory / unpinWorkingMemoryToggle pinned status
refreshWorkingMemoryUpdate lastAccessedAtTurn
advanceWorkingMemoryTick decay, recompute salience for all entries
workingMemoryItemsRead entries sorted by salience
formatWorkingMemoryEntriesFormat entries for LLM context

Episodic Memory Helpers

FunctionPurpose
encodeEpisodeWrite a new episode
recentEpisodesGet recent episodes
markEpisodesConsolidatedMark episodes as processed by consolidation

Semantic Memory Helpers

FunctionPurpose
addSemanticFactAdd a new fact (subject defaults to 'user')
updateSemanticFactUpdate existing fact content
reinforceSemanticFactIncrease confidence via reinforcement
removeSemanticFactRemove a fact (invalidation)
semanticFacts(ref, subject?)All facts, optionally filtered by subject
querySemanticFacts(ref, q, limit?, subject?)Query facts by keyword overlap, optionally scoped to subject
semanticCategoryEnumZod enum of valid semantic categories

Config Defaults

ConstantContents
DEFAULT_WORKING_MEMORY_CONFIGcapacity, maxPinnedSlots, decay
DEFAULT_EPISODIC_CONFIGscope, significanceThreshold, maxEpisodes
DEFAULT_CONSOLIDATION_CONFIGepisodicThreshold, onEviction, minInterval
DEFAULT_PRUNE_CONFIGpruneThreshold
DEFAULT_OBSERVER_CONFIGmaxAssistantChars

Pure Math (no side effects)

  • computeDecay(elapsed, strategy, rate) — Decay factor. Strategies: power-law, exponential, none.
  • computeSalience(entry, currentTurn, decay)importance × decay(elapsed).

metacognition

Bias detection, sycophancy scoring, and counter-argument generation.

Import: @thought-fabric/core/metacognition

Blocks

FunctionKindPurpose
biasAnalyzer(config?)sequencerBundled pipeline: detect → classify → score → counterpoint → format
biasDetectAgreement(config?)generatorDetects agreement patterns across four dimensions
biasClassify(config?)generatorClassifies six bias types with per-type confidence
biasScore(config?)handlerComputes composite sycophancy score (deterministic)
biasCounterpoint(config?)generatorGenerates counter-arguments when score exceeds threshold
biasFormat()handlerMaps accumulated data to AnalyzerResult output

Schemas

SchemaPurpose
biasAnalyzerInputSchemaInput: { userInput: string, aiResponse: string }
biasAnalyzerOutputSchemaFull output with bias annotations, score, counter-arguments
biasTypeSchemaEnum of six bias types
biasAnnotationSchemaPer-bias annotation (type, confidence, description, evidence)
counterArgumentSchemaCounter-argument (claim, counterpoint, strength, sources)
sycophancyScoreSchemaComposite score with label and four-dimension breakdown
sycophancyBreakdownSchemaFour dimension scores
sycophancyLabelSchemaEnum: balanced, mild_bias, moderate_bias, sycophantic
analyzerResultSchemaGeneric AnalyzerResult contract

Helpers

FunctionPurpose
labelForSycophancyScore(score)Score → label mapping
severityForSycophancyScore(score)Score → severity (info/warning/critical)
computeCompositeSycophancyScore(breakdown, biases, config?)Weighted composite from dimensions + bias confidence
shouldGenerateCounterpoints(score, threshold?)Whether score warrants counter-argument generation
summarizeBiasFindings(score, label, biases)Human-readable summary string

Config

ConstantContents
DEFAULT_BIAS_ANALYZER_CONFIGcounterpointThreshold (0.4), breakdownWeights, biasConfidenceWeight (0.3)

identity

Perspective and constitution — structured viewpoints and ranked value systems that shape how agents interpret and evaluate information.

Import: @thought-fabric/core/identity

Perspective Factory + System

FunctionPurpose
perspective(config)Create a frozen perspective instance from config
system(instance, config?)Factory that wires blocks, capability, resources, and capture pipeline

Static Blocks

FunctionKindPurpose
perspectiveApply(config)handlerInject perspective framing into content
perspectiveAnalyze(config)generatorLLM analysis through the perspective's lens
perspectiveAuditor(config)sequencerapply → analyze pipeline

Stateful Blocks

FunctionKindPurpose
perspectiveObserve(config)handlerRecord observations from analysis output or explicit batch
perspectivePosition(config)handlerRecord a position with supporting observations
perspectiveChallenge(config)handlerChallenge a position with counter-evidence
perspectiveSnapshot(config)handlerRead current observations + positions
perspectiveAdvance(config)handlerBump observation turn counter

Resources

ExportScopePurpose
perspectiveObservationsResourcesessionObservation store (singleton)
perspectivePositionsResourcesession/user/projectPosition store; scope decided by where the capability or block declares it

Capability

FunctionPurpose
createPerspectiveCapability(instance, config?)Create a capability with resources, context presets, and typed helpers

Presets: static (perspective framing), accumulated (observations + positions). Both on by default.

Static Helpers

FunctionPurpose
formatPerspective(instance)Full formatted perspective for LLM context
formatPerspectiveSalience(salience)Format salience model
formatPerspectiveReasoning(reasoning)Format reasoning config
summarizePerspective(instance)One-line summary
perspectiveContextFormatter(instance)Context slot function for generators

Observation Helpers

FunctionPurpose
addPerspectiveObservation(ref, input)Add an observation
removePerspectiveObservation(ref, id)Remove by ID
perspectiveObservations(ref, category?)Read observations, optionally filtered
advancePerspectiveObservations(ref)Bump turn counter
formatPerspectiveObservations(ref)Format for LLM context

Position Helpers

FunctionPurpose
addPerspectivePosition(ref, input, obsRef?)Add a position
challengePerspectivePosition(ref, id, evidence, obsRef?)Add counter-evidence
removePerspectivePosition(ref, id)Remove by ID
perspectivePositions(ref)Read all positions
formatPerspectivePositions(ref)Format for LLM context
formatPerspectiveAccumulated(obsRef, posRef?)Combined observations + positions

Schemas

SchemaPurpose
perspectiveConfigSchemaFull perspective configuration
perspectiveSalienceSchemaSalience model (amplify/suppress)
perspectiveReasoningSchemaReasoning config (priorities, risk model)
perspectiveCommunicationSchemaCommunication style
perspectiveAnalysisSchemaAnalysis output
perspectiveInputSchemaAnalysis input ({ content: string })
perspectiveApplyOutputSchemaApply block output
perspectiveObservationSchemaSingle observation
perspectiveObservationsStateSchemaObservations resource state
perspectivePositionSchemaSingle position
perspectivePositionChallengeSchemaChallenge entry
perspectivePositionsStateSchemaPositions resource state
perspectiveObserveInputSchemaObserve block input
perspectiveObserveOutputSchemaObserve block output
perspectivePositionInputSchemaPosition block input
perspectiveChallengeInputSchemaChallenge block input
perspectiveSnapshotOutputSchemaSnapshot block output

Constitution Factory

FunctionPurpose
constitution(config)Create a frozen constitution definition from config

Constitution Blocks

FunctionKindPurpose
constitutionAuditor(config)sequencerBundled pipeline: review → enforce
constitutionReview(config)generatorLLM-evaluates content against principles
constitutionEnforce(config)handlerComputes aggregate compliance and pass/fail verdict

Constitution Helpers

FunctionPurpose
rankConstitutionPrinciples(constitution, context?)Sort principles by effective priority, applying contextual overrides
computeConstitutionCompliance(results, constitution)Aggregate compliance score from per-principle results
formatConstitution(constitution)Human-readable string for LLM prompt injection
summarizeConstitutionReview(review)One-line summary with violation counts and severity

Constitution Schemas

SchemaPurpose
constitutionConfigSchemaFull constitution configuration
constitutionPrincipleSchemaSingle principle (id, statement, priority, rationale, weight)
constitutionContextualOverrideSchemaOverride rule (when, promote, demote, reasoning)
constitutionConflictResolutionSchemaEnum: priority, weighted, contextual
constitutionReviewInputSchemaInput: { content: string, context?: string }
constitutionReviewOutputSchemaFull review output with compliance verdict
constitutionPrincipleResultSchemaPer-principle evaluation result
constitutionViolationSchemaViolation entry (principleId, severity, description, evidence)
constitutionTradeoffSchemaTradeoff between two principles

Constitution Config

ConstantContents
DEFAULT_CONSTITUTION_CONFIGcomplianceThreshold (0.7)

Usage

import { system as memorySystem } from "@thought-fabric/core/memory";
import { perspective, system as perspectiveSystem } from "@thought-fabric/core/identity";
import { filterRelevance, scoreSalience } from "@thought-fabric/core/attention";
import { biasAnalyzer } from "@thought-fabric/core/metacognition";

const mem = memorySystem({ model: "preset/fast", working: true, episodic: true, semantic: true });

const sec = perspectiveSystem(
perspective({
name: "security-engineer",
description: "Security-focused code reviewer",
salience: { amplify: ["auth", "injection", "data exposure"] },
reasoning: { priorities: ["identify attack vectors", "assess blast radius"] },
}),
{ model: "preset/fast" },
);

const chat = generator({
uses: [mem.capability, sec.capability],
// ...
});

const pipeline = sequencer({ name: "pipeline", inputSchema: chatInput })
.then(chat)
.work(mem.captureFromItems)
.work((response) => ({ content: response }), sec.capture);

See Memory and Identity for full guides.