Document Version: 1.2.1

Scope: metarch-truthsrc / truthsrc-smt / co-arising compiler and AI Agent Harness toolchain

Reference Benchmark Project: co-arising/bank-wealth-demo (single-order subscription and refund FundOrder, financial quota thresholds FundQuota, unified stream-batch SIP SipPlan, user story CashFundPurchase)

Core Principles: Controlled EARS as Single Truth Source, Authoring Freedom (allowing LLM plain-language drafting), One-Way Read-Only Projections for AC/Decision Tables, Natural Verb-Object Syntax & High Information Density, Solution-Free (No Implementation Leakage), SMT-LIB 2 Standard Solver-Agnostic

1. Architecture Overview: Single Truth Source + Single-Hop Verification + Read-Only Projections

Given completed structured domain modeling (Event / Command / Role / Aggregate / Policy / Timer / Context Mapping / User Story Mapping), co-arising establishes a single-hop deterministic verification loop, avoiding the lossy two-hop round-trip of "Plain-Language AC -> LLM Translation -> EARS -> .smt2":

  [Authoring Assist Layer (Uncommitted)]   [Git Repo Single Truth Source]        [Deterministic Single-Hop Compilation & Read-Only Projections]
  ──────────────────────────────────────   ──────────────────────────────        ──────────────────────────────────────────────────────────────
  Plain-Language Ideas / EventStorming                                           ┌─▶ Projection 1: Style E (PM-Friendly Plain-Language AC)
        │                                                                        ├─▶ Projection 2: Style B (DMN Decision Table View)
        ▼ (Optional LLM Drafting)                                                ├─▶ Projection 3: SMT-LIB 2 (.smt2) ──▶ Z3/cvc5
  Domain Owner Review & Merge ───────────▶ Controlled EARS 1.0 Truth Source      │     ├── Conflicts/Gaps ──▶ A/B Clarification Card
                                           (Canonical EN + Bilingual Isomorphic  │     └── All Green      ──▶ Boundary Witness Samples
                                            Lexicon)                             └─▶ Projection 4: TestIR ──▶ Locked Gherkin / ScalaTest
                                                                                                          ──▶ @cloze TDD Cloze Completion

  1. Authoring Freedom: The role responsible for the EARS truth source (Architect, Domain Expert, or Tech Lead) can use an LLM to rapidly draft plain-language requirements into Controlled EARS, but plain-language drafts are never committed as a persistence layer.

  2. Single Truth Source: The Git repository maintains only one Controlled EARS source bound to the truthsrc symbol table (supporting Style A: Natural Indented as the primary standard, and optionally the isomorphic Style C: Block DSL).

  3. One-Way Read-Only Projections: Plain-language AC for PM review (Style E) and decision tables for risk/architecture blind-spot checks (Style B) are deterministically generated by the compiler from the EARS truth source. They can be rebuilt at any time and never drift.

2. co-arising EARS 1.0 Language Specification

2.1 Bilingual Isomorphic Keyword Table (Canonical EN + Optional CN Alias)

English keywords serve as the open-source primary standard (Canonical Profile), while the lexer natively supports Chinese isomorphic keywords and Unicode business predicate identifiers—both compile 100% into the exact same AST and .smt2.

Semantic Category Canonical EN CN Profile Alias Syntax & Expression Conventions
Slice / Story Header slice / story 切片 / 故事 Declares the owning aggregate slice or application-layer user story
Named Predicate Section where: / extern 定义: / 外部判定 Reuses high-frequency conditions; enforces positive/affirmative naming (no "un-/not-/no-" prefixes to prevent double negatives)
Global Axioms axioms: / ALWAYS 公理: / 恒成立 System baselines that hold in the initial state and after any state fold
Rules Section rules: / [RULE_ID] 规则: / [RULE_ID] Inline [RULE_ID] directly links to truthsrc's stable aggregateRuleRefs anchor
EARS Structural Keywords WHILE / WHEN / IF ... THEN / WHERE 当处于 / 当收到 / 如果 ... 则 / 当启用 Parser infers the sentence pattern from the leading keyword; no manual pattern: required
Modality SHALL / SHALL NOT 必须 / 禁止 Mandatory behavior and prohibited behavior (source of SMT mutual-exclusion conflicts)
Natural Logic and / or / not / in / is / is not 且 / 或 / 不满足 / 属于 / 为 / 不为 Replaces code logical operators; supports DMN FEEL-like intervals [min..max] and [start..end)
Domain Action reject [request] with <Code> 拒绝请求,返回 <Code> Strict verb-object grammar: the object is the rejected request; the error code is the reason/return code
Domain Action emit / transition ... -> ... / succeed-empty / keep 发射 / 状态变为 / 幂等空成功 / 维持 Covers event sourcing, state machine transitions, and idempotent side-effect-free replay semantics
Application Action pin ... from (...) / dispatch / respond ... with / expose ... as 固定 / 派发 / 响应 / 展示 Dedicated to trusted boundaries and read-model isolation in layer: application
Post-Fold post: (x' = ...) 变更后: Used by Z3 for inductive invariant proofs (Inv(s) ∧ Guard ∧ Post ⇒ Inv(s'))

2.2 Formal EBNF Grammar (Style A Bilingual Isomorphic Core)

The syntactic layer relies solely on abstract keyword tokens (KW_*), while the lexical layer uniformly maps both Canonical EN and CN Profile aliases, guaranteeing 100% identical ASTs for bilingual inputs:

(* ═══ 1. Syntactic Productions (Language-Agnostic) ═══ *)
SpecFile        ::= Header [ WhereSection ] [ AxiomsSection ] RulesSection ;
Header          ::= (KW_SLICE | KW_STORY) QualifiedName [ KW_LAYER (KW_DOMAIN | KW_APP) ] ;

WhereSection    ::= KW_WHERE_SEC ":" { PredDef | ExternDef } ;
PredDef         ::= Ident "=" BoolExpr [ KW_AS StringLit ] ;   (* "as" is used for Style E plain-language projection *)
ExternDef       ::= KW_EXTERN Ident [ "(" IdentList ")" ] [ KW_AS StringLit ] ;

AxiomsSection   ::= KW_AXIOMS ":" { "[" RuleId "]" KW_ALWAYS (BoolExpr | Modality ActionList) } ;
RulesSection    ::= KW_RULES ":" { RuleEntry } ;
RuleEntry       ::= "[" RuleId "]" Statement [ PostSection ] ;

Statement       ::= KW_ALWAYS Modality ActionList
                  | [ KW_OPT BoolExpr ] [ KW_WHILE BoolExpr ] KW_WHEN Ident [ KW_AND BoolExpr ] Modality ActionList
                  | [ KW_OPT BoolExpr ] [ KW_WHILE BoolExpr ] KW_IF BoolExpr [ KW_WHILE BoolExpr ] [ KW_WHEN Ident ] KW_THEN Modality ActionList ;

Modality        ::= KW_SHALL | KW_SHALL_NOT ;
ActionList      ::= Action { KW_AND Action } ;

Action          ::= RejectAction
                  | KW_EMIT Ident
                  | KW_TRANSITION Path "->" Expr
                  | KW_SUCCEED_EMPTY
                  | KW_KEEP BoolExpr
                  | KW_PIN Ident KW_FROM "(" IdentList ")"
                  | KW_DISPATCH QualifiedName
                  | KW_RESPOND Ident [ KW_WITH BoolExpr ]
                  | KW_EXPOSE Ident KW_AS BoolExpr ;

