ιαηδαπα

platform

polyglot

Multi-platform CLI for deep codebase diagnostics. Produces a single consolidated YAML (or JSON) report that describes the languages, dependencies, frameworks, structural symbols, security posture, code quality, API routes, infrastructure, and runtime configuration of any project.

como usar

ver todas as 58 tarefas
  • task polyglot:audit.gateDeploy gate: fails when a security control is reprovado em severidade critica.
  • task polyglot:benchmarkTime every pipeline stage of a Polyglot scan for one codebase.
  • task polyglot:build.deliverablesPackage the installed specification, DSL mirror, schemas and runtime assets.
  • task polyglot:build.syntaxBuild the scanner with real source grammars for the program extractor.
  • task polyglot:codebaseRun the full maximum Polyglot diagnostic for one codebase.
  • task polyglot:contextAggregate context-level Polyglot YAML + Atlas HTML.
  • task polyglot:doctor.cgoDiagnose the native Go/C bridge independently of the full scanner build.
  • task polyglot:doctor.llamaInspect local llama-server startup and health without scanning source files.
  • task polyglot:drainEscoa a fila do scan e gera os agregados assim que todos os filhos estiverem em dia.
  • task polyglot:ecosystemWrite the ecosystem pre-flight (the web of every published service of every org) for the pages that declare it.
  • task polyglot:fixmeRegenerate the complete actionable finding queue from an existing codebase report
  • task polyglot:formatFormat the Polyglot sources maintained by the focused test gate.
  • task polyglot:generateGenerate specification, DSL mirror and organized artifact portal from an existing diagnostic. Requires INPUT.
  • task polyglot:healthStrict health report over the generated Polyglot artifacts.
  • task polyglot:iconRegenerate Windows installer and executable icons from logo/logo.png.
  • task polyglot:kbGenerate the AI KB (json/jsonl/sqlite/card/mcp) + Atlas HTML from every .polyglot under one or more folders.
  • task polyglot:lint.childrenLint Polyglot JS children.
  • task polyglot:mirrorRegenerate the real Iandara DSL mirror and linked reports. Requires INPUT.
  • task polyglot:oldestScan the codebase that has waited longest for a Polyglot scan.
  • task polyglot:orgAggregate org-level Polyglot YAML + Atlas HTML.
  • task polyglot:package.linuxBuild the Linux tarball (CLI-only; no file-manager integration).
  • task polyglot:package.windowsBuild the Windows installer with the "Polyglot it" / "Polyglot it +" Explorer menu.
  • task polyglot:platformRun the full maximum Polyglot diagnostic on the whole platform root.
  • task polyglot:projectAggregate project-level Polyglot YAML + Atlas HTML.
  • task polyglot:scanRun the full maximum Polyglot diagnostic on any folder.
  • task polyglot:scan.changedScan only the codebases that changed since their last Polyglot scan (static, no AI), a few per run, and keep going past failures.
  • task polyglot:scan.no-aiFull static scan, SAST, REA, specification, mirror and portal without local model enrichment; clears output first. Requires DIR.
  • task polyglot:scan.pendingList which codebases still owe a Polyglot scan (content fingerprint against the checkpoint), without scanning.
  • task polyglot:scan.publishCommit and push completed scan outputs and checkpoint to main (CI publication)
  • task polyglot:scan.smart.fullRun a resumable complete Polyglot scan for one org, aggregating each namespace level in order. Defaults to iandara.
  • task polyglot:scan.smart.no-aiRun a resumable static Polyglot scan for one org without local model enrichment. Defaults to iandara.
  • task polyglot:scansRefresh and show the Polyglot scan ledger (who was scanned when).
  • task polyglot:value-keyMint, once per machine, the vault key the Polyglot manifest uses to fingerprint secret values.
  • task polyglot:setup.helpVerify the standalone setup CLI loads without provisioning.
  • task polyglot:setup.preflightCheck in seconds, before downloading anything, that every pinned asset of the Polyglot setup still exists.
  • task polyglot:setup.reaProvision matching REA native controls and pinned WABT; scans remain offline.
  • task polyglot:setup.reviewProvision the offline code-review stack (engines + AI) into the per-user data dir.
  • task polyglot:smartSmart complete deep scan: find every codebase under one folder, scan each, cluster each fork.
  • task polyglot:specRegenerate specification and linked deliverables from an existing diagnostic. Requires INPUT.
  • task polyglot:testRun the Polyglot unit/regression suite without packaging or scanning a target.
  • task polyglot:test.artifactsValidate the offline REA adapter, contracts and Polyglot artifact sidecars.
  • task polyglot:test.childrenRun focused offline JS child tests without building the Go distribution.
  • task polyglot:test.deliverablesVerify the complete product deliverables gate with one package build.
  • task polyglot:test.distributionVerify the installed Go CLI and bundled deliverables outside the repository.
  • task polyglot:test.progressVerify scanner progress output and detector scheduling.
  • task polyglot:test.evidenceVerify evidence schemas, authenticated part links and focused scanner serialization regressions.
  • task polyglot:test.llamaCheck local assistant startup diagnostics and request regressions.
  • task polyglot:test.outputsVerify source extraction, specification, DSL mirror, package integrity and portal.
  • task polyglot:test.portalVerify local artifact links, hashes, Atlas overlay and mobile/desktop keyboard interaction. Requires INPUT.
  • task polyglot:test.productVerify Go orchestration and CLI command integration.
  • task polyglot:test.textVerify parser-safe comments, message values and lexical evidence associations.
  • task polyglot:validateValidate an existing Polyglot report without scanning. Requires INPUT.

documentação

Multi-platform CLI for deep codebase diagnostics. Produces a single consolidated YAML (or JSON) report that describes the languages, dependencies, frameworks, structural symbols, security posture, code quality, API routes, infrastructure, and runtime configuration of any project.

Offline artifact analysis adds REA inspections of JavaScript/CDN applications, managed assemblies, native artifacts and WASM, with authenticated evidence YAMLs and reconstruction obligations. It requires no AI model.

The Go CLI also owns deliverables generation: polyglot generate --input diagnostic.yaml --source-root ./project --output ./report rebuilds the specification, YAML capability scenarios, DSL units and portal from an existing scan. Normal positional scans run this stage after analysis. The product ships its worker under children/deliverables/dist, including schemas and homoiconic assets; it does not need this monorepo or npm at runtime. Node remains an explicit runtime dependency, following the existing children architecture.

Every product generation includes the reader-facing specification using the configured local assistant. This invariant lives in the Go generation layer shared by the CLI, Explorer and host tasks; callers do not need an extra flag. The older --narrative flag remains accepted for compatibility, while --narrative=false is rejected. spec.md and spec.html explain the acquired behavior, while md/spec-technical.md retains the static walkthrough. The Go assistant returns structured paragraphs with evidence IDs, and rejects missing or unknown references; this validates traceability, not semantic truth. Narratives are explicitly marked as inferred. Input, prompt version and model label determine reuse from the previous specification. Context omissions remain visible. If model startup or narrative validation fails, generation fails before publishing the package, without substituting the template-only specification.

Functional overview synthesis groups use cases into product capabilities. Requests use bounded evidence batches and short internal aliases; validated assignments expand back to the original use-case IDs. Larger inputs consolidate the intermediate capabilities recursively, with a finite depth and explicit failure if consolidation cannot finish. Each source use case must belong to exactly one final capability. Overview inputs include source-derived chapter summaries, identified rules and partial-coverage markers. This synthesis remains an interpretation and does not establish complete cross-feature journeys or behavioral equivalence.

Evidence IDs are scoped to each use case, including their file and line. Human-readable chapters expose the acquired input signatures and open questions alongside flows, rules, failures and coverage limits. Signature optionality is not presented as proof of runtime request validation. Cached overviews are included in the final checkpoint as well as freshly synthesized ones. The model starts lazily on the first uncached completion. When no implementation behavior was acquired, only the entry contract becomes evidence; the compiler requires an explicit limitation and rejects generated flows, rules or failures for that unavailable body.

The structured specification reuses the diagnostic's acquired facts and source-derived inputs, conditions and failures. Validated chapters and the functional overview are reused by fingerprint; the mandatory narrative stage does not require repeating inference for unchanged inputs. Focused internal renderer fixtures explicitly disable inference to verify schemas, links and mirror packaging independently; the installed-product distribution fixture instead exercises the default CLI narrative path through a test-only local endpoint.

Narrative contract v4 preserves every acquired observation in source order, including full condition text and returned object fields. Go partitions each operation into requests of at most five observations and 9000 serialized UTF-8 bytes. Every part contributes its prose to the final chapter; the chapter has no fixed five-rule ceiling. An indivisible observation or entry contract exceeding the request budget fails explicitly before inference instead of truncating expressions. The existing acquisition limits still apply: processing every acquired observation does not mean every source behavior was acquired.

Chapters distinguish observed results and returned data from state changes and external effects. Evidence sent to inference but not cited by any resulting paragraph is recorded in unexplained and displayed as an incomplete explanation in Markdown and HTML. Citation coverage is not a semantic completeness score: a citation can still accompany an incorrect or incomplete interpretation. Comments remain declared intent; unresolved calls do not establish successful external effects. REA methodology appears after the reader-facing specification.

Operation discovery combines diagnostic entries and source-level callables. HTTP routes no longer suppress exported library functions or public methods; class containers are not operations. JavaScript/TypeScript extraction records ESM visibility, including arrow exports and local export lists. Scripts and other language inventories without proven visibility retain explicitly labelled candidates. Ambiguous handlers keep an unavailable body instead of borrowing a same-line declaration. Operation identities include their module origin.

Each operation carries the input/result types and their reachable local or imported model definitions. Field optionality, aliases, base types and unresolved type bindings remain explicit. The same data structures appear in the inference evidence and the Markdown/HTML chapters; they do not establish runtime validation or persistence. Branch observations retain their true/false predicates and source locations across inference batches, including the continuation after simple guard exits. Code following unconditional exits is marked unreachable. Complex control flow remains unexpanded source syntax; this is not a complete control-flow or type checker.

The specification renders a source-derived walkthrough, rather than embedding diagnostic dumps. For JavaScript/TypeScript, handlers bind to callable declarations; calls expand through local declarations and resolved named/default imports and typed instance fields. Conditions, returns, explicit throws and source comments remain attached to their source locations. Interface injection, inheritance, dynamic dispatch and unresolved imports remain explicit boundaries; the renderer does not substitute unrelated methods with matching names. Expansion is limited to four call levels and 24 routines per entry. Complex control statements retain their source syntax. This is static reconstruction, not execution evidence or a complete semantic specification. Full inventories, hashes and translation TODOs remain in the linked YAML artifacts. Configuration values are omitted from the human-readable specification.

The mirror is a partial translation. Its reports distinguish emitted units, syntax validation, behavioral validation and equivalence. Unsupported behavior remains a localized throwing TODO; compilation alone does not establish equivalence. The generated macro.html and README.md link the organized yaml/, json/, html/, md/, ia/ artifacts.

md/fixme.md and json/fixme.json are emitted only when the scan contains actionable codebase work. The queue combines the audit fronts with source-anchored security, dependency, architecture, reliability, observability, style, schema, hardening, CI/CD and reproducibility findings. It separates scan warnings/errors from code findings, preserves full evidence and confidence in JSON, and ends with a fresh-scan step. If no codebase action exists, neither FIXME artifact is published; scan diagnostics remain in polyglot.yaml.

O que é o Polyglot — quatro leituras

O mesmo produto, contado para quatro públicos. Escolha o seu.

1. Para qualquer pessoa

O Polyglot tira um raio-X completo de um software. Você aponta para uma pasta de código — mesmo sem fazer ideia do que tem dentro — e ele devolve um dossiê que qualquer um consegue abrir no navegador: que tecnologias existem ali, do que aquilo depende, onde estão os riscos, o quanto está bem cuidado. É como um laudo de vistoria de um imóvel, mas para sistemas. Tudo acontece no seu computador: nada é enviado para a internet, e nenhum arquivo seu é alterado.

2. Para quem decide (gestão, produto, due diligence)

