Scope & Source Baseline: Written directly against
metarch-truthsrcv2.0.0 (pinned commitdf54bbb,bank-wealth-demo@7b5de44), this is a coarse-to-fine, macro-to-seam engineering battle map. Unlike the co-arising 2.0 Long-Term Architecture Blueprint (design philosophy) or the GA Complete Guide (user workflow), this manual slices the compiler open to chart its module boundaries, vertical dataflows, 14 cross-file hidden couplings ("underground tunnels"), and an empirically validated probe-based mine-sweeping playbook covering 86 confirmed fixes (Waves 1–8: 36 locked inSPEC-S13..S31; Wave-9: 50 locked into thetest:wave9regression suite & black-box Play E2E) plus the remaining honest targets (M32 / M34 / M35), machine-locked to the repository commit viaartifact-maps.lock.json.
1. Strategic Overview (Level 0): The Macro Terrain Map
To hunt latent bugs systematically inside metarch-truthsrc, discard one misconception first: it is not a "YAML-to-template" scaffolder; it is a five-stage domain compiler built across two historical geological strata.
- Stratum 1 (v1 Strict-Governance Legacy Layer,
emitter/families/): 24 deterministic Scala CQRS/Play emitters locked by golden-file parity inemitter/parity.mjs(value objects, aggregate protocols, Akka persistence, Protobuf converters, Play runtime, and more). - Stratum 2 (v2 EARS-Native Trunk,
lib/ears/+lib/v2/): Orthogonal YAML structure loader, EARS 1.0 lexer/parser/binder/Z3 SMT solver, DMN First-Hit witness synthesizer,Canonical Model v2, local SQLite knowledge graph, TS/Scala dual-stack and Scala single-stack generators, locked BDD oracle emitters, mutation testing, and anti-cheat write guards.
Most real-world bugs do not live inside isolated function logic; they live at stratum boundaries and fan-out seams where one semantic concept is independently translated by multiple downstream consumers. Figure 1 maps the six macro stages alongside the four high-risk fault lines:
Two Essential Top-Level Mental Models
- Dual-Stack vs. Scala Single-Stack Delivery:
typescriptgives millisecond zero-compile Node 22 feedback for rapid prototyping and demos;scala-cqrs-play-service-v2delivers the full production Akka/Play/Protobuf/ScalikeJDBC runtime.- Since
0b925adintroducedlib/v2/target-resolution.mjs, Scala production projects no longer carry dual-slot overhead (*.cloze.ts+*Impl.scala): when onlygenerated-scaffold/scala(or.truthsrc/generated-scala-manifest.json) exists withoutgenerated-scaffold/ts,tasks-v2,verify-v2, andcheck-v2automatically operate in Scala single-stack mode.
- The Blind Spot Between Offline
scalacand Livesbt stage:- To keep TDD loops sub-second/second-level,
verify-v2invokes standalonescalac+ ScalaTest while filtering out Akka/Play/ScalaPB/ScalikeJDBC framework files. - Therefore green offline
verify-v2does NOT guarantee greensbt -batch stageor HTTP 200 on Play. Play controllers, ReadSide JDBC repositories, Protobuf converters, Guice DI modules, andconf/routesare only truly verified by a realsbt -batch stageand live Play 2.8.18 HTTP roadshow.
- To keep TDD loops sub-second/second-level,
2. Module & Directory Atlas (Level 1): Six Zones Down to Exact Source Files
As of 8950ba3, the v2 engine spans six operational zones. Use this atlas as a direct jump-table during triage and bug-hunting:
| Zone | Core Modules (clickable GitHub links) | LOC | Ownership & Responsibility | Key I/O Contract |
|---|---|---|---|---|
| A · Entrypoints & Locks | bin/truthsrc.js / lib/v2/cli.mjs |
559 / 517 | 44 CLI commands and v2 subcommand dispatch (including --bc / --packaging monolith) |
Strict BOOL_FLAGS whitelist; unknown or missing flag values fail closed |
| A · Entrypoints & Locks | mcp/server.mjs / lib/v2/surface-registry.mjs |
370 / 300 | 32 MCP tools (6 v2_*) and single-source capability lock |
npm run check:contracts pins CLI, MCP, Skills, and error-code counts |
| A · Entrypoints & Locks | tools/lint.mjs / lib/runtime-profile.mjs |
168 / — | Zero-business-hardcoding architectural gate and sole runtime coordinate registry | Forbids domain names and net.imadz literals across core lib/, bin/, and active emitter/ |
| B · Frontend & SMT | lib/v2/structure-loader.mjs |
2,378 | Largest single file: loads YAML structs, rejects legacy @guard, normalizes resolvedType, validates 5-layer Authz/PII/ReadModels |
Emits structures, symbolTable, and resolveCanonicalEventFields |
| B · Frontend & SMT | lib/ears/parser.mjs / lib/ears/binder.mjs |
772 / 1,146 | Isomorphic EN/ZH EARS 1.0 parsing, normalization (normalize.mjs), and strongly typed symbol binding |
Binds state/param/event/extern symbols and classifies L1/L2/L3 |
| B · Frontend & SMT | lib/ears/smt-encoder.mjs / lib/v2/first-hit-witness.mjs |
847 / 467 | Single-hop EARS → SMT-LIB 2 encoding, 5 Z3 proofs + k-BMC, DMN First-Hit exact witness synthesis |
Any unreachable, conflicting, or shadowed rule blocks Canonical v2 emission |
| B · Frontend & SMT | lib/v2/compiler.mjs / lib/v2/lineage.mjs |
594 / 1,061 | v2 compile orchestrator, full-chain field lineage, Event Sourcing post: fold validation, bilingual equivalence |
Writes canonical-v2.json, knowledge.sqlite, Style E/B signoff docs |
| C · Graph & Tasks | lib/v2/knowledge-db.mjs / lib/v2/tasks-v2.mjs |
401 / 294 | Node 22 built-in node:sqlite dependency graph and drift-free @cloze task queue derivation |
Preserves existing cloze_slots.provenance review records across rebuilds |
| C · Graph & Tasks | lib/v2/atlas-viewer.mjs / lib/v2/diagrams.mjs / lib/v2/view-v2.mjs |
1,474 / 1,283 / 1,077 | 11-diagram offline atlas.html and interactive Workshop HTML exporter |
Pure read-only consumers of canonical-v2.json + SQLite |
| D · Codegen & Bridge | generators/scala-cqrs-play-service-v2/generate.mjs |
396 | scala-cqrs-play-service:2 top assembler, @generated stamping, multi-subdomain merge (mergeCanonicalsForBc) |
Wires Block A/B/C/D bridges and writes .truthsrc/generated-scala-manifest.json |
| D · Codegen & Bridge | lib/v2/bridge/v1-strict-scala.mjs / ears-simplify.mjs |
1,231 / 298 | Block A domain bridge invoking 1.0 #1/#2/#3/#45 families + EARS NNF simplification + @cloze stubs |
Emits domain/values, entities, invariants, Computations, *Impl.scala |
| D · Codegen & Bridge | lib/v2/bridge/v1-strict-block-cd.mjs |
1,354 | Block C/D coordinator invoking 1.0 protocol/aggregate/repo/Protobuf/serializer/Play runtime/sbt scaffold + Authz/DI | Delegates to readside, policy, api-auth, and orchestration bridges |
| D · Codegen & Bridge | v1-strict-readside.mjs / v1-strict-api-auth.mjs / v1-strict-policy.mjs / v1-strict-orchestration.mjs |
709 / 576 / 569 / 702 | Full Play vertical slices: CQRS ReadSide+JDBC, auth-core Play controllers + ServerSnapshotProvider, reactive PolicyMachine, Saga/Effect/ToolGate |
Highest-frequency zone for sbt stage compile errors |
| D · Codegen & Bridge | lib/v2/codegen/onion-routes.mjs / typescript.mjs / onion-ts.mjs / onion-scala.mjs |
120 / 1,085 / 761 / 603 | Single HTTP route derivation (deriveStoryHttpRoutes) and TS/Scala Onion interface layers |
Must remain strictly isomorphic with v1-strict-api-auth and interfaces-http |
| E · Oracle Emitters | lib/v2/test-emitter/witness-materialize.mjs |
686 | Expands sparse Z3 witnesses into concrete typed TS/Scala commands, states, snapshots, and trusted contexts | Primary leverage point behind bulk application-suite failures |
| E · Oracle Emitters | scala-strict-scalatest.mjs / typescript-node-test.mjs / interfaces-http.mjs |
427 / 342 / 796 | Emits Domain/Application ScalaTest, Node 22 TS suites, and 5-layer Authz/CSRF/PDP HTTP oracles | Stamps generated-tests/manifest.sha256.json tamper lock |
| F · Gates & Guard | lib/v2/verify-gate.mjs / mutation-gate.mjs / guard-write.mjs |
843 / 381 / 232 | Tamper check, TS + offline scalac runners, Onion DIP check, Domain mutation gate, and PreToolUse write guard |
Restricts AI writes strictly inside @cloze:start..end; blocks all locked zones |
3. Core Dataflows & State Machines (Level 2): Tracing a Rule End-to-End
Zooming from modules to execution paths, every bug investigation starts by tracking two vertical pipelines and one derived task state machine:
Disk Territory Ownership Contract
| Disk Territory | Owner | Generator Write Behavior | guard-write.mjs Enforcement |
|---|---|---|---|
truth/ (YAML + .ears + bindings) |
Domain author / architect | Read-only input, never rewritten | Editable (requires re-running compile-v2) |
generated-scaffold/, generated-tests/, projections/ |
Compiler & generators | Full deterministic overwrite | Physically blocked (TERRITORY_LOCKED, exit 2) |
handwritten/ (*Impl.scala, *.cloze.ts, ServerSnapshotProviderImpl.scala, HandwrittenBindingsModule.scala) |
Humans / isolated AI Agents | Created once; never overwritten once present (overwrite: false) |
Edits allowed only inside @cloze:start(<id>)..@cloze:end(<id>); full-file overwrites blocked |
.truthsrc/ (canonical-v2.json, knowledge.sqlite, manifests) |
Derived state cache | Rebuilt on compile/verify (preserves cloze_slots.provenance) |
Rebuildable, with provenance & blind-review state retained in SQLite |
4. Underground Tunnels Map (Level 3): 14 Hidden Cross-File Couplings
On the surface the compiler pipeline looks clean and modular. What actually breaks multi-subdomain production projects (such as a 6-subdomain exam platform with 50 domain behaviors and 23 @cloze slots) are 14 underground tunnels (T01–T14)—pairs of modules that never directly call each other yet silently share fragile invariants:
Network A · Type & Nominal System Faults (T01–T03)
- T01 · 6-Way
resolvedType.kind === 'record'Re-Translation:structure-loader.mjsnormalizes bothExactType(such asMoney) andValueObjectinto{ kind: 'record', typeName }.- At least six downstream files each maintain their own
buildNominalIndex/scalaTypeOf/defaultScalaExpr:v1-strict-scala.mjs,v1-strict-block-cd.mjs,v1-strict-readside.mjs,v1-strict-policy.mjs,v1-strict-api-auth.mjs, andwitness-materialize.mjs. - Failure mechanism: Missing
case 'record'in any single consumer silently degrades types toString—directly causing Play ReadSideStringassigned toBigDecimal/Long(Issue #2) and ReadModel nominal-field compile errors (Bug #4).
- T02 ·
SPEC-S10Idiomatic PrimitiveJson.toJsonvs. Nominal Codecs:- In
v1-strict-readside.mjs, primitive sequences likeVector[String]must keepJson.stringify(Json.toJson(row.topics))and.as[Vector[String]](pinned bySPEC-S10), while collections/maps containingExactTypeorValueObjectmust branch viatypeUsesNominalinto recursivejsEncodeExpr/jsDecodeExpr.
- In
- T03 · Four-Way Implicit Assumption That
aliasesIncludes'state':- If YAML defines custom
aliases: [bal]without'state',v1-strict-scala.mjsandwitness-materialize.mjsmisreadstate.fieldas a nested record member and emitstate.copy(state = state.state.copy(...))(Bug #7). Every consumer must normalize aggregate aliases to include'state'.
- If YAML defines custom
Network B · 1.0/2.0 Bridge & Offline scalac Faults (T04–T07)
- T04 · Duplicated
SBT_FRAMEWORK_IMPORT_REOfflinescalacFilter:verify-gate.mjs:359andmutation-gate.mjs:210each hold a copy of the framework import regex that strips Akka/Play/ScalaPB/ScalikeJDBC/converter files out of standalonescalac.- Rule of thumb: Any generated Scala file referencing a filtered trait (such as zero-VO
DomainConverters.scalaextending<Agg>ProtoConverters) MUST carry a matching framework import—otherwisesbt stagesucceeds while offlineverify-v2fails withnot found: type. Always update both copies together.
- T05 · 1.0
emitter/families/24-Family Parity Red Line:emitter/parity.mjspins golden bytes andrunNegativesassertions across all 24 families (for instance,proto-converter.mjsrequiresvalueObjects.length > 0).- Rule of thumb: Handle v2 edge cases (like zero-VO projects) in
v1-strict-block-cd.mjsrather than weakening 1.0 negative batteries.
- T06 · Hybrid L1+L2 Aggregate
RuleParams&SPEC-S4Zero-Noop Contract:- Aggregates mixing L1 deterministic rules and L2
@clozerules must unify all params under<Agg>RuleParams(never splitting out<Agg>DomainServiceRuleParams). - Because
SPEC-S4forbids exposingval Noopon non-empty<Agg>Computationsin production code,scala-strict-scalatest.mjspassesnull.asInstanceOf[<Agg>Computations]for L1 rule tests on hybrid aggregates.
- Aggregates mixing L1 deterministic rules and L2
- T07 ·
tools/lint.mjsArchitecture Guard:tools/lint.mjsscans all 626 JS/MJS files: zero domain/business identifiers in generic core, zeronet.imadzliterals outsidelib/runtime-profile.mjs, and zero hardcoded'app/'paths inside activeemitter/families/.
Network C · Witness Materialization & Oracle Faults (T08–T10)
- T08 · Sparse Z3 Witness →
witness-materializeSemantic Distortion:first-hit-witness.mjsprobes Z3 only for guard-referenced symbols;witness-materialize.mjsfills the rest.- Two classic traps: (1) Overwriting
[]with synthetic non-empty lists on rejected rules destroyslen(items) == 0witnesses (Bug #1); (2) OmittingbindPrincipal, serverstateSnapshot, or sending scalars to sequence fields breaks entire application test suites (Issue #3).
- T09 · Dual Event-Field Resolution:
- Event fields can be explicitly declared or derived from command parameters/lineage. Both
v1-strict-scala.mjsand[POSTCOND]emitters inscala-strict-scalatest.mjsmust shareresolveCanonicalEventFields(agg, ev)or case-class arities drift apart (Bug #6).
- Event fields can be explicitly declared or derived from command parameters/lineage. Both
- T10 · 4-Way 5-Layer Authz PEP/PDP Mirroring:
-
onion-ts.mjs,onion-scala.mjs,v1-strict-api-auth.mjs(Play controllers), andinterfaces-http.mjs(HTTP oracles) must stay byte-for-byte semantically aligned on: skippingpublicroutes for 401/403 checks, injecting allow-PDP for bothexternal-pdpandresource-policy, appending query params forGETroutes, mapping errors viaHttpStatusMapper.statusForRejection, convertingJsNull => null, parsingX-Entitlements/X-Principal-Attr-*, and enforcingownerField/requiresEntitlement/rowScope+ServerSnapshotProvider.load.
Network D · Monolith Packaging, Targets & Gate Faults (T11–T14)
- T11 · Silent
dedupBySwallowing inmergeCanonicalsForBc& Stale Files: - Look atgenerators/scala-cqrs-play-service-v2/generate.mjs:135: multi-subdomain monolith merges deduplicatevalueObjects,exactTypes,readModels,aggregates,ports, andstoriesby shortx.name. Two subdomains defining same-named types with different fields silently drop the second definition. Meanwhile incremental regeneration does not garbage-collect stale.scalafiles left under old package paths (Issue #4). - T12 ·
target-resolution.mjsSingle-Stack Detection &init-v2Import Rules: -lib/v2/target-resolution.mjsunifies target resolution acrosstasks-v2,verify-gate,check-v2, andcli.mjs;init-v2.mjsmust correspondingly switchforbiddenImportsfor Scala-only repos so Play controller imports are never false-flagged. - T13 ·
verify-gateShort-Circuiting Mutation & Open HTTP Server Handles: - Any single failure in the base test suite causesverify-gate.mjsto skip the built-inmutation-gate, deferring mutation timeouts or surviving-mutant surprises until after the entire suite turns green. Additionally, unclosed HTTP listeners ininterfaces-httpcan keep standalonenode --testworkers alive after reporting counts. - T14 · Cross-Version DI Signature Drift in
overwrite: falseHandwritten Files: - PreservingHandwrittenBindingsModule.scala,ServerSnapshotProviderImpl.scala, and@cloze*Impl.scalafiles is a strict guarantee—which means when a newer generator adds a constructor dependency (likeServerSnapshotProvider), clean directories pass while pre-existing repos fail to compile until their handwritten bindings are upgraded.
5. Empirical Retrospective (Level 4A): Nine-Wave Mine-Sweeping Battle Report (SPEC-S13..S31 + Wave-9 Regression Suite)
Right after fixing the first real-world 6-subdomain run (Issue #2, #3, #4), we used the tunnel map above to drive eight consecutive waves of real adversarial probes (compileCanonicalV2 + node --test + offline scalac/ScalaTest/Mutation Gate + real sbt -batch compile). Wave-1 (7/7) validated the methodology on the very first run:
| # | Confirmed Bug Symptom | Tunnel Traversed | Minimal Adversarial Probe | Fix & Regression Lock |
|---|---|---|---|---|
| #1 | len(items) == 0 rejected rule test failed |
T08 | Aggregate command with Seq[String] rejected when empty |
Added allowEmptySeq in witness-materialize, preserving [] when isRejected (SPEC-S13) |
| #2 | Hybrid L1+L2 aggregate failed sbt compile (DomainServiceRuleParams missing) |
T06 | Single aggregate combining 1 L1 rule + 1 L2 extern rule |
Unified <Agg>RuleParams; preserved SPEC-S4 zero-Noop via null.asInstanceOf in L1 tests (SPEC-S14) |
| #3 | First public route hijacked 401/403 tests; resource-policy lacked PDP; GET missed query params |
T10 | First route mode: public, plus resource-policy and GET routes |
Selected first non-public route, unified routeNeedsPdp, appended buildQuerySuffix (SPEC-S16) |
| #4 | ReadModel with ExactType/ValueObject failed sbt compile |
T01 + T02 | ReadModel containing Money (unit-decimal) + custom VO |
Wired nominalIdx & typeUsesNominal in v1-strict-readside while keeping SPEC-S10 (SPEC-S15) |
| #5 | Play controller hardcoded 400, omitted X-Entitlements/ownerField/rowScope, and mismatched JsNull |
T10 | Play route declaring owner, entitlement, and rowScope | Aligned v1-strict-api-auth with HttpStatusMapper, 403 checks, and recursive PlayHttpBridge (SPEC-S16) |
| #6 | Zero-VO project missed ProtoConverters; [POSTCOND] arity mismatched derived event fields |
T04 + T05 + T09 | Primitive-only project with lineage-derived event fields | Emitted zero-VO fallback in v1-strict-block-cd with framework import; shared resolveCanonicalEventFields (SPEC-S15) |
| #7 | Custom aliases: [bal] omitting 'state' emitted invalid state.state.copy(...) |
T03 | YAML aggregate with custom aliases excluding state |
Normalized aggregate aliases to always include 'state' across bridge & witness (SPEC-S14) |
All regressions are locked in test/scala-cqrs-play-service-v2-acceptance.spec.mjs (SPEC-S1..S31, 31/31 PASS), verified with real sbt -batch compile / stage and 100% Mutation Gate runs (see the status page).
Wave-2 Empirical Sweep (Commit df54bbb · 6/6 Probes Confirmed & Eliminated)
Immediately after charting targets M01–M08, we ran Wave-2 adversarial probes (probe_wave2_mines.mjs) through real compileCanonicalV2 + generateScalaCqrsPlayServiceV2/ForBc + emitV2ExecutableTests + offline scalac + real sbt -batch compile. All 6 probe groups confirmed as real defects (10 underlying fixes, locked in SPEC-S18..S20):
| Radar ID | Confirmed Defect & Root Cause | Fix & Regression Lock (df54bbb) |
|---|---|---|
| M01 | Same-named structurally conflicting SharedInfo VO silently dropped by dedupBy, causing value score is not a member in sbt |
Replaced with dedupStructuralChecked: identical Shared Kernel deduplicates cleanly; conflicts fail closed with BC_MERGE_CONFLICT (SPEC-S18) |
| M03 | Scala reserved keywords (type, match) passed compile-v2 then crashed generate-v2 with VO_INPUT |
Added RESERVED_TARGET_IDENTIFIERS check in structure-loader.mjs, failing fast with V2_RESERVED_IDENTIFIER (SPEC-S18) |
| M06 | v1-strict-orchestration.mjs lacked nominal index and degraded Money/TagVO in externContracts to String (even catching a real legacy amount: String degradation in bank-wealth-demo's BankCashSubmitPortConnectorPort!) |
Added buildNominalIndex + domain.values._; upgraded bank-wealth-demo connector to strongly typed amount: Money (SPEC-S19) |
| M07 | ReadSide nested Seq[Optional[String]] / Map[String, Optional[TagVO]] / Optional[Seq[Money]] hit 3 sbt compile errors (missing Reads[Option], JsValue.toOption, and Option[JsObject].getOrElse(JsNull) widening to Object) |
Added needsExplicitJsCodec, separated JsLookupResult.toOption vs Option(JsValue), explicit : play.api.libs.json.JsValue widening, and depth-indexed lambda vars (SPEC-S19) |
| M08-A/B | Pre-Z3: missing len/count >= 0 caused Z3 fake -1 gap; missing quantifier Skolem equivalence; Scala bridge: ears-simplify emitted p.x.score; Post-Z3: witness-materialize ignored @quant and let scalar x=0 shadow x.score=1 |
Added len/count >= 0 + Skolem axioms in smt-encoder, boundVars + integer comparisons in ears-simplify, and record-subfield-first + @quant materialization in witness-materialize (SPEC-S20) |
| M05 + M04 | Pre-existing repos adding their first ReadModel later never installed ProjectionModule due to overwrite: false on HandwrittenBindingsModule; full-suite mutation runs risked timeouts at scale |
Moved ProjectionModule installation into compiler-owned GeneratedBindingsModule (preserving existing handwritten setups); targeted per-aggregate specs and 180s baseline timeout in mutation-gate (SPEC-S19) |
Wave-3 Empirical Sweep (Commit 57e6440 · M02/M09–M12 + 4 Bonus Mines Eliminated)
Targeting the entire Wave-3 radar (M02 + Pre-Z3/Post-Z3 M09–M12), commit 57e6440 confirmed and eliminated all 5 radar mines plus 4 bonus deep defects uncovered during execution, verified via node --test, offline scalac, 100% Scala Mutation Gate, and real Play 2.8.18 sbt -batch compile (69 Scala + 2 .proto, 0 errors) and locked into SPEC-S21..S24:
| ID | Confirmed Defect & Root Cause | Fix & Regression Lock (57e6440) |
|---|---|---|
| M02 | Locked application tests asserted verbatim toString equality on dispatched command snapshot fields, falsely failing handwritten handlers that normalize or recompute derived values |
Relaxed scala-strict-scalatest, scala-scalatest, and typescript-node-test to non-null + runtime type-validity assertions while preserving strict equality for bindPrincipal (SPEC-S21) |
| M09 + M10 | Pre-Z3: uncoupled len == 0 / sum == 0 and vacuous forall/exists; opposing quantifiers reusing variable x collided under a single Skolem; Post-Z3: boundary witnesses failed to substitute bound vars and dropped @qdef(col), leaving M10 mutation kill rate at 71.43% |
Added alpha-normalized quantifier signatures, scoped witnesses @qel_N, default element @qdef(col), coupled collection axioms, and distinct-scalar len >= 2 in smt-encoder; aligned first-hit-witness and witness-materialize (defaultElem + activeElements), raising M10 mutation kill rate to 100% (SPEC-S22) |
| M11 | Rules guarding sum(scores) > 100 solved @agg(sum:scores) in Z3, but witness-materialize still emitted small default lists that fell short of the target sum |
Implemented exact BigInt scaled decomposition of @agg(sum:col) in witness-materialize for both Seq[Int] and fixed-scale Seq[Decimal(scale)], cooperating with len/count and active quantifier elements (SPEC-S22) |
| M12 | Map[String, ValueObject] member access (state.entries[key].score) was broken across binder, SMT, witness materialization, Scala, and TS emitters |
Wired end-to-end: binder type inference through index -> member, typed map-subfield SMT arrays with scale/enum propagation, map-subfield probing & mapPresence gating in first-hit-witness, Scala .get(k).map(_.f).getOrElse(...) in ears-simplify, and TS ?.[f] ?? fallback in typescript.mjs (SPEC-S23) |
| Bonus #1–#4 | Real probes surfaced 4 additional latent defects: (1) multi-branch L1 commands dropped extra acceptance rules in 1.0's single-else template; (2) typescript.mjs emitted cmd.x.score inside quantifiers; (3) nested ExactType post: updates emitted invalid .copy(...) on sealed abstract case class ... private (...); (4) unconstrained ExactType unit fields materialized as "", making Money.create fall back to Money.Zero |
(1) Emitted full First-Hit if / else if / else for multi-branch L1 in v1-strict-scala (24/24 1.0 parity intact); (2) tracked boundVars/boundVarTypes and sum/len/count in typescript.mjs; (3) emitted .create(...).getOrElse(...) in buildNestedCopy; (4) defaulted unconstrained unit fields to resolvedType.units?.[0] (SPEC-S22..S24) |
Wave-4 Empirical Sweep (Commit 1e87c6a · Proto3 Nested Containers + Play 5-Layer Authz Parity)
Wave-4 targeted T01/T05 (Proto3 persistence for nested containers on Aggregate state) and T10 (PlayController 5-layer Authz parity) using a 2-subdomain monolith probe (orders + billing with ReadModels, Stories, Authz, and nested containers). Commit 1e87c6a eliminated both cross-layer defects, verified by real sbt -batch compile (111 Scala sources + 3 .proto files, 0 errors in 16s) and locked into SPEC-S25:
| Radar ID | Confirmed Defect & Root Cause | Fix & Regression Lock (1e87c6a) |
|---|---|---|
| M13 | T01 + T05 · Invalid Proto3 Nested Containers: Aggregate states declaring Optional[Seq[String]], Seq[Optional[String]], or Map[String, Optional[TagVO]] broke scalapb / sbt compile because Proto3 forbids nested repeated/optional inside repeated/map |
Added recursive Proto3 BoxPO wrapper synthesis (SeqStringBoxPO, OptStringBoxPO, OptTagVOBoxPO, etc.) in v1-strict-block-cd.mjs and spliced encode<BoxPO> / decode<BoxPO> into SharedValueProtoConverters.scala (including zero-VO fallback) without touching 1.0 emitter/families/ (24/24 parity preserved) (SPEC-S25) |
| M15 | T10 · PlayController Principal Map & HTTP/2 Header Case Drift: v1-strict-api-auth.mjs omitted "entitlements" and "attributes" from PlayController's principal map (diverging from HttpRouter), and resolvePrincipalBinding used case-sensitive header lookups that broke under HTTP/2 lowercased headers |
Added "entitlements" -> ctx.entitlements, "attributes" -> ctx.attributes in PlayController and case-insensitive lookupAttr in resolvePrincipalBinding, restoring full parity between HttpRouter and live Play (SPEC-S25) |
Wave-5 Empirical Sweep (Commit 93a6350 · Nested-Map Stack Overflow + Handwritten Method Sync + Package-Rename Pruning)
Wave-5 probed all four M16–M19 targets through real sbt -batch compile + Z3 + TS/Scala + Mutation Gate: M16 (form: decimal ExactType) (66 Scala + 2 .proto, 0 errors) and M18B (nonlinear QF_NIA qty * unitPrice) verified healthy end-to-end, while 3 confirmed high-impact defects (M18A / M17 / M19) were detonated, eliminated in commit 93a6350, and locked into SPEC-S26..S27:
| Radar ID | Confirmed Defect & Root Cause | Fix & Regression Lock (93a6350) |
|---|---|---|
| M18A | T08 · Nested Map[String, Map[String, VO]] Stack Overflow + Invalid Scala _.: state.grid[row][col].score triggered infinite mutual recursion (encVal <-> encBool → RangeError: Maximum call stack size exceeded) in smt-encoder.mjs; ears-simplify emitted invalid Scala _.; unconstrained map presence caused Z3 to default present=false and wipe witnesses |
Broke encVal/encBool recursion, generalized extractIndexedAccess to arbitrary-depth nested (Array Int ...) SMT arrays with hasPresence gating, and wired arbitrary-depth indexing across ears-simplify, typescript.mjs, first-hit-witness, and witness-materialize; TS + Scala + 100% Mutation Gate + real sbt -batch compile (54 Scala + 2 .proto, 0 errors in 15s) pass (SPEC-S26) |
| M17 | T14 · Evolving Existing Repos with New L2 Commands or externContracts Broke sbt: overwrite: false skipped ScorerComputationsImpl.scala and EnginePortConnectorImpl.scala, so adding scoreBeta / checkBeta caused sbt compile to fail with class needs to be abstract |
Added non-destructive syncMissingScalaMethods (appends only missing override def stubs before the class's closing }, preserving 100% of existing user code/comments) plus handwrittenDrift diagnostics when HandwrittenBindingsModule lacks GeneratedBindingsModule; real sbt -batch compile (62 Scala + 1 .proto, 0 errors in 14s) pass (SPEC-S27) |
| M19 | T11 · Package Rename Left Stale handwritten/ Starter Files Breaking sbt: Renaming packageName pruned old generated-scaffold/ files but left unmodified starter ServerSnapshotProviderImpl / HandwrittenBindingsModule under handwritten/scala/<oldPkg>/, causing not found: type in sbt |
Persisted packageName and starterHandwrittenHashes in .truthsrc/generated-scala-manifest.json: automatically prunes untouched starter files (matching starter SHA-256) and old-package src_managed proto caches, while preserving user-modified files and reporting STALE_HANDWRITTEN_FILE; real sbt -batch compile (69 Scala + 2 .proto, 0 errors in 16s) pass (SPEC-S27) |
Wave-6 Empirical Sweep (Commit 8950ba3 · Event-Triggered Policy Lineage + Null-Safe Optional[VO] Member Access)
Wave-6 probed T01/T08/T09 across reactive Policy stories, Map post: mutations, and Optional[ValueObject] member chains: M21 (state.buckets'[bucket] = ... + state.note' = none) verified healthy end-to-end (49 Scala + 1 .proto, 0 errors + 100% Mutation Gate), while 2 deep defects (M20 / M23) were confirmed, eliminated in commit 8950ba3, and locked into SPEC-S28:
| Radar ID | Confirmed Defect & Root Cause | Fix & Regression Lock (8950ba3) |
|---|---|---|
| M20 | T09 · False V2_LINEAGE_UNCONSUMED_NUMERIC_FIELD Error on Event-Triggered Policy Stories: When a reactive story declared WHEN event Trade.TradeConfirmed SHALL dispatch Ledger.PostEntry, verifyDispatchLineage marked amount: Money as @PROPAGATED but failed to record it in consumedEventFields, causing compile-v2 to fail closed |
Passed consumedEventFields into verifyDispatchLineage so every @PROPAGATED field consumed by an event-triggered story is registered; full reactive Policy build with Money/TagVO/Optional[String] passed real sbt -batch compile (87 Scala + 3 .proto, 0 errors in 22s) (SPEC-S28) |
| M23 | T01 + T08 · Optional[ValueObject] Member Access Failed scalac & Risked TS Null Dereference: Guards like state.profile is some AND state.profile.score < 50 emitted state.profile.score < BigDecimal("50") in Scala (value score is not a member of Option[ProfileVO]) and unguarded .score in TS under conjunction reordering |
Added stepFieldType and arbitrary-depth optional chaining across ears-simplify (.map(_.score).getOrElse(0L), switching to .flatMap for nested Optional) and typescript.mjs ((state.profile?.score ?? 0)); TS + Scala + 100% Mutation Gate + real sbt -batch compile (52 Scala + 2 .proto, 0 errors in 20s) pass (SPEC-S28) |
Wave-7 Empirical Sweep (Commit cf4545a · Scalar Optional Narrowing + OR/Optional Boundary Witness + GET Query Coercion + forall+sum LIA + Sync Drift Surfacing)
Wave-7 hit 4/4 across radar targets M24–M27, and the 100% Mutation Gate additionally caught bonus defect M24B (<= -> < mutants masked behind OR short-circuiting), eliminating 5 cross-layer defects in commit cf4545a, verified across TS + Scala + 100% Mutation Gate + three real sbt -batch compile builds (M24 48 Scala + 1 .proto, M25 48 Scala, M26 48 Scala + 1 .proto, all 0 errors) and locked into SPEC-S29..S30:
| Radar ID | Confirmed Defect & Root Cause | Fix & Regression Lock (cf4545a) |
|---|---|---|
| M24 | T01 + T08 · Guarded Scalar Optional[Int/Decimal/String] Rejected by binder: Even when guarded by state.optLimit is some AND requested > state.optLimit or (state.optLimit is none OR requested <= state.optLimit), binder.mjs rejected all three scalar optionals with EARS_TYPE_MISMATCH |
Added flow-sensitive narrowing (extractEmptinessFacts + narrowLookupWithSomePaths) in binder.mjs: narrows Optional[T] to T strictly under is some / != none conjunctions or is none / == none disjunctions while keeping unguarded comparisons rejected; synced safe .getOrElse(...) / (x ?? fallback) unwrapping across ears-simplify.mjs, scala.mjs, and typescript.mjs (SPEC-S29) |
| M24B (Bonus) | T08 + T13 · OR/Optional Short-Circuiting Masked Boundary Mutants (60% Kill Rate): For (state.optLimit is none OR requested <= state.optLimit), first-hit-witness asserted (= requested state.optLimit) without requiring state.optLimit is some; Z3 chose None, deduplication dropped the witness, and <= -> < survived |
Extended collectBoundaryEqualityAssertions with disjunctive path conditions (negating sibling OR branches) and .__present = true presence constraints for referenced optionals, lifting M24 mutation kill rate from 60% to 100% (SPEC-S29) |
| M25 | T10 · GET Query Params Degraded to Raw String Across TS/Scala/Play & Scala HTTP Oracle Cheated via body: GET ?page=2&onlyActive=true&minPrice=10.00 arrived as strings in onion-ts, onion-scala, v1-strict-block-cd, and PlayController, while Scala InterfacesHttpSpec bypassed query by placing GET params into body |
Derived queryParamTypes in onion-routes.mjs; wired typed Int/Bool/Decimal coercion across onion-ts (coerceQueryParams), onion-scala & v1-strict-block-cd (QueryParamCoercer), and v1-strict-api-auth (PlayController.coerceQueryValue); switched Scala InterfacesHttpSpec GET cases to real query = Map[String, String] (SPEC-S30) |
| M26 | T08 · Missing Linear forall+sum Axioms Caused Spurious Z3 Gaps: Exhaustive rules combining len(scores) > 0 AND forall x in scores: x > 0 AND sum(scores) >= len(scores) failed V2_SMT_GATE_FAILED |
Added pure-LIA (QF_AUFLIA) constant-bound axioms in smt-encoder.mjs (forall / not exists → sum >= lo * len & sum <= hi * len, len == 1 => sum == def, plus active-witness coupling) with zero nonlinearity; TS + Scala + 100% Mutation Gate + real sbt pass (SPEC-S29) |
| M27 | T14 · check-v2 --sync Dropped Handwritten Sync/Stale/Drift Diagnostics: generateScalaCqrsPlayServiceV2 returned syncedHandwrittenMethods, prunedHandwrittenFiles, staleHandwrittenFiles, and handwrittenDrift, yet check-v2.mjs omitted them from syncSummary and human output |
Aggregated all four fields into res.sync in check-v2.mjs and emitted actionable [WARN] STALE_HANDWRITTEN_FILE / HANDWRITTEN_DRIFT lines in renderCheckV2Human on both PASS and FAIL paths (SPEC-S30) |
Wave-8 Empirical Sweep (Commit df54bbb · Multi-BC External-Event-Bridge Typed Payloads + ReadSide Multi-Event Option Wrapping)
Wave-8 pushed real sbt -batch compile across four deep seams—Multi-BC packaging (Saga + Effect + #46 external-event-bridge + ReadModel), Seq[VO] quantifiers with Optional subfields, multi-event partial ReadSide projections, and Map invariant axioms: M29 (Seq[VO] with Optional[String] subfield quantifier) (52 Scala + 2 .proto, 0 errors + 100% Mutation Gate) and M31 (Map[String, Decimal(2)] ALWAYS invariant + in + post: update) (48 Scala + 1 .proto, 0 errors + 100% Mutation Gate) verified healthy end-to-end, while 2 real sbt compile bombs (M28 / M30) were confirmed, eliminated in commit df54bbb, and locked into SPEC-S31:
| Radar ID | Confirmed Defect & Root Cause | Fix & Regression Lock (df54bbb) |
|---|---|---|
| M28 | T05 + T11 · Multi-BC #46 external-event-bridge Broke sbt compile: When domainMap.integrations wired a cross-BC bridge, v1-strict-orchestration.mjs passed outputType = String and empty slotMembers = [] to 1.0 external-event-bridge, emitting invalid def billingPaid(output: String): OrderPlaced = OrderPlaced() and Vector(output.orderId) |
Emitted a typed <Producer>Payload case class under domain/values/ (carrying full canonical event fields and a String identity key) and populated slotMembers / identityKeys in v1-strict-orchestration.mjs without touching 1.0 emitter/families/ (24/24 parity preserved); 100 Scala + 4 .proto multi-subdomain BC passed real sbt -batch compile with 0 errors (SPEC-S31) |
| M30 | T01 · ReadSide Multi-Event Partial Projection Missing T -> Option[T] Wrapping Broke #26 & #28 in sbt: When a ReadModel stored fields from later lifecycle events (LoanApproved) as Optional[Decimal(2)] / Optional[RiskNote], both LoanOverviewApplyEvent.scala (#26) and LoanOverviewReadsideProjectionHandler.scala (#28) assigned raw e.rate / e.riskNote, failing scalac (found: T, required: Option[T]) |
Resolved canonical event field types via resolveCanonicalEventFields in v1-strict-readside.mjs to wrap Some(e.field) (T -> Option[T]) or unwrap e.field.getOrElse(default) (Option[T] -> T), fixed #28 assignment rendering and domain.values._ imports; 68 Scala + 2 .proto passed real sbt -batch compile with 0 errors (SPEC-S31) |
Wave-9 Empirical Sweep (Commits 114cd92..df54bbb · Play Production Interception + 48 Numbered Defects Across Nine Batches)
Wave-9 was the first sweep driven by real Play production delivery demands: an external contributor targeted real sbt stage + live Play boot of scala-cqrs-play-service:2 as the acceptance bar and landed nine consecutive batches, each re-verified end-to-end (628-file lint:arch 0 issues, check:contracts, test:ears 15/15, test:acceptance-v2 31/31 including all scalac/scalatest stages, real sbt -batch stage + black-box Play HTTP E2E) before merging:
| Batch (Commit) | Defects Cleared | Blast Radius |
|---|---|---|
P0 (114cd92) |
A01 real JdbcProjection.atLeastOnceAsync + ProjectionBehavior assembly (previously discarded handlers and returned Behaviors.empty shells), A02 fail-closed AuthorizationPortImpl + Guice binding + 403 FORBIDDEN_PDP, A04 Guice play.modules.enabled boot (previously a loader cast), F1 ReadSide projection handler population from canonical event fields, A03-wildcard removal of the RoleGate "*" bypass, A07 403 PRINCIPAL_BINDING_MISSING fail-closed |
ReadSide/Policy no-op boot, authz bypass, service bootstrap |
P1 (90b5321) |
A4-01/02 multi-subdomain BC merge conflict detection preserving testing/readside/lineage, A06, F2/F5–F9 ReadSide identifiers & SQL, A10 DLQ semantics | BC merge, ReadSide SQL, dead letters |
P2 (18f0547) |
A4-05/07, A13/15/16/17 guard/HTTP/Policy runtime, E2-08/12/13 SMT hardening | guard-write, HTTP runtime, SMT |
Batch4 (f23cf14) |
A4-10/17, A09 route collision, E2-01/02/05/06/07 SMT quantifier & gate soundness | route collision, SMT quantifiers |
Batch5 (64db480) |
A14, A19, E2-09/17/18/20b authz / witness materialization / solver robustness | authz, witness, solver |
Batch6 (85d55d6) |
A08 CSRF filter, A12 multi-value query params, E2-10 nested Optional post, E2-14 aggregate arity |
radar M33 mostly cleared |
Batch7 (c070fb5) |
A4-11, A11, F13, E2-04 final items | ReadSide / check-v2 gates |
Batch8 (3589163) |
Test infrastructure: 47-assertion Wave-9 regression suite (test:wave9 26/26), fail-fast lint guardrails, black-box Play E2E (test:e2e-play: sbt stage → boot real Play → /health 200 / unauth 401 / authed 200 / aggregate query 200) |
lock-in mechanism upgrade |
Batch9 (df54bbb) |
AuthorizationPortImpl orphan app/ emission path fix (written into an sbt-uncompiled v1 directory breaking sbt stage; caught by the E2E's very first run) + arch/no-orphan-handwritten-app-path lint guardrail + regression assertion tightened from loose fallback to exact path; parallelized mutation gate (acceptance wall time 1104s → 627s, -43%) |
emission paths, verification performance |
End-to-end re-verification on this machine additionally caught and fixed 2 collateral defects: the PolicyMachine bury paths' $aggType· interpolation parsed by scalac 2.12 as a single undefined identifier (pre-existing bug surfaced the first time SPEC-S28's scalac stage was actually compiled; fixed and SPEC-S28 green), and the SPEC-S10 golden assertion adapted after Batch7 changed the ReadSide reader emission shape.
Lock-in mechanism upgrade: Wave-9 regressions no longer add SPEC-S* numbers; they are pinned into test/v2-wave9-regressions.test.mjs (47 assertions) + fail-fast lint guardrails + real Play E2E, and acceptance was upgraded from "18 non-scalac items" to the full 31/31 (scalac/scalatest/sbt mandatory).
6. Next-Wave Mine-Sweeping Playbook (Level 4B): Probe Method & Residual Honest Radar
The 4-Step Adversarial Probe Method
- Pick a Tunnel: Choose an under-tested cross-module seam from T01–T14 in Figure 3.
- Craft a Minimal Adversarial Truth: Write 10–40 lines of valid but edge-case YAML +
.ears(zero VO, hybrid L1+L2, nestedOption[ExactType], Scala reserved keywords, cross-subdomain colliding names). - Run the Full Real Pipeline (never rely on regex-only unit tests):
compileCanonicalV2(real Z3)generateScalaCqrsPlayServiceV2/generateScalaCqrsPlayServiceV2ForBcemitV2ExecutableTestsnode --test+ offlinescalac+ realsbt -batch stage+ live Play HTTP roadshow
- Lock Every Confirmed Hit: Fix via general derivation (
npm run lint:arch= 0 issues,emitter/parity.mjs= 24/24 green) and lock the probe permanently asSPEC-S32+.
Residual High-Risk Radar (Honest Boundaries as of df54bbb)
M01–M31 (8 waves, 36 confirmed defects + 5 deep seams empirically verified healthy) were closed and locked in SPEC-S13..S31 through df54bbb..df54bbb. Wave-9 (114cd92..df54bbb) cleared 50 more (48 numbered defects + 2 collateral catches from full-chain re-verification) locked into the test:wave9 regression suite and black-box Play E2E — radar M33 (malformed queries & nested Optional[VO] JSON against live Play) is mostly cleared by Batch6 (A08/A12/E2-10/E2-14) verified by the Batch8 live Play E2E. The table below inventories the 3 remaining engineering boundaries (M32 / M34 / M35):
| Radar ID | Suspected Latent Mine / Known Boundary | Linked Tunnel | Recommended Adversarial Probe | Blast Radius |
|---|---|---|---|---|
| M32 | Seq[VO] Field-Level Aggregation (sum(items.amount)) & Incremental post: Append/Remove Folds: Scalar sum(scores) and full sequence replacement state.items' = items are verified end-to-end, while VO-field sums and incremental sequence append/remove folds remain unimplemented |
T08 + T09 | .ears combining sum(items.amount) <= limit and incremental state.items' append/remove folds → SMT, TS/Scala & mutation gate |
Expressiveness boundary on line-item aggregation and incremental sequence folds |
| M34 | Guided Migration CLI (migrate-handwritten-v2) for User-Edited Stale Files: Wave-7 surfaces staleHandwrittenFiles and handwrittenDrift via check-v2 --sync, but major package refactors still require manual file moves |
T14 | Add dry-run / interactive migration helper verified by zero-regression verify-v2 --strict |
Manual refactor friction on large package renames |
| M35 | ReadSide #26 projection-apply-event Advanced Forms (updateOnly / delete / persistenceIdCreate) & Cross-Aggregate Views: v2 currently routes projections through create form (Option-safe as of M30); delete events and cross-aggregate merged projections await full bridge support |
T01 + T05 | Probe a ReadModel updated by two aggregates plus a delete event through real sbt -batch compile while keeping 1.0 parity 24/24 |
Expressiveness boundary on delete & multi-aggregate CQRS views |
30-Second Failure Attribution Protocol
| Failure Signature | Owner | Required Action |
|---|---|---|
compile-v2 emits V2_SMT_GATE_FAILED, V2_FIRST_HIT_SHADOWED_RULE, V2_LINEAGE_*, or EARS_* |
Truth Source | Fix YAML / .ears specification; never weaken the Z3 gate |
Locked oracle matches truth, but @cloze implementation or ServerSnapshotProviderImpl diverges |
Handwritten Isolation Zone | Fix logic strictly inside @cloze:start..end or handwritten provider |
Generated code fails sbt stage, locked oracle sends inputs violating truth/Authz contracts, or incremental packaging leaves stale artifacts |
Compiler / Generator (metarch-truthsrc) |
File upstream issue with file:line & minimal repro → fix via 4-step probe and lock in SPEC-S* |
Closing Takeaway: Do not read this map once and file it away. Before every major release or multi-subdomain onboarding, pick the 3–5 riskiest seams from Figure 3 and radar targets M32 / M34 / M35, write a 100-line adversarial probe, and run it through real
sbt stage+ Play HTTP. Turning underground tunnels into lit corridors and turning surprises into locked probes is howmetarch-truthsrcconverges on industrial-grade determinism.