RejectAction    ::= "reject" [ "request" | Ident ] "with" Ident
                  | "拒绝" [ "请求" | Ident ] ("," | ",") "返回" Ident ;

PostSection     ::= KW_POST ":" { Path "'" "=" Expr } ;

BoolExpr        ::= OrExpr ;
OrExpr          ::= AndExpr { KW_OR AndExpr } ;
AndExpr         ::= NotExpr { KW_AND NotExpr } ;
NotExpr         ::= KW_NOT NotExpr | AtomPred ;
AtomPred        ::= Expr ("==" | "!=" | ">" | ">=" | "<" | "<=") Expr
                  | Expr [ KW_NOT ] KW_IN ( SetLit | IntervalLit | Path )
                  | Path KW_IS [ KW_NOT ] (KW_EMPTY | KW_NON_EMPTY)
                  | "(" BoolExpr ")"
                  | Ident [ "(" ArgList ")" ] ;
IntervalLit     ::= ("[" | "(") Expr ".." Expr ("]" | ")") ;

(* ═══ 2. Bilingual Lexical Productions ═══ *)
KW_SLICE        ::= "slice"         | "切片" ;
KW_STORY        ::= "story"         | "故事" ;
KW_LAYER        ::= "layer"         | "层级" ;
KW_DOMAIN       ::= "domain"        | "领域" ;
KW_APP          ::= "application"   | "应用" ;
KW_WHERE_SEC    ::= "where"         | "定义" ;
KW_EXTERN       ::= "extern"        | "外部判定" ;
KW_AXIOMS       ::= "axioms"        | "公理" ;
KW_RULES        ::= "rules"         | "规则" ;
KW_POST         ::= "post"          | "变更后" ;

KW_ALWAYS       ::= "ALWAYS"        | "恒成立" ;
KW_OPT          ::= "WHERE"         | "当启用" ;
KW_WHILE        ::= "WHILE"         | "当处于" ;
KW_WHEN         ::= "WHEN"          | "当收到" ;
KW_IF           ::= "IF"            | "如果" ;
KW_THEN         ::= "THEN"          | "则" ;
KW_SHALL        ::= "SHALL"         | "必须" ;
KW_SHALL_NOT    ::= "SHALL" "NOT"   | "禁止" ;

KW_AND          ::= "and" | "AND"   | "且" ;
KW_OR           ::= "or"  | "OR"    | "或" ;
KW_NOT          ::= "not" | "NOT"   | "不满足" ;
KW_IN           ::= "in"            | "属于" ;
KW_IS           ::= "is"            | "为" ;
KW_EMPTY        ::= "empty"         | "空" ;
KW_NON_EMPTY    ::= "non-empty"     | "非空" ;

KW_EMIT         ::= "emit"          | "发射" ;
KW_TRANSITION   ::= "transition"    | "状态变为" ;
KW_SUCCEED_EMPTY::= "succeed-empty" | "幂等空成功" ;
KW_KEEP         ::= "keep"          | "维持" ;
KW_PIN          ::= "pin"           | "固定" ;
KW_FROM         ::= "from"          | "来自" ;
KW_DISPATCH     ::= "dispatch"      | "派发" ;
KW_RESPOND      ::= "respond"       | "响应" ;
KW_WITH         ::= "with"          | "携带" ;
KW_EXPOSE       ::= "expose"        | "展示" ;
KW_AS           ::= "as"            | "作为" ;

(* Supports both ASCII and Unicode business predicate identifiers *)
Ident           ::= UnicodeLetter { UnicodeLetter | Digit | "_" | "-" } ;

(Note: Style C is an isomorphic block-structured variant that simply replaces indented blocks with KW_SLICE X { KW_DEFINE ... KW_RULE [ID] { ... } }, sharing the exact same parsed AST.)

2.3 Predicate Expressiveness and SMT-LIB 2 Tiered Boundaries

Following AWS Cedar's design philosophy of "intentionally trading away Turing completeness for 100% analyzability," all predicates are automatically routed by SMT theory:

Predicate Tier Share Typical Enterprise Business Rules SMT-LIB 2 Theory Compiler Strategy
L1 Core Decidable Tier ~85% Fixed-point monetary amounts (cents), state machine enums, cursor ordering, dual-threshold accumulation, revision intervals [effectiveSlot..end), Map membership QF_AUFLIA + DT Default mode; millisecond-level, 100% decidable solving
L2 Strings / Multi-Step Temporal / Local Multiplication ~10% Fund NAV and share floor-division sandwich checks (shares * nav <= netAmount), multi-step state machines (pause -> skip -> resume never resurrects) QF_NIA (slice-isolated) / QF_SLIA (cvc5) / k-step BMC Enable QF_NIA per isolated slice (with 2s timeout); downgrade to extern during cross-aggregate verification
L3 External I/O & Black-Box Logic ~5% Session authentication, CSRF verification, external TA callback parsing, host deterministic IDs (@host) extern uninterpreted Boolean predicates Preserves 100% Boolean branching and gap checks without intruding into infrastructure

3. Four Complete Practical Examples from bank-wealth-demo (Bilingual Comparison)

Sections 3.1 through 3.4 each provide both the Canonical EN and CN Profile versions. Their compiled ASTs and .smt2 outputs are 100% equivalent.

3.1 Example 1 (Domain Logic · Single Order): Cash Fund Subscription & Independent Refund (FundOrder)

(1) Subscription Settlement Request: FundOrder.RequestFundPurchaseSettlement

Canonical EN (Style A)

slice FundOrder.RequestFundPurchaseSettlement

where:
  validAmount      = amount.currency == "CNY" and amount.amount > 0.00      as "subscription amount is positive CNY"
  validAccounts    = investorAccountId != fundCollectionAccountId           as "investor account differs from collection account"
  validIdentity    = operationId is non-empty and fundCode is non-empty     as "operation ID and fund code are non-empty"
  sameAsRecorded   = operationId == order.operationId
                     and investorAccountId == order.investorAccountId
                     and fundCollectionAccountId == order.fundCollectionAccountId
                     and fundCode == order.fundCode
                     and amount == order.amount                             as "replay parameters match original subscription record"
  extern matchesCashOriginal                                                as "matches trusted inbound original request"

axioms:
  [AX-FO-1] ALWAYS order.status in {"new", "payment-requested", "payment-succeeded", "ta-confirmed", "canceled"}

rules:
  [ORDER_RESOURCE]              IF fundOrderId != order.id
                                THEN SHALL reject request with ORDER_RESOURCE

  [ORDER_ACCOUNTS]              IF not validAccounts
                                THEN SHALL reject request with ORDER_ACCOUNTS

  [ORDER_AMOUNT]                IF not validAmount
                                THEN SHALL reject request with ORDER_AMOUNT

  [ORDER_OPERATION]             IF not validIdentity
                                THEN SHALL reject request with ORDER_OPERATION

  [CASH_ADMITTED_PAYMENT_MATCH] IF order.cashRequestSource is non-empty and not matchesCashOriginal
                                THEN SHALL reject request with CASH_ADMITTED_PAYMENT_MATCH

  [ORDER_REPLAY_CONFLICT]       IF not sameAsRecorded WHILE order.status != "new"
                                THEN SHALL reject request with ORDER_REPLAY_CONFLICT

  [ORDER_REQUEST_ONCE]          WHILE order.status != "new"
                                WHEN RequestFundPurchaseSettlement AND sameAsRecorded
                                SHALL succeed-empty

  [SETTLEMENT_REQUESTED]        WHILE order.status == "new"
                                WHEN RequestFundPurchaseSettlement
                                  AND fundOrderId == order.id
                                  AND validAccounts AND validAmount AND validIdentity
                                  AND (order.cashRequestSource is empty or matchesCashOriginal)
                                SHALL transition order.status -> "payment-requested"
                                  AND emit FundPurchaseSettlementRequested
                                post:
                                  order.status' = "payment-requested"
                                  order.amount' = amount

