# @govlab/patterns ## Purpose One pattern-analysis substrate over a shared kernel, laid out in the `configuration`, `core` and `runtime` containers with a flat `types` bucket. - The axis kernel holds the four PROTOCOL axes, generated from the reasoning ontology into `configuration/generated/axis.generated.ts`, with their predicates and the coordinate factory (`core/factories/axis.factory.ts`). - The analysis graph (`core/models/graph.model.ts`) validates single production, acyclicity and monotone reasoning through `core/validators/graph.validator.ts`. - Schema detection, the representation resolver and the six representation kinds each fold records into a summary through an aggregator under `core/aggregators/`. - Each representation kind is a self-registering plugin under `core/plugins/`. `core/loaders/representation.loader.ts` imports every file in that folder at load, so adding a representation adds one file. - The declared null models (`core/analyzers/baseline.analyzer.ts`) score every finding's significance. - Code ingestion parses source through `@govlab/code-parse` into records, symbols and imports, and the package coordinator renders each module's walk, call graph and findings into its report artifacts. `createGovlabPatterns(options)` folds every registered pattern face into one typed port over this kernel. The face registry is the extension seam and holds no face today. ## When to use - Analyzing any record dataset: detect its schema, map fields to representations, and stream reusable analyses that emit coordinate-stamped findings scored against a declared null. - Reasoning over the codebase's own structured data (quality findings, catalog records) as records, with distribution, entropy, drift and anomaly analyses measured against a null instead of asserted. - Producing a graph-validated, provenance-carrying findings report where every derived statistic has a single producer and every finding a typed coordinate. - Generating each module's code walk, call graph and structural findings as report artifacts, and verifying them against a fresh generation. ## When NOT to use - As a linter or code scanner. It holds the analysis substrate, not the quality tooling (`@govlab/quality`). - As a runtime presentation layer. Its output is structured findings and, at build time, static artifacts. - For records whose shape resists every representation. Refuse the mapping instead of forcing one that does not fit. ## Architecture charts The structure, logical-flow and dependency diagrams derived from the source AST live in [_code.info.generated/mermaid-charts.generated.md](./_code.info.generated/mermaid-charts.generated.md). ## Install A private workspace package resolved through the root `package.json` `workspaces` glob `govlab.root/govlab.*`. Import the bare specifier `@govlab/patterns` from its barrel. It runs directly from TypeScript source with no build step. ## Quick start ```ts EXAMPLE: Analyze a record set into coordinate-stamped findings import { report } from "@govlab/patterns"; const result = report([ { tool: "Read", tokens: 1 }, { tool: "Edit", tokens: 2 }, ]); result.headline.findings; ``` ```ts EXAMPLE: Compose the substrate port import { createGovlabPatterns } from "@govlab/patterns"; const lab = createGovlabPatterns(); lab.faces; ``` ## API - `const ANALYSIS_AXIS: readonly ["structure", "time", "space", "statistical", "frequency", "sequential", "relation", "behavior", "function", "meaning", "cause", "prediction", "anomaly", "change", "fractal", "transformation", "invariant", "optimization", "complexity"]` - `class AnalysisGraph` - `function analysisNode(field: string, matcher: string): Node` - `enum AnalysisTag` - `function analyze(records: readonly unknown[], options?: AnalyzeOptions): AnalyzeResult` - `interface AnalyzeOptions` - `interface AnalyzeReport` - `interface AnalyzeResult` - `function applicableAnalyses(representation: string): readonly AnalysisTag[]` - `function assertHardened(svg: string, label: string): void` - `function autocorrelationSignificance(correlation: number, count: number): Significance` - `function availableLanguages(): string[]` - `interface BridgeConfig` - `function buildContext(modules: readonly string[], scope: ModuleScope): Promise` - `function buildModuleReport(moduleDir: string, ctx: RepoContext, scope: ModuleScope): Promise` - `const CELL_COLUMNS: readonly string[]` - `function chiSquareSf(statistic: number, dof: number): number` - `interface CodeFinding` - `function codeInsight(symbols: readonly CodeSymbol[], records: readonly Record[]): CodeInsight` - `interface CodeInsight` - `interface CodeSymbol` - `interface Composition` - `interface Compressibility` - `function coordinate(input: CoordinateInput): Coordinate` - `interface Coordinate` - `class CoordinateError` - `interface CoordinateInput` - `interface Coverage` - `function createCompressibility(): Compressibility` - `function createGovlabPatterns(options?: GovlabPatternsOptions): GovlabPatterns` - `function createInterventionBridge(config?: BridgeConfig): InterventionBridge` - `function createRng(seed: number): Rng` - `function crossModuleFanIn(units: readonly ModuleUnit[], packageMap: ReadonlyMap): Map` - `class DataLoadError` - `function definePatternFace

(definition: PatternFaceDefinition

): PatternFaceDefinition