O Polyglot transforma qualquer base de código em um inventário auditável. Um clique (ou um comando) responde: o que temos, em que estado, com quais riscos — linguagens e frameworks, dependências e licenças, segredos expostos, qualidade e dívida técnica, rotas de API, governança e documentação. Cada conclusão carrega a evidência (arquivo e linha) que a sustenta. Três propriedades importam para o negócio: offline por design (a propriedade intelectual nunca sai da máquina), tudo-ou-nada (nunca existe um relatório parcial fingindo ser completo) e consumível por IA (o diagnóstico vira uma base de conhecimento que assistentes consultam com segurança, sem acesso ao código-fonte).

3. Para quem desenvolve

CLI em Go, binário único. polyglot --path ./projeto roda 39 detectores em paralelo (scheduler topológico) e emite um YAML canônico com tudo: linguagens (enry + hyperpolyglot), SBOM, símbolos (tree-sitter), rotas HTTP, grafo interno de módulos, segredos/vulns, complexidade, design patterns e vereditos SOLID, env vars com evidência, infra, reproducibility score. No Windows tem verbo de Explorer ("Polyglot it..."); no monorepo, task polyglot:codebase -- <nome>. Além do YAML: atlas HTML standalone (abre sem servidor), KB para agentes (card/jsonl/sqlite + servidor MCP), code review offline opt-in (--review, findings com diff sugerido — nunca aplica nada), cache incremental por Merkle e saída determinística (mesmo input, YAML byte-idêntico). Não exige git, não exige rede, não escreve no alvo.

4. Para quem arquiteta sistemas

O Polyglot é um pipeline de análise estática multi-linguagem organizado como kernel + plugins puros: cada detector implementa Detect(ctx, input) → Fragment sem estado global; um scheduler topológico resolve o DAG de Requires() e paraleliza ondas independentes; o orquestrador faz stitch determinístico dos fragments no AnalysisResult, cuja forma é um contrato versionado (JSON Schema gerado de pkg/types, com capabilities por detector explicando ok/skipped/failed). Runtimes heterogêneos entram pelo children pattern (JSON-over-stdio) com dois regimes de falha deliberados: degradação graciosa para enriquecimentos (text evidence, Veritas-KG) e all-or-nothing para o que não pode ser parcial (review engines). A camada semântica sintetiza truths em linguagem natural e as eleva a um grafo de conhecimento offline — embeddings multilíngues + NLI cross-encoder detectando entailment/contradição entre o declarado e o inferido. A agregação é bottom-up com formas agregáveis (codebase → cluster/context → project → org), fingerprints de input pulam reescritas idênticas, e a identidade é canônica cross-repo. A função objetivo da extração é reconstrução: cada seção nova responde "um gerador conseguiria reconstruir o codebase a partir disto?".

Polyglot em números

O código deste diretório mais as pontas da pipeline no monorepo (tools de atlas/namespace, KB de IA, templates, schemas, installer). Escopo excluído da conta: children/ de terceiros, testdata/, node_modules/ e target/ — com esse recorte a medição é reproduzível a qualquer momento.

Componente Linguagem Linhas
Kernel do scanner (39 detectores, scheduler, orquestrador, camada de veredito, truths, console, golyplot) Go 84.730 (22.082 de testes)
Tools de atlas/renderers, audit, geradores de namespace, children JS JavaScript/Node 17.586
Schemas dos 9 contratos (codebase, cluster, cluster-openapi, context, project, org, veritas, kb, scans) YAML (JSON Schema) 8.330
Worker Veritas-KG, text evidence, KB builder + servidor MCP Python 12.487
Templates do atlas (codebase, context, project, org + base) HTML/CSS/JS 3.579
Ponte hyperpolyglot (CGO FFI) + child de strings Rust 432
Taskfile de orquestração no monorepo YAML (go-task) 974
Installer Windows (verbos de Explorer) + gerador de ícone Inno Setup + Python 219
Total 8 linguagens ≈128.000

Tecnologias orquestradas na pipeline: go-enry (reconhece 400+ linguagens), hyperpolyglot via FFI Rust, tree-sitter (13 gramáticas nativas + fallback regex puro-Go), go-git, base OSV de vulnerabilidades, modelos HuggingFace offline (~1 GB: MiniLM multilíngue para embeddings + mDeBERTa-XNLI para NLI), SQLite (grafo de truths e KB), servidor MCP para agentes, OpenGrep e ast-grep (review offline), go-winres + Inno Setup (identidade no Windows), GoReleaser (release multi-OS) e llama.cpp + um GGUF local para a camada de IA (review e narracao pt-BR dos use-cases).

Feature Escala
Detectores em paralelo 39, ordenados por dependência, timeout individual
Linguagens reconhecidas 400+ (consenso enry × hyperpolyglot)
Análise estrutural 13 gramáticas tree-sitter + fallback universal
SBOM 9 ecossistemas de manifesto no piso puro-Go + a largura do syft por cima (.NET, Swift, Dart, Elixir, Erlang, Haskell, Conan/vcpkg…)
Heurísticas 20+ frameworks, 18+ build tools, 15+ package managers, 11 padrões arquiteturais
Qualidade complexidade com percentis, duplicação, GoF patterns, SOLID com veredito por princípio
Semântica truths declaradas × inferidas, clusters por embedding, relações NLI, conflitos promovidos
Review offline 2 engines, findings com diff sugerido (spike: 360 arquivos em 0,6–6 s)
Artefatos por codebase {polyglot,openapi,veritas}.yaml, a família de BOMs (CycloneDX 1.6), card, fixme (a fila de trabalho), statements, kb.json, kg.sqlite, mcp.json + 5 HTMLs auto-contidos: atlas (panorama), API reference (viewer próprio, não Redoc), cagüete (só os podres + contradições), norte (o caminho a seguir) e BOM (o ecossistema radial de bills-of-materials)
Agregação bottom-up: codebase → cluster (fork points) → context → project → org; o cluster ganha cluster.{polyglot,openapi,veritas}.yaml + atlas/API/cagüete próprios