CN Profile (Style A)

切片 FundOrder.RequestFundPurchaseSettlement

定义:
  申购金额合法     = amount.currency == "CNY" 且 amount.amount > 0.00
  出入账户不同     = investorAccountId != fundCollectionAccountId
  身份与基金非空   = operationId 为 非空 且 fundCode 为 非空
  重入参数一致     = operationId == order.operationId
                     且 investorAccountId == order.investorAccountId
                     且 fundCollectionAccountId == order.fundCollectionAccountId
                     且 fundCode == order.fundCode
                     且 amount == order.amount
  外部判定 与入站原单一致

公理:
  [AX-FO-1] 恒成立 order.status 属于 {"new", "payment-requested", "payment-succeeded", "ta-confirmed", "canceled"}

规则:
  [ORDER_RESOURCE]              如果 fundOrderId != order.id
                                则 必须 拒绝请求,返回 ORDER_RESOURCE

  [ORDER_ACCOUNTS]              如果 不满足 出入账户不同
                                则 必须 拒绝请求,返回 ORDER_ACCOUNTS

  [ORDER_AMOUNT]                如果 不满足 申购金额合法
                                则 必须 拒绝请求,返回 ORDER_AMOUNT

  [ORDER_OPERATION]             如果 不满足 身份与基金非空
                                则 必须 拒绝请求,返回 ORDER_OPERATION

  [CASH_ADMITTED_PAYMENT_MATCH] 如果 order.cashRequestSource 为 非空 且 不满足 与入站原单一致
                                则 必须 拒绝请求,返回 CASH_ADMITTED_PAYMENT_MATCH

  [ORDER_REPLAY_CONFLICT]       当处于 order.status != "new"
                                如果 不满足 重入参数一致
                                则 必须 拒绝请求,返回 ORDER_REPLAY_CONFLICT

  [ORDER_REQUEST_ONCE]          当处于 order.status != "new"
                                当收到 RequestFundPurchaseSettlement 且 重入参数一致
                                必须 幂等空成功

  [SETTLEMENT_REQUESTED]        当处于 order.status == "new"
                                当收到 RequestFundPurchaseSettlement
                                  且 fundOrderId == order.id
                                  且 出入账户不同 且 申购金额合法 且 身份与基金非空
                                  且 (order.cashRequestSource 为 空 或 与入站原单一致)
                                必须 状态变为 order.status -> "payment-requested"
                                  且 发射 FundPurchaseSettlementRequested
                                变更后:
                                  order.status' = "payment-requested"
                                  order.amount' = amount

(2) Independent Refund Slice: FundOrder.RequestFundPurchaseRefund

Canonical EN (Style C Block Variant)

slice FundOrder.RequestFundPurchaseRefund {
  define paymentSucceeded = paymentTxId == order.selectedPaymentTxId
                            and order.cashPaymentFinalResults[paymentTxId] == "succeeded"
  define taRejected       = order.taStatus == "rejected"
  define refundPending    = order.refundOperationId is non-empty

  rule [REFUND_RESOURCE]    { if fundOrderId != order.id then reject request with REFUND_RESOURCE }
  rule [REFUND_PAYMENT]     { if not paymentSucceeded    then reject request with REFUND_PAYMENT }
  rule [REFUND_TA_REJECTED] { if not taRejected          then reject request with REFUND_TA_REJECTED }

  rule [REFUND_INTENT_ONCE] {
    while refundPending
    when RequestFundPurchaseRefund and paymentSucceeded and taRejected
    then succeed-empty
  }

  rule [REFUND_REQUESTED] {
    while not refundPending
    when RequestFundPurchaseRefund and fundOrderId == order.id and paymentSucceeded and taRejected
    then emit FundPurchaseRefundRequested
     and transition order.refundOutcome -> "pending"
  }
}

CN Profile (Style C Block Variant)

切片 FundOrder.RequestFundPurchaseRefund {
  定义 付款已成功   = paymentTxId == order.selectedPaymentTxId
                      且 order.cashPaymentFinalResults[paymentTxId] == "succeeded"
  定义 TA已拒绝     = order.taStatus == "rejected"
  定义 退款已发起   = order.refundOperationId 为 非空

  规则 [REFUND_RESOURCE]    { 如果 fundOrderId != order.id 则 拒绝请求,返回 REFUND_RESOURCE }
  规则 [REFUND_PAYMENT]     { 如果 不满足 付款已成功        则 拒绝请求,返回 REFUND_PAYMENT }
  规则 [REFUND_TA_REJECTED] { 如果 不满足 TA已拒绝          则 拒绝请求,返回 REFUND_TA_REJECTED }

  规则 [REFUND_INTENT_ONCE] {
    当处于 退款已发起
    当收到 RequestFundPurchaseRefund 且 付款已成功 且 TA已拒绝
    必须 幂等空成功
  }

  规则 [REFUND_REQUESTED] {
    当处于 不满足 退款已发起
    当收到 RequestFundPurchaseRefund 且 fundOrderId == order.id 且 付款已成功 且 TA已拒绝
    必须 发射 FundPurchaseRefundRequested
      且 状态变为 order.refundOutcome -> "pending"
  }
}

3.2 Example 2 (Domain Logic · Financial Quotas & NAV Shares): Dual-Threshold Control + Exact Share Conversion

In DDD, fund-wide / per-account subscription caps belong to FundQuota (pure QF_AUFLIA), while current-period fund NAV and share confirmation belong to FundOrder.ConfirmTAShares (isolated QF_NIA solving, using fixed-point integer floor-division sandwich inequalities instead of floating-point division).

(1) Dual-Threshold Control: FundQuota.ReserveSubscriptionQuota

Canonical EN

slice FundQuota.ReserveSubscriptionQuota

where:
  validAmount   = amount in [quota.minPurchase..quota.maxSingleLimit]       as "single subscription amount is within valid range"
  withinFundCap = quota.fundTotalUsed + amount <= quota.fundTotalCap        as "within fund total subscription cap"
  withinAcctCap = quota.accountUsed[accountId] + amount <= quota.perAccountCap as "within per-account subscription cap"

axioms:
  [AX-Q-1] ALWAYS quota.fundTotalUsed <= quota.fundTotalCap
  [AX-Q-2] ALWAYS quota.accountUsed[accountId] <= quota.perAccountCap

rules:
  [QUOTA_AMOUNT_RANGE] IF not validAmount   THEN SHALL reject request with QUOTA_AMOUNT_RANGE
  [QUOTA_FUND_CAP]     IF not withinFundCap THEN SHALL reject request with QUOTA_FUND_CAP
  [QUOTA_ACCOUNT_CAP]  IF not withinAcctCap THEN SHALL reject request with QUOTA_ACCOUNT_CAP

  [QUOTA_RESERVED]     WHILE validAmount and withinFundCap and withinAcctCap
                       WHEN ReserveSubscriptionQuota
                       SHALL emit SubscriptionQuotaReserved
                       post:
                         quota.fundTotalUsed'          = quota.fundTotalUsed + amount
                         quota.accountUsed'[accountId] = quota.accountUsed[accountId] + amount

CN Profile

切片 FundQuota.ReserveSubscriptionQuota

