Back to Ruflo

API Quick Reference

v3/@claude-flow/guidance/docs/reference/api-quick-reference.md

3.6.3018.5 KB
Original Source

API Quick Reference

All exports from @claude-flow/guidance. Each module is also available as a standalone import.

Import Map

Import PathKey Exports
@claude-flow/guidanceGuidanceControlPlane, createGuidanceControlPlane
@claude-flow/guidance/compilerGuidanceCompiler, createCompiler
@claude-flow/guidance/retrieverShardRetriever, createRetriever, HashEmbeddingProvider
@claude-flow/guidance/gatesEnforcementGates, createGates
@claude-flow/guidance/hooksGuidanceHookProvider, createGuidanceHooks
@claude-flow/guidance/ledgerRunLedger, createLedger, TestsPassEvaluator, ForbiddenCommandEvaluator, ForbiddenDependencyEvaluator, ViolationRateEvaluator, DiffQualityEvaluator
@claude-flow/guidance/optimizerOptimizerLoop, createOptimizer
@claude-flow/guidance/persistencePersistentLedger, EventStore, createPersistentLedger, createEventStore
@claude-flow/guidance/headlessHeadlessRunner, createHeadlessRunner, createComplianceSuite
@claude-flow/guidance/gatewayDeterministicToolGateway, createToolGateway
@claude-flow/guidance/artifactsArtifactLedger, createArtifactLedger
@claude-flow/guidance/evolutionEvolutionPipeline, createEvolutionPipeline
@claude-flow/guidance/manifest-validatorManifestValidator, ConformanceSuite, createManifestValidator, createConformanceSuite
@claude-flow/guidance/proofProofChain, createProofChain
@claude-flow/guidance/memory-gateMemoryWriteGate, createMemoryWriteGate, createMemoryEntry
@claude-flow/guidance/coherenceCoherenceScheduler, EconomicGovernor, createCoherenceScheduler, createEconomicGovernor
@claude-flow/guidance/capabilitiesCapabilityAlgebra, createCapabilityAlgebra
@claude-flow/guidance/conformance-kitSimulatedRuntime, MemoryClerkCell, ConformanceRunner, createMemoryClerkCell, createConformanceRunner
@claude-flow/guidance/ruvbot-integrationRuvBotGuidanceBridge, AIDefenceGate, RuvBotMemoryAdapter, createRuvBotBridge, createAIDefenceGate, createRuvBotMemoryAdapter
@claude-flow/guidance/meta-governanceMetaGovernor, createMetaGovernor
@claude-flow/guidance/adversarialThreatDetector, CollusionDetector, MemoryQuorum, createThreatDetector, createCollusionDetector, createMemoryQuorum
@claude-flow/guidance/trustTrustAccumulator, TrustScoreLedger, TrustSystem, getTrustBasedRateLimit, createTrustAccumulator, createTrustSystem
@claude-flow/guidance/truth-anchorsTruthAnchorStore, TruthResolver, createTruthAnchorStore, createTruthResolver
@claude-flow/guidance/uncertaintyUncertaintyLedger, UncertaintyAggregator, createUncertaintyLedger, createUncertaintyAggregator
@claude-flow/guidance/temporalTemporalStore, TemporalReasoner, createTemporalStore, createTemporalReasoner
@claude-flow/guidance/authorityAuthorityGate, IrreversibilityClassifier, createAuthorityGate, createIrreversibilityClassifier, isHigherAuthority, getAuthorityHierarchy
@claude-flow/guidance/continue-gateContinueGate, createContinueGate
@claude-flow/guidance/wasm-kernelgetKernel, isWasmAvailable, resetKernel
@claude-flow/guidance/generatorsgenerateClaudeMd, generateClaudeLocalMd, generateSkillMd, generateAgentMd, generateAgentIndex, scaffold
@claude-flow/guidance/analyzeranalyze, benchmark, autoOptimize, optimizeForSize, headlessBenchmark, validateEffect, abBenchmark, getDefaultABTasks, formatReport, formatBenchmark

GuidanceControlPlane

The all-in-one orchestrator.