` - `interface DefinitionRecord` - `function detectLanguage(filename: string, content?: string): string | null` - `function detectSchema(records: Iterable, floatFields?: ReadonlySet): FieldSchema[]` - `function discoverModules(root: string, pruned: Pruned): string[]` - `function discoverSources(dir: string): string[]` - `interface Distribution` - `class DistributionAccumulator` - `function distributionFindings(field: string, summary: DistributionSummary): Finding[]` - `interface DistributionSummary` - `function emptyContext(): RepoContext` - `function erf(x: number): number` - `function erfc(x: number): number` - `interface FaceContext` - `interface FieldSchema` - `interface FileEntry` - `interface Finding` - `interface FindingInput` - `function findingNode(producer: string, name: string, coord: Coordinate): Node` - `interface FindingSignificance` - `function foldFaces(definitions: readonly PatternFaceDefinition[], context: FaceContext): Map` - `function gaussian(rng: Rng, mean?: number, stddev?: number): number` - `interface GovlabPatterns` - `interface GovlabPatternsOptions` - `class GraphAccumulator` - `class GraphError` - `function graphFindings(field: string, summary: GraphSummary): Finding[]` - `interface GraphSummary` - `function graphToDict(graph: AnalysisGraph): GraphDict` - `class GridAccumulator` - `function gridFindings(field: string, summary: GridSummary): Finding[]` - `interface GridSummary` - `function hardenIssues(svg: string): string[]` - `interface HexGridOptions` - `interface ImportBinding` - `function inferMapping(schema: readonly FieldSchema[]): Map` - `function ingestCode(source: string, filename: string, options?: CodeParseOptions): Promise[]>` - `function ingestFile(source: string, filename: string, options?: CodeParseOptions): Promise` - `interface IngestFile` - `function ingestImports(source: string, filename: string, options?: CodeParseOptions): Promise` - `function ingestSymbols(source: string, filename: string, options?: CodeParseOptions): Promise` - `interface Intervention` - `interface InterventionBridge` - `interface InterventionResult` - `function isAnalysisTag(value: string): value is AnalysisTag` - `function isCoordinatePair(field: FieldSchema): boolean` - `function isMathType(value: string): boolean` - `function isOntologyTag(value: string): value is OntologyTag` - `function isReasoningRung(value: string): value is ReasoningRung` - `function isRepresentationTag(value: string): value is RepresentationTag` - `enum Kind` - `function kindOf(value: unknown): Kind` - `interface LoadedData` - `function loadPlugins(dir: string): Promise` - `function loadRecords(path: string): LoadedData` - `interface Logger` - `function makeFinding(input: FindingInput): Finding` - `const MATH_TYPES: ReadonlySet` - `function mathTypeOf(analysis: AnalysisTag): string` - `interface ModuleReport` - `interface ModuleReportBuild` - `interface ModuleScope` - `interface Narrative` - `interface Node` - `enum NodeKind` - `const NOOP_LOGGER: Logger` - `function normalSignificance(z: number): Significance` - `function numberTokenIsFloat(token: string): boolean` - `const ONTOLOGY_AXIS: readonly ["identity", "composition", "structure", "relation", "space", "time", "state", "change", "behavior", "function", "cause", "meaning", "scale", "probability", "novelty"]` - `enum OntologyTag` - `interface OrderedStats` - `function packCells(cells: readonly WalkCell[]): PackedCells` - `interface PackedCells` - `enum PackedRow` - `function parseCode(source: string, language: string, options?: CodeParseOptions): Promise` - `interface PatternFaceDefinition` - `interface Prediction` - `enum Primitive` - `function proposerFromRules(rules: ReadonlyMap): (finding: Finding) => Intervention | null` - `const REASONING_AXIS: readonly ["observation", "description", "comparison", "classification", "explanation", "prediction", "intervention", "creation", "reflection"]` - `function reasoningRank(rung: ReasoningRung): number` - `enum ReasoningRung` - `function reasonOf(observation: string, explanation: string): Narrative` - `function registeredRepresentations(): string[]` - `function registerRepresentation(definition: RepresentationDefinition): void` - `function renderHexGrid(nodes: readonly WalkNode[], options?: HexGridOptions): string` - `interface RepoContext` - `function report(records: readonly unknown[], options?: AnalyzeOptions): AnalyzeReport` - `interface ReportMetrics` - `interface ReportPage` - `const REPRESENTATION_AXIS: readonly ["symbolic", "logic", "number", "algebra", "geometry", "topology", "graph", "matrix", "function", "information-theory", "probability", "dynamical-systems", "computation", "category-theory"]` - `interface RepresentationDefinition` - `interface RepresentationRuntime` - `enum RepresentationTag` - `interface Rng` - `function scanFloatFields(text: string, recordDepth: number): Set` - `function schemaFromDict(data: unknown): FieldSchema[]` - `class SequenceAccumulator` - `function sequenceFindings(field: string, summary: SequenceSummary): Finding[]` - `interface SequenceSummary` - `interface Significance` - `const SOURCE_ID: "records"` - `function sourceNode(): Node` - `const STATE_LEGEND: readonly LegendItem[]` - `function streamJsonlFile(path: string): AsyncGenerator` - `function streamReports(source: AsyncIterable | Iterable, windowSize: number, options?: AnalyzeOptions): AsyncGenerator` - `function syntaxDistribution(records: readonly Record[]): Distribution` - `function synthesize(records: readonly unknown[], options?: SynthesizeOptions): Record[]` - `interface SynthesizeOptions` - `interface Temporal` - `interface Transition` - `function transitionIndependence(transitions: readonly Transition[]): Significance` - `class TreeAccumulator` - `function treeFindings(field: string, summary: TreeSummary): Finding[]` - `interface TreeSummary` - `function uniformity(counts: ReadonlyMap): Uniformity` - `interface Uniformity` - `function unpackCells(packed: PackedCells): WalkCell[]` - `function unrepresentable(schema: readonly FieldSchema[]): FieldSchema[]` - `function validateMapping(mapping: ReadonlyMap, schema: readonly FieldSchema[]): void` - `function validateRecord(record: unknown, schema: readonly FieldSchema[]): Record` - `class VectorAccumulator` - `function vectorFindings(field: string, summary: VectorSummary): Finding[]` - `interface VectorSummary` - `interface WalkCell` - `function walkCells(nodes: readonly WalkNode[], flagged?: ReadonlyMap): WalkCell[]` - `interface WalkNode` - `function walkSubtitle(steps: number): string` - `function weightedChoice(rng: Rng, weights: ReadonlyMap): string | null` - `function weightedSample(rng: Rng, weights: ReadonlyMap, size: number): string[]` - `function windowedReports(records: readonly unknown[], windowSize: number, options?: AnalyzeOptions): Generator` - `interface WindowSnapshot` ## Configuration `createGovlabPatterns(options)` accepts an options object with an injected `logger` that defaults to a no-op. `analyze`, `report` and the streaming pipelines accept an explicit field-to-representation `mapping` and the set of fields to read as floats. `synthesize` takes a `seed` and a `count`, so a synthesis run is reproducible. The report entry point takes `--all`, `--check`, `--fast` and `--ignore`, and reads the shared cache switch `GOVLAB_NO_CACHE`. ## Dependencies - `@govlab/argv` - `@govlab/canonical-write` - `@govlab/code-parse` - `@govlab/content-fingerprint` - `@govlab/context` - `@govlab/quality` - `@ssot/paths` ## AI context - The substrate is one composed port over a shared kernel. `createGovlabPatterns()` returns a port whose face registry is ready for self-registering faces and holds none today. The barrel exposes the analysis concerns (schema detection, representation mapping, aggregators, null models and findings), each bounded over the kernel. - A finding carries a four-axis PROTOCOL coordinate (Ontology, Analysis, Reasoning, Representation) drawn from the shared canonical vocabulary. `runtime/entrypoints/axis.entrypoint.ts` regenerates that vocabulary from `@govlab/context`, so a consumer that also has the context resolves the same id by identity. - A representation is a plugin file under `core/plugins/` that calls `registerRepresentation` with its name, its applicable analyses and a runtime factory. `loadPlugins(dir)` loads further plugin folders the same way. - `@govlab/patterns` composes the sibling leaves `@govlab/code-parse` (tree-sitter parsing) and `@govlab/content-fingerprint` (fingerprint caching and body hashing). ## Domains This package serves these software domains, which `_manifest.json` declares in `domains` from the two-tier software-domain vocabulary (`meta → sub`): - **data** — data-modeling - **developer-tooling** — linting-quality - **observability** — analytics ## Architecture principles The principle ontology resolves the architectural principles that govern this package, which `_manifest.json` declares in `governance.principles`: - **Single Responsibility Principle (SRP)** — _Core Modular Design_ · mandatory. Reinforces Separation of Concerns, Modularity, Testability. Enables Replaceability, Reusability. Tensions with Excessive Fragmentation. Conflicts with God Object, Blob Class, Divergent Change. - **Open/Closed Principle (OCP)** — _SOLID / Object-Oriented Design_ · recommended. Reinforces Plugin Architecture, Strategy Pattern. Enables Feature Extension without Modification. Tensions with Simplicity. Conflicts with Switch-Based Extension. - **Dependency Inversion Principle (DIP)** — _SOLID / Object-Oriented Design_ · mandatory. Reinforces Low Coupling, Clean Architecture. Enables Dependency Injection, Ports and Adapters. Tensions with Runtime Indirection. Conflicts with Concrete Dependency. ## Quality governance The canonical quality catalog resolves the quality concepts that govern this package. `_manifest.json` declares them in `governedBy`, and a lint package derives them from the concepts its own rules enforce. Each maps to the custom lint rules that enforce it: - **immutability** — _best-practice_ - **separation-of-concerns** — _complexity_ - **type-safety** — _correctness_ ## Disposal - Remove `govlab.root/govlab.patterns/`. - Drop the `Validate SVG` step from `govlab.root/govlab.pipeline/core/factories/validation.factory.ts`. - Remove the `govlab.patterns` branch and the `findings` key from `project.paths/paths.yaml`. - Remove every import of `@govlab/patterns` in consumers, which are the build member's anatomy converters and the test suites. --- stable · 166 exports · 7 deps · 3 principles · 3 concepts