定义:
  单笔额度合法     = amount 属于 [quota.minPurchase..quota.maxSingleLimit]
  在基金总门限内   = quota.fundTotalUsed + amount <= quota.fundTotalCap
  在单户总门限内   = quota.accountUsed[accountId] + amount <= quota.perAccountCap

公理:
  [AX-Q-1] 恒成立 quota.fundTotalUsed <= quota.fundTotalCap
  [AX-Q-2] 恒成立 quota.accountUsed[accountId] <= quota.perAccountCap

规则:
  [QUOTA_AMOUNT_RANGE] 如果 不满足 单笔额度合法   则 必须 拒绝请求,返回 QUOTA_AMOUNT_RANGE
  [QUOTA_FUND_CAP]     如果 不满足 在基金总门限内 则 必须 拒绝请求,返回 QUOTA_FUND_CAP
  [QUOTA_ACCOUNT_CAP]  如果 不满足 在单户总门限内 则 必须 拒绝请求,返回 QUOTA_ACCOUNT_CAP

  [QUOTA_RESERVED]     当处于 单笔额度合法 且 在基金总门限内 且 在单户总门限内
                       当收到 ReserveSubscriptionQuota
                       必须 发射 SubscriptionQuotaReserved
                       变更后:
                         quota.fundTotalUsed'          = quota.fundTotalUsed + amount
                         quota.accountUsed'[accountId] = quota.accountUsed[accountId] + amount

(2) Current-Period NAV & Share Confirmation: FundOrder.ConfirmTAShares

Canonical EN

slice FundOrder.ConfirmTAShares

where:
  validNav       = nav > 0.0000                                             as "current fund NAV is positive"
  exactFloorMath = shares >= 0
                   and shares * nav <= order.netAmount
                   and (shares + 1) * nav > order.netAmount                 as "confirmed shares equal exact floor division of net amount by NAV"

rules:
  [TA_INVALID_NAV]     IF not validNav       THEN SHALL reject request with TA_INVALID_NAV
  [TA_SHARES_MISMATCH] IF not exactFloorMath THEN SHALL reject request with TA_SHARES_MISMATCH

  [TA_CONFIRMED]       WHILE order.paymentOutcome == "succeeded" and order.taStatus != "confirmed"
                       WHEN RecordFundTAConfirmed AND validNav AND exactFloorMath
                       SHALL transition order.taStatus -> "confirmed"
                         AND emit FundTASharesConfirmed

CN Profile

切片 FundOrder.ConfirmTAShares

定义:
  本期净值合法   = nav > 0.0000
  份额折算精确   = shares >= 0
                   且 shares * nav <= order.netAmount
                   且 (shares + 1) * nav > order.netAmount

规则:
  [TA_INVALID_NAV]     如果 不满足 本期净值合法 则 必须 拒绝请求,返回 TA_INVALID_NAV
  [TA_SHARES_MISMATCH] 如果 不满足 份额折算精确 则 必须 拒绝请求,返回 TA_SHARES_MISMATCH

  [TA_CONFIRMED]       当处于 order.paymentOutcome == "succeeded" 且 order.taStatus != "confirmed"
                       当收到 RecordFundTAConfirmed 且 本期净值合法 且 份额折算精确
                       必须 状态变为 order.taStatus -> "confirmed"
                         且 发射 FundTASharesConfirmed

3.3 Example 3 (Domain Logic · Unified Stream-Batch): Finite Cash SIP (SipPlan)

Fully covers SipPlan in bank-wealth-demo: batch observation cursor (observedCount), stream dispatch cursor (startCount), discrete clock maturity (dueSlot <= currentTick), multi-version revision effective intervals ([effectiveSlot..revisionEnd)), isolation between paused-skipped slots and backlog, and the "first-terminal-only counting, no auto-pause on three consecutive failures" invariant.

Canonical EN

slice SipPlan.StreamBatchExecution

where:
  scheduleReady     = plan.initialized and plan.scheduleSealed              as "SIP plan is initialized and schedule is sealed"
  slotValid         = position in plan.slots and plan.slots[position] == dueSlot as "position matches scheduled due slot"
  slotDue           = dueSlot <= plan.currentTick                           as "slot has reached current business clock"
  inRevisionWindow  = revision in plan.revisions
                      and plan.revisions[revision] == config
                      and dueSlot >= config.effectiveSlot
                      and (revision not in plan.revisionEnds or dueSlot < plan.revisionEnds[revision])
                                                                            as "slot falls within revision effective interval"
  alreadyTriggered  = dueSlot in plan.occurrences                           as "slot has already triggered an installment"
  sameTriggerReplay = alreadyTriggered
                      and plan.occurrences[dueSlot].revision == revision
                      and plan.occurrences[dueSlot].config == config        as "trigger replay parameters match recorded occurrence"

axioms:
  [AX-SIP-1] ALWAYS plan.startCount <= plan.observedCount and plan.observedCount <= plan.scheduleCount
  [AX-SIP-2] ALWAYS plan.successTotal + plan.failureTotal <= plan.scheduleCount
  [AX-SIP-3] ALWAYS plan.currentTick >= -1

rules:
  # --- Batch Observation: due slots during pause are marked skipped and never enter backlog ---
  [SIP_SKIP_ONCE]       WHILE dueSlot in plan.slotDisposition and plan.slotDisposition[dueSlot] == "skipped"
                        WHEN SkipPausedSipDueSlot AND scheduleReady AND slotValid
                        SHALL succeed-empty

  [SIP_SKIP_CONFLICT]   IF dueSlot in plan.slotDisposition and plan.slotDisposition[dueSlot] != "skipped"
                        WHEN SkipPausedSipDueSlot
                        THEN SHALL reject request with SIP_OBSERVATION_CONFLICT

  [SIP_SKIP_ORDER]      IF position != plan.observedCount
                        WHEN SkipPausedSipDueSlot
                        THEN SHALL reject request with SIP_OBSERVATION_ORDER

  [SIP_SKIP_NOT_DUE]    IF not slotDue
                        WHEN SkipPausedSipDueSlot
                        THEN SHALL reject request with SIP_SLOT_DUE

  [SIP_SKIP_NOT_PAUSED] IF not (plan.paused and dueSlot >= plan.pauseTick)
                        WHEN SkipPausedSipDueSlot
                        THEN SHALL reject request with SIP_PAUSE_CLASSIFICATION

  [SIP_SKIP_RECORDED]   WHILE scheduleReady and dueSlot not in plan.slotDisposition
                        WHEN SkipPausedSipDueSlot
                          AND slotValid AND position == plan.observedCount
                          AND slotDue AND plan.paused AND dueSlot >= plan.pauseTick
                        SHALL emit SipPausedDueSlotSkipped
                        post:
                          plan.slotDisposition'[dueSlot] = "skipped"
                          plan.observedCount'            = plan.observedCount + 1

  # --- Stream Dispatch: strictly consumes backlog by startCount, never resurrects skipped ---
  [SIP_ACTIVE_START]    IF plan.paused                                      WHEN TriggerSipInstallment THEN SHALL reject request with SIP_ACTIVE_START
  [SIP_START_ORDER]     IF position != plan.startCount                      WHEN TriggerSipInstallment THEN SHALL reject request with SIP_START_ORDER
  [SIP_BACKLOG_REQ]     IF plan.slotDisposition[dueSlot] != "backlog"       WHEN TriggerSipInstallment THEN SHALL reject request with SIP_BACKLOG_REQUIRED
  [SIP_REV_INTERVAL]    IF not inRevisionWindow                             WHEN TriggerSipInstallment THEN SHALL reject request with SIP_REVISION_INTERVAL
  [SIP_OCC_CONFLICT]    IF alreadyTriggered and not sameTriggerReplay       WHEN TriggerSipInstallment THEN SHALL reject request with SIP_OCCURRENCE_REPLAY_CONFLICT

  [SIP_OCC_ONCE]        WHILE sameTriggerReplay
                        WHEN TriggerSipInstallment AND scheduleReady AND slotValid
                        SHALL succeed-empty

  [SIP_TRIGGERED]       WHILE scheduleReady and not plan.paused and not alreadyTriggered
                        WHEN TriggerSipInstallment
                          AND slotValid AND position == plan.startCount
                          AND plan.slotDisposition[dueSlot] == "backlog"
                          AND inRevisionWindow
                        SHALL emit SipInstallmentTriggered
                        post:
                          plan.occurrences'[dueSlot] = @host(StableSipOccurrence)
                          plan.startCount'           = plan.startCount + 1

  # --- Terminal Deduplication: count only on first terminal state, never auto-pause on failures ---
  [SIP_TERMINAL_ONCE]   WHILE occurrenceId in plan.firstTerminals and plan.firstTerminals[occurrenceId] == "failed"
                        WHEN RecordSipInstallmentFailed
                        SHALL succeed-empty

  [SIP_FAIL_NO_PAUSE]   WHILE occurrenceId not in plan.firstTerminals
                        WHEN RecordSipInstallmentFailed
                        SHALL emit SipInstallmentFailed
                          AND keep plan.paused == plan.paused
                        post:
                          plan.firstTerminals'[occurrenceId] = "failed"
                          plan.failureTotal'                 = plan.failureTotal + 1
                          plan.paused'                       = plan.paused