ts
const plane = createGuidanceControlPlane(config?)
await plane.initialize()
MethodReturnsDescription
initialize()Promise<void>Read CLAUDE.md, compile, load shards, activate gates
compile(root, local?)Promise<PolicyBundle>Compile without reading files
retrieveForTask(request)Promise<RetrievalResult>Get constitution + relevant shards
evaluateCommand(cmd)GateResult[]Gate a shell command
evaluateToolUse(tool, params)GateResult[]Gate a tool call
evaluateEdit(path, content, lines)GateResult[]Gate a file edit
startRun(taskId, intent)RunEventBegin tracking a run
recordViolation(event, violation)voidLog a violation
finalizeRun(event)Promise<EvaluatorResult[]>Close run, evaluate
optimize()Promise<{promoted, demoted, adrsCreated}>Evolve rules
getStatus()ControlPlaneStatusSystem status
getMetrics()Metrics objectViolation rate, rework, etc.
getBundle()PolicyBundle | nullCurrent compiled bundle
getLedger()RunLedgerAccess the run ledger

EnforcementGates

ts
const gates = createGates(config?)
MethodReturnsDescription
evaluateCommand(cmd)GateResult[]Check command against all gates
evaluateToolUse(tool, params)GateResult[]Check tool call
evaluateEdit(path, content, lines)GateResult[]Check file edit
setActiveRules(rules)voidLoad compiled rules
getActiveGateCount()numberNumber of active gates

GateResult: { decision: 'allow'|'deny'|'warn', rule, reason, evidence }


DeterministicToolGateway

ts
const gw = createToolGateway(config?)
MethodReturnsDescription
evaluate(tool, params)GatewayDecisionFull pipeline: idempotency → schema → budget → gates
registerSchema(schema)voidRegister tool parameter schema
setBudget(budget)voidSet multi-dimensional budget
getBudget()BudgetCurrent budget state

ProofChain

ts
const chain = createProofChain(hmacKey)
MethodReturnsDescription
appendEvent(event, toolCalls, memOps)ProofEnvelopeAdd envelope
verify()booleanVerify entire chain
verifyEnvelope(index)booleanVerify single envelope
getEnvelope(index)ProofEnvelopeGet envelope by index
serialize()SerializedProofChainExport for persistence
ProofChain.deserialize(data, key)ProofChainRestore from export
lengthnumberNumber of envelopes

ContinueGate

ts
const gate = createContinueGate(config?)
MethodReturnsDescription
evaluate(context)ContinueDecisionDecide: continue/checkpoint/throttle/pause/stop
getHistory()ContinueDecision[]Past decisions
getStats()Stats objectCounts per decision type

StepContext fields: stepNumber, tokensUsed, tokenBudget, toolCallsUsed, toolCallBudget, timeMs, timeBudgetMs, coherenceScore, uncertaintyScore, reworkCount


MemoryWriteGate

ts
const gate = createMemoryWriteGate(config?)
MethodReturnsDescription
registerAuthority(auth)voidRegister agent permissions
evaluateWrite(agentId, ns, key, val, ttl)WriteDecisionAuthorize a write

CapabilityAlgebra

ts
const algebra = createCapabilityAlgebra()
MethodReturnsDescription
grant(params)CapabilityCreate a new capability
check(agentId, scope, resource, action)CapabilityCheckResultCheck permission
attenuate(capId, changes)CapabilityNarrow a capability
delegate(capId, toAgent, limits)CapabilityDelegate to another agent
revoke(capId)voidRevoke (cascades to delegations)
intersect(capA, capB)CapabilityActions in both
merge(capA, capB)CapabilityConstraints from both

TrustSystem

ts
const trust = createTrustSystem(config?)
MethodReturnsDescription
recordOutcome(agentId, outcome)voidRecord allow/deny/warn
getSnapshot(agentId)TrustSnapshotCurrent score and tier
getLedger()TrustScoreLedgerFull history

Tiers: trusted (>=0.8), standard (>=0.5), probation (>=0.3), untrusted (<0.3)


AuthorityGate

ts
const auth = createAuthorityGate(signingKey)
MethodReturnsDescription
registerScope(scope)voidSet authority requirements
check(level, action)AuthorityCheckResultCheck if level is sufficient
recordIntervention(params)HumanInterventionRecord signed approval