A complexidade real está na orquestração: um clique no Explorer (ou task polyglot:smart -- <pasta>) dispara a descoberta de codebases (manifesto forte, contêiner ≠ codebase, vendor nunca entra); cada codebase passa pelas ondas paralelas dos 39 detectores; os fragments são costurados num YAML validado por schema; as truths sobem para o worker Python que roda dois modelos de linguagem sem rede; o builder de KB deriva card, statements, sqlite e servidor MCP; o template engine renderiza um atlas HTML auto-contido (abre de file://, sem servidor); e toda pasta com mais de um codebase (um fork point) ganha o roll-up: o chef agrega cluster.polyglot.yaml (totais, médias ponderadas, distribuições, rollup de segurança/licença + as contradições entre children que nenhum scan isolado enxerga, achadas por um passe NLI sobre as truths unidas dos membros) mais cluster.{openapi,veritas}.yaml, e as cinco páginas do cluster (atlas panorama, API reference, cagüete, norte e BOM) só servem esses YAMLs — nenhum HTML deriva dado. Do clique ao dossiê navegável, cruzando 4 runtimes (Go, Rust, Python, Node), com saída determinística e nenhum byte saindo da máquina.

Features

  • Language intelligence via go-enry, optional hyperpolyglot (Rust, CGO), and file-level consensus.
  • SBOM generation — pure-Go manifest parser for npm, pip, go modules, cargo, maven, composer, bundler, poetry, pipenv, plus a mature engine layer: one syft pass yields both halves of what it sees. It reads the per-package licenses the manifest parser cannot resolve (in sbom.license_engine), unblocking the legal-risk join (a copyleft dependency in a closed product, a dependency with no declared license); and it catalogues the ecosystems the floor cannot parse at all — .NET/NuGet, Swift/CocoaPods, Dart, Elixir, Erlang, Haskell, Conan/vcpkg — which enter sbom.artifacts marked source: syft with syft's authoritative purl. The two layers stay disjoint on purpose: the floor owns the ecosystems it parses (deterministic, anchored to file:line), the engine fills only what the floor is blind to, so nothing is counted twice and the declared-vs-installed line never blurs.
  • Structural analysis via tree-sitter with a pure-Go regex fallback (13 languages).
  • Heuristics — 20+ frameworks, 18+ build tools, 15+ package managers, 11 architectural patterns.
  • Language-version detection — 7 runtimes (Node.js, Python, Go, Rust, Java, Ruby, PHP).
  • Cloud & database detection — 9 cloud providers, 10 database technologies.
  • Security posture — secret scanning (a native regex+entropy floor plus a mature engine layer: gitleaks' full curated ruleset over the working tree, in security.secret_engine, its findings joining the floor's on the shared value_hash), vulnerability matching (OSV), lockfile integrity, auth-pattern detection, supply-chain signals.
  • Code quality — cyclomatic complexity (with percentile stats), code duplication, test intelligence, observability readiness, GoF design patterns, SOLID principles with per-principle verdicts (adherence signals × violation strategies).
  • Code review (opt-in, all-or-nothing) — offline review engines (OpenGrep, ast-grep) run over the explicit first-party file list; normalized SARIF-like findings with suggested fixes captured as diffs (never applied). Enabled with --review.
  • Ignored receipt — every directory the walkers never entered and every file excluded as third-party, with the rule that excluded it. No git repository is ever required — this section makes the ignore contract auditable.
  • Data layer — ORM entities/fields and migration scripts reconstructed statically.
  • Git intelligence — recent version-control history scoped to the codebase (monorepo-aware), when a repository is present.
  • Internal dependency graph — module fan-in/fan-out, circular dependency detection, entry-point inventory.
  • External dependencies — HTTP endpoints, env-var references, API contracts (OpenAPI/gRPC/GraphQL/AsyncAPI), cloud resources, messaging channels, identity providers, observability sinks.
  • Governance — CODEOWNERS, license detection, ADR parsing, docs health, Markdown corpus.
  • AI assets — model files, prompt files, vector-store integrations, LLM clients, dataset files.
  • Naming conventions — identifier case-style distribution across source files, with per-language breakdown, plus a code_style verdict (community convention by kind) with a formatting engine layer: editorconfig-checker (in code_style.formatting_engine) judges the whitespace axis (indent, trailing whitespace, final newline, charset, max line) against the repo's own .editorconfig.
  • API routes — HTTP route inventory extracted from framework route registrations (method, path, handler, auth hint).
  • Infrastructure — Dockerfile / docker-compose / CI-CD pipeline / Kubernetes / IaC signals, plus a two-tier hardening verdict: a native curated floor (root user, :latest, literal secret in ENV, no HEALTHCHECK, privileged port/container, host network — zero provisioning, anchored to file:line) and, on top of it, a mature engine layer (hadolint's full DL#### Dockerfile ruleset and trivy's whole misconfig bundle over Dockerfile/compose/Kubernetes/Terraform/CloudFormation — the k8s and IaC breadth the floor cannot reach), each resolved from the offline review-bin (trivy air-gapped via the embedded checks bundle) and reported with a status so the gap is never silent.
  • Runtime config — environment-variable schema, config-file inventory.
  • Scaffold detection — generator/template identification, bootstrap commands.
  • File inventory — reconstruction-oriented file map with role, language, hashes, size, and generated/test flags.
  • Reproducibility score — 0-1 completeness score for recreating the codebase from scratch.
  • OWASP Top 10:2025 checklist — the ten categories answered from what the scan already extracts, each fail carrying concrete file:line evidence. The injection family, path traversal/SSRF and unsafe deserialization are answered by the proven taint paths rather than by a name match, so a finding marked proven means dataflow walked the whole way from user input to the sink; when a lexical match and a proven path point at the same line, the weaker one is dropped so one defect is never counted twice. Honest by construction: static analysis proves a hole, never blindness — a clean category reads "no hole detected", one with no surface reads "no surface", and an engine that did not run is never read as "nothing found", never a false "passed".
  • Logging intelligence — the log call-site inventory (which loggers, how many, at what levels, which mechanisms) plus everything that is not good: useless/placeholder messages, duplicated messages, logs with no static message, unstructured console/print output, error handlers that swallow or never log, logs written at the wrong level (a severe logger carrying a success/lifecycle message with no failure token), and system boundaries whose handler never logs — HTTP routes and the background edges alike: a scheduled job or a queue consumer that fails in production without leaving a trace is the same hole, and it is judged by the same rule (a container routine with known bounds must be found before any claim is made).
  • Algorithms & complexity — an estimated Big-O per routine (own loop/recursion structure; an opaque call lowers confidence instead of erasing the bound), 43 classic algorithms recognised by structure (the name only corroborates, and it never decides alone), in-loop performance smells (N+1, serial await, recompiled regex, string concat) and the canonical×estimated cross-check. On top of the routine's own structure, the Code Property Graph refines the bound where dispatch hid it: an inherited or field-dispatched callee that the lexical and AST passes read as opaque resolves to its real declaration, and because the graph carries the line of the call, the callee's own measured cost is multiplied by the loop depth at that call site — an O(n) helper called once is O(n), the same helper called inside one variable loop is O(n²), proven instead of surrendered to unknown. That layer only ever refines: a callee whose own bound is unknown adds a named caveat rather than dragging the caller down, and a routine whose own structure yielded no bound keeps unknown. Labelled an estimate, never a formal proof — unanalysable structure yields unknown, never a wrong O().
  • Cryptographic inventory (CBOM) — every primitive with the one flag that matters for a sovereign-identity platform: quantum-vulnerable (RSA/ECC/DH, Shor-breakable) vs PQC-safe (ML-KEM/ML-DSA), plus the broken/obsolete ones (MD5/SHA-1/DES/RC4).
  • CI/CD audit — the offline governance subset over GitHub Actions / Jenkins / GitLab / Azure / Bitbucket / CircleCI: unpinned actions and images, over-broad permissions, the pull_request_target injection combo, credentials written into the workflow (redacted), and the missing test / dependency-scan / SECURITY.md.
  • Dead code — oversized files, unreferenced modules, unused declarations and unused parameters, as a zero-provisioning floor with mature engines layered on top: vulture for Python and knip for JS/TS, which resolves the whole project graph and so catches what the floor cannot — an import island whose modules reference only each other and are reachable from no entry point.
  • Code Property Graph — the layers no lexical or per-file pass can produce, harvested from Joern in a single invocation: a call graph with resolved dispatch (a field or interface call the lexical pass reads as opaque resolves to its real callee), the type hierarchy, control structures read off the AST, declarative annotations with their literal argument (a framework mapping carries the route path; a parameter annotation marks it user-controlled), and proven taint paths — a source-to-sink flow with every hop anchored, crossing method boundaries. That last one is what turns a lexical injection pista into evidence, and it is multi-language by construction: every ecosystem marks user input differently, so three source strategies run side by side — an annotated parameter (Spring/JAX-RS), a parameter typed as the request object (Go's *http.Request), and a known input accessor (req.query, request.args) — with each proven path recording which one found it. Seven classes are covered (SQL, command and code injection, path traversal, SSRF, deserialization, XSS), and two rules keep them honest against real framework code: a value that travelled through an argument other than the first went in through the bound-parameter channel — which is what parameterisation is — and a real injection builds the value into the command string, which a bound parameter never touches. A sanitizer found on the path labels the finding rather than deleting it, because dropping it would trade a false positive for a false negative. Where dataflow stops, the layer says so instead of going quiet: a value written into an object's field in one method and read back in another — the DTO/entity shape that dominates enterprise code — is where the engine's heap reasoning ends, so the two halves it can prove are linked by the field they share (the input reaches the field write; a read of that same field reaches the sink) and reported as a lower tier, link: object-field, carrying both anchors. Three tiers, each named for what it is: a proven end-to-end path, a field-linked finding whose halves are proven and whose heap link is inferred, and a pista where a command is built dynamically but no path reached it. Read the result the way static analysis actually works: a reported flow is evidence of a defect, but the absence of one is not evidence of safety — silence here means "nothing was proven", never "nothing is there".
  • Schema coverage — every YAML/JSON data file classified against the schemas that reach it, then validated in cascade: orphans (no schema), invalid data (breaks its own schema) and invalid schemas (won't compile / duplicate id).
  • Use cases — one reverse-engineered case per system boundary with its real call chain: every HTTP route, plus each non-HTTP entry point (a scheduled job, a queue consumer), which carries a trigger instead of a method/path and names the actor that fires it — a scheduler or a broker rather than a client. A codebase that is purely a background worker still has a use-case anatomy. Each case is given a friendly pt-BR title and narrated steps by the local model (identifiers are never translated; an echo of the code is rejected).
  • Family of BOMs — the whole CycloneDX 1.6 family derived from the same scan (SBOM, CBOM, LBOM, SaaSBOM, ML-BOM, ABOM, DBOM, OBOM, ConfigBOM, IBOM) tied together by a System BOM hub via BOM-Link. See Sidecar artifacts.
  • Multi-target mode — analyze multiple codebases in one pass and write an aggregate.yaml summary.
  • Structured diagnostics — per-detector severity-tagged messages replace the flat errors list.
  • Single static binary — no runtime dependencies.

Install

Linux (tarball, CLI-only)

task polyglot:package.linux builds dist/polyglot_<version>_linux_amd64.tar.gz — the maximum CGO scanner, golyplot, the interactive console, the native library and the children. The Linux side has no file-manager integration: everything is a command.

tar -xzf polyglot_*_linux_amd64.tar.gz && cd polyglot_*_linux_amd64
./install.sh                    # ~/.local/opt/polyglot + symlinks in ~/.local/bin
./install.sh --prefix /usr/local  # system-wide (needs sudo)
polyglot-console                # start here

The build itself runs inside a container (installer/linux/Dockerfile): CGO does not cross-compile from Windows without two cross toolchains, so the Linux binary is built natively there.

Pre-built binary

curl -fsSL https://github.com/iandara-solutions/polyglot/releases/latest/download/polyglot_linux_amd64.tar.gz | tar -xz
./polyglot --version

From source in this monorepo (all-or-nothing setup)

Inside the monorepo, the setup is not a separate task: the two public tasks — task polyglot:codebase -- <name> and task polyglot:all — install and verify every dependency before scanning (Go, Rust + GNU target, MSYS2/MinGW toolchain via pacman on Windows, Python + the Veritas-KG virtualenv and models), then build the full CGO scanner. If any dependency cannot be installed the task fails with the cause; there is no partial or degraded mode.

For standalone development of the CLI itself, use the Makefile inside .platform/polyglot/ (make build, make build-nocgo, make test).

Console (polyglot-console) — scan a workspace, then ask about it

A terminal with two features and three steps. It accumulates: every workspace you feed it stays registered and queryable in later sessions, so today's monorepo and tomorrow's are answered from the same index. Everything runs locally — only the first run downloads (the venv, the NLI models, and any runtime the hermetic store can provision).

  1. Boot — checks every dependency, resolves what it can, downloads what is missing, then waits for a workspace.
  2. Scan — the deep pipeline over the whole tree (discover → scan each codebase → build its KB), writing .polyglot/ artifacts in place. The Atlas HTML is skipped on purpose: the consumer here is the model. Each codebase becomes queryable the moment it finishes, so you can ask while the scan is still running.
  3. Chat — question/answer over everything indexed, with live vitals (context fill, average answer time, tokens/s).
polyglot-console                 # interactive: the three steps
polyglot-console scan <folder>   # just the deep scan of one workspace
polyglot-console ask '<question>'  # one question, no terminal

Inside the terminal: /scan <folder> (runs in background — the chat stays open), /workspaces, /status, /ajuda, /sair. Anything else is a question.

Answers are grounded by construction: a mechanical retrieval picks which briefs the model sees, a panorama of the whole index always travels with the question, and the reply is grammar-constrained JSON. The model narrates what the diagnostic proved — it never invents a route, a version or a dependency. Without a provisioned local model the console refuses to answer instead of guessing.

The model is plug-and-play: drop a different .gguf in <DataDir>/review-llm/ or point POLYGLOT_LLAMA_MODEL at one.

It narrates everything, and it adapts to the machine

Nothing happens silently — not a success, not a failure, not an automatic choice. The console says which dependency resolved and where, what it is downloading and how long that will take, which codebase just became queryable, and which strategy it is trying.

The context window is a measured ladder, not a constant: strategies are ordered best-first, the top one the hardware can hold is chosen, and the rest stay as runtime fallbacks. Nothing is deleted because today's card is small — the same build climbs when the machine improves.

Hardware medido: GPU NVIDIA com 6144 MiB de VRAM

Estrategia 1/4: gpu-wide (16384 tokens de contexto)
  medido: 90,7s numa 2060 de 6 GB (VRAM insuficiente: camadas sobraram na CPU)
  ↷ pulada: exige 10240 MiB de VRAM e a maquina tem 6144

Estrategia 2/4: gpu-fit (8192 tokens de contexto)
  medido: 17,7s na 2060 de 6 GB — 5x mais rapido que gpu-wide
  → subindo o modelo (qwen2.5-coder-7b-instruct-q5_k_m.gguf)...
  ✓ no ar em 5s — estrategia gpu-fit ativa

The chat model is provisioned on first use — the console downloads the right llama-server for the machine and narrates it. The GPU build is chosen per platform: CUDA on Windows, Vulkan on Linux (llama.cpp ships no prebuilt CUDA for Linux), CPU otherwise. The server only gets --n-gpu-layers when the GPU backend is actually next to the binary — passing it to a CPU-only build is silently ignored, which would fake an acceleration that never happened. Measured on the reference machine: the same question went from timing out on CPU to 4,2s at 20,8 tok/s with the CUDA offload.

On Linux the server needs libgomp1 (OpenMP) — present on every desktop, but not on a minimal image; install.sh checks for it and tells you the one-line install for your distro.

Overrides, all optional: POLYGLOT_LLAMA_CTX (pins the window), POLYGLOT_LLAMA_GPU_LAYERS (0 forces CPU), POLYGLOT_LLAMA_VARIANT (cpu/cuda), POLYGLOT_LLAMA_TIMEOUT (seconds per request).

Usage

# Analyze current directory
polyglot

# Analyze a specific project
polyglot --path ./my-project --output report.yaml

# Stream YAML to stdout
polyglot --path ./my-project --output - | yq '.summary'

# JSON output
polyglot --path ./my-project --format json --output - | jq '.summary'

# Fail CI on any detected secret or more than 5 unpinned dependencies
polyglot --fail-on secrets --fail-on unpinned:5

# Multi-target: analyze three services and write per-service reports + aggregate
polyglot --path ./api,./worker,./frontend --output ./reports/

# Incremental run with a local cache
polyglot --path ./my-project --cache .polyglot-cache

# Offline code review (requires the engines; fails loudly if any is missing)
polyglot --path ./my-project --review

Monorepo tasks

O diagnostico e tudo-ou-nada; as tasks que escaneiam sao estas:

task polyglot:codebase -- <codebase>   # diagnostico maximo de um codebase (setup + scan c/ Veritas-KG + validate + atlas + fixme)
task polyglot:scan.no-ai DIR=<pasta>  # scan estático completo com SAST e REA; limpa .generated/polyglot; sem modelos de IA
task polyglot:scan.smart.full         # varredura retomável por org, codebase -> context -> project -> org (IA local)
task polyglot:scan.smart.no-ai        # mesmo pipeline retomável, sem enriquecimento por modelos locais
task polyglot:all                      # diagnostico maximo do monorepo inteiro (scan + contexts/projects/orgs + validate + testes + atlas + health)
task polyglot:platform                 # UM scan sobre a raiz inteira — o que so existe ENTRE os codebases e fora deles
task polyglot:oldest                   # escaneia o codebase que espera ha mais tempo (a fila, sem ninguem escolher)

E estas apenas leem o que ja foi escrito — nao rodam motor nenhum:

task polyglot:audit -- <codebase>|all  # tudo que falta fazer, nove frentes, pior primeiro
task polyglot:audit.gate -- <codebase> # a decisao no lugar da narrativa: sai 1 se reprovou critico em seguranca
task polyglot:scans                    # o livro de datas: quem foi escaneado quando, e quem esta na frente da fila

As tasks máximas provisionam Go, Rust, toolchain C e Python; all e codebase também habilitam Veritas-KG, revisão por IA local e narração dos casos de uso. task polyglot:scan.no-ai DIR=<pasta> oferece o pipeline estático completo com SAST, REA, spec estática, mirror e portal; desativa sugestões de IA no review, narração e Veritas-KG. Não baixa llama.cpp nem pesos de modelo e limpa todos os arquivos e subpastas de <DIR>/.generated/polyglot antes do scan. Pode-se informar OUTPUT_DIR=<pasta chamada polyglot> dentro do projeto. A geração importa o relatório recém-criado e publica o pacote final nessa mesma pasta. As tasks polyglot:scan.smart.full e polyglot:scan.smart.no-ai percorrem um org por vez (por padrão iandara), na ordem codebase → context → project → org. Cada codebase concluído é registrado em .generated/polyglot-scan-smart/<org>/<modo>.json; ao interromper, a próxima chamada valida os checkpoints e retoma no primeiro pendente. Quando a volta termina, a próxima chamada começa novamente pelo primeiro codebase. ORG=<org> troca a organização-alvo. Cada nível agrega seu YAML e gera seu Atlas somente depois que os filhos daquele nível concluíram. Utilitarios de debug (diff, health avulso) continuam disponiveis como scripts em .platform/tools/polyglot/.

Os geradores de namespace sao deterministicos e incrementais; task polyglot:all roda a agregacao com --force para reescrever os YAMLs mesmo sem mudanca de fingerprint.

Flags

Flag Description Default
--path Project directory or comma-separated list .
--output Output file / directory (- for stdout) ./manifest.yaml
--format Output format: yaml | json yaml
--cache Cache directory for incremental runs (none)
--truth-kg Veritas-KG truth enrichment: semantic clusters, NLI relations, conflicts + *.veritas.yaml (same as POLYGLOT_TRUTH_KG=1) false
--review code_review section via offline engines (OpenGrep + ast-grep) over the explicit first-party file list (same as POLYGLOT_REVIEW=1). All-or-nothing: the scan fails if any engine is missing false
--skip-dir Directory basename the walkers must never enter, on top of the canonical skip list (repeatable / comma-separated) (none)
--fail-on Exit 2 when signal exceeds threshold (repeatable) (none)
--verbose Verbose logs false
--quiet Errors only (also disables progress) false
--progress Phase milestones on stderr (self-rewriting X/Y detector line in a terminal; files, Veritas-KG child + per-batch heartbeat). Auto-on in a terminal unless --verbose; this flag forces it on when stderr is redirected (auto: on in a TTY)
--version Show version and exit
--help Show help and exit

--fail-on signals

Signal Meaning
secrets Any secret detected
unpinned[:N] Unpinned dependency count >= N (default 1)
high-vulns[:N] High/critical vulnerability count >= N (default 1)
cycles[:N] Circular dependency count >= N (default 1)
lockfile Any ecosystem missing a lockfile
unschemed[:N] YAML/JSON data files no schema reaches (orphans) >= N (default 1)
invalid-data[:N] Data files violating their own declared schema >= N (default 1)
invalid-schema[:N] Schemas that fail to compile or duplicate an id >= N (default 1)
architecture[:N] Architectural-policy violations >= N (default 1) — "who may talk to whom" judged over the proven graph (layer rules, frontend-no-db, forbidden edges/packages); policy = embedded default + architecture: key of the policy.yaml next to the artifacts

Exit codes

Code Meaning
0 Analysis completed without issues
1 Analysis error (internal failure or invalid path)
2 CI gate triggered by --fail-on

The five pages — each answers one question

Every page is self-contained (opens from file://, no server, zero CDN, no external reference) and is a pure view: the chef chewed the answer once into the YAML/KB, the page only serves it. Nothing is derived in HTML, and no two pages repeat the same information — whatever has its own page becomes a link elsewhere. All five cross-link to each other.

Page Question it answers Emitted as
Atlas What IS this? — the panorama: languages, structure, dependencies, routes, quality, tabs per domain <level>.atlas.html
API reference What is the contract? — Polyglot's own viewer over the reverse-engineered OpenAPI, with an honest coverage meter <level>.api.html
Cagüete What is WRONG? — only the rot: risks, secrets, vulnerabilities, smells, dead code/config, proven contradictions, and the OWASP Top 10 headline. Nothing that is fine appears <level>.caguete.html
Norte What do I DO? — the radial map of diagnostic domains, each card opening a checklist saying what is wrong, why, how to fix it and where <level>.norte.html
BOM What is it MADE OF? — the radial BOM ecosystem: the System BOM at the centre, every BOM of the family on a spoke, demystifying the acronym and linking its document <level>.bom.html

<level> is codebase or cluster — a fork point (a folder holding more than one codebase) gets the same five pages over the aggregated artifacts.

Sidecar artifacts

Written next to the manifest (<base>.polyglot.yaml); each exists only when its source facts do. Every one is a pure projection of the finished scan — a serializer reads the manifest and writes the market-standard document, never a second detection and never a reshape of the manifest itself.

Artifact What it is
<base>.openapi.yaml OpenAPI 3.2 contract reverse-engineered from the implemented routes
models/*.yaml Model YAML (table.v1 / dynamodb.v1) reverse-engineered from the data layer
<base>.vex.json OpenVEX: per-CVE exploitability against the real import surface
<base>.catalog-info.yaml Backstage Component derived from identity/governance/contracts
<base>.veritas.yaml Truth knowledge graph (with --truth-kg)
<base>.attestation.json Output seal: in-toto Statement hashing every artifact above; signed into a DSSE envelope (Ed25519) when POLYGLOT_SIGN_KEY points at a PKCS#8 PEM key — key present and broken fails the scan with the cause

The family of BOMs (CycloneDX 1.6)

CycloneDX formalizes a whole family of Bills of Materials, each describing one facet of the software. The Polyglot serializes the ones it has material for as sidecars, every one BOM-Linked back to the root SBOM (urn:cdx:<serial>/1) so the set reads as one linked dossier, and every one sealed by the attestation above. Absent material yields no sidecar (never an empty BOM).

Artifact BOM What it inventories CycloneDX construct
<base>.cyclonedx.json SBOM dependencies / components components (per-ecosystem purls)
<base>.cbom.json CBOM cryptographic primitives + quantum-vulnerability cryptographic-asset + cryptoProperties
<base>.lbom.json LBOM dependency licenses (legal attention) components + licenses
<base>.saasbom.json SaaSBOM external services the app talks to (HTTP / brokers / IdPs / cloud) services[] (endpoints, data flow, auth)
<base>.mlbom.json ML-BOM local ML artifacts (model weights, shipped datasets) machine-learning-model + data
<base>.abom.json ABOM the AI/agent surface that crosses the boundary: LLM providers, vector stores, shipped prompts services[] + data
<base>.dbom.json DBOM reconstructed tables + PII columns (LGPD/GDPR pista) data + data-classification
<base>.obom.json OBOM CI/CD platforms + delivery posture application + properties
<base>.configbom.json ConfigBOM configuration surface (sources, environments, secret/unused counts — never a value) data
<base>.ibom.json IBOM declared infrastructure (container images, compose services) container + application
<base>.systembom.json System BOM the hub — inventories nothing of its own; BOM-Links every member above into one ecosystem externalReferences (BOM-Link)

The manifest records what was emitted in its own boms[] section (kind, file, serial, item count), built in the same pass that writes the files — so the inventory and the documents can never disagree, the attestation seals the family from that list, and the radial bom.html page serves it without re-reading a single sidecar.

Out of scope by nature: HBOM/FBOM/MBOM (hardware/factory) and a Runtime SBOM (would require observing execution — the Polyglot never runs the target). The KBOM (knowledge) is subsumed: the AI assets are serialized in the ML-BOM/ABOM, and the truth graph lives in <base>.veritas.yaml.

A camada de veredito — de achados para "o que falta fazer"

Uma lista de achados não responde a única pergunta que importa antes de subir: sobrou alguma coisa? Ela lê igual quando o codebase está são e quando nada foi verificado. Por isso o scan termina com um passo que não detecta nada — ele julga o que os detectores concluíram.

27 controles fixos, de quatro catálogos (OWASP Top 10:2025, OWASP API Top 10, OWASP Top 10 for LLM Applications, e a família de fronteira de identidade), cada um respondido com quatro estados:

Estado Significa
pass avaliado e satisfeito
fail avaliado e violado
not_applicable o codebase não tem essa superfície (uma biblioteca não reprova pergunta sobre rota)
unknown o fato necessário não foi produzido por este scan

unknown nunca é arredondado. Nem para pass — que faria detector faltando virar atestado de saúde — nem para fail — que faria buraco do scanner virar incidente. O controle continua no catálogo, com a razão.

O mesmo princípio governa o sink_kinds do CPG: o harvest declara o que procurou, não só o que achou. Sem isso, um codebase limpo e um motor que não olha aquela classe seriam indistinguíveis.

A camada roda por último, depois de todos os estágios que produzem evidência — inclusive o CPG. Um veredito perguntado antes da resposta chegar sai unknown sobre um scan que tinha o fato, e nada quebra ao fazer isso: é o modo de falha que os quatro estados existem para impedir, e está fixado por teste de ordem.

O filtro de origem

Detector que lê os bytes de um arquivo carimba o achado como first_party ou third_party. Um bundler concatena uma árvore de dependências num arquivo só — ser gigante é o que um bundle é; um minificador transforma catch(e) { log(e) } em catch(e){}. Achados assim são propriedade do build, não do trabalho de alguém.

Eles continuam no relatório (artefato embarcado é embarcado), mas não decidem veredito: a contagem vendorada aparece na frase, e a decisão sai do código autoral. Apontar refatoração para arquivo que ninguém edita é como se ensina uma pessoa a ignorar relatório.

O audit — nove frentes, uma fila

task polyglot:audit -- <codebase> lê o manifesto inteiro e imprime tudo que falta, na ordem em que uma pessoa age:

Frente O que traz
Segurança os 27 controles, com o que barra deploy
Code review achados do SAST, agrupados por regra
Algoritmos rotinas superlineares e smells de laço (await/regex/concat)
Complexidade funções densas demais para revisar ou testar
Design violações SOLID e oportunidades de refatoração
Duplicação blocos repetidos, por cluster
Código morto arquivos sem referência, parâmetros não usados
Tamanho arquivos acima do limite de linhas
Testes ausência de teste ou de cobertura

Ele não calcula nada: cada veredito foi decidido por um motor durante o scan e escrito no YAML. Por isso o terminal, o --json, o fixme.md e o portão de deploy não têm como discordar entre si.

Quando não sobra nada: Nothing to do here :) — e só quando todas as frentes rodaram. Fila vazia com frente não avaliada é declarada como lista incompleta, nunca como boa notícia.

Ele também confere o frescor: se o manifesto é mais velho que as fontes, diz quantos arquivos mudaram desde o scan. Só reporta defasagem, nunca frescor — mtime anda sem o arquivo mudar, e afirmar "está atual" seria o mesmo erro de ler silêncio como saúde.

O portão de deploy

task workspace:namespaces.gate -- <codebase> valida o namespace e depois consulta o veredito. Sai com 1 quando um controle de segurança reprovou em severidade crítica.

Só segurança barra, e por enquanto só o crítico. Uma rotina cúbica e um arquivo de 900 linhas são trabalho real, mas subir com eles é escolha do time; subir com credencial em claro não é. E high fica de fora enquanto seu backlog não foi trabalhado — um portão que ninguém consegue passar é burlado uma vez e depois para sempre. A regra vive num lugar só (internal/posture.Blocking); todo consumidor lê a mesma decisão.

A fila de trabalho — fixme.md e fixme.json

Os dois arquivos só são publicados quando há uma ação concreta para o codebase. Se não há correção ou melhoria identificada, o gerador remove saídas antigas e não cria uma fila vazia. Avisos de execução e frentes sem veredito continuam no polyglot.yaml; eles não são apresentados como defeitos do código.

Quando existe trabalho, o Markdown prioriza as ações para leitura humana e de agentes: cada item traz origem, evidência, motivo, recomendação e confiança quando o detector a fornece. O JSON mantém os mesmos itens com todos os locais, IDs estáveis, lacunas de cobertura e avisos do scan. Recomendações que dependem de contexto são marcadas para verificação antes de qualquer alteração. O último passo da fila é sempre Re-scan the codebase, para confirmar as correções e atualizar o diagnóstico.

A fila é derivada do relatório e dos detectores; não deve ser editada à mão.

O ciclo contínuo

task polyglot:oldest varre o workspace, escolhe o codebase que espera há mais tempo e escaneia. O livro .generated/polyglot-scans.yaml guarda as datas — lidas da attestation que o scanner assina, não do mtime, que um checkout ou uma cópia reescrevem sem scan nenhum ter acontecido.

O livro é derivado: apagar a saída de um codebase o faz voltar a ler nunca e ir para a frente da fila. Um único campo é lembrado, attempted_at, porque um scan morto no meio não deixa nada em disco — sem ele, um codebase grande sempre interrompido seria escolhido para sempre e todos os outros passariam fome.

Ligado ao runner de ociosidade (orgs/.manifests/idle.yaml), o efeito é que a máquina parada mantém os manifestos atualizados sozinha, um codebase por janela.

Everything a scan writes

Two levels emit artifacts, and they emit different sets — not the same list with a different prefix. A codebase is scanned, so it gets the raw diagnostic plus every document derived from it. A cluster (a fork point: a folder holding more than one codebase) is aggregated from the children that were already scanned, so it gets the roll-up and the pages — never a second detection.

Everything lands in <level>/.generated/polyglot/. Nothing is written into the analysed source tree.

Codebase level — codebase.*

File Type What is in it What it is for / who consumes it
polyglot.yaml YAML (JSON Schema) The whole diagnostic: every detector section, capabilities per detector, truths, boms[], and security_controls — the verdict layer The source of truth. Every other file here is derived from it; schema-validated, byte-deterministic
openapi.yaml YAML (OpenAPI 3.2) The route contract reverse-engineered from the implemented handlers The API reference page; client generators, gateways, contract diffing
veritas.yaml YAML Truth knowledge graph: semantic clusters, NLI relations, per-statement embedding vectors Contradiction detection (declared × inferred); the KB
models/*.yaml YAML (table.v1 / dynamodb.v1) One reconstructed entity/table per file: columns, FKs, indexes, PII hints Code generation and DDL — the data layer read back as a spec
vex.json JSON (OpenVEX) Per-CVE exploitability judged against the real import surface Vulnerability triage: separates "present" from "actually reachable"
catalog-info.yaml YAML (Backstage) Component descriptor from identity, governance and contracts A developer portal (Backstage catalog)
cyclonedx.json JSON (CycloneDX 1.6) The SBOM: dependencies as components with purls Supply-chain tooling; the root every other BOM links back to
codebase.{cbom,lbom,saasbom,mlbom,abom,dbom,obom,configbom,ibom}.json JSON (CycloneDX 1.6) One facet each — crypto, licenses, external services, ML artifacts, AI surface, data/PII, CI/CD, config shape, infrastructure Each answers one compliance/audit question; all BOM-Linked to the SBOM (see The family of BOMs)
systembom.json JSON (CycloneDX 1.6) The hub: inventories nothing, BOM-Links every member emitted Entry point of the BOM ecosystem; what bom.html draws
attestation.json JSON (in-toto + DSSE) A hash of every artifact above, signed when a key is provided Supply-chain verification: proves these outputs came from that input
fixme.md Markdown Human-readable queue of actionable code findings and recommendations; omitted when empty Agents/LLMs and people — prioritized actions with evidence, rationale and suggested next step
fixme.json JSON Agent contract mirroring the queue with stable IDs, complete evidence, confidence, scan notices and coverage gaps; omitted when empty Agents/LLMs and tooling — reliable issue ingestion and tracking
card.md Markdown The chewed summary: what this codebase is, its risks, its posture Agents/LLMs — the "ready plate"; the console and MCP serve it
statements.jsonl JSONL One truth statement per line, with evidence refs Retrieval (one record per unit); grep-able truth corpus
kb.json JSON The KB document: sections, derived risks, compliance, OWASP block, recommendations The console, the MCP server, the cagüete and norte pages
kg.sqlite SQLite Truth graph and code graph (symbols, calls, route handlers) Queryable retrieval for agents — joins the two graphs without re-deriving
mcp.json JSON A ready-to-paste MCP server configuration pointing at this KB Plugging the diagnostic into an MCP client (agent tooling)
atlas.html HTML (self-contained) The panorama, tabs per domain What IS this? — opens from file://, zero CDN
api.html HTML (self-contained) The contract viewer with an honest coverage meter What is the contract?
caguete.html HTML (self-contained) Only the rot + the OWASP Top 10 headline What is WRONG?
norte.html HTML (self-contained) Radial checklist: what is wrong, why, how to fix, where What do I DO?
bom.html HTML (self-contained) The radial BOM ecosystem, demystifying each acronym What is it MADE OF?

Cluster level — cluster.*

A cluster aggregates; it never re-scans. So there is no SBOM/VEX/attestation/model here — those describe a scanned unit. What the cluster owns is the roll-up and the cross-child findings no single scan can see.

File Type What is in it What it is for / who consumes it
cluster.polyglot.yaml YAML (JSON Schema) The roll-up: totals, weighted averages, distributions, members[] with each child's risks and code style, security/licence/CBOM/CI-CD/logging aggregates, boms inventory across children The source of truth for the fork point; the cluster pages serve only this
cluster.openapi.yaml YAML (OpenAPI 3.2) The union of the children's contracts — the whole surface of the group The cluster API reference; "what does this set of services expose?"
cluster.veritas.yaml YAML The joined truth graph of the members Contradictions between children — the finding no isolated scan can produce
cluster.card.md Markdown The chewed summary of the group Agents/LLMs asking about the group rather than one service
cluster.statements.jsonl JSONL The members' truths, unified Retrieval across the group
cluster.kb.json JSON The group KB: aggregates, roll-up risks, compliance, cross-child contradictions The console, the MCP server, the cluster cagüete and norte
cluster.kg.sqlite SQLite The unified truth graph of the group Queryable retrieval spanning the members
cluster.mcp.json JSON MCP server configuration for the group KB Agent tooling pointed at the fork point
cluster.atlas.html HTML (self-contained) Group panorama: members, distributions, majority code style What IS this set?
cluster.api.html HTML (self-contained) The group's whole route surface What does the group expose?
cluster.caguete.html HTML (self-contained) The group's rot, naming which member and where Which child is the problem?
cluster.norte.html HTML (self-contained) The group's checklist What do we fix first?
cluster.bom.html HTML (self-contained) The BOM ecosystem rolled up across children — each spoke names its contributors, heaviest first, with each one's share of the whole What is the group made of, and which child carries it? — a count says "5 codebases"; this says which service holds the crypto and which one drags the dependency weight

The same shapes repeat one level up (context.*, project.*, org.*) — the aggregation is bottom-up and the artifacts are aggregable by construction, so a context reads exactly like a cluster of clusters.

Example output

codebase: /home/user/meu-projeto
blueprint_version: polyglot.blueprint.v1
summary:
  primary_language: TypeScript
  languages: [TypeScript, JavaScript, CSS]
  language_detector: enry+hyperpolyglot
  language_profile: {TypeScript: 46.6, JavaScript: 37.8, CSS: 15.6}
  framework: Next.js
  build_tool: Vite
  package_manager: npm
  version: "2.4.1"
  description: Customer-facing storefront
  domain: ecommerce
  port: 3000
  health_path: /api/health
  dockerized: true
enry:
  languages: {TypeScript: 45.2, JavaScript: 38.7, CSS: 16.1}
hyperpolyglot:
  method: file_count
  languages: {TypeScript: 49.1, JavaScript: 36.0, CSS: 14.9}
  files_detected: 214
language_intelligence:
  method: weighted_consensus
  primary_language: TypeScript
  confidence: 0.95
  sources: [enry, hyperpolyglot]
file_inventory:
  total_files: 260
  total_bytes: 884120
  by_role: {source: 182, test: 41, manifest: 5, config: 18, asset: 14}
sbom:
  count: 247
  artifacts:
    - {type: npm, name: next, version: 14.0.0}
    - {type: npm, name: react, version: 18.2.0}
naming_conventions:
  total_identifiers: 4812
  dominant: camel_case
  styles:
    camel_case: {count: 3104, prevalence: 0.65}
    pascal_case: {count: 1380, prevalence: 0.29}
api_routes:
  total: 18
  base_path: /api
  routes:
    - {method: GET, path: /api/products, handler: listProducts, auth_hint: jwt}
    - {method: POST, path: /api/orders, handler: createOrder, auth_hint: jwt, rate_limited: true}
infrastructure:
  k8s_present: true
  iac_present: false
  containers:
    - {file: Dockerfile, base_image: "node:20-alpine", exposed_ports: [3000], multi_stage: true}
  cicd:
    platform: github_actions
    workflows:
      - {name: CI, triggers: [push, pull_request], jobs: [lint, test, build]}
reproducibility:
  install_cmd: npm install
  build_cmd: npm run build
  dev_cmd: npm run dev
  start_cmd: npm start
  manifests_required: [package.json, package-lock.json]
  entrypoints: [src/main.ts]
  missing_pieces: []
  port: 3000
  health_path: /api/health
  docker_support: true
  score: 0.87

Project layout

polyglot/
├── cmd/polyglot/              # CLI entry point (flags, multi-target, --fail-on)
├── internal/
│   ├── orchestrator/          # Parallel detector scheduler, gate evaluation
│   ├── analyzer/              # enry + manifest-based SBOM
│   ├── rust_bridge/           # CGO bridge to hyperpolyglot
│   ├── treesitter/            # Structural analysis (CGO + nocgo fallback)
│   ├── heuristics/            # Framework / pattern / version / cloud / DB detectors
│   ├── externals/             # HTTP endpoints, env vars, API contracts, messaging
│   ├── security/              # Secret scanning, vuln matching, auth patterns, supply chain
│   ├── quality/               # Complexity, duplication, test intelligence, obs readiness,
│   │                          #   design patterns, SOLID principles + verdicts
│   ├── review/                # Offline code review: engine adapters (opengrep, ast-grep),
│   │                          #   embedded house rulepacks, normalized findings
│   ├── graph/                 # Internal module dependency graph
│   ├── governance/            # CODEOWNERS, license, ADRs, docs health
│   ├── ignored/               # Scan-transparency receipt (skipped dirs / third-party files)
│   ├── datalayer/             # ORM entities and migrations
│   ├── gitintel/              # Recent git history scoped to the codebase
│   ├── aiassets/              # ML models, prompts, vector stores, LLM clients, datasets
│   ├── identity/              # Canonical cross-repo identity & fingerprints
│   ├── naming/                # Identifier naming-style analysis
│   ├── apiroutes/             # HTTP route inventory
│   ├── infrastructure/        # Docker, compose, CI/CD, K8s, IaC
│   ├── runtimeconfig/         # Env-var schema, config-file inventory
│   ├── externalconfig/        # Config-file key map + deployment environments
│   ├── scaffold/              # Generator/template detection
│   ├── codestyle/             # Cascade-resolved code style + indentation verdict
│   ├── algorithms/            # Routine inventory, estimated Big-O, classic-algorithm
│   │                          #   signatures, in-loop performance smells
│   ├── deadcode/              # Oversized files, unreferenced modules, unused decls/params
│   ├── errorhandling/         # Swallowed exceptions (A10) + handled-but-unlogged paths
│   ├── logging/               # Log call-site inventory, log rot, boundaries without a log
│   ├── srcskel/               # Shared source "skeleton" (strings/comments blanked)
│   ├── cbom/                  # Cryptographic inventory + quantum-vulnerability flag
│   ├── cicd/                  # CI/CD pipeline governance audit
│   ├── schemacov/             # Schema coverage + cascade validation of data files
│   ├── usecases/              # Reverse-engineered use cases (boundary → call chain)
│   ├── ucnarrative/           # pt-BR titles/steps for the use cases (local model)
│   ├── modelyaml/             # Data layer → model YAML (table.v1 / dynamodb.v1)
│   ├── archcomp/              # Architectural-compliance verdict over the proven graph
│   │                          # + dependency-cruiser: import cycles, orphan modules
│   ├── cpg/                   # Code Property Graph (Joern): resolved call graph, type
│   │                          # hierarchy, annotations, AST control flow, proven taint
│   ├── vex/                   # OpenVEX exploitability enrichment
│   ├── catalog/               # Served-ready exports: Backstage + the CycloneDX BOM family
│   └── attestation/           # in-toto Statement + DSSE envelope over every artifact
├── pkg/
│   ├── reporter/              # YAML / JSON writer, aggregate report writer
│   └── types/                 # Shared data types (single source of truth)
├── lib/hyperpolyglot/         # Rust library source
├── children/                  # Language-specific child algorithms (JS, Python, Rust)
├── scripts/                   # Build & CI scripts
├── testdata/                  # Integration fixtures
└── .github/workflows/         # CI/CD

Architecture

Pipeline overview

graph TB
    CLI["cmd/polyglot<br/>CLI flags, multi-target, --fail-on"]
    ORCH["orchestrator<br/>Cache, stitch, summary, truths, gate"]
    SCHED["scheduler<br/>Topological parallel runner"]

    subgraph Detectors ["39 Detectors"]
        direction LR
        D1["enry / sbom / hyperpolyglot"]
        D2["inventory / ignored / roadhash / treesitter"]
        D3["7 heuristics detectors"]
        D4["textevidence / externals / security"]
        D5["quality / review / graph / governance"]
        D6["aiassets / identity / naming"]
        D7["apiroutes / infrastructure / datalayer"]
        D8["runtimeconfig / externalconfig / scaffold / gitintel"]
    end

    TYPES["pkg/types — shared data model"]
    REPORT["pkg/reporter — YAML / JSON / aggregate"]
    TRUTHS["truths — natural-language synthesis"]
    CHILD["childrunner — JSON-over-stdin"]

    CLI --> ORCH
    ORCH --> SCHED
    SCHED --> Detectors
    Detectors --> TYPES
    ORCH --> TRUTHS
    ORCH --> REPORT
    D4 -.->|optional| CHILD

How the pipeline works

  1. CLI (cmd/polyglot/main.go) parses flags, validates paths, and delegates to the orchestrator. Multi-target mode (--path a,b,c) writes per-service manifests plus an aggregate.yaml.
  2. Orchestrator (internal/orchestrator/) coordinates the full run:
    • Checks incremental cache using the Merkle root from roadhash — if unchanged, the previous YAML is reused.
    • Passes all 39 detectors to the scheduler with a 30-second per-detector timeout.
    • Stitches fragments into AnalysisResult using a generic payload[T]() helper.
    • Runs post-processing: buildLanguageIntelligence() (enry + hyperpolyglot consensus), generateSummary(), attachTruths(), buildReproducibility().
    • Evaluates CI gates from --fail-on conditions.
  3. Scheduler (internal/scheduler/) runs detectors in topological order respecting Requires() edges. Independent detectors in the same level run in parallel (bounded by NumCPU workers). Ordering is deterministic (alphabetical at every step) so repeated runs produce byte-identical YAML.
  4. Detectors implement the Detector interface: Name(), Requires(), Detect(ctx, input) (Fragment, error). Each returns a typed Fragment that the orchestrator stitches into the final report. Detectors that cannot run (e.g. hyperpolyglot without CGO) mark themselves as skipped with a reason.

Key components

Component Package Role
CLI entry point cmd/polyglot/ Flag parsing, multi-target, exit codes
Orchestrator internal/orchestrator/ Pipeline coordinator: cache, stitch, summary, truths, gate
Scheduler internal/scheduler/ Topological parallel execution with per-detector timeout
Shared types pkg/types/ Single source of truth for all data structures (~3.250 linhas)
Reporter pkg/reporter/ YAML / JSON / aggregate writer
Child runner internal/childrunner/ JSON-over-stdin protocol for language-specific helpers
Truths engine internal/truths/ Natural-language truth synthesis from detector data
Rust bridge internal/rust_bridge/ CGO FFI to the hyperpolyglot Rust static library

All 39 detectors (+ the verdict post-pass)

Trinta e nove detectores produzem evidência. A última linha da tabela não é um deles: é o passo que julga o que todos concluíram, e por isso roda por último.

Detector Package Description
enry analyzer Language detection by bytes (go-enry)
sbom analyzer SBOM from manifests (npm, pip, go.mod, cargo, maven, etc.), plus the syft engine layer: per-package licenses and the ecosystems the floor cannot parse (.NET, Swift, Dart, Elixir…), marked source: syft
hyperpolyglot rust_bridge Language detection via Rust CGO bridge
file_inventory inventory Reconstruction file map with roles, hashes, sizes
ignored ignored Scan-transparency receipt: skipped dirs and third-party files with the excluding rule
roadhash roadhash Deterministic SHA-256 Merkle hash map
treesitter treesitter Structural symbol analysis (CGO + regex fallback)
frameworks heuristics 20+ framework detection
build_tools heuristics 18+ build tool detection
package_managers heuristics 15+ package manager detection
patterns heuristics 11 architectural pattern detection
language_versions heuristics 7 runtime version detection
cloud_services heuristics 9 cloud provider signals
databases heuristics 10 database technology signals
text_evidence textevidence Evidence extraction via child processes (JS/Python)
externals externals HTTP endpoints, env vars, API contracts, messaging
security security Secrets, vulns, lockfile integrity, auth patterns, supply chain
quality quality Complexity, duplication, test intelligence, design patterns, SOLID verdicts
code_review review Offline review engines over the explicit first-party file list (opt-in --review, all-or-nothing)
internal_graph graph Module dependency graph, cycles, entry points
governance governance CODEOWNERS, license, ADRs, docs health
ai_assets aiassets ML models, prompts, vector stores, LLM clients, datasets
canonical_identity identity Cross-repo stable identity and fingerprints
naming_conventions naming Identifier case-style distribution
api_routes apiroutes HTTP route inventory (method, path, handler, auth hint)
infrastructure infrastructure Docker, compose, CI/CD, K8s, IaC
runtime_config runtimeconfig Env-var schema, config-file inventory
external_config externalconfig Config-file key map (all formats) + deployment environments (dev/hml/prod)
scaffold scaffold Generator/template detection, bootstrap commands
data_layer datalayer ORM/SQL/NoSQL entities + migrations; reverses each into model YAML (models/ sidecars) with mixin folding, FK/index recovery, PII hints
git_intelligence gitintel Recent git history scoped to the codebase (skipped outside a repo)
code_style codestyle The style the repo DECLARES, resolved by cascade (eslint/checkstyle/prettier/editorconfig/ruff) — violations vs the project's own rule, divergences vs the community norm, and the indentation verdict
algorithms algorithms Routine inventory + estimated Big-O per routine, the classic algorithms recognised by structure (43 signatures across sorting, search, graph, DP, string, math and pattern families), in-loop performance smells, and the canonical×estimated cross-check
dead_code deadcode Oversized files, unreferenced modules, unused declarations and unused params — the zero-provisioning floor, with engines on top (vulture for Python, knip for JS/TS: unused files/exports/types/dependencies)
error_handling errorhandling Swallowed exceptions (OWASP A10) and handled-but-unlogged paths, multi-language over a string/comment-blanked skeleton
logging logging Log call-site inventory (loggers, levels, mechanisms) + the rot: useless/duplicated/no-message/unstructured logs, logs at the wrong level (a success/lifecycle message at error/fatal — an error log with no error), and system boundaries that never log, both HTTP handlers and background edges (scheduled jobs, queue consumers) (OWASP A09)
cbom cbom Cryptographic inventory with the quantum-vulnerability flag (Shor-breakable vs PQC) — the source of the CBOM sidecar
cicd cicd CI/CD pipeline audit: unpinned actions/images, broad permissions, pull_request_target injection, secrets in the workflow, missing test/dependency-scan/SECURITY.md
schema_coverage schemacov Every YAML/JSON data file classified against the schemas that reach it, then cascade-validated: orphans, invalid data, invalid schemas
security_controls posture Post-pass, not a detector: answers the fixed catalogue of 27 controls (OWASP 2025 / API / LLM / identity boundary) over what every other section concluded, with pass / fail / not_applicable / unknown. Runs LAST, after the CPG, so no control reports unknown on a scan that produced the fact
use_cases usecases Reverse-engineered use cases per system boundary — every HTTP route plus each non-HTTP entry point (scheduled job, queue consumer, carrying a trigger) — with the call chain, and pt-BR titles/steps narrated by the local model

Build modes

Mode Make target CGO Hyperpolyglot Tree-sitter Size target
Full make build Yes Rust static lib via CGO CGO native parsers Large
Portable make build-nocgo No Skipped (reported in capabilities) Pure-Go regex fallback <15 MB

The full build requires Go 1.22+, Rust stable, and a C compiler. The portable build is a single static binary with zero runtime dependencies — the hyperpolyglot capability is reported as skipped in the YAML.

Child process protocol

Language-specific helper algorithms live in children/ and communicate with the Go kernel via internal/childrunner:

  • Transport: JSON over stdin (request) / stdout (response).
  • Exit codes: 0 = success, 1 = error, 2 = skipped (runtime unavailable).
  • Graceful degradation: if the child binary is not on PATH, the detector marks itself as skipped without failing the pipeline.

Children:

Script Runtime Purpose
text-evidence-js.mjs Node.js Text evidence extraction from JS/TS codebases
text_evidence_python.py Python Text evidence extraction from Python codebases
string-generic-rust/ Rust (Cargo) Generic string analysis
veritas-kg/veritas_kg.py Python (venv) Semantic truth clustering, NLI relations, embeddings (see Veritas-KG below)

Code review engines

The code_review section (internal/review/) drives external review engines through own adapters — the children pattern, but with the opposite failure contract:

  • Opt-in: only runs with --review (or POLYGLOT_REVIEW=1); without it the scan is byte-identical to before and the capability reads skipped.
  • All-or-nothing: once requested, a missing or broken engine aborts the whole scan — there is no partial review.
  • Explicit scope: engines receive the first-party file list selected by the inventory walker (source/test roles, reviewable languages, no vendor/generated) as positional targets, chunked to respect the Windows 32 KiB argv limit. No engine walks or decides scope, and no git repository is required.
  • Never writes to the target: fixes are captured as minimal diffs in suggested_fix; house rulepacks (embedded via go:embed, overridable with POLYGLOT_REVIEW_RULES) materialize into a temp dir, never into the codebase.

Engines, in two tiers. Cross-language: OpenGrep (Semgrep-compatible rules, engine-native fingerprints) and ast-grep (tree-sitter structural rules with rewrite) run on every reviewable file. Per-ecosystem elite (the Sonar-class breadth): PMD 7 for Java (quickstart ruleset, invoked straight through java -cp lib/* with --file-list — no launcher scripts, no argv limits), Ruff for Python (single-line fixes and whole-line deletions become suggested diffs), oxlint for JS/TS (the default correctness category) and golangci-lint v2 for Go (the default meta-linter set — errcheck/govet/staticcheck/unused/ineffassign — with --no-config so target-local .golangci.yml never changes the review). golangci-lint is the one engine that type-checks whole packages, so its adapter groups the walker's targets by their nearest go.mod, runs one invocation per module over ./dir patterns, and filters the findings back to the exact target set — Go files with no enclosing module are outside its operable domain (the cross-language packs still cover them lexically), and its runtime dependency on the go toolchain is checked at provision time exactly like PMD's JVM. The engine matrix is per language: an elite engine is mandatory when the scan has files in its language and irrelevant otherwise — PMD missing on a Java codebase aborts the scan; on a Python one it is simply not part of the matrix. Each engine resolves most-explicit-first: env override (POLYGLOT_OPENGREP / POLYGLOT_ASTGREP / POLYGLOT_RUFF / POLYGLOT_OXLINT / POLYGLOT_PMD_HOME + POLYGLOT_JAVA / POLYGLOT_GOLANGCI) → the setup-review pin under <DataDir>/review-bin/ → PATH → the tool's own installer layout. The pinned review-bin/ copy is what lets a provisioned install run fully offline with the exact versions — always the real executables, sidestepping npm launchers' cmd.exe argv wall. The house rulepack is a curated high-signal floor (security + correctness across the four elite ecosystems); the packs split responsibilities — detection in OpenGrep, mechanical rewrites in ast-grep, ecosystem depth in the native engines — so the engines complement instead of duplicating findings.

Provisioning (task polyglot:setup.review): downloads and pins the engines (review-bin/) and the AI layer (review-llm/: llama.cpp server + one GGUF) into the per-user data dir — the only network step, idempotent and all-or-nothing. The same pass provisions the security/risk engines that other sections resolve from review-bin/ — gitleaks (secret scanning, working tree + git history), hadolint (the Dockerfile hardening engine wired into infrastructure.hardening_engines), trivy (broad IaC misconfig, run air-gapped via --skip-check-update — its networked vuln DB is never invoked; osv-scanner owns vulns), syft (SBOM + per-package license) and editorconfig-checker (formatting conformance). Each is a single static binary that runs fully offline, resolved most-explicit-first (env override → review-bin/ pin → PATH) exactly like the review engines. The standalone front door (the Explorer verb / smart scan) treats these five as part of max power: its preflight auto-provisions them on demand (setup-review --risk-only, air-gapped, no OSV DB or AI layer) and refuses the scan with the reason if they cannot be resolved — never a silently thinner report. After it, --review runs with nothing on PATH and no network. The same pass also provisions the language-native engines the structure sections layer on: a pinned Python venv (review-py/) with lizard (routine metrics) and vulture (Python dead code); a pinned npm prefix (review-node/) with knip (JS/TS dead code) and dependency-cruiser (JS/TS import cycles and orphan modules) — plus typescript, which is not a CLI Polyglot drives but the peer dependency-cruiser resolves to parse .ts: without it the engine cruises zero TypeScript modules and reports a falsely clean architecture, with no warning at all. Both Node engines are invoked as node <entry> rather than through their .bin shims, the one call that works cross-platform (a Windows batch shim cannot be started as a process image). The heaviest engine is Joern (review-joern/, with its own pinned JDK resolved through Polyglot's toolchain): it is what produces the cpg section, and it is the one engine whose whole distribution is measured in gigabytes — the price of a control- and data-flow graph that needs no build command for the target, which is exactly what disqualified the alternatives. Its launchers are shell/batch scripts, so on Windows they are routed through the command processor for the same reason the Node shims are not. One invocation harvests every CPG layer, because the JVM start dominates its cost. The AI half is mandatory under the same contract: findings whose engine brought no mechanical autofix go to the local model for a constrained {replacement, rationale} — the scan aborts if no model resolves, and the model may honestly decline a fix (visible, never hidden).

Truths engine

The truths subsystem (internal/truths/) synthesises natural-language statements from all detector outputs:

  • Declared truths — facts read from workspace manifests (e.g. codebase.yaml).
  • Inferred truths — deterministic conclusions drawn from detectors and inventory signals.
  • Conflicts — contradictory declared vs inferred facts, surfaced without promoting either side.
  • Unknowns — intentionally withheld conclusions where evidence is insufficient.

Each truth statement carries an ID, confidence score, evidence references, and stability tag. The orchestrator cross-references truth evidence IDs with TextEvidence entries so consumers can trace conclusions back to source files.

Veritas-KG (semantic truth knowledge graph)

internal/truthgraph + the children/veritas-kg/ Python worker turn the flat truth lists into a knowledge graph. Enabled by --truth-kg (or POLYGLOT_TRUTH_KG=1) — the public tasks always enable it:

  • Clusters — statements with the same meaning grouped by multilingual embeddings (paraphrase-multilingual-MiniLM-L12-v2, PT+EN in the same vector space, cosine >= 0.85, union-find). Each cluster elects a canonical representative (declared > inferred, then shortest).
  • Relationships — labelled edges between clusters: contradiction / entails (NLI cross-encoder mDeBERTa-v3-base-xnli-multilingual, both directions, on cosine-pruned pairs) and similar (cosine band).
  • Conflicts — contradiction edges that cross the declared×inferred boundary are promoted to truths.conflicts (the field existed but was never populated before).
  • Unified artifact — <codebase>/.generated/veritas.yaml (schema iandara.schema.polyglot.veritas.v1): graph + clusters + per-statement embedding vectors + model_info (revisions) + input_fingerprint, fully deterministic (no timestamps, sorted output, rounded floats). The namespace generators produce context/project/veritas.yaml the same way via veritas-client.mjs.

Offline: models (1 GB) live in the git-ignored .platform/data/models/; the worker runs with HF_HUB_OFFLINE=1 and a dedicated virtualenv at `/.iandara/veritas-venv(short home path — torch wheels break Windows MAX_PATH under deep repo paths; created by the task setup;.platform/data/veritas-venvis still probed as fallback; override the interpreter withPOLYGLOT_PYTHON). Embeddings are cached in sqlite (.platform/data/veritas-cache/) keyed by statement hash, so re-runs encode nothing. With the KG active, the incremental cache key gains a +kg-` suffix so plain and KG runs never collide and any worker change auto-invalidates cached KG results.

Release pipeline

GoReleaser (.goreleaser.yaml) cross-compiles nocgo binaries for Linux (amd64/arm64), macOS (amd64/arm64), and Windows (amd64). Archives are .tar.gz for Unix and .zip for Windows, with SHA-256 checksums.

Schema

The full manifest schema is at .platform/schemas/polyglot/codebase.schema.yaml. It is the authoritative contract for downstream consumers (aggregators, dashboards, exporters).

Top-level sections produced by each detector:

YAML key Detector Description
summary orchestrator High-level conclusions from the language intelligence consensus
capabilities orchestrator Per-detector run status (ok / skipped / failed + duration)
enry enry Language percentages by bytes
hyperpolyglot hyperpolyglot Language percentages plus per-file language evidence (CGO only)
language_intelligence orchestrator Reconciled language profile, confidence, and detector disagreements
file_inventory file_inventory Reconstruction file map with roles, hashes, and sizes
ignored ignored Scan-transparency receipt: skipped dirs / third-party files with the excluding rule
roadhash roadhash Deterministic path-aware Merkle map for included files and directories
sbom sbom Software Bill of Materials
structural treesitter Symbol counts by kind
heuristics frameworks / build_tools / package_managers / patterns Framework & pattern heuristics
language_versions language_versions Runtime version declarations
cloud_services cloud_services Cloud provider signals
databases databases Database technology signals
external_dependencies externals HTTP endpoints, env vars, API contracts, messaging
security security Secrets, vulns, lockfile integrity, auth patterns, supply chain
quality quality Complexity, duplication, test intelligence, obs readiness, patterns, SOLID verdicts
code_review code_review Normalized findings + suggested-fix diffs from the offline review engines (opt-in)
internal_graph internal_graph Module dependency graph, cycles, entry points
architecture orchestrator Architectural-compliance verdict: policy rules judged over the proven graph, plus an engine layer (dependency-cruiser) for import cycles and orphan modules
cpg cpg Code Property Graph (Joern), harvested in one invocation: call graph with resolved dispatch (each edge anchored at the callee's declaration), type hierarchy, AST control structures, annotations with their literal argument, and taint in three named tiers — proven source-to-sink path, field-linked (both halves proven, heap link inferred), and pista
governance governance CODEOWNERS, license, ADRs, docs health
ai_assets ai_assets ML models, prompts, vector stores, LLM clients, datasets
canonical_identity canonical_identity Cross-repo stable identity & fingerprints
naming_conventions naming_conventions Identifier case-style distribution
complexity quality (raw) Aggregate cyclomatic complexity stats
dependencies internal_graph (raw) Module count, circular chains, depth
api_routes api_routes HTTP route inventory
infrastructure infrastructure Containers, compose, CI/CD, K8s, IaC
runtime_config runtime_config Env-var schema, config files
external_config external_config Config-file keys across formats + deployment environments (secrets hashed)
scaffold scaffold Generator detection, bootstrap commands
data_layer data_layer ORM entities/fields and migration scripts
git_intelligence git_intelligence Recent git history scoped to the codebase
text_evidence text_evidence Mined string evidence (messages, labels) from source files
code_style code_style The style the repo declares (cascade-resolved), its violations, the community divergences and the indentation verdict
algorithms algorithms Routines with an estimated Big-O (refined by the CPG call graph: a resolved callee's cost composed at the loop depth of its call site), classic algorithms recognised by structure, in-loop performance smells, canonical×estimated cross-check
dead_code dead_code Oversized files, unreferenced modules, unused declarations/params
error_handling error_handling Swallowed exceptions (A10) and handled-but-unlogged paths
logging logging Log inventory (loggers/levels/mechanisms) + the log rot and boundaries without a log (A09)
cbom cbom Cryptographic inventory with the quantum-vulnerability flag
cicd cicd Pipeline governance audit (unpinned, permissions, PR injection, secrets, missing steps)
schema_coverage schema_coverage Data files classified against their schemas, then cascade-validated
use_cases use_cases Reverse-engineered use cases per system boundary (routes + non-HTTP triggers), with pt-BR titles/steps narrated by the local model
boms orchestrator Inventory of the emitted BOM family (kind, file, serial, item count) — see Sidecar artifacts
truths orchestrator Declared / inferred natural-language truths, conflicts, unknowns
reproducibility orchestrator Consolidated blueprint + 0-1 score
diagnostics all Structured severity-tagged messages

Development

task polyglot:codebase -- acme-assets   # full diagnostic of one codebase (setup included)
task polyglot:all                          # full diagnostic of the whole monorepo

# Standalone development of the CLI itself (inside .platform/polyglot/):
make build          # CGO build with hyperpolyglot
make build-nocgo    # portable build
make test           # Go unit tests in nocgo mode
~/.iandara/veritas-venv/Scripts/python children/veritas-kg/test_veritas_kg.py   # worker tests (POSIX: bin/python)

Dicionário — todo o vocabulário técnico do Polyglot

É muita sigla e muito jargão. Este glossário desmistifica tudo que aparece no contexto do Polyglot — do conceito próprio da casa (card, cagüete) ao termo de mercado (OWASP, CBOM), passando por linguagens, frameworks e as ferramentas orquestradas. Uma linha por termo, no sentido de TI/programação.

Conceitos do Polyglot

Termo O que é
Polyglot O próprio CLI: tira um raio-X completo de um codebase, 100% offline, sem alterar nada.
codebase Uma base de código (um projeto/serviço). No monorepo, a folha da hierarquia soberana.
cluster Uma pasta com mais de um codebase (um fork point); ganha artefatos agregados próprios.
fork point O ponto da árvore onde os codebases se ramificam — é o que vira um cluster.
chef O gerador (scan + build_kb) que "mastiga" tudo uma vez; os consumidores só servem o prato.
detector Plugin que extrai uma faceta (linguagem, segredo, rota…); ~30 rodam em paralelo.
fragment A saída tipada de um detector, costurada no manifesto.
stitch A costura determinística dos fragments no AnalysisResult.
manifesto O YAML consolidado (polyglot.yaml) — a fonte da verdade do diagnóstico.
sidecar Artefato derivado escrito ao lado do manifesto (um BOM, o OpenAPI, o VEX…).
capability Status de um detector: ok / skipped / failed, sempre com a razão.
roll-up Agregação bottom-up: codebase → cluster → context → project → org.
risk / risco Um ponto de atenção graduado (low/medium/high/critical) com categoria e evidência.
evidence / evidência O arquivo:linha que sustenta uma conclusão.
card O resumo em Markdown do codebase para agentes/IA — o "prato pronto" do KB.
KB (knowledge base) A base que a IA consome (card + jsonl + sqlite + servidor MCP).
truth / verdade Uma afirmação em linguagem natural sobre o codebase (declarada × inferida).
Veritas-KG O grafo semântico de truths (embeddings + NLI) que acha contradições.
atlas O HTML panorama do codebase/cluster (abre sem servidor, de file://).
cagüete O HTML que dedura só os podres (riscos, segredos, contradições) — nada que está certo.
norte O HTML radial que aponta o caminho: o que fazer para chegar ao state-of-art.
página BOM O HTML radial do ecossistema de BOMs: o System BOM no centro, cada BOM da família num raio, dizendo o que inventaria e onde está o documento.
API reference O viewer HTML do contrato de rotas (próprio, aposenta o Redoc).
podre Gíria da casa: "o que não está bom ou o que falta".
tudo-ou-nada Nunca há modo parcial/degradado; dependência faltando = falha com a causa.
roadhash O Merkle SHA-256 do conteúdo do codebase — a chave do cache incremental.
children pattern Runtimes externos (JS/Python/Rust) falam com o kernel Go via JSON-over-stdio.

Segurança & risco

Termo O que é
OWASP Open Worldwide Application Security Project — ONG que publica padrões de segurança.
OWASP Top 10 A lista das 10 categorias de risco de segurança web mais críticas (A01…A10); o cagüete mostra as 10.
CWE Common Weakness Enumeration — catálogo numerado de tipos de falha (ex.: CWE-89 = SQL injection).
CVE Common Vulnerabilities and Exposures — id único de uma vulnerabilidade conhecida específica.
GHSA GitHub Security Advisory — id de vulnerabilidade do GitHub (alternativo ao CVE).
CVSS Common Vulnerability Scoring System — nota 0–10 da severidade de uma vuln.
OSV Open Source Vulnerabilities — base de dados de vulns (Google), usada offline.
SAST Static Application Security Testing — achar falhas sem executar o código.
taint (source → sink) Rastrear um valor que veio do usuário (a source: um parâmetro de rota, req.query, um campo de tela) até um ponto perigoso (o sink: uma query SQL, um exec, um readFile). Se o caminho fecha, a injeção não é suspeita — é provada, com cada salto ancorado em file:line.
tier de evidência O quanto o achado está provado, dito em voz alta: provado (o dataflow andou o caminho inteiro), field-linked (os dois meios provados — a entrada grava um campo do objeto, uma leitura do mesmo campo alcança o sink — só o elo pelo heap é inferido) e pista (o comando é construído dinamicamente, mas nenhum caminho chegou até ele). Nunca se apaga o mais fraco: rotula-se.
sanitizer Uma guarda no caminho (escape, parameteriz…, normalização de path). No Polyglot ela rotula o achado, nunca o descarta — sumir com ele trocaria um falso positivo por um falso negativo.
secret / segredo Credencial embutida no código (chave de API, senha, token).
vuln Vulnerabilidade: uma dependência com falha conhecida (casada via OSV).
supply chain Cadeia de suprimentos — risco vindo das dependências (não pinadas, licenças, lockfile).
lockfile Arquivo que fixa as versões exatas das dependências (package-lock.json, go.sum…).
hardening Endurecimento: checagens de má-configuração de container/infra (usuário root, :latest…).
PII Personally Identifiable Information — dado pessoal (email, CPF, telefone…).
LGPD / GDPR Leis de proteção de dado pessoal (Brasil / União Europeia).
PQC Post-Quantum Cryptography — cripto resistente a computador quântico.
Shor O algoritmo quântico que quebra RSA/ECC — a razão de essas primitivas serem "quantum-vulnerable".
quantum-vulnerable Cripto clássica que um computador quântico quebra (RSA, ECC, DH, incl. Ed25519/X25519).
ML-KEM / ML-DSA Os padrões PQC (troca de chave / assinatura), antes chamados Kyber / Dilithium.
VEX Vulnerability Exploitability eXchange — diz se uma vuln é de fato explorável naquele código.
in-toto Framework de atestado de proveniência da cadeia de build.
DSSE Dead Simple Signing Envelope — o envelope de assinatura usado no atestado.
SLSA Supply-chain Levels for Software Artifacts — níveis de integridade de build.
attestation / atestado O selo assinado que amarra as entradas às saídas de um scan.

A família de BOMs

Termo O que é
BOM Bill of Materials — "lista de materiais": inventário estruturado de um aspecto do software.
SBOM Software BOM — inventário de dependências/componentes.
CBOM Cryptography BOM — inventário das primitivas criptográficas (+ flag quantum).
LBOM License BOM — inventário das licenças das dependências.
SaaSBOM Inventário dos serviços externos que o app consome (HTTP, filas, provedores de identidade).
ML-BOM Machine-Learning BOM — inventário dos artefatos locais de IA (pesos de modelo, datasets).
ABOM AI/Agent BOM — a superfície de IA que atravessa a fronteira: provedores de LLM, bancos vetoriais e prompts embarcados.
DBOM Data BOM — inventário das tabelas/entidades + colunas de PII.
OBOM Operations BOM — inventário do pipeline de CI/CD e da postura de entrega.
ConfigBOM Inventário da configuração (fontes, ambientes, contagens) — nunca um valor.
IBOM Infrastructure BOM — inventário da infra declarada (imagens de container, serviços de compose).
System BOM O guarda-chuva: não inventaria nada, só amarra todos os outros BOMs por BOM-Link — é o centro do ecossistema.
KBOM Knowledge BOM — aqui subsumido pelo ML-BOM/ABOM (os ativos de IA já estão lá; as truths vivem no veritas.yaml).
CycloneDX O padrão de formato de BOM (OWASP); o Polyglot emite a versão 1.6.
SPDX O padrão de identificação de licença (ex.: MIT, AGPL-3.0-only).
purl Package URL — id universal de um pacote (pkg:npm/lodash@4.17.21).
BOM-Link A referência que amarra um BOM a outro (urn:cdx:<serial>/1).

CI/CD & DevOps

Termo O que é
CI Continuous Integration — integrar + testar o código a cada mudança, automaticamente.
CD Continuous Delivery/Deployment — entregar/publicar automaticamente após o CI.
CI/CD O pipeline que junta as duas — a "esteira" de build → teste → deploy.
pipeline / esteira A sequência automatizada que leva o código do commit à produção.
GitHub Plataforma de hospedagem de código (git) e colaboração.
GitHub Actions O CI/CD nativo do GitHub — workflows em .github/workflows/.
Jenkins / GitLab CI / Azure Pipelines / CircleCI Outras plataformas de CI/CD que o Polyglot detecta.
IaC Infrastructure as Code — infra declarada em arquivo, versionada como código.
Terraform / CloudFormation / Pulumi Ferramentas de IaC.
Kubernetes (K8s) Orquestrador de containers em escala.
Docker / container Empacotamento de um app + suas dependências numa imagem isolada e portátil.
Dockerfile A receita de build de uma imagem Docker.
docker-compose Define e sobe vários containers/serviços a partir de um arquivo.
pull_request_target Gatilho perigoso do GitHub Actions (roda com segredos sobre código de PR não confiável).

Linguagens (as que aparecem no contexto)

Termo O que é
Go Linguagem compilada da Google; o kernel do Polyglot é escrito nela.
Rust Linguagem de sistemas com segurança de memória; a ponte hyperpolyglot é nela.
Python Linguagem de scripting; o Veritas-KG, o build_kb e várias children são nela.
JavaScript (JS) / TypeScript (TS) A linguagem da web; TS é JS com tipos. As tools de atlas/children são nela.
Node.js O runtime que roda JS/TS fora do navegador.
Java / Kotlin Linguagens da JVM; Kotlin é o "Java moderno".
C# / .NET Linguagem e plataforma da Microsoft.
PHP / Ruby / Swift / Scala Outras linguagens que os detectores reconhecem.
C / C++ Linguagens de sistemas de baixo nível.

Ferramentas & engines orquestrados

Termo O que é
tree-sitter Parser incremental que vira código em AST — a base da análise estrutural.
go-enry Biblioteca que reconhece 400+ linguagens por conteúdo/extensão.
hyperpolyglot Detector de linguagem alternativo (Rust), cruzado com o enry por consenso.
syft Engine que cataloga componentes e resolve licença por pacote (do lockfile/metadata). No Polyglot uma passada rende os dois lados: a licença de cada dependência e os ecossistemas que o parser puro-Go não lê (.NET, Swift, Dart, Elixir…), que entram no SBOM marcados source: syft.
gitleaks Engine de varredura de segredos (working tree + histórico git).
hadolint Linter de Dockerfile (regras DL####).
trivy Scanner de má-configuração de IaC (Docker/compose/K8s/Terraform), rodado air-gapped.
editorconfig-checker Verifica conformidade de formatação contra o .editorconfig do repo.
OpenGrep / ast-grep Engines de code review offline (regras semânticas / estruturais com reescrita).
PMD / Ruff / oxlint / golangci-lint Linters "elite" por linguagem (Java / Python / JS-TS / Go).
lizard Extrator de métricas de função (linhas, parâmetros, complexidade) multi-linguagem.
vulture Engine de código morto em Python (por cima do piso léxico próprio).
knip Engine de código morto em JS/TS: arquivos, exports, tipos e dependências sem uso, resolvidos no grafo do projeto inteiro.
dependency-cruiser Engine de arquitetura JS/TS: ciclos de import e módulos órfãos sobre o grafo resolvido. Exige o pacote typescript para enxergar .ts.
Joern Engine de CPG (AST+CFG+PDG) que o Polyglot usa para call graph com dispatch resolvido, hierarquia de tipos, anotações e taint provado — multi-linguagem e sem exigir build do alvo (o que desqualificou o Infer).
KICS Scanner de IaC da Checkmarx (2.400+ queries) — a base do inventário de recurso do IBOM.
osv-scanner O casador de vulnerabilidades contra a base OSV, offline.
llama.cpp / GGUF O runtime de LLM local e o formato de peso que a camada de IA usa.
MCP Model Context Protocol — o servidor que expõe o KB para agentes.
HuggingFace O hub de onde vêm os modelos offline (embeddings + NLI).
SQLite Banco embutido (arquivo único) que guarda o grafo de truths e o KB.
GoReleaser / Inno Setup Empacotador multi-OS / instalador do Windows.
Backstage / Mermaid / Redoc Portal de dev (catalog-info) / diagramas em texto / viewer de OpenAPI (aposentado).

Qualidade & análise estrutural

Termo O que é
Big-O Notação da complexidade de um algoritmo em função do tamanho da entrada (O(n), O(n²)…).
complexidade ciclomática Número de caminhos independentes numa função — proxy de "quão difícil de testar/entender".
SOLID Cinco princípios de design orientado a objetos (SRP/OCP/LSP/ISP/DIP).
GoF / design pattern Padrões de projeto do livro "Gang of Four" (Singleton, Factory, Strategy…).
dead code Código que nada referencia/usa — candidato a remoção.
tech debt / dívida técnica Atalhos marcados no código (TODO/FIXME/HACK/XXX).
code smell "Cheiro" — sinal de problema de design sem ser um bug.
duplication Trechos de código repetidos (candidatos a extração).
AST / CFG / PDG / CPG Árvore sintática / grafo de fluxo de controle / de dependência de programa / a fusão dos três. É do CPG que saem o call graph resolvido, a hierarquia de tipos e o taint.
call graph O grafo de "quem chama quem" entre funções. Resolvido quando a chamada por campo ou interface (repo.weight(id)) aponta para o callee real, e não para um alvo desconhecido.
taint analysis Rastreio de dado não confiável da source até o sink. É o que separa prova de palpite: em vez de casar um padrão ("SELECT " + x), demonstra o caminho do dado — inclusive atravessando funções e arquivos. Um caminho provado é a evidência de injeção; um casamento de padrão é só pista.
source (taint) Onde dado controlado pelo usuário entra. Cada ecossistema marca de um jeito: parâmetro anotado (@RequestParam), parâmetro tipado como o objeto de requisição (*http.Request), ou acessor conhecido (req.query, request.args).
sink (taint) Onde o dado vira perigoso se chegar sujo: executeQuery, db.Query, cursor.execute, exec, eval. Um acessor de entrada nunca é sink — senão o mesmo nó seria as duas pontas do fluxo.
hotspot Um ponto do código que concentra risco (alta complexidade, muitas mudanças).
bus factor Quantas pessoas precisariam "sumir" para o conhecimento de um trecho se perder (1 = risco).

Formatos, protocolos & cripto

Termo O que é
YAML / JSON Formatos de dados legíveis; o manifesto é YAML, os BOMs são JSON.
JSON Schema Contrato que valida a forma de um YAML/JSON; o Polyglot valida todo artefato contra o seu.
OpenAPI Padrão de descrição de API REST; o Polyglot faz engenharia reversa das rotas para ele.
gRPC / GraphQL / AsyncAPI Outros estilos de contrato de API (RPC / query / orientado a eventos).
Merkle Árvore de hashes que resume o conteúdo — muda se qualquer arquivo mudar (base do cache).
SHA-256 Função de hash criptográfica de 256 bits usada nos fingerprints e no atestado.
Ed25519 / X25519 Assinatura / troca de chave em curva elíptica (clássicas, quantum-vulneráveis).
RSA / ECC / DH Cripto assimétrica clássica (chave pública) — quebrável por Shor.
PASETO Formato de token de sessão (alternativa segura ao JWT) usado no ecossistema Iandara.
NLI / embedding Natural Language Inference (entailment/contradição) / vetor que representa o significado de um texto.
ORM / DDL / migration Mapeamento objeto-relacional / SQL que define tabelas / script que evolui o schema do banco.
mixin / FK Conjunto de colunas reutilizável (auditable…) / foreign key (chave estrangeira).

License

No LICENSE file is currently tracked for this module; check the repository's licensing terms before reuse.