CN Profile

切片 SipPlan.StreamBatchExecution

定义:
  日程已就绪       = plan.initialized 且 plan.scheduleSealed
  槽位匹配         = position 属于 plan.slots 且 plan.slots[position] == dueSlot
  槽位已到期       = dueSlot <= plan.currentTick
  在修订有效期内   = revision 属于 plan.revisions
                     且 plan.revisions[revision] == config
                     且 dueSlot >= config.effectiveSlot
                     且 (不满足 (revision 属于 plan.revisionEnds) 或 dueSlot < plan.revisionEnds[revision])
  当期已触发       = dueSlot 属于 plan.occurrences
  触发重入一致     = 当期已触发
                     且 plan.occurrences[dueSlot].revision == revision
                     且 plan.occurrences[dueSlot].config == config

公理:
  [AX-SIP-1] 恒成立 plan.startCount <= plan.observedCount 且 plan.observedCount <= plan.scheduleCount
  [AX-SIP-2] 恒成立 plan.successTotal + plan.failureTotal <= plan.scheduleCount
  [AX-SIP-3] 恒成立 plan.currentTick >= -1

规则:
  # --- 批处理观察侧:暂停期间到期槽位记为 skipped,绝不进入 backlog ---
  [SIP_SKIP_ONCE]       当处于 dueSlot 属于 plan.slotDisposition 且 plan.slotDisposition[dueSlot] == "skipped"
                        当收到 SkipPausedSipDueSlot 且 日程已就绪 且 槽位匹配
                        必须 幂等空成功

  [SIP_SKIP_CONFLICT]   如果 dueSlot 属于 plan.slotDisposition 且 plan.slotDisposition[dueSlot] != "skipped"
                        当收到 SkipPausedSipDueSlot
                        则 必须 拒绝请求,返回 SIP_OBSERVATION_CONFLICT

  [SIP_SKIP_ORDER]      如果 position != plan.observedCount
                        当收到 SkipPausedSipDueSlot
                        则 必须 拒绝请求,返回 SIP_OBSERVATION_ORDER

  [SIP_SKIP_NOT_DUE]    如果 不满足 槽位已到期
                        当收到 SkipPausedSipDueSlot
                        则 必须 拒绝请求,返回 SIP_SLOT_DUE

  [SIP_SKIP_NOT_PAUSED] 如果 不满足 (plan.paused 且 dueSlot >= plan.pauseTick)
                        当收到 SkipPausedSipDueSlot
                        则 必须 拒绝请求,返回 SIP_PAUSE_CLASSIFICATION

  [SIP_SKIP_RECORDED]   当处于 日程已就绪 且 不满足 (dueSlot 属于 plan.slotDisposition)
                        当收到 SkipPausedSipDueSlot
                          且 槽位匹配 且 position == plan.observedCount
                          且 槽位已到期 且 plan.paused 且 dueSlot >= plan.pauseTick
                        必须 发射 SipPausedDueSlotSkipped
                        变更后:
                          plan.slotDisposition'[dueSlot] = "skipped"
                          plan.observedCount'            = plan.observedCount + 1

  # --- 流式派发侧:严格按 startCount 消费 backlog,永不复活 skipped ---
  [SIP_ACTIVE_START]    如果 plan.paused                                    当收到 TriggerSipInstallment 则 必须 拒绝请求,返回 SIP_ACTIVE_START
  [SIP_START_ORDER]     如果 position != plan.startCount                    当收到 TriggerSipInstallment 则 必须 拒绝请求,返回 SIP_START_ORDER
  [SIP_BACKLOG_REQ]     如果 plan.slotDisposition[dueSlot] != "backlog"     当收到 TriggerSipInstallment 则 必须 拒绝请求,返回 SIP_BACKLOG_REQUIRED
  [SIP_REV_INTERVAL]    如果 不满足 在修订有效期内                          当收到 TriggerSipInstallment 则 必须 拒绝请求,返回 SIP_REVISION_INTERVAL
  [SIP_OCC_CONFLICT]    如果 当期已触发 且 不满足 触发重入一致              当收到 TriggerSipInstallment 则 必须 拒绝请求,返回 SIP_OCCURRENCE_REPLAY_CONFLICT

  [SIP_OCC_ONCE]        当处于 触发重入一致
                        当收到 TriggerSipInstallment 且 日程已就绪 且 槽位匹配
                        必须 幂等空成功

  [SIP_TRIGGERED]       当处于 日程已就绪 且 不满足 plan.paused 且 不满足 当期已触发
                        当收到 TriggerSipInstallment
                          且 槽位匹配 且 position == plan.startCount
                          且 plan.slotDisposition[dueSlot] == "backlog"
                          且 在修订有效期内
                        必须 发射 SipInstallmentTriggered
                        变更后:
                          plan.occurrences'[dueSlot] = @host(StableSipOccurrence)
                          plan.startCount'           = plan.startCount + 1

  # --- 终态防重计数:首次终态才计数,三连败不自动暂停 ---
  [SIP_TERMINAL_ONCE]   当处于 occurrenceId 属于 plan.firstTerminals 且 plan.firstTerminals[occurrenceId] == "failed"
                        当收到 RecordSipInstallmentFailed
                        必须 幂等空成功

  [SIP_FAIL_NO_PAUSE]   当处于 不满足 (occurrenceId 属于 plan.firstTerminals)
                        当收到 RecordSipInstallmentFailed
                        必须 发射 SipInstallmentFailed
                          且 维持 plan.paused == plan.paused
                        变更后:
                          plan.firstTerminals'[occurrenceId] = "failed"
                          plan.failureTotal'                 = plan.failureTotal + 1
                          plan.paused'                       = plan.paused

3.4 Example 4 (Application Logic · User Story): CashFundPurchase (PurchaseFundWithCash)