IrreversibilityClassifier

ts
const irrev = createIrreversibilityClassifier()
MethodReturnsDescription
classify(action)IrreversibilityResultreversible/costly-reversible/irreversible
addPattern(class, regex)voidAdd custom pattern (ReDoS-validated)

ThreatDetector

ts
const detector = createThreatDetector(config?)
MethodReturnsDescription
analyzeInput(input, context)ThreatSignal[]Scan for threats
analyzeMemoryWrite(ns, key, val, ctx)ThreatSignal[]Scan memory write

CollusionDetector

ts
const detector = createCollusionDetector(config?)
MethodReturnsDescription
recordInteraction(from, to, hash)voidLog agent interaction
detectCollusion()CollusionReportCheck for rings/frequency anomalies

MemoryQuorum

ts
const quorum = createMemoryQuorum(config?)
MethodReturnsDescription
propose(key, value, agentId)stringCreate proposal, get ID
vote(proposalId, agentId, approve)voidCast vote
resolve(proposalId)QuorumResultTally votes

MetaGovernor

ts
const gov = createMetaGovernor(config?)
MethodReturnsDescription
checkInvariants(state)InvariantReportVerify constitutional invariants
proposeAmendment(desc, changes, author)stringPropose change
voteOnAmendment(id, voter, approve)voidCast vote
resolveAmendment(id)AmendmentResolve with supermajority

UncertaintyLedger

ts
const ledger = createUncertaintyLedger(config?)
MethodReturnsDescription
assert(ns, claim, params)stringCreate belief
addEvidence(id, evidence)voidAdd supporting/opposing evidence
get(id)BeliefGet belief with computed confidence
query(filters)Belief[]Filter by namespace/status/confidence/tags

TemporalStore

ts
const store = createTemporalStore()
MethodReturnsDescription
assert(ns, key, value, window)stringCreate temporal assertion
retract(id)voidSoft-delete
getAt(ns, timestamp)TemporalAssertion[]Active at time T

TruthAnchorStore

ts
const store = createTruthAnchorStore(signingKey)
MethodReturnsDescription
create(params)TruthAnchorCreate immutable signed anchor
get(id)TruthAnchorRetrieve anchor
verify(id)booleanVerify signature
verifyAll()VerifyAllResultVerify entire store

CoherenceScheduler

ts
const scheduler = createCoherenceScheduler(config?)
MethodReturnsDescription
computeScore(events)CoherenceScoreCompute from recent events
getPrivilegeLevel(score)PrivilegeLevelfull/restricted/read-only/suspended

EconomicGovernor

ts
const econ = createEconomicGovernor(config?)
MethodReturnsDescription
recordUsage(usage)voidTrack resource consumption
checkBudgets()BudgetAlert[]Check for threshold crossings
getUsage()BudgetUsageCurrent usage across all dimensions

WASM Kernel

ts
const k = getKernel()
MethodReturnsDescription
k.availablebooleantrue = WASM, false = JS fallback
k.sha256(input)stringSHA-256 hash (hex)
k.hmacSha256(key, input)stringHMAC-SHA256 (hex)
k.contentHash(json)stringSorted-key content hash
k.signEnvelope(key, json)stringSign proof envelope
k.verifyChain(json, key)booleanVerify proof chain
k.scanSecrets(content)string[]Scan for secrets
k.detectDestructive(cmd)string | nullDetect destructive commands
k.batchProcess(ops)BatchResult[]Batch operations
HelperReturnsDescription
isWasmAvailable()booleanCheck without loading
resetKernel()voidForce re-detection on next getKernel()

Generators

ts
import { generateClaudeMd, scaffold } from '@claude-flow/guidance/generators';
FunctionReturnsDescription
generateClaudeMd(profile)stringGenerate CLAUDE.md from a ProjectProfile
generateClaudeLocalMd(profile)stringGenerate CLAUDE.local.md from a LocalProfile
generateSkillMd(skill)stringGenerate a skill definition markdown
generateAgentMd(agent)stringGenerate an agent manifest markdown
generateAgentIndex(agents)stringGenerate an agent index file
scaffold(options)ScaffoldResultFull project scaffolding

Key types: ProjectProfile, LocalProfile, SkillDefinition, AgentDefinition, ScaffoldOptions, ScaffoldResult


Analyzer

ts
import { analyze, validateEffect } from '@claude-flow/guidance/analyzer';

Scoring & Reporting

FunctionReturnsDescription
analyze(content, localContent?)AnalysisResult6-dimension analysis with composite score (0-100) and grade (A-F)
benchmark(before, after, local?)BenchmarkResultCompare two CLAUDE.md versions
formatReport(result)stringFormatted analysis report
formatBenchmark(result)stringFormatted benchmark comparison

AnalysisResult: { compositeScore, grade, dimensions[], metrics, suggestions[], analyzedAt }

6 Dimensions: Structure (20%), Coverage (20%), Enforceability (25%), Compilability (15%), Clarity (10%), Completeness (10%)

Optimization

FunctionReturnsDescription
autoOptimize(content, local?, maxIter?){ optimized, benchmark, appliedSuggestions }Iterative score improvement
optimizeForSize(content, options){ optimized, benchmark, appliedSteps, proof }Context-size-aware optimization

OptimizeOptions: { contextSize: 'compact'|'standard'|'full', targetScore?, maxIterations?, proofKey? }

Context SizeLine BudgetUse Case
compact80 linesSmall context windows, cost optimization
standard200 linesDefault for most projects
full500 linesLarge context windows, maximum coverage

Headless Benchmarking

FunctionReturnsDescription
headlessBenchmark(original, optimized, options?)Promise<HeadlessBenchmarkResult>Run compliance tasks via claude -p

Options: { executor?, proofKey?, workDir? }

Accepts an IHeadlessExecutor for testing without the real CLI.

Empirical Behavioral Validation

FunctionReturnsDescription
validateEffect(original, optimized, options?)Promise<ValidationReport>Prove score improvements produce behavioral improvements

Options: { executor?, tasks?, proofKey?, workDir?, trials? }

ValidationReport fields:

FieldTypeDescription
before / afterValidationRunAnalysis + task results + adherence per phase
correlation.pearsonRnumberLinear correlation (-1 to 1)
correlation.spearmanRhonumberRank correlation (-1 to 1)
correlation.cohensDnumber | nullEffect size magnitude
correlation.effectSizeLabelstringnegligible / small / medium / large
correlation.verdictstringpositive-effect / negative-effect / no-effect / inconclusive
proofChainProofEnvelope[]Tamper-evident audit trail
reportstringFull formatted evidence report

IContentAwareExecutor: Extends IHeadlessExecutor with setContext(claudeMdContent) — called before each phase so the executor can vary behavior based on guidance quality.

15 default validation tasks cover all 6 dimensions: secret handling, force push prevention, type safety, test-before-commit, build/test awareness, security rules, architecture knowledge, destructive action blocking, code style, error handling, deployment, and environment variables.

A/B Benchmark Harness

FunctionReturnsDescription
abBenchmark(claudeMd, options?)Promise<ABReport>Run 20 tasks under Config A (no guidance) vs Config B (with guidance)
getDefaultABTasks()ABTask[]Get the 20 default benchmark tasks spanning 7 classes

Options: { executor?, tasks?, proofKey?, workDir? }

ABReport fields:

FieldTypeDescription
configA / configB{ label, taskResults, metrics }Per-config results
configA.metrics.compositeScorenumbersuccess_rate − 0.1*cost − 0.2*violations − 0.1*interventions
configB.metrics.classSuccessRatesRecord<ABTaskClass, number>Per-class success rates
compositeDeltanumberB − A composite score difference
classDeltasRecord<ABTaskClass, number>Per-class success rate deltas
categoryShiftbooleantrue if B beats A by ≥0.2 across ≥3 task classes
proofChainProofEnvelope[]Tamper-evident audit trail
reportstringFull formatted A/B benchmark report

7 task classes: bug-fix (3), feature (5), refactor (3), security (3), deployment (2), test (2), performance (2)

Gate simulation detects 7 violation categories: destructive-command, hardcoded-secret, force-push, unsafe-type, skipped-hook, missing-test, policy-violation.