Canonical EN

story CashFundPurchase layer application

where:
  validSubmit = amount.currency == "CNY" and amount.amount > 0.00           as "submitted amount is positive CNY"
  extern sessionAuthenticated(principal)                                    as "customer session is authenticated"
  extern originAndCsrfValid                                                 as "origin and CSRF validation passed"
  extern fundCodeActive(fundCode)                                           as "fund code is open for subscription"
  extern requestExists(principal, clientRequestId)                          as "original record exists for this client request ID"
  extern payloadMatchesOriginal(principal, clientRequestId, fundCode, amount) as "replay payload matches original request"

axioms:
  [AX-APP-1] ALWAYS BankCashSubmit SHALL NOT supply operationId, investorAccountId, fundCollectionAccountId

rules:
  [US-CFP-01] IF not sessionAuthenticated(principal) or not originAndCsrfValid
              WHEN BankCashSubmitPort.submit
              THEN SHALL reject request with UNAUTHORIZED_OR_CSRF

  [US-CFP-02] IF not fundCodeActive(fundCode) or not validSubmit
              WHEN BankCashSubmitPort.submit
              THEN SHALL reject request with INVALID_CASH_SUBMIT

  [US-CFP-03] WHILE not requestExists(principal, clientRequestId)
              WHEN BankCashSubmitPort.submit
                AND sessionAuthenticated(principal) AND originAndCsrfValid
                AND fundCodeActive(fundCode) AND validSubmit
              SHALL pin BankCashOriginal from (principal, clientRequestId)
                AND dispatch FundOrder.RecordCashRequestSource
                AND dispatch FundOrder.RequestFundPurchaseSettlement
                AND respond BankCashAcknowledgement with ack.replayed == false and ack.accepted == true

  [US-CFP-04] WHILE requestExists(principal, clientRequestId)
              WHEN BankCashSubmitPort.submit AND payloadMatchesOriginal(principal, clientRequestId, fundCode, amount)
              SHALL respond BankCashAcknowledgement with ack.replayed == true
                AND SHALL NOT dispatch FundOrder.RequestFundPurchaseSettlement

  [US-CFP-05] IF not payloadMatchesOriginal(principal, clientRequestId, fundCode, amount)
              WHILE requestExists(principal, clientRequestId)
              WHEN BankCashSubmitPort.submit
              THEN SHALL reject request with CASH_SOURCE_CONFLICT

  [US-CFP-06] WHILE order.paymentOutcome == "succeeded" and order.taStatus != "confirmed"
              WHEN BankOrderQuery.get
              SHALL expose bank-order-view as view.paymentCompleted == true and view.taFinalized == false

CN Profile

故事 CashFundPurchase layer application

定义:
  提交金额合法               = amount.currency == "CNY" 且 amount.amount > 0.00
  外部判定 客户会话已认证(principal)
  外部判定 来源与CSRF合法
  外部判定 基金代码可申购(fundCode)
  外部判定 原请求已存在(principal, clientRequestId)
  外部判定 重入参数与原单一致(principal, clientRequestId, fundCode, amount)

公理:
  [AX-APP-1] 恒成立 禁止 BankCashSubmit 携带 operationId, investorAccountId, fundCollectionAccountId

规则:
  [US-CFP-01] 如果 不满足 客户会话已认证(principal) 或 不满足 来源与CSRF合法
              当收到 BankCashSubmitPort.submit
              则 必须 拒绝请求,返回 UNAUTHORIZED_OR_CSRF

  [US-CFP-02] 如果 不满足 基金代码可申购(fundCode) 或 不满足 提交金额合法
              当收到 BankCashSubmitPort.submit
              则 必须 拒绝请求,返回 INVALID_CASH_SUBMIT

  [US-CFP-03] 当处于 不满足 原请求已存在(principal, clientRequestId)
              当收到 BankCashSubmitPort.submit
                且 客户会话已认证(principal) 且 来源与CSRF合法
                且 基金代码可申购(fundCode) 且 提交金额合法
              必须 固定 BankCashOriginal from (principal, clientRequestId)
                且 派发 FundOrder.RecordCashRequestSource
                且 派发 FundOrder.RequestFundPurchaseSettlement
                且 响应 BankCashAcknowledgement with ack.replayed == false 且 ack.accepted == true

  [US-CFP-04] 当处于 原请求已存在(principal, clientRequestId)
              当收到 BankCashSubmitPort.submit 且 重入参数与原单一致(principal, clientRequestId, fundCode, amount)
              必须 响应 BankCashAcknowledgement with ack.replayed == true
                且 禁止 派发 FundOrder.RequestFundPurchaseSettlement

  [US-CFP-05] 当处于 原请求已存在(principal, clientRequestId)
              如果 不满足 重入参数与原单一致(principal, clientRequestId, fundCode, amount)
              当收到 BankCashSubmitPort.submit
              则 必须 拒绝请求,返回 CASH_SOURCE_CONFLICT

  [US-CFP-06] 当处于 order.paymentOutcome == "succeeded" 且 order.taStatus != "confirmed"
              当收到 BankOrderQuery.get
              必须 展示 bank-order-view as view.paymentCompleted == true 且 view.taFinalized == false

4. Read-Only Projections Automatically Derived from the Truth Source (Style E + Style B)

Using the as "..." business phrase labels in where:, the compiler deterministically generates two read-only review views with zero LLM involvement:

4.1 Style E Projection: PM-Friendly Plain-Language AC (Using FundQuota as an Example)

Feature Specification: Fund Subscription Quota Reservation (Read-Only Projection, Truth Source: fund-quota-reserve.ears)

  • AC-1 [QUOTA_AMOUNT_RANGE]: If "single subscription amount is within valid range" is not satisfied, the system shall reject the request with QUOTA_AMOUNT_RANGE.

  • AC-2 [QUOTA_FUND_CAP]: If "within fund total subscription cap" is not satisfied, the system shall reject the request with QUOTA_FUND_CAP.

  • AC-3 [QUOTA_ACCOUNT_CAP]: If "within per-account subscription cap" is not satisfied, the system shall reject the request with QUOTA_ACCOUNT_CAP.

  • AC-4 [QUOTA_RESERVED]: While "single subscription amount is within valid range", "within fund total subscription cap", and "within per-account subscription cap" are all satisfied, when a quota reservation request is received, the system shall emit SubscriptionQuotaReserved and accumulate both the fund total used quota and the per-account used quota.

4.2 Style B Projection: DMN Decision Table View (At-a-Glance Blind-Spot Detection)

Rule ID validAmount withinFundCap withinAcctCap Outcome
QUOTA_AMOUNT_RANGE false any any reject request with QUOTA_AMOUNT_RANGE
QUOTA_FUND_CAP true false any reject request with QUOTA_FUND_CAP
QUOTA_ACCOUNT_CAP true true false reject request with QUOTA_ACCOUNT_CAP
QUOTA_RESERVED true true true emit SubscriptionQuotaReserved + update totals

5. Single-Hop Deterministic Compilation from Controlled EARS 1.0 to SMT-LIB 2

truthsrc-smt translates the EARS AST directly into standard .smt2 (compatible with both z3 -smt2 and cvc5):

  • Type Mapping: Money is scaled to integer cents (×100); nav is scaled to 4-decimal fixed-point integers (×10000); Map[K, V] compiles to an existence bitmap (Array K Bool) + value array (Array K V); every rule binds a precise provenance tag via (! <expr> :named <RuleId>).

  • Five Standard (push 1) ... (pop 1) Health Checks:

    1. Mutual-Exclusion Conflict: SAT(Axioms ∧ G_emit ∧ G_reject) expects unsat.

    2. Logical Gap: SAT(Axioms ∧ ¬(G_1 ∨ ... ∨ G_n)) expects unsat.

    3. Inductive Invariant Proof: SAT(Inv(s) ∧ G_i ∧ Post(s, s') ∧ ¬Inv(s')) expects unsat.

    4. Dead Rule Detection: UNSAT(Axioms ∧ G_i) expects sat.

    5. Boundary Witness Synthesis: For each boundary condition (e.g., amount == minPurchase, quota.fundTotalUsed + amount == fundTotalCap, dueSlot == currentTick), invoke (get-model) to export exact BDD test samples.

Compilation Snippet Example: Dual-Threshold Invariant Proof (QF_AUFLIA) + Share Sandwich Check (QF_NIA Isolated)

; === A. FundQuota Slice (QF_AUFLIA, millisecond-level) ===
(set-option :produce-models true)
(set-option :produce-unsat-cores true)
(set-logic QF_AUFLIA)

(declare-const amount Int)
(declare-const min_purchase Int)
(declare-const max_single Int)
(declare-const fund_used Int)
(declare-const fund_used_next Int)
(declare-const fund_cap Int)

(assert (! (<= fund_used fund_cap) :named AX-Q-1))

; Inductive invariant proof: QUOTA_RESERVED can never breach fund total cap
(push 1)
  (assert (! (and (>= amount min_purchase) (<= amount max_single) (<= (+ fund_used amount) fund_cap)) :named QUOTA_RESERVED))
  (assert (= fund_used_next (+ fund_used amount)))
  (assert (> fund_used_next fund_cap)) ; Negation: assume cap is breached
  (check-sat) ; Expect unsat
(pop 1)

; Boundary witness synthesis: valid boundary sample hitting the exact fund total cap
(push 1)
  (assert (and (> min_purchase 0) (< min_purchase max_single) (> fund_cap max_single)))
  (assert (and (>= amount min_purchase) (<= amount max_single) (= (+ fund_used amount) fund_cap)))
  (check-sat)
  (get-model)
(pop 1)

; === B. ConfirmTAShares Isolated Slice (QF_NIA isolated + 2s timeout) ===
(set-logic QF_NIA)
(declare-const nav Int)        ; 4-decimal fixed point, e.g., 1.2500 => 12500
(declare-const net_amount Int) ; 4-decimal aligned net amount, e.g., 100.00 => 1000000
(declare-const shares Int)
(assert (and (> nav 0) (>= shares 0) (<= (* shares nav) net_amount) (> (* (+ shares 1) nav) net_amount)))
(check-sat)
(get-model)

6. Mathematical Verification Artifacts: Clarification Cards + BDD Breakdown 1:1 Aligned with the Four Examples

6.1 Conflict & Gap Clarification Card (for PMs / Architects)

When Z3 catches sat (a gap or conflict), co-arising check-spec --format json outputs the counterexample model and :named rule IDs, projecting them into an A/B clarification card:

[Requirement Gap Clarification] SipPlan.SkipPausedSipDueSlot misses the unsealed schedule scenario

  • Z3 Counterexample: plan.initialized = true, plan.scheduleSealed = false, plan.paused = true, dueSlot = 1, currentTick = 1.

  • Decision Required:

    • Option A: Explicitly reject by adding [SIP_SCHEDULE_SEALED] IF not plan.scheduleSealed WHEN SkipPausedSipDueSlot THEN SHALL reject request with SIP_SCHEDULE_SEALED.

    • Option B: Allow early skipping of unsealed schedules.

6.2 Gherkin (.feature) Breakdown — Strictly 1:1 Aligned with Section 3's Four Examples

# AUTO-GENERATED BY co-arising EARS 1.0 (LOCKED — DO NOT EDIT)

# --- Aligned with Example 3.1: Single-Order Cash Fund Subscription & Independent Refund ---
@layer:domain @aggregate:FundOrder @slice:RequestFundPurchaseSettlement
Feature: Single-Order Cash Fund Subscription Settlement and Independent Refund

  @spec:SETTLEMENT_REQUESTED @spec:ORDER_AMOUNT @spec:ORDER_ACCOUNTS @z3-witness
  Scenario Outline: Subscription settlement amount and account boundary validation
    Given FundOrder "ord-001" has status "new"
    When RequestFundPurchaseSettlement(investor=<inv>, collection=<col>, amount=<amt> <ccy>) is sent
    Then the outcome shall be <outcome>

    Examples:
      | inv     | col     | amt    | ccy | outcome                              |
      | acc-inv | acc-col | 0.01   | CNY | emit FundPurchaseSettlementRequested |
      | acc-inv | acc-col | 0.00   | CNY | reject ORDER_AMOUNT                  |
      | acc-inv | acc-inv | 100.00 | CNY | reject ORDER_ACCOUNTS                |

  @spec:REFUND_REQUESTED @spec:REFUND_INTENT_ONCE @spec:REFUND_TA_REJECTED
  Scenario: Independent refund is allowed only when payment succeeded and TA rejected; duplicate requests succeed-empty
    Given FundOrder "ord-001" has final payment outcome "succeeded" and taStatus "rejected"
    When RequestFundPurchaseRefund(order="ord-001", paymentTxId="tx-1") is sent
    Then emit FundPurchaseRefundRequested and transition refundOutcome to "pending"
    When the identical RequestFundPurchaseRefund(order="ord-001", paymentTxId="tx-1") is sent again
    Then return idempotent empty success (succeed-empty)

# --- Aligned with Example 3.2: Financial Dual-Threshold & NAV Share Confirmation ---
@layer:domain @aggregate:FundQuota @aggregate:FundOrder
Feature: Fund Subscription Dual-Threshold and TA Current-Period NAV Share Confirmation

  @spec:QUOTA_RESERVED @spec:QUOTA_FUND_CAP @spec:QUOTA_ACCOUNT_CAP @z3-witness
  Scenario Outline: Fund total cap and per-account cap boundary enforcement
    Given fund purchase range is [10.00..50000.00], fund total cap is 100000.00 (used 99000.00), per-account cap is 20000.00 (used 19500.00)
    When account "acc-inv" requests ReserveSubscriptionQuota(amount=<amt> CNY)
    Then the outcome shall be <outcome>

    Examples:
      | amt     | outcome                           |
      | 500.00  | emit SubscriptionQuotaReserved    |
      | 500.01  | reject QUOTA_ACCOUNT_CAP          |
      | 1000.01 | reject QUOTA_FUND_CAP             |
      | 9.99    | reject QUOTA_AMOUNT_RANGE         |

  @spec:TA_CONFIRMED @spec:TA_SHARES_MISMATCH @z3-witness:QF_NIA
  Scenario Outline: TA current-period NAV and share exact sandwich validation
    Given FundOrder "ord-001" has net subscription amount 100.00 CNY and payment succeeded
    When RecordFundTAConfirmed(nav=<nav>, shares=<shares>) is received
    Then the outcome shall be <outcome>

    Examples:
      | nav    | shares | outcome                    |
      | 1.2500 | 80     | emit FundTASharesConfirmed |
      | 1.2500 | 81     | reject TA_SHARES_MISMATCH  |
      | 0.0000 | 0      | reject TA_INVALID_NAV      |

# --- Aligned with Example 3.3: Unified Stream-Batch Finite Cash SIP (SipPlan) ---
@layer:domain @aggregate:SipPlan @slice:StreamBatchExecution
Feature: Unified Stream-Batch Finite Cash SIP Scheduling, Skipping, and Deduplicated Counting

  @spec:SIP_SKIP_RECORDED @spec:SIP_BACKLOG_REQ @bmc:4-step
  Scenario: Due slots during pause are marked skipped and must never be resurrected after resume
    Given SipPlan "plan-1" is sealed and paused at tick=1, with position=0 mapped to dueSlot=1
    When the clock advances to tick=1 and SkipPausedSipDueSlot(position=0, dueSlot=1) is executed
    Then emit SipPausedDueSlotSkipped, set slotDisposition[1] to "skipped", and set observedCount to 1
    When the plan resumes and TriggerSipInstallment(position=0, dueSlot=1) is attempted
    Then reject the request with SIP_BACKLOG_REQUIRED

  @spec:SIP_FAIL_NO_PAUSE @spec:SIP_TERMINAL_ONCE
  Scenario: Consecutive failures do not auto-pause and duplicate failure receipts are counted once
    Given SipPlan "plan-1" is active (paused=false) and occurrence "occ-1" has no recorded terminal state
    When RecordSipInstallmentFailed("occ-1") is received twice consecutively
    Then the first call emits SipInstallmentFailed, increments failureTotal by 1, and keeps paused=false
    And the second call returns idempotent empty success (failureTotal unchanged)

# --- Aligned with Example 3.4: Application-Layer User Story (CashFundPurchase) ---
@layer:application @story:cash-fund-purchase
Feature: Cash Fund Purchase User Story (Trusted Inbound, Replay Deduplication, and View Isolation)

  @spec:US-CFP-03 @spec:US-CFP-04 @spec:US-CFP-05 @spec:US-CFP-06
  Scenario: Replay after lost response recovers original order without double debit, and payment success does not equal TA finalization
    Given authenticated customer "cust-1" has sufficient account balance
    When the customer submits BankCashSubmit(clientRequestId="req-101", fundCode="FUND-A", amount=100.00 CNY)
    Then pin BankCashOriginal and return ack(replayed=false, accepted=true)
    When the customer resends with the same clientRequestId="req-101" and identical parameters
    Then return ack(replayed=true) and do not dispatch RequestFundPurchaseSettlement again
    When the customer resends with the same clientRequestId="req-101" but tampered amount 200.00 CNY
    Then reject the request with CASH_SOURCE_CONFLICT
    When the payment saga succeeds but TA has not yet confirmed, and the customer queries BankOrderQuery
    Then bank-order-view exposes paymentCompleted=true and taFinalized=false

6.3 ScalaTest and Multi-Language EarsTestEmitter Projections

From TestIR, the compiler simultaneously generates locked ScalaTest files tailored to bank-wealth-demo (placed in generated-tests/scala/example/bankwealth/ears/), with each test carrying a @CoArisingSpec anchor:

// LOCKED BDD ORACLE — GENERATED BY co-arising EARS 1.0 (DO NOT MODIFY)
package example.bankwealth.ears

import org.scalatest.funsuite.AnyFunSuite
import example.bankwealth.domain._
import example.bankwealth.domain.SipPlanProtocol._
import example.bankwealth.domain.values._

final class SipPlanStreamBatchEarsSpec extends AnyFunSuite {
  // @CoArisingSpec(id="SIP_BACKLOG_REQ", witness="bmc-skip-no-resurrect")
  test("[SIP_BACKLOG_REQ] paused skipped dueSlot cannot be resurrected after resume") {
    // Driven by the same ActorTestKit + PersistenceTestKit as BankSipStateSpec:
    // 1. CreateSipPlan -> AppendSipDueSlot(0, 1L) -> SealSipSchedule -> PauseSipPlan(1L)
    // 2. AdvanceSipClock(1L) -> SkipPausedSipDueSlot(0, 1L) -> Accepted(SipPausedDueSlotSkipped)
    // 3. ResumeSipPlan -> TriggerSipInstallment(0, 1L, ...) -> Refused("SIP_BACKLOG_REQUIRED")
  }

  // @CoArisingSpec(id="SIP_FAIL_NO_PAUSE", witness="first-terminal-idempotent")
  test("[SIP_FAIL_NO_PAUSE] duplicate failure receipts count once and never auto-pause") {
    // Assert after first RecordSipInstallmentFailed: failureTotal == 1 && !paused
    // Assert after second RecordSipInstallmentFailed: Accepted(Vector.empty) && failureTotal == 1
  }
}

For future multi-language expansion (TypeScript / Java / Rust / Go), implementing the unified EarsTestEmitter interface suffices to reuse the entire upstream EARS + SMT asset suite:

trait EarsTestEmitter {
  def language: String                 // "scala" | "typescript" | "java" | "rust" | "go"
  def framework: String                // "scalatest" | "vitest" | "junit5" | "cargo-test"
  def emitDomainSpec(ir: TestIR): GeneratedFile
  def emitApplicationSpec(ir: TestIR): GeneratedFile
}

7. Isolated BDD Test Locking and AI Agent Cloze-Completion Loop

7.1 Territory Read/Write Protection Matrix

Directory Path Asset Role Write Permission Physical Protection Mechanism
truth/**/*.ears Single truth source of behavior Human-approved (LLM drafting allowed before human merge) co-arising check-spec (Z3/cvc5 gate)
projections/ac/** & projections/tables/** Style E plain-language AC & Style B decision tables Compiler read-only projection only Rebuilt from truth source at any time; reverse editing strictly forbidden
generated-tests/** & generated-scaffold/** Locked BDD test oracles & code scaffolds Compiler-writable only (Agent forbidden) PreToolUse Hook (exit 2) + SHA-256 digest verification
handwritten/** (@cloze slots) AI Agent behavioral logic cloze-completion zone Edits allowed only within @cloze:start(<id>)..@cloze:end(<id>) PreToolUse line-range lock + Stop Hook (exit 2)

7.2 Deterministic Anti-Cheating Hooks (.claude/settings.json)

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|MultiEdit",
        "hooks": [{ "type": "command", "command": "node tools/coarising-guard-write.mjs" }]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "node tools/coarising-verify-cloze.mjs --slice $COARISING_ACTIVE_SLICE" }]
      }
    ]
  }
}

  • PreToolUse (coarising-guard-write.mjs): If the Agent attempts to modify generated-tests/, generated-scaffold/, or lines outside @cloze slots in handwritten/, it immediately blocks the write with exit 2, forcing the Agent to pass tests strictly by implementing business logic.

  • Stop (coarising-verify-cloze.mjs): Automatically executes a three-step check before ending a turn—(1) verifies SHA-256 digests of generated-tests/ to prevent sed-based tampering bypasses; (2) runs sbt "testOnly *EarsSpec" to pass the full domain and application BDD suite; (3) runs reverse AST anchor reconciliation (verify-handwritten-map.mjs). If any check fails, it prints the failing @CoArisingSpec(id=...) to stderr and intercepts with exit 2, forcing the Agent to self-heal in place.

  • Blind Contract Review Sign-off: Once all checks are green, an independent subagent (contract-reviewer) with zero conversation-history contamination is spun up, fed only the *.ears truth source, TestIR, and the @cloze git diff with skip style enforced. It intercepts any hardcoded cheating tailored to Z3 boundary witnesses, and finally persists a layered multi-domain Digest (Provenance Record).


8. References and Standards

The external standards, tools and projects below are the design references and landing dependencies of this specification; the numbering maps to the sections that cite them: