{"version":3,"sources":["../src/substrate/errors.ts","../src/substrate/currency.ts","../src/substrate/money.ts","../src/substrate/canonical-json.ts","../src/substrate/clock.ts","../src/substrate/uuid.ts","../src/substrate/format-version.ts","../src/substrate/id-generator.ts","../src/substrate/calendar-date.ts","../src/substrate/account-number.ts","../src/substrate/period-ref.ts","../src/substrate/dimension-value.ts","../src/domain-error.ts","../src/substrate/types.ts","../src/substrate/account.ts","../src/substrate/entry-line.ts","../src/substrate/journal-entry.ts","../src/records/voucher.ts","../src/substrate/period.ts","../src/substrate/fiscal-year.ts","../src/records/audit-record.ts","../src/records/audit-filter.ts","../src/policies/projection/entry-authors.ts","../src/policies/projection/unfinalized-entries.ts","../src/policies/projection/system-description.ts","../src/policies/constraint/account-combination-registry.ts","../src/policies/projection/tenant-configuration.ts","../src/composition/tenant-config-store.ts","../src/policies/projection/reversal-index.ts","../src/policies/projection/parameters.ts","../src/policies/projection/cash-journal.ts","../src/records/open-item.ts","../src/policies/expansion/settlement.ts","../src/substrate/post-result.ts","../src/policies/constraint/dimension-registry.ts","../src/policies/expansion/tax/tax-bases.ts","../src/policies/expansion/tax/tax-code.ts","../src/policies/expansion/tax/tax-code-version.ts","../src/policies/expansion/tax/tax-code-registry.ts","../src/ledger/audit-writer.ts","../src/ledger/chart-admin-service.ts","../src/ledger/lookups.ts","../src/ledger/fiscal-period-service.ts","../src/ledger/settlement-service.ts","../src/ledger/ledger.ts","../src/in-memory.ts","../src/policies/expansion/assets/asset.ts","../src/policies/expansion/assets/asset-route.ts","../src/policies/expansion/assets/asset-service.ts","../src/policies/expansion/costing/costing-run.ts","../src/policies/expansion/inventory/inventory-valuation.ts","../src/substrate/rational.ts","../src/policies/expansion/inventory/inventory-service.ts","../src/policies/expansion/provisions/provision.ts","../src/policies/expansion/provisions/provision-service.ts","../src/policies/expansion/deferrals/deferral.ts","../src/policies/expansion/deferrals/deferral-service.ts","../src/policies/expansion/costing/simultaneous-allocation.ts","../src/policies/expansion/costing/costing-service.ts","../src/partner/partner.ts","../src/partner/partner-service.ts","../src/policies/expansion/tax/tax-mechanisms.ts","../src/policies/projection/ec-sales-list.ts","../src/policies/projection/trial-balance.ts","../src/policies/projection/open-items.ts","../src/policies/projection/account-sheet.ts","../src/policies/projection/accounts.ts","../src/policies/projection/fiscal-years.ts","../src/policies/projection/journal.ts","../src/policies/projection/audit-log.ts","../src/policies/projection/vat-return.ts","../src/policies/projection/mapping/unassigned.ts","../src/policies/projection/income-statement.ts","../src/policies/projection/mapping/mapping.ts","../src/policies/projection/balance-sheet.ts","../src/policies/projection/cash-basis.ts","../src/policies/projection/asset-register.ts","../src/policies/projection/journal-export.ts","../src/policies/projection/datev-export.ts","../src/policies/projection/mapping/mapping-registry.ts","../src/policies/projection/mapping/mapping-importer.ts","../src/policies/expansion/tax/tax-profile.ts","../src/policies/expansion/tax/tax-service.ts","../src/policies/projection/unappropriated-result.ts","../src/policies/expansion/result-appropriation-service.ts","../src/policies/projection/legal-forms.ts","../src/policies/expansion/tax/input-tax-adjustment-service.ts","../src/composition/tenant.ts","../src/policies/projection/asset-schedule.ts","../src/policies/projection/audit-data-export.ts","../src/policies/projection/gdpdu-export.ts","../src/policies/projection/audit-trail-integrity.ts","../src/policies/projection/costing-runs.ts","../src/policies/projection/measurement-consistency.ts","../src/policies/projection/personal-data-description.ts","../src/policies/projection/duplicate-vouchers.ts","../src/composition/post-voucher-service.ts","../src/composition/projection-parameters.ts","../src/composition/operation-parameters.ts","../src/composition/tenant-operations.ts","../src/composition/tenant-factory.ts","../src/composition/pack-resolver.ts"],"names":["Big","key","randomBytes","iso","text","createHash","inRange","asString","isRecord","matches","taxLines","grossTotal","byAccount"],"mappings":";;;;;;;;;;AACO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACtC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EACd;AACF;AAGO,IAAM,gBAAA,GA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AAA,EAAyB,OAAO,MAAA,CAAO,YAAY,CAAC,CAAA,CAAE,CAAA;AAAA,EAClG;AACA,EAAA,MAAM,WAAA,GAAcA,UAAAA,CAAS,MAAA,CAAO,sBAAsB,CAAA;AAC1D,EAAA,IAAI,gBAAgB,IAAA,IAAQ,CAAC,iBAAA,CAAkB,QAAA,CAAS,WAAW,CAAA,EAAG;AACpE,IAAA,MAAM,IAAI,YAAY,kBAAA,EAAoB,CAAA,gCAAA,EAAmC,OAAO,MAAA,CAAO,sBAAsB,CAAC,CAAA,CAAE,CAAA;AAAA,EACtH;AACA,EAAA,MAAM,QAAQ,MAAA,CAAO,aAAA;AACrB,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,KAAA,GAAQ,CAAA,IAAK,KAAA,GAAQ,CAAA,EAAG;AACnF,IAAA,MAAM,IAAI,WAAA,CAAY,kBAAA,EAAoB,mCAA8B,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EACzF;AACF;AAEA,SAAS,UAAA,CAAW,GAA4B,CAAA,EAAqC;AACnF,EAAA,OACE,CAAA,CAAE,YAAA,KAAiB,CAAA,CAAE,YAAA,IACrB,CAAA,CAAE,2BAA2B,CAAA,CAAE,sBAAA,IAC/B,CAAA,CAAE,aAAA,KAAkB,CAAA,CAAE,aAAA;AAE1B","file":"index.cjs","sourcesContent":["/** Business-invalid value (amount, weight, code, UUID …). */\nexport class InvalidValue extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = 'InvalidValue';\n  }\n}\n\n/** Different currencies cannot be offset against each other. */\nexport class CurrencyMismatch extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = 'CurrencyMismatch';\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * Currency per ISO 4217 with a fixed decimal-places scale\n * (datenformat.md: \"fixed decimal places per currency\").\n *\n * Scales deviating from the default 2 — deliberately small, v1 is EUR-centric,\n * foreign currency comes only in v2.\n */\nconst SCALES: Readonly<Record<string, number>> = {\n  JPY: 0,\n  KRW: 0,\n  BHD: 3,\n  KWD: 3,\n  TND: 3,\n};\n\nexport class Currency {\n  private constructor(\n    readonly code: string,\n    readonly scale: number,\n  ) {}\n\n  /**\n   * `scaleOverride` sets the decimal-places scale explicitly (pack parameter\n   * `packPolicy.currencyScale`) — overrides the global default/ISO scale per\n   * tenant (jurisdiction-free substrate: scale is a pack matter, not global).\n   */\n  static of(code: string, scaleOverride?: number): Currency {\n    if (!/^[A-Z]{3}$/.test(code)) {\n      throw new InvalidValue(`Invalid ISO 4217 code: \"${code}\"`);\n    }\n    return new Currency(code, scaleOverride ?? SCALES[code] ?? 2);\n  }\n\n  equals(other: Currency): boolean {\n    return this.code === other.code;\n  }\n\n  toJSON(): string {\n    return this.code;\n  }\n\n  toString(): string {\n    return this.code;\n  }\n}\n","import Big from 'big.js';\nimport { Currency } from './currency.js';\nimport { CurrencyMismatch, InvalidValue } from './errors.js';\n\n// Determinism appendix §2: commercial HALF_UP, away from zero at exactly .5\n// (NOT banker's). big.js `roundHalfUp` (=1) rounds away-from-zero.\nconst HALF_UP = Big.roundHalfUp;\n\n/**\n * The amount format of the data format (`format.schema.json`\n * `$defs/money/properties/amount`) — the SAME expression lives in PHP's `Money`.\n * No exponent notation, no leading `+`, digits required on both sides of the point.\n */\nconst AMOUNT_FORMAT = /^-?\\d+(\\.\\d{1,4})?$/;\n\n/** Decimal places of a Big value (big.js holds coefficient `c` + exponent `e`). */\nfunction decimalPlaces(value: Big): number {\n  return Math.max(0, value.c.length - value.e - 1);\n}\n\n/**\n * Amount = decimal value + currency, never float (Glossary `money`).\n *\n * Determinism rules (determinismus.md §2):\n * - rounding: commercial half-up, away from zero at exactly .5.\n * - allocate: largest-remainder, tie → first part; Σ parts = amount, always.\n *\n * The amount internally always lies exactly on the currency scale.\n */\nexport class Money {\n  private constructor(\n    private readonly amount: Big,\n    readonly currency: Currency,\n  ) {}\n\n  private static currencyOf(currency: Currency | string): Currency {\n    return currency instanceof Currency ? currency : Currency.of(currency);\n  }\n\n  /**\n   * Exact amount on the currency scale. More decimal places than the currency\n   * allows is an error — nothing is ever silently rounded here.\n   *\n   * The string must match the **data format** (`format.schema.json`\n   * `$defs/money/properties/amount`), not merely be something the decimal library\n   * can parse. The library is more permissive than the format: it read `\"1e3\"` as\n   * 1000.00 and `\"1.5e+21\"` as a booking of 1.5 sextillion, and it disagreed\n   * across languages on a leading `+`. An amount that would not survive a\n   * round-trip through the exported format has no business entering the journal.\n   */\n  static of(amount: string, currency: Currency | string): Money {\n    const cur = Money.currencyOf(currency);\n    if (!AMOUNT_FORMAT.test(amount)) {\n      throw new InvalidValue(`Invalid amount \"${amount}\" for currency ${cur.code} (scale ${cur.scale})`);\n    }\n    let value: Big;\n    try {\n      value = new Big(amount);\n    } catch {\n      throw new InvalidValue(`Invalid amount \"${amount}\" for currency ${cur.code} (scale ${cur.scale})`);\n    }\n    const scaled = value.round(cur.scale, HALF_UP);\n    if (!scaled.eq(value)) {\n      throw new InvalidValue(`Invalid amount \"${amount}\" for currency ${cur.code} (scale ${cur.scale})`);\n    }\n    return new Money(scaled, cur);\n  }\n\n  /**\n   * Bring the result of a calculation to the currency scale: half-up\n   * (2.225 → 2.23, -2.345 → -2.35). The only path on which Money rounds.\n   */\n  static fromCalculation(value: Big | string, currency: Currency | string): Money {\n    const cur = Money.currencyOf(currency);\n    let big: Big;\n    try {\n      big = value instanceof Big ? value : new Big(value);\n    } catch {\n      throw new InvalidValue(`Invalid calculation value for currency ${cur.code}`);\n    }\n    return new Money(big.round(cur.scale, HALF_UP), cur);\n  }\n\n  static zero(currency: Currency | string): Money {\n    return new Money(new Big(0), Money.currencyOf(currency));\n  }\n\n  add(other: Money): Money {\n    this.assertSameCurrency(other);\n    return new Money(this.amount.plus(other.amount), this.currency);\n  }\n\n  subtract(other: Money): Money {\n    this.assertSameCurrency(other);\n    return new Money(this.amount.minus(other.amount), this.currency);\n  }\n\n  negate(): Money {\n    return new Money(this.amount.times(-1), this.currency);\n  }\n\n  abs(): Money {\n    return new Money(this.amount.abs(), this.currency);\n  }\n\n  /** -1, 0 oder 1 */\n  compareTo(other: Money): number {\n    this.assertSameCurrency(other);\n    return this.amount.cmp(other.amount);\n  }\n\n  equals(other: Money): boolean {\n    return this.currency.equals(other.currency) && this.amount.eq(other.amount);\n  }\n\n  isZero(): boolean {\n    return this.amount.eq(0);\n  }\n\n  isPositive(): boolean {\n    return this.amount.gt(0);\n  }\n\n  isNegative(): boolean {\n    return this.amount.lt(0);\n  }\n\n  /**\n   * Distributes the amount by weights (determinismus.md §2): largest-remainder,\n   * tie → first part. Σ parts = amount, always.\n   *\n   * Weights: non-negative decimal values (number or string), sum > 0.\n   * Negative amounts are distributed as a negated mirror image.\n   */\n  allocate(...weights: Array<number | string>): Money[] {\n    if (weights.length === 0) {\n      throw new InvalidValue('allocate needs at least one weight');\n    }\n\n    if (this.isNegative()) {\n      return this.negate()\n        .allocate(...weights)\n        .map((part) => part.negate());\n    }\n\n    const scale = this.currency.scale;\n    const integerWeights = Money.normalizeWeights(weights);\n\n    let weightSum = 0n;\n    for (const weight of integerWeights) {\n      weightSum += weight;\n    }\n    if (weightSum === 0n) {\n      throw new InvalidValue('Weight sum must be > 0');\n    }\n\n    const factor = new Big(10).pow(scale);\n    const totalMinor = BigInt(this.amount.times(factor).toFixed(0));\n\n    const parts = integerWeights.map((weight) => {\n      const product = totalMinor * weight;\n      return { base: product / weightSum, remainder: product % weightSum };\n    });\n\n    let assigned = 0n;\n    for (const part of parts) {\n      assigned += part.base;\n    }\n\n    // Remainder distribution by largest remainder; tie → smallest index.\n    const leftover = Number(totalMinor - assigned);\n    const order = parts.map((part, index) => ({ remainder: part.remainder, index }));\n    order.sort((a, b) =>\n      a.remainder > b.remainder ? -1 : a.remainder < b.remainder ? 1 : a.index - b.index,\n    );\n    for (let i = 0; i < leftover; i++) {\n      parts[order[i]!.index]!.base += 1n;\n    }\n\n    return parts.map((part) => Money.fromMinor(part.base, scale, this.currency));\n  }\n\n  /** Distribution into n equal parts (collective-item fifths, depreciation monthly rates). */\n  allocateEvenly(parts: number): Money[] {\n    if (parts < 1) {\n      throw new InvalidValue('allocateEvenly needs at least one part');\n    }\n    return this.allocate(...new Array<number>(parts).fill(1));\n  }\n\n  /** Amount as a string decimal with fixed scale, e.g. \"1234.56\" (datenformat.md). */\n  amountAsString(): string {\n    return this.amount.toFixed(this.currency.scale);\n  }\n\n  toJSON(): { amount: string; currency: string } {\n    return { amount: this.amountAsString(), currency: this.currency.code };\n  }\n\n  toString(): string {\n    return `${this.amountAsString()} ${this.currency.code}`;\n  }\n\n  private static fromMinor(minor: bigint, scale: number, currency: Currency): Money {\n    const value = new Big(minor.toString()).div(new Big(10).pow(scale));\n    return new Money(value.round(scale, HALF_UP), currency);\n  }\n\n  /** Bring decimal weights losslessly to integer weights of the same scale. */\n  private static normalizeWeights(weights: Array<number | string>): bigint[] {\n    const decimals: Big[] = [];\n    let maxScale = 0;\n\n    for (const weight of weights) {\n      let decimal: Big;\n      try {\n        decimal = new Big(weight);\n      } catch {\n        throw new InvalidValue(`Invalid weight \"${weight}\"`);\n      }\n      if (decimal.lt(0)) {\n        throw new InvalidValue('Weights must not be negative');\n      }\n      decimals.push(decimal);\n      maxScale = Math.max(maxScale, decimalPlaces(decimal));\n    }\n\n    const factor = new Big(10).pow(maxScale);\n    return decimals.map((decimal) => BigInt(decimal.times(factor).toFixed(0)));\n  }\n\n  private assertSameCurrency(other: Money): void {\n    if (!this.currency.equals(other.currency)) {\n      throw new CurrencyMismatch(\n        `Currencies do not mix: ${this.currency.code} vs. ${other.currency.code}`,\n      );\n    }\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * Canonical JSON per RFC 8785 (JCS) — basis of all hashes and\n * determinism comparisons (datenformat.md principle 1, determinismus.md §5).\n *\n * Deliberate deviation from the full RFC: floats are rejected instead of\n * ECMAScript-serialized — the data format forbids JSON Number for amounts\n * (string decimal), and integers (sequenceNumber, year) are exactly representable.\n *\n * Key sorting by UTF-16 code units: JS strings are UTF-16, the\n * native `Array#sort` compares exactly by that — RFC-compliant without manual work\n * (surrogate pairs sort before U+E000..U+FFFF).\n *\n * Objects with `toJSON()` are unpacked (JS counterpart to PHP's JsonSerializable).\n */\nconst MAX_SAFE_INTEGER = 9007199254740991; // 2^53 - 1\n\nexport function canonicalJson(value: unknown): string {\n  return encodeValue(value);\n}\n\nfunction encodeValue(value: unknown): string {\n  if (value === null) {\n    return 'null';\n  }\n  if (typeof value === 'boolean') {\n    return value ? 'true' : 'false';\n  }\n  if (typeof value === 'number') {\n    if (!Number.isInteger(value)) {\n      throw new InvalidValue(\n        'Floats are forbidden in the data format (amounts as string decimal, datenformat.md)',\n      );\n    }\n    if (Math.abs(value) > MAX_SAFE_INTEGER) {\n      throw new InvalidValue(`Integer outside the safe range (|x| > 2^53-1): ${value}`);\n    }\n    return String(value);\n  }\n  if (typeof value === 'string') {\n    return encodeString(value);\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(encodeValue).join(',')}]`;\n  }\n  if (typeof value === 'object') {\n    const candidate = value as { toJSON?: () => unknown };\n    if (typeof candidate.toJSON === 'function') {\n      return encodeValue(candidate.toJSON());\n    }\n    return encodeObject(value as Record<string, unknown>);\n  }\n  throw new InvalidValue(`Non-serializable type: ${typeof value}`);\n}\n\nfunction encodeObject(object: Record<string, unknown>): string {\n  const keys = Object.keys(object);\n  if (keys.length === 0) {\n    return '{}';\n  }\n  // Native sort = UTF-16 code unit order = RFC 8785.\n  keys.sort();\n  return `{${keys.map((key) => `${encodeString(key)}:${encodeValue(object[key])}`).join(',')}}`;\n}\n\n/**\n * JCS string serialization (RFC 8785 §3.2.2.2): short escapes for the usual\n * control characters, \\u00xx (lowercase) for the rest below U+0020, everything else raw.\n */\nfunction encodeString(value: string): string {\n  let out = '\"';\n  for (let i = 0; i < value.length; i++) {\n    const char = value[i]!;\n    const code = value.charCodeAt(i);\n    if (char === '\"') {\n      out += '\\\\\"';\n    } else if (char === '\\\\') {\n      out += '\\\\\\\\';\n    } else if (code === 0x08) {\n      out += '\\\\b';\n    } else if (code === 0x09) {\n      out += '\\\\t';\n    } else if (code === 0x0a) {\n      out += '\\\\n';\n    } else if (code === 0x0c) {\n      out += '\\\\f';\n    } else if (code === 0x0d) {\n      out += '\\\\r';\n    } else if (code < 0x20) {\n      out += `\\\\u${code.toString(16).padStart(4, '0')}`;\n    } else {\n      out += char;\n    }\n  }\n  return `${out}\"`;\n}\n","/**\n * Time source of the core (determinism hook). Deliberately a dedicated interface,\n * PSR-20-/Temporal-compatible in spirit: returns a point in time.\n */\nexport interface Clock {\n  now(): Date;\n}\n\n/** Real system time (production). */\nexport class SystemClock implements Clock {\n  now(): Date {\n    return new Date();\n  }\n}\n\n/** Fixed time for tests and deterministic runs. */\nexport class FixedClock implements Clock {\n  private current: Date;\n\n  private constructor(at: Date) {\n    this.current = at;\n  }\n\n  static at(iso8601: string): FixedClock {\n    return new FixedClock(new Date(iso8601));\n  }\n\n  now(): Date {\n    return this.current;\n  }\n\n  advanceMilliseconds(milliseconds: number): void {\n    this.current = new Date(this.current.getTime() + milliseconds);\n  }\n}\n","import { randomBytes } from 'node:crypto';\nimport { type Clock, SystemClock } from './clock.js';\nimport { InvalidValue } from './errors.js';\n\n/**\n * UUIDv7 (RFC 9562): 48 bit Unix milliseconds + random — time-sortable\n * as a string, generatable independent of implementation (datenformat.md principle 3).\n * Fixtures never compare ID values, only placeholder equality.\n */\nconst PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nexport class Uuid {\n  private constructor(readonly value: string) {}\n\n  static fromString(value: string): Uuid {\n    const normalized = value.toLowerCase();\n    if (!PATTERN.test(normalized)) {\n      throw new InvalidValue(`Not a valid UUID: \"${value}\"`);\n    }\n    return new Uuid(normalized);\n  }\n\n  static v7(clock: Clock = new SystemClock()): Uuid {\n    const time = clock.now().getTime().toString(16).padStart(12, '0');\n    const random = randomBytes(10).toString('hex'); // 20 hex chars of entropy\n    // Variant nibble: top two bits = 10 -> 8, 9, a or b.\n    const variant = ((parseInt(random[3]!, 16) & 0x3) | 0x8).toString(16);\n\n    return new Uuid(\n      `${time.slice(0, 8)}-${time.slice(8, 12)}-7${random.slice(0, 3)}-${variant}${random.slice(4, 7)}-${random.slice(7, 19)}`,\n    );\n  }\n\n  equals(other: Uuid): boolean {\n    return this.value === other.value;\n  }\n\n  /** Byte-wise = chronological order for v7. */\n  compareTo(other: Uuid): number {\n    return this.value < other.value ? -1 : this.value > other.value ? 1 : 0;\n  }\n\n  toJSON(): string {\n    return this.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n}\n","/**\n * The data-format version every export manifest carries.\n *\n * The spec is explicit that this always states the *current* spec version\n * (`datenformat.md`: „`formatVersion` trägt stets die aktuelle Spec-Version\"). It sat at 0.4 while\n * the schema, the pack modules and the parameter contract had long moved to 0.6 — an export that\n * understated its own format, which is the one field a reading system uses to decide whether it\n * can read the file at all.\n *\n * It lives here, in one place per language, and a test asserts it matches the version in the\n * schema's `$id`. Bumping the schema without bumping this now turns a build red instead of\n * shipping a mislabelled export.\n */\nexport const FORMAT_VERSION = '0.10';\n","import { type Clock, SystemClock } from './clock.js';\nimport { Uuid } from './uuid.js';\n\n/**\n * ID source of the core — port, so that tests and determinism runs can control\n * generation. Production: UUIDv7.\n */\nexport interface IdGenerator {\n  next(): Uuid;\n}\n\n/** Production generator: real UUIDv7 from time + random. */\nexport class UuidV7IdGenerator implements IdGenerator {\n  constructor(private readonly clock: Clock = new SystemClock()) {}\n\n  next(): Uuid {\n    return Uuid.v7(this.clock);\n  }\n}\n\n/**\n * UUIDv7-shaped IDs from a fixed clock + counter instead of random — for tests and the\n * double-run determinism check of the conformance suite (stream hashes contain\n * IDs; two runs must be byte-identical).\n */\nexport class DeterministicIdGenerator implements IdGenerator {\n  private counter = 0;\n\n  constructor(private readonly clock: Clock) {}\n\n  next(): Uuid {\n    this.counter++;\n\n    const time = this.clock.now().getTime().toString(16).padStart(12, '0');\n    const sequence = this.counter.toString(16).padStart(18, '0');\n\n    return Uuid.fromString(\n      `${time.slice(0, 8)}-${time.slice(8, 12)}-7${sequence.slice(0, 3)}-8${sequence.slice(3, 6)}-${sequence.slice(6, 18)}`,\n    );\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * Zoneless calendar date (determinismus.md §4): voucher and posting date\n * know no time zone — no UTC shift risk. ISO format sorts\n * lexicographically correctly (= chronologically).\n *\n * The arithmetic below is deliberately done by hand instead of through `Date`.\n * `Date.UTC(year, …)` maps years 0–99 onto 1900+year (a JavaScript legacy rule),\n * which silently made `0000-01-01` … `0099-12-31` fail the round-trip check while\n * the PHP reference accepted them — same input, different result, in the one layer\n * that is supposed to be frozen and jurisdiction-free. Keeping the host `Date` out\n * of the substrate removes the whole class of such divergences.\n */\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;\n\nfunction isLeapYear(year: number): boolean {\n  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\nfunction daysInMonth(year: number, month: number): number {\n  return month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n}\n\nfunction iso(year: number, month: number, day: number): string {\n  return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n}\n\n/**\n * Days since the civil epoch (1970-01-01), by Howard Hinnant's `days_from_civil`.\n * Hand-rolled for the same reason as the rest of this file: the host `Date` is out of\n * the substrate, so year 0042 subtracts like any other year. Valid for the proleptic\n * Gregorian calendar, which is what a zoneless bookkeeping date is.\n */\nfunction daysFromCivil(year: number, month: number, day: number): number {\n  const y = month <= 2 ? year - 1 : year;\n  const era = Math.floor(y / 400);\n  const yoe = y - era * 400; // [0, 399]\n  const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1; // [0, 365]\n  const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy; // [0, 146096]\n  return era * 146097 + doe - 719468;\n}\n\nexport class CalendarDate {\n  private constructor(readonly iso: string) {}\n\n  static of(value: string): CalendarDate {\n    if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) {\n      throw new InvalidValue(`Not a valid calendar date: \"${value}\"`);\n    }\n    const year = Number(value.slice(0, 4));\n    const month = Number(value.slice(5, 7));\n    const day = Number(value.slice(8, 10));\n    // Catches 2026-13-01, 2026-02-30, 2026-02-29 in a non-leap year, …\n    if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {\n      throw new InvalidValue(`Not a valid calendar date: \"${value}\"`);\n    }\n    return new CalendarDate(value);\n  }\n\n  /**\n   * Whole days from `other` up to this date; negative when this date is earlier.\n   * Zoneless subtraction — no hours, no DST, no leap seconds to lose a day to.\n   */\n  daysSince(other: CalendarDate): number {\n    return this.dayNumber() - other.dayNumber();\n  }\n\n  private dayNumber(): number {\n    return daysFromCivil(\n      Number(this.iso.slice(0, 4)),\n      Number(this.iso.slice(5, 7)),\n      Number(this.iso.slice(8, 10)),\n    );\n  }\n\n  compareTo(other: CalendarDate): number {\n    return this.iso < other.iso ? -1 : this.iso > other.iso ? 1 : 0;\n  }\n\n  equals(other: CalendarDate): boolean {\n    return this.iso === other.iso;\n  }\n\n  isBefore(other: CalendarDate): boolean {\n    return this.compareTo(other) < 0;\n  }\n\n  isAfter(other: CalendarDate): boolean {\n    return this.compareTo(other) > 0;\n  }\n\n  isBetween(start: CalendarDate, end: CalendarDate): boolean {\n    return !this.isBefore(start) && !this.isAfter(end);\n  }\n\n  year(): number {\n    return Number(this.iso.slice(0, 4));\n  }\n\n  month(): number {\n    return Number(this.iso.slice(5, 7));\n  }\n\n  /**\n   * The same day-of-month `months` later, clamped to the target month's last day (31 January plus\n   * one month is 28 February, never 3 March). Zoneless like everything else here: this is calendar\n   * arithmetic on three numbers, not a timestamp shifted by seconds.\n   */\n  plusMonths(months: number): CalendarDate {\n    const zeroBased = (this.year() * 12 + (this.month() - 1)) + months;\n    const year = Math.floor(zeroBased / 12);\n    const month = zeroBased - year * 12 + 1;\n    const day = Math.min(Number(this.iso.slice(8, 10)), daysInMonth(year, month));\n    return new CalendarDate(iso(year, month, day));\n  }\n\n  lastDayOfMonth(): CalendarDate {\n    return new CalendarDate(iso(this.year(), this.month(), daysInMonth(this.year(), this.month())));\n  }\n\n  firstDayOfNextMonth(): CalendarDate {\n    const rollsOver = this.month() === 12;\n    return new CalendarDate(iso(rollsOver ? this.year() + 1 : this.year(), rollsOver ? 1 : this.month() + 1, 1));\n  }\n\n  toJSON(): string {\n    return this.iso;\n  }\n\n  toString(): string {\n    return this.iso;\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * Account number as a string — leading zeros significant (datenformat.md).\n * Comparison by Unicode code points, no locale collation: \"10\" < \"9\",\n * \"0420\" < \"1200\" < \"8400\" (determinismus.md §3). JS `<` on strings\n * compares UTF-16 code units = code points in the BMP.\n */\nexport class AccountNumber {\n  private constructor(readonly value: string) {}\n\n  static of(value: string): AccountNumber {\n    if (value === '' || value.length > 64) {\n      throw new InvalidValue('Account number must be 1-64 characters long');\n    }\n    if (!/^[^\\s\\p{C}]+$/u.test(value)) {\n      throw new InvalidValue(`Account number contains whitespace or control characters: \"${value}\"`);\n    }\n    return new AccountNumber(value);\n  }\n\n  compareTo(other: AccountNumber): number {\n    return this.value < other.value ? -1 : this.value > other.value ? 1 : 0;\n  }\n\n  equals(other: AccountNumber): boolean {\n    return this.value === other.value;\n  }\n\n  toJSON(): string {\n    return this.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * Reference to a period: fiscal year + period number (datenformat.md\n * `periodRef`). `fiscalYear` = calendar year of the fiscal year end.\n */\nexport class PeriodRef {\n  constructor(\n    readonly fiscalYear: number,\n    readonly period: number,\n  ) {\n    if (fiscalYear < 1 || fiscalYear > 9999) {\n      throw new InvalidValue(`Invalid fiscal year: ${fiscalYear}`);\n    }\n    if (period < 1 || period > 999) {\n      throw new InvalidValue(`Invalid period number: ${period}`);\n    }\n  }\n\n  /** Chronological: year first, then period. */\n  compareTo(other: PeriodRef): number {\n    if (this.fiscalYear !== other.fiscalYear) {\n      return this.fiscalYear < other.fiscalYear ? -1 : 1;\n    }\n    return this.period < other.period ? -1 : this.period > other.period ? 1 : 0;\n  }\n\n  equals(other: PeriodRef): boolean {\n    return this.fiscalYear === other.fiscalYear && this.period === other.period;\n  }\n\n  toJSON(): { fiscalYear: number; period: number } {\n    return { fiscalYear: this.fiscalYear, period: this.period };\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * Additional allocation of a posting line: dimension type + value code\n * (datenformat.md). The validity check against master data happens at the\n * operation (E_DIMENSION_INVALID), not here.\n */\nexport class DimensionValue {\n  private constructor(\n    readonly type: string,\n    readonly code: string,\n  ) {}\n\n  static of(type: string, code: string): DimensionValue {\n    if (type === '' || code === '') {\n      throw new InvalidValue('Dimension type and code must not be empty');\n    }\n    return new DimensionValue(type, code);\n  }\n\n  equals(other: DimensionValue): boolean {\n    return this.type === other.type && this.code === other.code;\n  }\n\n  toJSON(): { type: string; code: string } {\n    return { type: this.type, code: this.code };\n  }\n}\n","/**\n * Domain error with catalog code (fehlerkatalog.md). Contract part: same\n * violation → same code in all implementations. `message` is free-form,\n * `details` carries the IDs/values involved.\n */\nexport class DomainError extends Error {\n  constructor(\n    readonly errorCode: string,\n    message = '',\n    readonly details: Record<string, unknown> = {},\n  ) {\n    super(message !== '' ? message : errorCode);\n    this.name = 'DomainError';\n  }\n}\n\n/**\n * Echoes a rejected input value back in `details` so the caller can spot their typo.\n *\n * Only strings and safe integers are rendered; everything else becomes `null`. That is the\n * same line canonical JSON draws (integers are exactly representable, floats are rejected\n * rather than serialized) — and it has to be drawn here too, because a plain cast is not\n * the same operation in both languages: PHP renders `true` as `\"1\"` and Node as `\"true\"`,\n * PHP `1.0E+25` against Node `1e+25`. A detail that differs by language is a detail that\n * breaks equivalence, so it is better dropped than guessed at.\n */\nexport function rejectedValue(value: unknown): string | null {\n  if (typeof value === 'string') {\n    return value;\n  }\n  // Safe integers only — beyond 2^53 a JS number is no longer an exact integer, while the\n  // PHP side is still an int, and the two would render differently.\n  if (typeof value === 'number' && Number.isSafeInteger(value)) {\n    return String(value);\n  }\n  return null;\n}\n","/** Debit/credit. */\nexport type Side = 'debit' | 'credit';\n\n/**\n * Account type determines the balance mechanics (ledger-modell.md): balance-sheet accounts\n * accumulate over years, income accounts per fiscal year.\n */\nexport type AccountType = 'asset' | 'liability' | 'equity' | 'expense' | 'revenue';\n\nconst BALANCE_CARRYING: ReadonlySet<AccountType> = new Set<AccountType>([\n  'asset',\n  'liability',\n  'equity',\n]);\n\n/** Balance-sheet account: balance carries forward implicitly (no closing/opening account). */\nexport function isBalanceCarrying(type: AccountType): boolean {\n  return BALANCE_CARRYING.has(type);\n}\n\nexport function isAccountType(value: unknown): value is AccountType {\n  return (\n    value === 'asset' ||\n    value === 'liability' ||\n    value === 'equity' ||\n    value === 'expense' ||\n    value === 'revenue'\n  );\n}\n\nexport type AccountStatus = 'active' | 'locked';\n\n/** Record lifecycle: entered (correctable) → finalized (only reversal). */\nexport type EntryStatus = 'entered' | 'finalized';\n\nexport type PeriodStatus = 'open' | 'closed';\n\nexport type FiscalYearStatus = 'open' | 'closed';\n\nexport type OpenItemKind = 'receivable' | 'payable';\n\nexport type OpenItemStatus = 'open' | 'partially_settled' | 'settled' | 'cancelled';\n\n/**\n * Why an open item was settled (IMPL-008). `payment` is the ordinary case and the default when the\n * field is absent; `cancellation` arises only from `reverse` and means the item is done because its\n * origin entry was reversed — no money moved. Without the distinction a reversal is indistinguishable\n * from a payment, and cash-basis VAT would declare tax for money that never arrived.\n */\nexport type SettlementCause = 'payment' | 'cancellation';\n\nexport function parseSettlementCause(value: unknown): SettlementCause {\n  return value === 'cancellation' ? 'cancellation' : 'payment';\n}\n\n/**\n * Settlement with difference (api.md G2): cash discount, bad debt, minor difference.\n * The difference must be materialized as explicit posting line(s).\n */\nexport type SettlementDifferenceKind = 'discount' | 'bad_debt' | 'minor';\n\nexport function parseSettlementDifferenceKind(value: unknown): SettlementDifferenceKind | null {\n  return value === 'discount' || value === 'bad_debt' || value === 'minor' ? value : null;\n}\n\nexport function parseOpenItemKind(value: unknown): OpenItemKind | null {\n  return value === 'receivable' || value === 'payable' ? value : null;\n}\n\n/**\n * What a business partner is to this tenant. The manual has named these three since the partner\n * record existed; the field was a plain string that took anything, so `custommer` was a partner\n * kind like any other and only turned up as a category nobody could filter on.\n */\nexport type PartnerKind = 'customer' | 'supplier' | 'both';\n\nexport function parsePartnerKind(value: unknown): PartnerKind | null {\n  return value === 'customer' || value === 'supplier' || value === 'both' ? value : null;\n}\n\n/**\n * The canonical subtypes an account may carry.\n *\n * **Why this is closed.** `subtype` is the field through which the chart tells the engine what an\n * account *is*: which movements are profit-neutral, which account is a tax account and on which\n * side its tax stands, which posting opens a receivable. The field was a free string, so a pack\n * that wrote `tax-out` instead of `tax_out` produced an account that looked annotated and was\n * inert — the VAT return simply skipped it, and nothing in the output said a tax account had gone\n * missing. That is the same defect the tax mechanisms were closed for in v0.8.0 (`reverse-charge`\n * fell back to plain VAT under the ordinary reporting key) and the one `PartnerKind` was closed\n * for (`custommer` was a partner kind like any other). Third time, same shape, same answer.\n *\n * **The stored value stays a string.** This union is the validator, not a change to the data\n * format — exactly as `PartnerKind` is. Nothing here changes what an export writes.\n *\n * **Where it is enforced, and deliberately where it is not.** At the two boundaries where a\n * subtype is *authored*: `createAccount`/`importChartOfAccounts` (`E_INPUT_INVALID` /\n * `E_COA_FORMAT_INVALID`) and pack resolution (`E_PACK_INCOHERENT`, so a composed pack fails at\n * `resolvePack` rather than at the first posting). It is **not** enforced in the `Account`\n * constructor, and that is not an oversight: hydrating a stored account runs through the same\n * constructor, so a database written before this repertoire existed would stop loading. A\n * validation that refuses to read what it once wrote is a worse failure than the one it prevents.\n *\n * **Two tiers, one list.** Eight of these the engine reads and branches on; `fixed_asset`,\n * `opening_balance` and `private` are annotation that every shipped pack carries and no code\n * consults. They are in the repertoire because the packs use them, and keeping them here is what\n * makes the list safe to check against — a repertoire that only held the eight would refuse the\n * three shipped charts.\n */\nexport type AccountSubtype =\n  /** Read: cash-basis (profit-neutral movement), payment account. */\n  | 'bank'\n  /** Read: cash journal (F-CORE-030), cash-basis. */\n  | 'cash'\n  /** Read: cash-basis — money in transit is not a profit event. */\n  | 'transit'\n  /** Read: a debit opens a receivable. */\n  | 'ar'\n  /** Read: a credit opens a payable. */\n  | 'ap'\n  /** Read: VAT return (input side), cash-basis, DATEV export. */\n  | 'tax_in'\n  /** Read: VAT return (output side), cash-basis, DATEV export. */\n  | 'tax_out'\n  /** Read: where an appropriated result lands (F-CORE-038). */\n  | 'result_allocation'\n  /** Read: stock, the only account `valuateInventory` may value onto (F-CORE-050). */\n  | 'inventory'\n  /** Read: provisions, the only account `recognizeProvision` may form one on (F-CORE-051). */\n  | 'provision'\n  /** Annotation: the packs mark their asset accounts; the asset expansion uses its own module. */\n  | 'fixed_asset'\n  /** Annotation: the opening-balance account of a chart. */\n  | 'opening_balance'\n  /** Annotation: owner's drawings and contributions. */\n  | 'private';\n\n/**\n * The repertoire, in declaration order. Published for the same reason `TaxMechanisms.all()` is: a\n * document that names the subtypes — `docs/handbuch` and the pack docs do — is making a checkable\n * claim, and a claim nothing checks goes stale.\n */\nexport const ACCOUNT_SUBTYPES: readonly AccountSubtype[] = [\n  'bank',\n  'cash',\n  'transit',\n  'ar',\n  'ap',\n  'tax_in',\n  'tax_out',\n  'result_allocation',\n  'inventory',\n  'provision',\n  'fixed_asset',\n  'opening_balance',\n  'private',\n];\n\nexport function isAccountSubtype(value: unknown): value is AccountSubtype {\n  return typeof value === 'string' && (ACCOUNT_SUBTYPES as readonly string[]).includes(value);\n}\n","import { AccountNumber } from './account-number.js';\nimport type { CalendarDate } from './calendar-date.js';\nimport type { Uuid } from './uuid.js';\nimport type { AccountStatus, AccountType } from './types.js';\n\n/**\n * Account (ledger-modell.md aggregate 2). No balance in the aggregate — balances are\n * projections of the journal, always.\n */\nexport class Account {\n  private accountStatus: AccountStatus;\n\n  constructor(\n    readonly id: Uuid,\n    readonly number: AccountNumber,\n    readonly name: string,\n    readonly type: AccountType,\n    readonly subtype: string | null,\n    status: AccountStatus = 'active',\n    /**\n     * The window in which the account may be POSTED to (F-CORE-045). `null` on either side means\n     * unbounded, which is what every account had before the window existed and what almost every\n     * account will keep.\n     *\n     * **Not the same thing as a lock, and that is why both exist.** A lock is unconditional and\n     * about now: it stops every posting, including a correction dated before the lock, which is\n     * exactly wrong for an account being retired at a year end. A window is about the posting's own\n     * date, so an account valid to 2026-12-31 keeps accepting a late correction for December and\n     * refuses January.\n     */\n    readonly validFrom: CalendarDate | null = null,\n    readonly validTo: CalendarDate | null = null,\n  ) {\n    this.accountStatus = status;\n  }\n\n  /**\n   * Writes only, and never reads: an account outside its window still appears in every report that\n   * has postings on it, because the history happened. A window that hid past figures would be a way\n   * to make the books say less than the journal does.\n   */\n  isValidOn(date: CalendarDate): boolean {\n    if (this.validFrom !== null && date.isBefore(this.validFrom)) return false;\n    return !(this.validTo !== null && date.isAfter(this.validTo));\n  }\n\n  status(): AccountStatus {\n    return this.accountStatus;\n  }\n\n  isLocked(): boolean {\n    return this.accountStatus === 'locked';\n  }\n\n  lock(): void {\n    this.accountStatus = 'locked';\n  }\n\n  /**\n   * The way back (F-CORE-033).\n   *\n   * The lock had no counterpart for a long time, and the question that decided this was whether the\n   * irreversibility was *law*. It is not. What the German rules protect against unrecognisable\n   * change are **postings**; for master data they ask that the change be *logged* — which the audit\n   * trail does, in both directions. And that is the German answer to a question no other\n   * jurisdiction answers differently either: no chart of accounts anywhere is a one-way door. So\n   * nothing here is a jurisdiction's answer and nothing belongs in a pack. The sources are in the\n   * knowledge base (`knowledge/10-fachwissen/17-gobd-compliance.md`), where a statute may be named.\n   *\n   * What a lock protects is the books, and it keeps doing that: an account cannot be posted to\n   * while it is locked, and every posting ever made on it stays exactly where it is. Unlocking\n   * changes nothing about the past — it only allows a future posting again, which is why a\n   * mis-clicked lock does not have to be repaired by abandoning the account and opening a second\n   * one under a new number.\n   */\n  unlock(): void {\n    this.accountStatus = 'active';\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      number: this.number.value,\n      name: this.name,\n      type: this.type,\n      subtype: this.subtype,\n      status: this.accountStatus,\n      validFrom: this.validFrom?.iso ?? null,\n      validTo: this.validTo?.iso ?? null,\n    };\n  }\n}\n","import type { AccountNumber } from './account-number.js';\nimport type { DimensionValue } from './dimension-value.js';\nimport type { Money } from './money.js';\nimport type { Uuid } from './uuid.js';\nimport type { Side } from './types.js';\n\n/**\n * Posting line — value object within the posting (no own identity;\n * reference = posting ID + line index).\n */\nexport class EntryLine {\n  constructor(\n    readonly accountId: Uuid,\n    readonly account: AccountNumber,\n    readonly side: Side,\n    readonly money: Money,\n    readonly dimensions: DimensionValue[] = [],\n    readonly taxTag: Record<string, unknown> | null = null,\n  ) {}\n\n  negated(): EntryLine {\n    return new EntryLine(\n      this.accountId,\n      this.account,\n      this.side,\n      this.money.negate(),\n      this.dimensions,\n      this.taxTag,\n    );\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      accountId: this.accountId.value,\n      account: this.account.value,\n      side: this.side,\n      money: this.money.toJSON(),\n      dimensions: this.dimensions.map((dimension) => dimension.toJSON()),\n      taxTag: this.taxTag,\n    };\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type { CalendarDate } from './calendar-date.js';\nimport type { PeriodRef } from './period-ref.js';\nimport type { Uuid } from './uuid.js';\nimport type { EntryLine } from './entry-line.js';\nimport type { EntryStatus } from './types.js';\n\n/**\n * Posting — the most important aggregate (ledger-modell.md). Created complete and\n * valid (validation in the ledger service); lifecycle entered → finalized,\n * afterwards only reversal (new posting with back-reference, full reversal).\n */\nexport class JournalEntry {\n  private entryText: string;\n  private entryLines: EntryLine[];\n  private entryReversedBy: Uuid | null;\n  private entryStatus: EntryStatus;\n\n  constructor(\n    readonly id: Uuid,\n    readonly sequenceNumber: number,\n    readonly entryDate: CalendarDate,\n    readonly voucherDate: CalendarDate | null,\n    readonly recordedAt: string,\n    readonly periodRef: PeriodRef,\n    readonly voucherId: Uuid,\n    text: string,\n    lines: EntryLine[],\n    readonly reverses: Uuid | null = null,\n    reversedBy: Uuid | null = null,\n    status: EntryStatus = 'entered',\n  ) {\n    this.entryText = text;\n    this.entryLines = lines;\n    this.entryReversedBy = reversedBy;\n    this.entryStatus = status;\n  }\n\n  status(): EntryStatus {\n    return this.entryStatus;\n  }\n\n  isFinalized(): boolean {\n    return this.entryStatus === 'finalized';\n  }\n\n  text(): string {\n    return this.entryText;\n  }\n\n  lines(): EntryLine[] {\n    return this.entryLines;\n  }\n\n  reversedBy(): Uuid | null {\n    return this.entryReversedBy;\n  }\n\n  changeText(text: string): void {\n    this.assertCorrectable();\n    this.entryText = text;\n  }\n\n  changeLines(lines: EntryLine[]): void {\n    this.assertCorrectable();\n    this.entryLines = lines;\n  }\n\n  finalize(): void {\n    this.entryStatus = 'finalized';\n  }\n\n  markReversed(reversalId: Uuid): void {\n    if (this.entryReversedBy !== null) {\n      throw new DomainError(\n        'E_ENTRY_ALREADY_REVERSED',\n        `Posting ${this.id.value} is already reversed (by ${this.entryReversedBy.value})`,\n        { entryId: this.id.value, reversedBy: this.entryReversedBy.value },\n      );\n    }\n    this.entryReversedBy = reversalId;\n  }\n\n  private assertCorrectable(): void {\n    if (this.entryStatus !== 'entered') {\n      throw new DomainError(\n        'E_ENTRY_FINALIZED',\n        `Posting ${this.id.value} is finalized — correction not possible, only reversal`,\n        { entryId: this.id.value },\n      );\n    }\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      sequenceNumber: this.sequenceNumber,\n      status: this.entryStatus,\n      entryDate: this.entryDate.iso,\n      voucherDate: this.voucherDate?.iso ?? null,\n      recordedAt: this.recordedAt,\n      periodRef: this.periodRef.toJSON(),\n      voucherId: this.voucherId.value,\n      text: this.entryText,\n      lines: this.entryLines.map((line) => line.toJSON()),\n      reverses: this.reverses?.value ?? null,\n      reversedBy: this.entryReversedBy?.value ?? null,\n    };\n  }\n}\n","import type { CalendarDate } from '../substrate/calendar-date.js';\nimport type { Uuid } from '../substrate/uuid.js';\n\n/**\n * Voucher (ledger-modell.md aggregate 4): exists before/without a posting, several\n * postings can reference it. Metadata for cash-basis/tax projections (due, recurring,\n * economicYear, serviceDate/servicePeriod, partnerId, kind …).\n */\nexport interface VoucherProps {\n  readonly id: Uuid;\n  readonly voucherNumber: string;\n  readonly voucherDate: CalendarDate;\n  readonly due?: CalendarDate | null;\n  readonly recurring?: boolean;\n  readonly economicYear?: number | null;\n  readonly supplierTaxationMethod?: string | null;\n  readonly serviceDate?: CalendarDate | null;\n  readonly servicePeriodFrom?: CalendarDate | null;\n  readonly servicePeriodTo?: CalendarDate | null;\n  readonly kind?: string | null;\n  readonly partnerId?: Uuid | null;\n  readonly issuer?: string | null;\n}\n\nexport class Voucher {\n  readonly id: Uuid;\n  readonly voucherNumber: string;\n  readonly voucherDate: CalendarDate;\n  readonly due: CalendarDate | null;\n  readonly recurring: boolean;\n  readonly economicYear: number | null;\n  readonly supplierTaxationMethod: string | null;\n  readonly serviceDate: CalendarDate | null;\n  readonly servicePeriodFrom: CalendarDate | null;\n  readonly servicePeriodTo: CalendarDate | null;\n  readonly kind: string | null;\n  readonly partnerId: Uuid | null;\n  readonly issuer: string | null;\n\n  constructor(props: VoucherProps) {\n    this.id = props.id;\n    this.voucherNumber = props.voucherNumber;\n    this.voucherDate = props.voucherDate;\n    this.due = props.due ?? null;\n    this.recurring = props.recurring ?? false;\n    this.economicYear = props.economicYear ?? null;\n    this.supplierTaxationMethod = props.supplierTaxationMethod ?? null;\n    this.serviceDate = props.serviceDate ?? null;\n    this.servicePeriodFrom = props.servicePeriodFrom ?? null;\n    this.servicePeriodTo = props.servicePeriodTo ?? null;\n    this.kind = props.kind ?? null;\n    this.partnerId = props.partnerId ?? null;\n    this.issuer = props.issuer ?? null;\n  }\n\n  /** Tax-relevant date: service date, fallback voucher date. */\n  taxDate(): CalendarDate {\n    return this.serviceDate ?? this.servicePeriodTo ?? this.voucherDate;\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      voucherNumber: this.voucherNumber,\n      voucherDate: this.voucherDate.iso,\n      due: this.due?.iso ?? null,\n      recurring: this.recurring,\n      economicYear: this.economicYear,\n      supplierTaxationMethod: this.supplierTaxationMethod,\n      serviceDate: this.serviceDate?.iso ?? null,\n      servicePeriod:\n        this.servicePeriodFrom === null\n          ? null\n          : { from: this.servicePeriodFrom.iso, to: this.servicePeriodTo?.iso ?? null },\n      kind: this.kind,\n      partnerId: this.partnerId?.value ?? null,\n      issuer: this.issuer,\n    };\n  }\n}\n","import type { CalendarDate } from './calendar-date.js';\nimport type { PeriodStatus } from './types.js';\n\n/**\n * Period — entity within the FiscalYear aggregate (gapless,\n * non-overlapping; status change only via the aggregate).\n */\nexport class Period {\n  private periodStatus: PeriodStatus;\n\n  constructor(\n    readonly number: number,\n    readonly start: CalendarDate,\n    readonly end: CalendarDate,\n    status: PeriodStatus = 'open',\n  ) {\n    this.periodStatus = status;\n  }\n\n  status(): PeriodStatus {\n    return this.periodStatus;\n  }\n\n  isOpen(): boolean {\n    return this.periodStatus === 'open';\n  }\n\n  contains(date: CalendarDate): boolean {\n    return date.isBetween(this.start, this.end);\n  }\n\n  /** Call only via FiscalYear (order check there). */\n  close(): void {\n    this.periodStatus = 'closed';\n  }\n\n  /** Call only via FiscalYear (year status check there). */\n  reopen(): void {\n    this.periodStatus = 'open';\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type { CalendarDate } from './calendar-date.js';\nimport { InvalidValue } from './errors.js';\nimport type { Uuid } from './uuid.js';\nimport { Period } from './period.js';\nimport type { FiscalYearStatus } from './types.js';\n\nexport interface PeriodDefinition {\n  readonly period: number;\n  readonly start: CalendarDate;\n  readonly end: CalendarDate;\n}\n\n/**\n * Fiscal year with periods (ledger-modell.md aggregate 3). Invariants:\n * periods gapless and non-overlapping; closing only in order;\n * reopening only before year-end closing. `year` = calendar year of the fiscal year end.\n */\nexport class FiscalYear {\n  private fiscalStatus: FiscalYearStatus;\n\n  private constructor(\n    readonly id: Uuid,\n    readonly year: number,\n    readonly start: CalendarDate,\n    readonly end: CalendarDate,\n    private readonly periodList: Period[],\n    status: FiscalYearStatus = 'open',\n  ) {\n    this.fiscalStatus = status;\n  }\n\n  static create(\n    id: Uuid,\n    year: number,\n    start: CalendarDate,\n    end: CalendarDate,\n    explicitPeriods: PeriodDefinition[] | null = null,\n  ): FiscalYear {\n    if (!start.isBefore(end)) {\n      throw new InvalidValue('Fiscal year: start must be before end');\n    }\n    const periods =\n      explicitPeriods === null\n        ? FiscalYear.monthlyPeriods(start, end)\n        : explicitPeriods.map((d) => new Period(d.period, d.start, d.end));\n    return new FiscalYear(id, year, start, end, periods);\n  }\n\n  /**\n   * Restore from persistence: take over status and periods explicitly\n   * (no rebuild, no validation) — counterpart to PHP's `FiscalYear::restore`.\n   */\n  static restore(\n    id: Uuid,\n    year: number,\n    start: CalendarDate,\n    end: CalendarDate,\n    status: FiscalYearStatus,\n    periods: Period[],\n  ): FiscalYear {\n    return new FiscalYear(id, year, start, end, periods, status);\n  }\n\n  private static monthlyPeriods(start: CalendarDate, end: CalendarDate): Period[] {\n    const periods: Period[] = [];\n    let cursor = start;\n    let number = 1;\n    while (!cursor.isAfter(end)) {\n      const monthEnd = cursor.lastDayOfMonth();\n      const periodEnd = monthEnd.isAfter(end) ? end : monthEnd;\n      periods.push(new Period(number, cursor, periodEnd));\n      cursor = cursor.firstDayOfNextMonth();\n      number++;\n    }\n    return periods;\n  }\n\n  status(): FiscalYearStatus {\n    return this.fiscalStatus;\n  }\n\n  isClosed(): boolean {\n    return this.fiscalStatus === 'closed';\n  }\n\n  periods(): Period[] {\n    return this.periodList;\n  }\n\n  period(number: number): Period {\n    const found = this.periodList.find((p) => p.number === number);\n    if (found === undefined) {\n      throw new DomainError(\n        'E_PERIOD_UNKNOWN',\n        `Period ${number} does not exist in fiscal year ${this.year}`,\n        { fiscalYear: this.year, period: number },\n      );\n    }\n    return found;\n  }\n\n  contains(date: CalendarDate): boolean {\n    return date.isBetween(this.start, this.end);\n  }\n\n  periodForDate(date: CalendarDate): Period {\n    const found = this.periodList.find((p) => p.contains(date));\n    if (found === undefined) {\n      throw new DomainError(\n        'E_PERIOD_UNKNOWN',\n        `No period range for ${date.iso} in fiscal year ${this.year}`,\n        { date: date.iso, fiscalYear: this.year },\n      );\n    }\n    return found;\n  }\n\n  closePeriod(number: number): Period {\n    this.assertNotClosed();\n    const target = this.period(number);\n    for (const period of this.periodList) {\n      if (period.number < number && period.isOpen()) {\n        throw new DomainError(\n          'E_PERIOD_OUT_OF_ORDER',\n          `Period ${number} cannot be closed: period ${period.number} is still open`,\n          { fiscalYear: this.year, period: number, openPeriod: period.number },\n        );\n      }\n    }\n    target.close();\n    return target;\n  }\n\n  reopenPeriod(number: number): Period {\n    this.assertNotClosed();\n    const target = this.period(number);\n    target.reopen();\n    return target;\n  }\n\n  /** Pure status change — no business posting effect (api.md v0.3). */\n  close(): void {\n    for (const period of this.periodList) {\n      if (period.isOpen()) {\n        throw new DomainError(\n          'E_PERIOD_OUT_OF_ORDER',\n          `Year-end closing ${this.year}: period ${period.number} is still open`,\n          { fiscalYear: this.year, openPeriod: period.number },\n        );\n      }\n    }\n    this.fiscalStatus = 'closed';\n  }\n\n  private assertNotClosed(): void {\n    if (this.isClosed()) {\n      throw new DomainError('E_FISCALYEAR_CLOSED', `Fiscal year ${this.year} is closed`, {\n        fiscalYear: this.year,\n      });\n    }\n  }\n}\n","import { createHash } from 'node:crypto';\nimport { canonicalJson } from '../substrate/canonical-json.js';\nimport type { Uuid } from '../substrate/uuid.js';\n\nexport type AuditChanges = Record<string, { from: unknown; to: unknown }>;\n\n/**\n * The value every field of a redacted record carries. A reserved `objectType`, so a redacted\n * record cannot be confused with a record about a real object and no existing filter matches it.\n */\nexport const REDACTED = 'redacted';\n\n/**\n * Audit entry (datenformat.md `auditLog.jsonl`): flat before/after diff of only the changed fields,\n * plus — since format 0.8 — its link in the trail's hash chain.\n *\n * **Why the chain is here and not on the journal entry.** `docs/gobd-conformance.md` §14 item 5c\n * asked for tamper evidence on the *trail*: today it is append-only because no code path updates or\n * deletes it, which is a property of the procedure rather than of the data — an auditor has to trust\n * the deployment instead of checking the file. The obvious-looking alternative, a chain over the\n * postings, is **not available**: `datenformat.md` reserves `previousEntryHash` on the posting and\n * says writers must not populate it in v0.x while readers must ignore it. A chain every conforming\n * reader is instructed to ignore is evidence for nobody (SPEC-022). The trail's records carry no\n * such reservation, and the trail is what the row asked about.\n *\n * **`recordHash` covers the record including its `previousRecordHash`**, so changing any earlier\n * record invalidates every later link. Removing a record breaks the link at its successor. What a\n * chain cannot do is notice records removed from the *end* — which is why the head is published.\n */\nexport class AuditRecord {\n  constructor(\n    readonly id: Uuid,\n    readonly at: string,\n    readonly actor: string,\n    readonly objectType: string,\n    readonly objectId: Uuid,\n    readonly action: string,\n    readonly changes: AuditChanges = {},\n    /** The predecessor's `recordHash`; `null` for the first record and for anything written before 0.8. */\n    readonly previousRecordHash: string | null = null,\n    /** This record's own hash; `null` only for records written before 0.8. */\n    readonly recordHash: string | null = null,\n  ) {}\n\n  /**\n   * The same record, linked behind `previousHash` and carrying its own hash.\n   *\n   * The trail computes this at `append`, because the head is the one thing only the store knows.\n   */\n  chainedTo(previousHash: string | null): AuditRecord {\n    const linked = new AuditRecord(\n      this.id,\n      this.at,\n      this.actor,\n      this.objectType,\n      this.objectId,\n      this.action,\n      this.changes,\n      previousHash,\n      null,\n    );\n    return new AuditRecord(\n      this.id,\n      this.at,\n      this.actor,\n      this.objectType,\n      this.objectId,\n      this.action,\n      this.changes,\n      previousHash,\n      hashOf(linked),\n    );\n  }\n\n  /**\n   * What is left of a record after an erasure (F-CORE-040): the link, and nothing else.\n   *\n   * **A lawful erasure and a manipulation must not look alike.** Deleting the row outright would\n   * break the chain at the successor and leave it broken for good, so every later verification would\n   * report tampering that never happened — and a warning that is always on is a warning nobody\n   * reads. The shell keeps `previousRecordHash` and `recordHash` so the linkage stays checkable, and\n   * drops everything the erasure was about.\n   *\n   * The honest limit, and it is the point rather than a flaw: a shell's *content* can no longer be\n   * verified against its hash, because there is no content left to hash. Linkage stays provable,\n   * content integrity of the erased record does not. If it did, the erasure would not be one.\n   */\n  redactedShell(): AuditRecord {\n    return new AuditRecord(\n      this.id,\n      this.at,\n      REDACTED,\n      REDACTED,\n      this.id,\n      REDACTED,\n      {},\n      this.previousRecordHash,\n      this.recordHash,\n    );\n  }\n\n  isRedacted(): boolean {\n    return this.objectType === REDACTED;\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      at: this.at,\n      actor: this.actor,\n      objectType: this.objectType,\n      objectId: this.objectId.value,\n      action: this.action,\n      // Empty diff → {} (not []), so the format stays stable.\n      changes: this.changes,\n      previousRecordHash: this.previousRecordHash,\n      recordHash: this.recordHash,\n    };\n  }\n}\n\n/**\n * The hash of a record: SHA-256 over its canonical JSON (RFC 8785) **without** `recordHash` itself.\n *\n * Both languages hash the same bytes because both produce the same canonical JSON — the property\n * the cross-test already proves for `journalExport`.\n */\nexport function hashOf(record: AuditRecord): string {\n  const payload = record.toJSON();\n  delete payload.recordHash;\n  return createHash('sha256').update(canonicalJson(payload)).digest('hex');\n}\n","import type { AuditCriteria } from '../port.js';\nimport type { AuditRecord } from './audit-record.js';\n\n/**\n * The criteria of `AuditTrail.find`, applied in memory (SPEC-018).\n *\n * One place, because the rule has to be the same wherever it runs: the in-memory adapter filters\n * with this, a database adapter filters with SQL, and the two must not answer differently. An\n * adapter suite in each language drives the same criteria through both and compares.\n *\n * The one asymmetry worth naming: a store can decline to *read* a row, and this cannot. That is the\n * whole point of the port method and the reason this is a fallback rather than the implementation.\n */\nexport function applyAuditCriteria(\n  records: readonly AuditRecord[],\n  criteria: AuditCriteria,\n): { records: AuditRecord[]; count: number } {\n  const matching = records.filter((record) => matches(record, criteria));\n  const offset = Math.max(0, criteria.offset ?? 0);\n  const limit = criteria.limit ?? null;\n\n  // An absent limit means \"everything from the offset on\" — the same rule `journal` publishes.\n  const page = limit === null || limit < 0 ? matching.slice(offset) : matching.slice(offset, offset + limit);\n\n  return { records: page, count: matching.length };\n}\n\nfunction matches(record: AuditRecord, criteria: AuditCriteria): boolean {\n  if (typeof criteria.objectType === 'string' && record.objectType !== criteria.objectType) return false;\n  if (typeof criteria.action === 'string' && record.action !== criteria.action) return false;\n  if (typeof criteria.actor === 'string' && record.actor !== criteria.actor) return false;\n  if (typeof criteria.objectId === 'string' && record.objectId.value !== criteria.objectId) return false;\n  if (Array.isArray(criteria.objectIds) && !criteria.objectIds.includes(record.objectId.value)) return false;\n\n  const date = record.at.slice(0, 10);\n  if (typeof criteria.from === 'string' && date < criteria.from) return false;\n\n  return !(typeof criteria.to === 'string' && date > criteria.to);\n}\n","import type { AuditTrail } from '../../port.js';\n\n/**\n * Who recorded which posting (F-CORE-037) — the one fact about an entry that lives only in the\n * audit trail.\n *\n * A journal entry carries no author. The actor of the operation that created it is written into the\n * audit record at that moment and nowhere else, so `journal` and `unfinalizedEntries` could report\n * everything about a posting except who made it. An application building **separation of duties**\n * (\"nobody may finalize a batch containing their own postings\") therefore read the entire audit\n * trail on every finalization and rebuilt the mapping itself — which is an embedding reconstructing\n * library state from a trail, the move this project has already named as a bug waiting for the\n * first change that does not pass through the screen that writes it.\n *\n * **The trail stays the single source.** The author is not copied onto the entry: that would be a\n * second place for the same fact, and the entry is append-only — an author written there could\n * never be corrected while the trail's record of who acted is what an audit actually asks for.\n *\n * **It asks for the entries it needs, not for the trail** (SPEC-018). The map is built from a `find`\n * over the ids on the page, so a journal view of forty postings reads forty records rather than ten\n * years of history. It used to read `all()`, which moved the embedding's walk into the library\n * without making it smaller.\n */\nexport function entryAuthors(audit: AuditTrail, entryIds: readonly string[]): Map<string, string> {\n  const byEntry = new Map<string, string>();\n  if (entryIds.length === 0) return byEntry;\n\n  const found = audit.find({ objectType: 'journalEntry', action: 'created', objectIds: entryIds });\n  for (const record of found.records) byEntry.set(record.objectId.value, record.actor);\n\n  return byEntry;\n}\n","import type { AuditTrail, JournalRepository } from '../../port.js';\nimport { entryAuthors } from './entry-authors.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { Clock } from '../../substrate/clock.js';\n\n/**\n * Postings still in status `entered` at a reference date (F-CORE-027).\n *\n * GoBD asks for finalization \"at the latest with the VAT return\" (Rz. 47 ff.) — a deadline\n * nothing in the data enforces, because it is a *German* rule and the substrate is\n * jurisdiction-free. What the substrate can do is make the deadline observable: the journal\n * already carries `entryDate` and `recordedAt`, so how long a posting has been sitting open\n * is a fold over the journal, not new state.\n *\n * The age is measured from `entryDate` (the bookkeeping date, zoneless) against `asOf`, not\n * from `recordedAt` — a posting recorded late for an old date is exactly the case the\n * deadline is about, and measuring from the recording moment would hide it.\n *\n * The projection reports; it never blocks. Which age is too old, and what happens then, is\n * the embedding application's workflow — the library supplies the number.\n *\n * Each row carries `actor` (F-CORE-037): who recorded the posting. This is the projection a\n * separation-of-duties check reads — \"nobody may finalize a batch containing their own postings\" —\n * and without the author it was the one question it could not ask here, so an application read the\n * whole audit trail per finalization and rebuilt the mapping itself. See `entryAuthors`.\n */\nexport class UnfinalizedEntriesProjection {\n  constructor(\n    private readonly journal: JournalRepository,\n    private readonly clock: Clock,\n    /**\n     * Where the author of a posting lives — the entry itself does not carry one.\n     *\n     * Required, not optional-with-a-default. An optional dependency is how three services in the\n     * database factory lost their audit writer and nobody noticed for a release: nothing fails to\n     * compile, nothing warns, the output is merely poorer in one setup.\n     */\n    private readonly audit: AuditTrail,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const asOf =\n      typeof params.asOf === 'string'\n        ? CalendarDate.of(params.asOf)\n        : CalendarDate.of(this.clock.now().toISOString().slice(0, 10));\n    const olderThanDays = typeof params.olderThanDays === 'number' ? params.olderThanDays : 0;\n    const fiscalYear = typeof params.fiscalYear === 'number' ? params.fiscalYear : null;\n\n    const source = fiscalYear === null ? this.journal.all() : this.journal.forFiscalYear(fiscalYear);\n    const entries: Array<Record<string, unknown>> = [];\n    let oldestAgeInDays = 0;\n\n    for (const entry of source) {\n      if (entry.isFinalized()) continue;\n      const ageInDays = asOf.daysSince(entry.entryDate);\n      if (ageInDays < olderThanDays) continue;\n\n      entries.push({\n        entryId: entry.id.value,\n        sequenceNumber: entry.sequenceNumber,\n        entryDate: entry.entryDate.iso,\n        recordedAt: entry.recordedAt,\n        fiscalYear: entry.periodRef.fiscalYear,\n        period: entry.periodRef.period,\n        ageInDays,\n        text: entry.text(),\n      });\n      if (ageInDays > oldestAgeInDays) oldestAgeInDays = ageInDays;\n    }\n\n    // The authors of exactly these postings, not of the whole trail (SPEC-018).\n    const authors = entryAuthors(\n      this.audit,\n      entries.map((row) => String(row.entryId)),\n    );\n    for (const row of entries) row.actor = authors.get(String(row.entryId)) ?? null;\n\n    // Journal order (sequenceNumber) is the order the entries arrive in; keeping it makes\n    // the result deterministic without a second sort key.\n    return {\n      asOf: asOf.iso,\n      olderThanDays,\n      count: entries.length,\n      oldestAgeInDays,\n      entries,\n    };\n  }\n}\n","import type { Currency } from '../../substrate/currency.js';\nimport { FORMAT_VERSION } from '../../substrate/format-version.js';\nimport type { Uuid } from '../../substrate/uuid.js';\n\n/**\n * Technical system description (F-IO-007) — the building block of a Verfahrensdokumentation\n * the *package* can supply (GoBD Rz. 151 ff.).\n *\n * The Verfahrensdokumentation has four parts: general description, user documentation,\n * technical system documentation, operating documentation. Three of them describe *your*\n * installation and processes and no library can write them. The technical one is different:\n * what the engine enforces, which operations exist, how the journal behaves and what the\n * stored format looks like are facts about the software, and stating them by hand means\n * stating them wrong within a release.\n *\n * So this projection reports them from the same constants the engine runs on. It is\n * deliberately **not** the whole document — it is the section an auditor would otherwise ask\n * the vendor for, in a form you paste into yours.\n *\n * Deterministic and tenant-independent apart from the identity block: same version of\n * summae, same description.\n *\n * `pack` names the manifest the tenant was composed from, or is null when it was built from\n * an inline rule bundle — in which case there is no manifest to name and a\n * Verfahrensdokumentation has to state the rule source by hand.\n */\n\n/**\n * Every operation and projection the dispatcher answers. This is the list the description\n * publishes; `tenant-operations-contract.test.ts` holds its own literal copy and asserts\n * both agree, so a case dropped from the dispatcher and a name dropped from here cannot\n * cancel each other out.\n *\n * The test asks **both** directions, and the second one was missing for a long time: every\n * published name resolves to a handler, *and* every routed name is published. Seven finished,\n * documented, fixture-covered capabilities were routed and unpublished — an embedding app\n * validating its calls against this list could not call them at all, which is how it was\n * found. A surface larger than its declaration is the same defect as one smaller than it.\n */\nexport const API_OPERATIONS = [\n   'acquireAsset', 'allocate', 'appropriateResult', 'bookSpecialDepreciation', 'closeFiscalYear', 'closePeriod',\n   'correct', 'createAccount', 'createFiscalYear', 'createPartner', 'createVoucher',\n   'adjustInputTax', 'deactivatePartner', 'defineDimensionType', 'defineDimensionValue', 'disposeAsset',\n   'erasePartner',\n   'expandTax', 'finalize', 'importChartOfAccounts', 'importMapping', 'lockAccount', 'post',\n   'postVoucher', 'reactivatePartner', 'releaseCosting', 'reopenPeriod', 'reportAssetUsage',\n   'recognizeDeferral', 'recognizeProvision', 'releaseProvision', 'remeasureProvision',\n  'reverse', 'runCosting', 'runDeferralRelease', 'runDepreciation', 'setAllocationScheme', 'setEntityProfile', 'setTaxProfile',\n  'useProvision', 'valuateInventory', 'settle',\n   'unlockAccount', 'updatePartner', 'writeDownAsset', 'writeUpAsset',\n] as const;\n\nexport const API_PROJECTIONS = [\n  'accountSheet', 'accounts', 'assetRegister', 'assetSchedule', 'auditDataExport', 'auditLog', 'auditTrailIntegrity', 'balanceSheet',\n  'cashBasisReport', 'cashJournal', 'costAllocationSheet', 'costingRuns', 'datevExport', 'deferralRegister',\n  'duplicateVouchers', 'ecSalesList',\n  'fiscalYears', 'gdpduExport', 'incomeStatement', 'inventoryValuation', 'journal', 'journalExport',\n  'measurementConsistency', 'openItems',\n  'personalDataDescription', 'overheadRates',\n  'productionCost', 'provisionRegister', 'systemDescription', 'tenantConfiguration', 'trialBalance',\n  'unappropriatedResult', 'unfinalizedEntries', 'vatReturn',\n] as const;\n\n/**\n * What the engine guarantees, in the words an auditor uses. Each entry names the mechanism\n * that makes it true, so the claim can be checked rather than believed — the same discipline\n * `docs/gobd-conformance.md` applies at the level of the whole system.\n */\nconst INVARIANTS: ReadonlyArray<{ id: string; statement: string; enforcedBy: string }> = [\n  {\n    id: 'balanced-posting',\n    statement: 'Every posting balances: the sum of its lines is zero.',\n    enforcedBy: 'Rejected on write with E_ENTRY_UNBALANCED; never checked on read.',\n  },\n  {\n    id: 'append-only-journal',\n    statement: 'The journal is append-only. Nothing is deleted, nothing is overwritten.',\n    enforcedBy: 'No delete or update path exists on the journal repository.',\n  },\n  {\n    id: 'immutable-after-finalization',\n    statement: 'A finalized posting cannot be changed; a correction is a reversal that references the original.',\n    enforcedBy: 'JournalEntry refuses the change itself (E_ENTRY_FINALIZED); reverse writes a new entry carrying `reverses`.',\n  },\n  {\n    id: 'gapless-numbering',\n    statement: 'Journal numbers are gapless; the number is assigned atomically while posting.',\n    enforcedBy: 'Number assignment is the serialization point of `post` in the persistence adapter.',\n  },\n  {\n    id: 'mandatory-voucher',\n    statement: 'No posting without exactly one voucher reference.',\n    enforcedBy: 'voucherId is not nullable; an unknown one is E_VOUCHER_UNKNOWN.',\n  },\n  {\n    id: 'closed-periods',\n    statement: 'A closed period accepts no further postings; periods close in order.',\n    enforcedBy: 'E_PERIOD_CLOSED on every write into a closed period.',\n  },\n  {\n    id: 'projections-not-stored-balances',\n    statement: 'Every balance, trial balance, balance sheet, income statement and VAT return is recomputed from the journal.',\n    enforcedBy: 'No balance is stored anywhere; there is no second source to diverge from.',\n  },\n  {\n    id: 'exact-money',\n    statement: 'Amounts are exact decimals, never floating point. Rounding is commercial half-up, away from zero.',\n    enforcedBy: 'Money is built on a decimal library (brick/math in PHP, big.js in Node).',\n  },\n  {\n    id: 'determinism',\n    statement: 'The same input produces a byte-identical result, in every implementation.',\n    enforcedBy: 'Injectable Clock and IdGenerator, canonical JSON (RFC 8785), sorting by Unicode code point; the conformance suite runs twice and compares.',\n  },\n  {\n    id: 'audit-trail',\n    statement: 'Every state-changing operation writes an audit record with actor, timestamp, object and before/after values.',\n    enforcedBy: 'Enumerating contract test over all state-changing operations, in both implementations.',\n  },\n  {\n    id: 'zoneless-dates',\n    statement: 'Posting and voucher dates carry no time zone, so no shift can move a posting into another period.',\n    enforcedBy: 'CalendarDate stores an ISO date and does its arithmetic without the host date type.',\n  },\n];\n\n/** What the audit trail records, so a reader can tell completeness from a sample. */\n/**\n * Exported because `audit-trail-contract.test.ts` holds it against the pairs the operations\n * *actually* write, in both directions — the same guard `capabilities` has. It used to be a\n * hand-kept literal that nothing compared to reality, and it had already fallen behind once\n * (0.11.0, where it under-reported what the trail records). A list published to an auditor is a\n * claim, and a claim without a test is the thing this project calls a gate gap.\n */\nexport const AUDITED_EVENTS: ReadonlyArray<{ objectType: string; actions: readonly string[] }> = [\n  { objectType: 'journalEntry', actions: ['created', 'corrected', 'finalized', 'reversed'] },\n  { objectType: 'voucher', actions: ['created'] },\n  { objectType: 'account', actions: ['created', 'locked', 'unlocked'] },\n  { objectType: 'openItem', actions: ['settled', 'cancelled'] },\n  { objectType: 'partner', actions: ['created', 'updated', 'deactivated', 'reactivated', 'erased'] },\n  { objectType: 'fiscalYear', actions: ['created', 'closed'] },\n  { objectType: 'period', actions: ['closed', 'reopened'] },\n  { objectType: 'taxProfile', actions: ['changed'] },\n  { objectType: 'entityProfile', actions: ['changed'] },\n  { objectType: 'mapping', actions: ['imported'] },\n  { objectType: 'allocationScheme', actions: ['changed'] },\n  { objectType: 'asset', actions: ['acquired', 'disposed', 'usageReported', 'specialDepreciationBooked', 'writtenDown', 'writtenUp'] },\n  { objectType: 'dimensionType', actions: ['created'] },\n  { objectType: 'dimensionValue', actions: ['created'] },\n  { objectType: 'depreciationRun', actions: ['completed'] },\n  { objectType: 'inventoryValuation', actions: ['valued'] },\n  { objectType: 'provision', actions: ['recognized', 'used', 'released', 'remeasured'] },\n  { objectType: 'deferral', actions: ['recognized'] },\n  { objectType: 'deferralRelease', actions: ['completed'] },\n  { objectType: 'inputTaxAdjustment', actions: ['adjusted'] },\n  { objectType: 'costingRun', actions: ['created', 'released'] },\n];\n\n/**\n * What this package deliberately does NOT do. An auditor reading a system description needs\n * the boundary as much as the capability list, and a Verfahrensdokumentation that claims\n * more than the software does is worse than one that claims less.\n */\nconst NOT_PROVIDED: readonly string[] = [\n  'No user model and no authentication: `actor` is recorded as supplied by the caller, never verified.',\n  'No access control, no separation of duties.',\n  'No document storage: vouchers are referenced, the files live elsewhere.',\n  'No retention or deletion logic; no automatic deletion by date.',\n  'No submission to authorities (ELSTER), no e-invoice creation or parsing, no banking, no POS/TSE.',\n  'No enforcement of national recording deadlines — the `unfinalizedEntries` projection reports them.',\n  'No mapping onto the GoBD Z3 Beschreibungsstandard (index.xml); `journalExport` supplies the self-describing data set it is built from.',\n  'Guarantees hold for operations made through the documented API; direct database writes bypass all of them.',\n];\n\nexport class SystemDescriptionProjection {\n  constructor(\n    private readonly tenantId: Uuid,\n    private readonly tenantName: string,\n    private readonly baseCurrency: Currency,\n    /** Null when the tenant was composed from an inline bundle: there is no manifest to name. */\n    private readonly packIdentity: { id: string; version: string } | null = null,\n    /**\n     * The tax profile the engine is actually running on (F-TAX-003).\n     *\n     * Nothing reported it, so an embedding could display only what it had written itself — the same\n     * value by construction *in that embedding*, which is a property of one caller and not a\n     * guarantee. It belongs here rather than in a projection of its own: this is the projection that\n     * already describes the tenant, and a Verfahrensdokumentation has to state which taxation method\n     * the books were kept under.\n     */\n    private readonly taxProfile: Record<string, unknown> | null = null,\n    /**\n     * What the embedding declares about the identity behind `actor` (SPEC-020, reported by an\n     * embedding app as its F-30).\n     *\n     * summae is handed an actor string and cannot know where it came from — that is what\n     * `auditTrail.actorIsAuthenticated: false` has always said, and it stays true. The trouble was\n     * what the field gets *used for*: an application generating the technical part of a\n     * Verfahrensdokumentation put it in as \"Urheber geprüft: **nein**\", and then grew a login. The\n     * document went on telling an auditor that every entry's author is unverified about an\n     * installation where a password had been proved before the actor was ever set.\n     *\n     * So the only party that can know says so, and summae reports it **as a declaration** rather\n     * than as a finding of its own. `null` — the default, and what every embedding gets until it\n     * speaks — means nothing was declared, which is not the same as \"no\".\n     *\n     * Deliberately **not** stored with the tenant. This describes the running installation, not the\n     * books: an embedding that drops its login tomorrow must not leave yesterday's claim behind in\n     * a record. It is passed on every construction, like the pack.\n     */\n    private readonly actorAuthentication: { declared: boolean; method: string | null } | null = null,\n  ) {}\n\n  compute(_params: Record<string, unknown>): Record<string, unknown> {\n    return {\n      formatVersion: FORMAT_VERSION,\n      tenant: {\n        id: this.tenantId.value,\n        name: this.tenantName,\n        baseCurrency: this.baseCurrency.code,\n      },\n      pack: this.packIdentity === null ? null : { ...this.packIdentity },\n      taxProfile: this.taxProfile === null ? null : { ...this.taxProfile },\n      journal: {\n        appendOnly: true,\n        ordering: 'sequenceNumber',\n        lifecycle: ['entered', 'finalized'],\n        correction: 'reversal with back-reference (`reverses` / `reversedBy`)',\n        dates: {\n          voucherDate: 'date on the voucher',\n          entryDate: 'bookkeeping date, zoneless',\n          recordedAt: 'moment of recording, canonical UTC timestamp',\n        },\n      },\n      invariants: INVARIANTS.map((i) => ({ ...i })),\n      auditTrail: {\n        events: AUDITED_EVENTS.map((e) => ({ objectType: e.objectType, actions: [...e.actions] })),\n        actorIsAuthenticated: false,\n        actorAuthentication: {\n          // Never goes stale, whatever any embedding does: this library authenticates nobody.\n          byLibrary: false,\n          // What the embedding states about itself. `null` = it has not said, which a generator\n          // must not turn into \"no\" — an unanswered question and a denial read differently to an\n          // auditor.\n          declaredByEmbedding: this.actorAuthentication === null ? null : this.actorAuthentication.declared,\n          method: this.actorAuthentication === null ? null : this.actorAuthentication.method,\n        },\n        // What makes the trail checkable rather than merely trusted (format 0.8). Published here\n        // because an auditor reads this block to learn what the trail is; a chain nobody is told\n        // about protects nobody.\n        hashChain: {\n          algorithm: 'sha256-over-canonical-json',\n          field: 'previousRecordHash',\n          verifiedBy: 'auditTrailIntegrity',\n          note:\n            'Each record carries the hash of its predecessor, computed over canonical JSON (RFC 8785). '\n            + 'Changing or removing a record breaks the link at its successor. Records erased under a '\n            + 'privacy right leave a shell that keeps both hashes, so a lawful erasure stays distinguishable '\n            + 'from a manipulation; a shell\\'s own content can no longer be verified, which is what an erasure '\n            + 'means. Records written before format 0.8 carry no hash and are reported as unchained, never as '\n            + 'broken. A chain cannot notice records dropped from the END of the trail — compare the published '\n            + 'head against one you kept.',\n        },\n        note:\n          'The actor is recorded as supplied by the caller; summae authenticates nobody, which is what '\n          + 'actorAuthentication.byLibrary states and what actorIsAuthenticated has always meant. Whether the '\n          + 'identity behind it was proved is a fact only the embedding knows, and it is reported here as that '\n          + \"embedding's declaration — never as summae's own finding.\",\n      },\n      capabilities: {\n        operations: [...API_OPERATIONS],\n        projections: [...API_PROJECTIONS],\n      },\n      notProvided: [...NOT_PROVIDED],\n    };\n  }\n}\n","import { DomainError } from '../../domain-error.js';\nimport type { AccountNumber } from '../../substrate/account-number.js';\n\nexport interface AccountRange {\n  readonly from: string;\n  readonly to: string;\n}\n\n/**\n * The conditions a rule may be keyed on. **Closed**, and the two that are absent are absent for\n * stated reasons (`docs/proposals/constraint-vocabulary.md`): `smallBusiness` is time-segmented and\n * would need a per-posting-date evaluation for one rule that only catches hand-postings, and an\n * amount condition would restate a threshold that already has an owner in the depreciation module —\n * a second source of truth for a number is worse than no rule.\n */\nexport const CONDITION_KEYS = ['legalForm', 'taxationMethod'] as const;\n\nexport type ConditionKey = (typeof CONDITION_KEYS)[number];\n\nexport type AppliesWhen = { readonly [K in ConditionKey]?: readonly string[] };\n\nexport interface ConstraintContext {\n  readonly legalForm: string | null;\n  readonly taxationMethod: string | null;\n}\n\nexport const EMPTY_CONSTRAINT_CONTEXT: ConstraintContext = { legalForm: null, taxationMethod: null };\n\nexport interface AccountCombinationRuleData {\n  readonly whenAccountIn: AccountRange;\n  readonly requireAccountIn?: AccountRange;\n  readonly forbidAccountIn?: AccountRange;\n  readonly appliesWhen?: AppliesWhen;\n  readonly note?: string;\n}\n\nexport interface AccountUsageRuleData {\n  readonly forbidAccountIn: AccountRange;\n  readonly appliesWhen?: AppliesWhen;\n  readonly note?: string;\n}\n\ninterface Rule {\n  readonly when: AccountRange;\n  readonly require: AccountRange | null;\n  readonly forbid: AccountRange | null;\n  readonly appliesWhen: AppliesWhen | null;\n}\n\ninterface UsageRule {\n  readonly forbid: AccountRange;\n  readonly appliesWhen: AppliesWhen | null;\n}\n\nfunction inRange(account: string, range: AccountRange): boolean {\n  // Unicode code points, inclusive, exactly like the dimension rule — account numbers are strings\n  // in this format and comparing them any other way would make \"0100\" and \"100\" disagree by\n  // jurisdiction.\n  return account >= range.from && account <= range.to;\n}\n\n/**\n * A condition nobody can read is a condition nobody applies, so an unknown key is refused here\n * rather than dropped. `E_PACK_INCOHERENT` because that is what it is: the modules resolve, the\n * bundle asks for a condition that does not exist — the same answer an unknown tax mechanism and an\n * unknown account subtype get.\n */\nfunction parseConditions(value: AppliesWhen | undefined): AppliesWhen | null {\n  if (value === undefined || value === null) return null;\n\n  const entries = Object.entries(value);\n  if (entries.length === 0) {\n    throw new DomainError('E_PACK_INCOHERENT', 'appliesWhen must name at least one condition', {\n      known: [...CONDITION_KEYS],\n    });\n  }\n\n  const out: Record<string, string[]> = {};\n  for (const [key, allowed] of entries) {\n    if (!(CONDITION_KEYS as readonly string[]).includes(key)) {\n      throw new DomainError('E_PACK_INCOHERENT', `Unknown appliesWhen condition: ${key}`, {\n        condition: key,\n        known: [...CONDITION_KEYS],\n      });\n    }\n    const values = (Array.isArray(allowed) ? allowed : []).filter(\n      (one): one is string => typeof one === 'string' && one !== '',\n    );\n    if (values.length === 0) {\n      throw new DomainError('E_PACK_INCOHERENT', `appliesWhen.${key} names no value`, { condition: key });\n    }\n    out[key] = values;\n  }\n  return out as AppliesWhen;\n}\n\n/**\n * Every named condition must hold; within one condition, any listed value does.\n *\n * **An unknown fact means the rule does not apply**, and that is a decision rather than a fallback.\n * A tenant that never called `setEntityProfile` has no legal form, and a rule keyed on one cannot be\n * evaluated for it — refusing the posting would punish a tenant for not having configured\n * something, and applying the rule anyway would enforce a rule whose precondition is unknown to be\n * true. The library reports the rules in force through `tenantConfiguration`, so a caller can see\n * that a conditional rule is dormant rather than having to infer it.\n */\nfunction applies(conditions: AppliesWhen | null, context: ConstraintContext): boolean {\n  if (conditions === null) return true;\n  for (const [key, allowed] of Object.entries(conditions)) {\n    const actual = context[key as ConditionKey];\n    if (typeof actual !== 'string' || !(allowed ?? []).includes(actual)) return false;\n  }\n  return true;\n}\n\n/**\n * The constraint socket's account-facing predicates (F-CORE-042, F-CORE-047).\n *\n * **Why a second predicate mattered more than the rule it carries.** The constraint kind — the one\n * of the three policy kinds that exists to let a jurisdiction say *no* — could express exactly one\n * thought: *this account may not be posted without that dimension*. Every other prohibition a\n * jurisdiction has had to go somewhere else or nowhere, and `docs/gobd-conformance.md` §14 item 6\n * has said so since the socket was built: the shape is settled, the vocabulary is not. A socket\n * with one predicate is not obviously a socket; it might be a feature with a data file. The second\n * one is what makes the first a vocabulary.\n *\n * **Three words now.**\n * - `accountCombinationRules` — an entry that touches an account in `whenAccountIn` must also touch\n *   one in `requireAccountIn`, or must not touch one in `forbidAccountIn`. Exactly one of the two\n *   per rule; a rule that said both would be two rules wearing one name.\n * - `accountUsageRules` — an entry must not touch an account in `forbidAccountIn` **at all**. Not a\n *   combination and deliberately not expressed as one: see below.\n * - `appliesWhen` — either kind of rule may be conditioned on a **closed** set of tenant facts\n *   (`legalForm`, `taxationMethod`). Closed on purpose: the moment conditions become an expression\n *   language, a pack carries logic, and the whole point of the pack/substrate split is gone.\n *\n * **Why \"the entry\", not \"the other side\".** The named case is a granted discount that has to carry\n * its tax correction (the app-obligation list calls it A-13), and there both lines sit on the\n * *same* side — the discount is a debit and so is the VAT correction, with the receivable on the\n * credit. A predicate about sides would have missed the case it was built for. \"Somewhere in the\n * same entry\" is also the weaker claim, and the weaker claim is the one a pack can reason about\n * without knowing how an application splits its lines.\n *\n * **Why usage rules are their own word and not `forbidAccountIn: 0000–9999`.** That trick was the\n * obvious way to say \"this account may not be used\" with the vocabulary that already existed, and\n * it is wrong twice. It reads as a range, so the next author has to work out that the range is\n * meant to cover everything; and account numbers compare by **code point**, so `0000`–`9999`\n * silently fails to cover a chart whose numbers start with a letter and covers a six-digit chart\n * only by accident. A prohibition whose correctness depends on how a foreign chart happens to\n * number its accounts is not a prohibition.\n *\n * **What all of this deliberately cannot do.** It sees one entry. It cannot say \"within ten days\",\n * cannot reach across entries, and cannot require that a *settlement* be accompanied by anything —\n * `settle` records an allocation and posts nothing, so there is no entry there to constrain. A-13\n * is reached through the posting the application makes for the discount, which is where the books\n * actually change; the settlement itself stays unconstrained and `docs/gobd-conformance.md` still\n * says so.\n */\nexport class AccountCombinationRegistry {\n  private constructor(\n    private readonly rules: readonly Rule[],\n    private readonly usageRules: readonly UsageRule[],\n  ) {}\n\n  static empty(): AccountCombinationRegistry {\n    return new AccountCombinationRegistry([], []);\n  }\n\n  static fromData(\n    rules: readonly AccountCombinationRuleData[],\n    usageRules: readonly AccountUsageRuleData[] = [],\n  ): AccountCombinationRegistry {\n    return new AccountCombinationRegistry(\n      rules.map((rule) => ({\n        when: rule.whenAccountIn,\n        require: rule.requireAccountIn ?? null,\n        forbid: rule.forbidAccountIn ?? null,\n        appliesWhen: parseConditions(rule.appliesWhen),\n      })),\n      usageRules.map((rule) => ({\n        forbid: rule.forbidAccountIn,\n        appliesWhen: parseConditions(rule.appliesWhen),\n      })),\n    );\n  }\n\n  /** What is in force, for `tenantConfiguration` — the same reason the dimension rules are readable. */\n  rulesInForce(): AccountCombinationRuleData[] {\n    return this.rules.map((rule) => ({\n      whenAccountIn: { ...rule.when },\n      ...(rule.require === null ? {} : { requireAccountIn: { ...rule.require } }),\n      ...(rule.forbid === null ? {} : { forbidAccountIn: { ...rule.forbid } }),\n      ...(rule.appliesWhen === null ? {} : { appliesWhen: rule.appliesWhen }),\n    }));\n  }\n\n  usageRulesInForce(): AccountUsageRuleData[] {\n    return this.usageRules.map((rule) => ({\n      forbidAccountIn: { ...rule.forbid },\n      ...(rule.appliesWhen === null ? {} : { appliesWhen: rule.appliesWhen }),\n    }));\n  }\n\n  /**\n   * Checked over the whole entry, once, after the lines resolve — a per-line hook could not see the\n   * combination, which is the entire subject.\n   */\n  validateEntry(\n    accounts: readonly AccountNumber[],\n    context: ConstraintContext = EMPTY_CONSTRAINT_CONTEXT,\n  ): void {\n    const numbers = accounts.map((account) => account.value);\n\n    for (const rule of this.usageRules) {\n      if (!applies(rule.appliesWhen, context)) continue;\n      const offender = numbers.find((number) => inRange(number, rule.forbid));\n      if (offender !== undefined) {\n        throw new DomainError(\n          'E_ACCOUNT_USE_FORBIDDEN',\n          `Account ${offender} must not be posted to by this tenant`,\n          {\n            account: offender,\n            forbiddenFrom: rule.forbid.from,\n            forbiddenTo: rule.forbid.to,\n            appliesWhen: rule.appliesWhen,\n          },\n        );\n      }\n    }\n\n    for (const rule of this.rules) {\n      if (!applies(rule.appliesWhen, context)) continue;\n\n      const trigger = numbers.find((number) => inRange(number, rule.when));\n      if (trigger === undefined) continue;\n\n      if (rule.require !== null) {\n        const satisfied = numbers.some((number) => number !== trigger && inRange(number, rule.require!));\n        if (!satisfied) {\n          throw new DomainError(\n            'E_COMBINATION_REQUIRED',\n            `Account ${trigger} requires the entry to also touch an account between ${rule.require.from} and ${rule.require.to}`,\n            { account: trigger, requiredFrom: rule.require.from, requiredTo: rule.require.to },\n          );\n        }\n      }\n\n      if (rule.forbid !== null) {\n        const offender = numbers.find((number) => number !== trigger && inRange(number, rule.forbid!));\n        if (offender !== undefined) {\n          throw new DomainError(\n            'E_COMBINATION_FORBIDDEN',\n            `Account ${trigger} must not appear in one entry with ${offender}`,\n            { account: trigger, forbidden: offender, forbiddenFrom: rule.forbid.from, forbiddenTo: rule.forbid.to },\n          );\n        }\n      }\n    }\n  }\n}\n","import { AccountCombinationRegistry } from '../constraint/account-combination-registry.js';\nimport type { DimensionRegistry } from '../constraint/dimension-registry.js';\nimport type { MappingRegistry } from './mapping/mapping-registry.js';\n\n/**\n * What a tenant is configured as (F-CORE-035) — the read side of the four things\n * `summae_tenants.config` holds.\n *\n * Since SPEC-015 the library stores a tenant's configuration: the tax profile, the dimension master\n * data, the allocation scheme and the imported mappings. Exactly one of the four was reported back\n * — the tax profile, through `systemDescription` — and the other three could be written and never\n * read.\n *\n * The reason that is worse than an ordinary gap is the seed rule that came with the same release.\n * Before it, an embedding passed its cost centres in on every open, so *its* copy was the truth by\n * construction. Now the stored record wins and what the caller passes is ignored from the second\n * open on: summae's copy is the truth, the embedding's is a guess, and nothing let it check. A\n * screen offering a cost-centre field had no way to ask which values the engine would accept except\n * to post and read `E_DIMENSION_INVALID`.\n *\n * **It reports what is in force, not what is stored**, and where the two differ the difference is\n * the point:\n * - `dimensionRules` and `accountCombinationRules` are the *pack's* — which accounts may not be\n *   posted without which dimension, and which may not (or must) meet in one entry.\n *   They are never stored (they come back from the pack on every open) and an embedding cannot\n *   derive them, so a form cannot know which field it must not leave empty.\n * - `mappings` lists the pack's mappings *and* the imported ones. The record holds only the\n *   imports, so mirroring it would answer \"none\" for a `de` tenant whose `balanceSheet`,\n *   `incomeStatement` and `cashBasisReport` all work — the opposite of useful.\n *\n * Identity — id, name, base currency, pack — is deliberately not repeated here: that is\n * `systemDescription`'s block and it already reports all four. This projection answers the other\n * question, what the tenant was *set up* as.\n *\n * Deterministic: every list comes back sorted from the registry that owns it.\n *\n * The SAME shape lives in the PHP TenantConfigurationProjection.\n */\nexport class TenantConfigurationProjection {\n  constructor(\n    private readonly taxProfile: Record<string, unknown>,\n    private readonly dimensions: DimensionRegistry,\n    /** Raw, as `setAllocationScheme` accepts it. */\n    private readonly allocationScheme: Record<string, unknown> | null,\n    private readonly mappings: MappingRegistry,\n    /**\n     * Which appropriation targets the pack offers. Same reason as `dimensionRules`: it is the\n     * *pack's* answer, an embedding cannot derive it, and without it a screen offering \"carry\n     * forward / distribute\" would have to find out by provoking E_APPROPRIATION_UNSUPPORTED.\n     * Empty means the pack supports no appropriation at all.\n     */\n    private readonly appropriationTargets: string[],\n    /**\n     * What the entity IS, and what it could be. Same reason again: which legal forms exist is the\n     * *pack's* answer, and the tenant's own form is stored library state an embedding cannot derive\n     * — a screen offering \"Rechtsform\" would otherwise have to carry its own list and hope the two\n     * agree. `entityProfile` is null until `setEntityProfile` has been called; `legalForms` is empty\n     * for a pack that ships no catalogue.\n     */\n    private readonly entityProfile: { legalForm: string; sizeClass: string | null } | null,\n    private readonly legalForms: string[],\n    private readonly sizeClasses: string[],\n    /** The constraint socket's second plug (F-CORE-042) — appended for the same reason it is last on `Tenant`. */\n    private readonly combinations: AccountCombinationRegistry = AccountCombinationRegistry.empty(),\n  ) {}\n\n  compute(_params: Record<string, unknown>): Record<string, unknown> {\n    const masterData = this.dimensions.toData();\n\n    return {\n      taxProfile: this.taxProfile,\n      dimensionTypes: masterData.types,\n      dimensionValues: masterData.values,\n      dimensionRules: this.dimensions.rulesData(),\n      // The socket's second predicate (F-CORE-042), reported for the same reason as the first: an\n      // embedding that offers a booking screen has to know which combinations will be refused.\n      accountCombinationRules: this.combinations.rulesInForce(),\n      // The socket's third word (F-CORE-047). Reported even when conditional and currently\n      // DORMANT — a caller has to be able to see that a rule exists and does not apply yet,\n      // because the alternative is inferring it from postings that go through.\n      accountUsageRules: this.combinations.usageRulesInForce(),\n      allocationScheme: this.allocationScheme,\n      mappings: this.mappings.summaries(),\n      appropriationTargets: [...this.appropriationTargets],\n      entityProfile: this.entityProfile,\n      legalForms: [...this.legalForms],\n      sizeClasses: [...this.sizeClasses],\n    };\n  }\n}\n","import type { TenantRecordData, TenantRecordRepository } from '../port.js';\n\n/**\n * Keeps a tenant's configuration where the books already live (SPEC-015).\n *\n * Six operations change configuration — `setTaxProfile`, `defineDimensionType`,\n * `defineDimensionValue`, `setAllocationScheme`, `importMapping` and `setEntityProfile` — and until\n * this existed each of them changed a live object and nothing else. They audited the change durably all the same, which\n * is the part that made it a defect rather than a limitation: the trail stated something the books\n * stopped carrying at the next restart.\n *\n * The store is the one place that writes. Each `remember…` is called by the service that just\n * succeeded, never before, so a rejected operation stores nothing — the same discipline the CLI's\n * `rememberMapping` had to invent for one of the five.\n */\nexport class TenantConfigStore {\n  constructor(\n    private readonly repository: TenantRecordRepository,\n    private readonly record: TenantRecordData,\n  ) {}\n\n  rememberTaxProfile(profile: Record<string, unknown>): void {\n    this.record.config.taxProfile = profile;\n    this.flush();\n  }\n\n  rememberDimensions(\n    types: Array<{ code: string }>,\n    values: Array<{ typeCode: string; code: string }>,\n  ): void {\n    this.record.config.dimensionTypes = types;\n    this.record.config.dimensionValues = values;\n    this.flush();\n  }\n\n  rememberEntityProfile(profile: { legalForm: string; sizeClass: string | null }): void {\n    this.record.config.entityProfile = profile;\n    this.flush();\n  }\n\n  rememberAllocationScheme(scheme: Record<string, unknown>): void {\n    this.record.config.allocationScheme = scheme;\n    this.flush();\n  }\n\n  /**\n   * Replace by id rather than append: importing the same id twice must update it, not leave two\n   * mappings behind that the next load would read as overlapping. (The rule comes from the CLI,\n   * which learned it the hard way; it belongs here now that the library does the storing.)\n   */\n  rememberMapping(mapping: Record<string, unknown>): void {\n    const id = typeof mapping.id === 'string' ? mapping.id : null;\n    const mappings = [...this.record.config.mappings];\n    const index = mappings.findIndex((m) => typeof m.id === 'string' && m.id === id);\n    if (index === -1) mappings.push(mapping);\n    else mappings[index] = mapping;\n    this.record.config.mappings = mappings;\n    this.flush();\n  }\n\n  /** What is stored right now — the seed written at first open, or what the operations made of it. */\n  snapshot(): TenantRecordData {\n    return JSON.parse(JSON.stringify(this.record)) as TenantRecordData;\n  }\n\n  private flush(): void {\n    this.repository.save(this.record);\n  }\n}\n\n/**\n * Opens a tenant's stored configuration, seeding it on first open.\n *\n * **The stored record wins.** What the caller passes at construction is a *seed*: it is written on\n * the first open of a tenant that has no record yet, and ignored on every open after that. The\n * alternative — the arguments win when given — sounds harmless and is the state this whole finding\n * came out of: an embedding's configuration file and the library's tables would both claim to hold\n * the truth, and the two would drift the first time an operation changed one of them.\n *\n * Living with the rule is what makes `defineDimensionType` work: an embedding that used to pass its\n * cost centres in AND declare them (and got `E_DIMENSION_INVALID` for its trouble) can now do\n * either one.\n *\n * The rule lives in the core, not in the adapters, so both languages cannot answer it differently.\n */\nexport function openTenantConfiguration(\n  repository: TenantRecordRepository,\n  seed: TenantRecordData,\n): { record: TenantRecordData; store: TenantConfigStore; seeded: boolean } {\n  const stored = repository.load();\n  if (stored !== null) {\n    return { record: stored, store: new TenantConfigStore(repository, stored), seeded: false };\n  }\n  repository.save(seed);\n  return { record: seed, store: new TenantConfigStore(repository, seed), seeded: true };\n}\n\n/** An empty configuration block — the shape every record carries, with nothing configured yet. */\nexport function emptyTenantConfig(): TenantRecordData['config'] {\n  return {\n    taxProfile: null,\n    dimensionTypes: [],\n    dimensionValues: [],\n    allocationScheme: null,\n    mappings: [],\n    entityProfile: null,\n  };\n}\n","import type { JournalRepository } from '../../port.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\n\n/**\n * Resolves the reversal back-references of an entry into journal sequence numbers.\n *\n * The journal stores them as ids (`reverses` / `reversedBy`), which is right for the data format and\n * useless on a printed sheet: a reader looking at a cash book finds the counterpart by its number,\n * not by a UUID. So the views a person reads publish numbers, and the export keeps publishing ids.\n *\n * Why the views must publish it at all: a reversal that is not shown as one leaves a reader unable to\n * tell a corrected mistake from a removed transaction, and that is a formal defect in its own right —\n * no evidence of manipulation needed. This core reverses by general reversal (same side, negated\n * amount), which makes it worse without the marker: the movement shows a negative amount on the\n * original side and nothing explaining it.\n *\n * Mechanism, not jurisdiction: every set of books needs its corrections to be traceable.\n */\nexport class ReversalIndex {\n  private constructor(private readonly sequenceById: ReadonlyMap<string, number>) {}\n\n  static of(journal: JournalRepository): ReversalIndex {\n    const sequenceById = new Map<string, number>();\n    for (const entry of journal.all()) {\n      sequenceById.set(entry.id.value, entry.sequenceNumber);\n    }\n    return new ReversalIndex(sequenceById);\n  }\n\n  /**\n   * The two fields a movement carries. Both null for an ordinary posting — present and null, never\n   * absent, so a reader can tell \"not a reversal\" from \"this view does not say\".\n   */\n  forEntry(entry: JournalEntry): { reversesEntry: number | null; reversedByEntry: number | null } {\n    const reversedBy = entry.reversedBy();\n    return {\n      reversesEntry: entry.reverses === null ? null : (this.sequenceById.get(entry.reverses.value) ?? null),\n      reversedByEntry: reversedBy === null ? null : (this.sequenceById.get(reversedBy.value) ?? null),\n    };\n  }\n}\n","/**\n * Reading projection parameters — one place that says what each declared type means.\n *\n * The types come from the parameter contract (`testing/testsuite/schema/api-parameters.json`),\n * which the dispatcher enforces before a projection ever sees the params. So the readers below\n * are NOT validation: by the time a projection runs, a declared parameter is either absent or\n * of the right type. They exist because the previous idiom — `typeof params.x === 'number' ? x\n * : <default>` at every single call site — used the type check as a silent policy decision, and\n * a wrong value became a plausible default 25 times over.\n *\n * They still do the check, for the two cases the dispatcher does not cover: a projection\n * constructed directly (tests, embedding code) and TypeScript's own narrowing, which cannot\n * know what the dispatcher already proved.\n */\n\n/**\n * The types the parameter contract knows.\n *\n * The first four describe a projection's parameters, which are scalars by nature. Operations\n * take structure as well — a voucher, a list of lines, an amount — so `object`, `array` and\n * `money` came with the operation contract (F-9). Their *inner* shape stays the operation's\n * business: this contract answers what a key may be, not what a voucher looks like.\n *\n * `money` is worth its own type rather than being an `object`, because the mistake it catches is\n * a real one: an amount passed as a JSON number was silently ignored by every operation that read\n * it with an is-object check, and the operation carried on with its default.\n */\nexport type ParameterType = 'integer' | 'string' | 'date' | 'boolean' | 'object' | 'array' | 'money';\n\n/** ISO calendar date, zoneless. Whether the date exists is `CalendarDate`'s business. */\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * A whole number. JSON has no int/float split, so 2026 and 2026.0 are the same value and both\n * pass — a rule that told them apart would be unimplementable here, because `JSON.parse` has\n * already merged them. 2026.4 does not pass. Bounded to 2^53-1, beyond which a JS number is no\n * longer an exact integer while PHP's int still is.\n */\nexport function isIntegerParam(value: unknown): value is number {\n  return typeof value === 'number' && Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;\n}\n\nexport function matchesParameterType(value: unknown, type: ParameterType): boolean {\n  switch (type) {\n    case 'integer':\n      return isIntegerParam(value);\n    case 'string':\n      return typeof value === 'string' && value !== '';\n    case 'date':\n      return typeof value === 'string' && ISO_DATE.test(value);\n    case 'boolean':\n      return typeof value === 'boolean';\n    case 'object':\n      // An empty list counts as an empty object, and the reason is the other language:\n      // `json_decode('{}', true)` and `json_decode('[]', true)` both yield `[]` in PHP, which\n      // cannot tell them apart. Accepting it here rather than rejecting it keeps the two\n      // implementations answering the same question the same way, which outranks being strict.\n      if (Array.isArray(value)) return value.length === 0;\n      return typeof value === 'object' && value !== null;\n    case 'array':\n      return Array.isArray(value);\n    case 'money':\n      return (\n        typeof value === 'object' &&\n        value !== null &&\n        !Array.isArray(value) &&\n        typeof (value as Record<string, unknown>).amount === 'string'\n      );\n  }\n}\n\n/** An integer parameter, or the projection's documented default when it is absent. */\nexport function integerOr(value: unknown, fallback: number): number {\n  return isIntegerParam(value) ? value : fallback;\n}\n\n/** An integer parameter, or `null` when it is absent (= \"not scoped to a year\"). */\nexport function integerOrNull(value: unknown): number | null {\n  return isIntegerParam(value) ? value : null;\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type { AccountRepository, JournalRepository } from '../../port.js';\nimport { ReversalIndex } from './reversal-index.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { isIntegerParam } from './parameters.js';\n\n/**\n * Cash journal — the separation of cash from non-cash transactions, and the cash-count check.\n *\n * GoBD Rz. 57 ff. asks for cash and non-cash transactions to be kept apart. In double-entry\n * that separation is already structural rather than a flag: a transaction *is* a cash\n * transaction exactly when it touches an account of subtype `cash`. So nothing has to be\n * marked and no field has to be added — what was missing is the view that presents the\n * separation, which is the form an auditor asks for (the cash account's sheet *is* the\n * Kassenbuch).\n *\n * The second half is the part that finds real defects: **a cash balance can never be\n * negative.** You cannot hold less than no cash — that is physics, not jurisdiction, which\n * is why it belongs in the substrate and not in a pack. A cash account that goes below zero\n * at any point means the books do not describe what was in the drawer, and it is one of the\n * first things a tax auditor looks for. The running balance is therefore checked at every\n * movement, not only at the end: a day that dips negative and recovers is exactly the case\n * a closing balance hides.\n *\n * Reports, never blocks. Whether a negative balance stops a workflow is the embedding\n * application's decision; the library supplies the finding.\n */\nexport class CashJournalProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    if (!isIntegerParam(params.fiscalYear)) {\n      throw new DomainError('E_INPUT_INVALID', 'cashJournal requires the parameter \"fiscalYear\"', {\n        fiscalYear: rejectedValue(params.fiscalYear),\n      });\n    }\n    const fiscalYear = params.fiscalYear;\n\n    // Ordered by account number so the result does not depend on repository order.\n    const cashAccounts = this.accounts\n      .all()\n      .filter((account) => account.subtype === 'cash')\n      .sort((a, b) => (a.number.value < b.number.value ? -1 : a.number.value > b.number.value ? 1 : 0));\n\n    const accounts: Array<Record<string, unknown>> = [];\n    const negativeBalances: Array<Record<string, unknown>> = [];\n    // Built once for the whole run, not per movement: the sheet has to show a reversal AS a\n    // reversal, and the journal only knows the counterpart by id.\n    const reversals = ReversalIndex.of(this.journal);\n\n    for (const account of cashAccounts) {\n      // Cash is balance-carrying: last year's drawer is this year's opening.\n      let opening = Money.zero(this.baseCurrency);\n      for (const entry of this.journal.all()) {\n        if (entry.periodRef.fiscalYear >= fiscalYear) continue;\n        for (const line of entry.lines()) {\n          if (!line.accountId.equals(account.id)) continue;\n          opening = line.side === 'debit' ? opening.add(line.money) : opening.subtract(line.money);\n        }\n      }\n\n      let running = opening;\n      const movements: Array<Record<string, unknown>> = [];\n      for (const entry of this.journal.forFiscalYear(fiscalYear)) {\n        for (const line of entry.lines()) {\n          if (!line.accountId.equals(account.id)) continue;\n          running = line.side === 'debit' ? running.add(line.money) : running.subtract(line.money);\n          movements.push({\n            sequenceNumber: entry.sequenceNumber,\n            entryDate: entry.entryDate.iso,\n            voucherId: entry.voucherId.value,\n            text: entry.text(),\n            side: line.side,\n            money: line.money.toJSON(),\n            runningBalance: running.amountAsString(),\n            ...reversals.forEntry(entry),\n          });\n\n          if (running.isNegative()) {\n            negativeBalances.push({\n              account: account.number.value,\n              sequenceNumber: entry.sequenceNumber,\n              entryDate: entry.entryDate.iso,\n              runningBalance: running.amountAsString(),\n            });\n          }\n        }\n      }\n\n      accounts.push({\n        account: account.number.value,\n        name: account.name,\n        openingBalance: opening.amountAsString(),\n        movements,\n        closingBalance: running.amountAsString(),\n      });\n    }\n\n    return {\n      fiscalYear,\n      accounts,\n      // Named as a finding, not as a boolean flag: an empty list is the statement \"no cash\n      // balance ever went below zero in this year\", which is what the check is for.\n      negativeBalances,\n      cashCountable: negativeBalances.length === 0,\n    };\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type { CalendarDate } from '../substrate/calendar-date.js';\nimport type { Money } from '../substrate/money.js';\nimport type { Uuid } from '../substrate/uuid.js';\nimport type { Settlement } from '../policies/expansion/settlement.js';\nimport type { OpenItemKind, OpenItemStatus } from '../substrate/types.js';\n\n/**\n * Open item (ledger-modell.md aggregate 5): arises from a posting to\n * an AR/AP account, references the origin posting + line. Invariant:\n * Σ settlements ≤ amount; partial settlements allowed.\n */\nexport class OpenItem {\n  private readonly settlementList: Settlement[] = [];\n\n  constructor(\n    readonly id: Uuid,\n    readonly kind: OpenItemKind,\n    readonly originEntryId: Uuid,\n    readonly originLineIndex: number,\n    readonly money: Money,\n    readonly voucherId: Uuid,\n    readonly openedAt: CalendarDate,\n    readonly partnerId: Uuid | null = null,\n  ) {}\n\n  /**\n   * Restore from persistence: set already-validated settlements directly\n   * (no re-check) — counterpart to PHP's `OpenItem::restore`.\n   */\n  static restore(\n    id: Uuid,\n    kind: OpenItemKind,\n    originEntryId: Uuid,\n    originLineIndex: number,\n    money: Money,\n    voucherId: Uuid,\n    openedAt: CalendarDate,\n    partnerId: Uuid | null,\n    settlements: Settlement[],\n  ): OpenItem {\n    const item = new OpenItem(id, kind, originEntryId, originLineIndex, money, voucherId, openedAt, partnerId);\n    item.settlementList.push(...settlements);\n    return item;\n  }\n\n  settlements(): Settlement[] {\n    return this.settlementList;\n  }\n\n  remaining(): Money {\n    return this.remainingAt(null);\n  }\n\n  /** Remaining amount as of a cutoff date (null = today/all). */\n  remainingAt(asOf: CalendarDate | null): Money {\n    let remaining = this.money;\n    for (const settlement of this.settlementList) {\n      if (asOf !== null && settlement.settledAt.isAfter(asOf)) continue;\n      remaining = remaining.subtract(settlement.money);\n    }\n    return remaining;\n  }\n\n  status(): OpenItemStatus {\n    return this.statusAt(null);\n  }\n\n  statusAt(asOf: CalendarDate | null): OpenItemStatus {\n    const remaining = this.remainingAt(asOf);\n    if (remaining.isZero()) {\n      // A cancelled item is closed but was never paid (IMPL-008). Reporting it as `settled` would\n      // read as \"the money came in\", which is the opposite of what a reversal means.\n      return this.settlementsUpTo(asOf).some((settlement) => settlement.cause === 'cancellation')\n        ? 'cancelled'\n        : 'settled';\n    }\n    return remaining.equals(this.money) ? 'open' : 'partially_settled';\n  }\n\n  private settlementsUpTo(asOf: CalendarDate | null): Settlement[] {\n    if (asOf === null) return this.settlementList;\n    return this.settlementList.filter((settlement) => !settlement.settledAt.isAfter(asOf));\n  }\n\n  settle(settlement: Settlement): void {\n    if (settlement.money.compareTo(this.remaining()) > 0) {\n      throw new DomainError(\n        'E_SETTLEMENT_EXCEEDS_ITEM',\n        `Allocation ${settlement.money.amountAsString()} exceeds remaining amount ${this.remaining().amountAsString()} of item ${this.id.value}`,\n        {\n          openItemId: this.id.value,\n          remaining: this.remaining().amountAsString(),\n          allocated: settlement.money.amountAsString(),\n        },\n      );\n    }\n    this.settlementList.push(settlement);\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      kind: this.kind,\n      originEntryId: this.originEntryId.value,\n      originLineIndex: this.originLineIndex,\n      money: this.money.toJSON(),\n      partnerId: this.partnerId?.value ?? null,\n      remaining: this.remaining().toJSON(),\n      status: this.status(),\n      settlements: this.settlementList.map((settlement) => settlement.toJSON()),\n    };\n  }\n}\n","import type { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { Money } from '../../substrate/money.js';\nimport type { Uuid } from '../../substrate/uuid.js';\nimport type { SettlementCause, SettlementDifferenceKind } from '../../substrate/types.js';\n\n/**\n * Single settlement of an open item. `money` is the settled\n * open-item amount INCLUDING the difference (api.md G2).\n *\n * `cause` says what closed the item, `difference` says by how much the amounts differed — the two\n * are independent: a payment can carry a discount, a cancellation never does.\n */\nexport class Settlement {\n  constructor(\n    readonly entryId: Uuid,\n    readonly money: Money,\n    readonly settledAt: CalendarDate,\n    readonly differenceMoney: Money | null = null,\n    readonly differenceKind: SettlementDifferenceKind | null = null,\n    readonly cause: SettlementCause = 'payment',\n  ) {}\n\n  toJSON(): Record<string, unknown> {\n    return {\n      entryId: this.entryId.value,\n      money: this.money.toJSON(),\n      settledAt: this.settledAt.iso,\n      cause: this.cause,\n      difference:\n        this.differenceMoney === null\n          ? null\n          : { money: this.differenceMoney.toJSON(), kind: this.differenceKind },\n    };\n  }\n}\n","import type { JournalEntry } from './journal-entry.js';\n\n/**\n * Result of `post`: the posting plus the open items created along the way\n * (AR/AP automation — follows with the open-items slice, hence empty for now).\n */\nexport class PostResult {\n  constructor(\n    readonly entry: JournalEntry,\n    readonly openItemsCreated: unknown[],\n  ) {}\n}\n","import { DomainError } from '../../domain-error.js';\nimport type { AccountNumber } from '../../substrate/account-number.js';\nimport type { DimensionValue } from '../../substrate/dimension-value.js';\n\ninterface DimensionRule {\n  readonly from: string;\n  readonly to: string;\n  readonly required: string;\n}\n\nexport interface DimensionTypeData {\n  readonly code: string;\n}\nexport interface DimensionValueData {\n  readonly typeCode: string;\n  readonly code: string;\n}\nexport interface DimensionRuleData {\n  readonly accountRange: { from: string; to: string };\n  readonly requiredDimension: string;\n}\n\n/**\n * Dimension validation: mechanism in the core, contents as rule module data\n * (ledger-modell.md). Types/values are master data; mandatory dimensions come\n * from `ruleModules.dimensionRules`.\n */\nexport class DimensionRegistry {\n  private constructor(\n    private readonly types: Set<string>,\n    private readonly values: Set<string>,\n    private readonly rules: readonly DimensionRule[],\n  ) {}\n\n  static empty(): DimensionRegistry {\n    return new DimensionRegistry(new Set(), new Set(), []);\n  }\n\n  static fromData(\n    dimensionTypes: DimensionTypeData[],\n    dimensionValues: DimensionValueData[],\n    dimensionRules: DimensionRuleData[],\n  ): DimensionRegistry {\n    const types = new Set(dimensionTypes.map((t) => t.code));\n    const values = new Set(dimensionValues.map((v) => `${v.typeCode}:${v.code}`));\n    const rules = dimensionRules.map((r) => ({\n      from: r.accountRange.from,\n      to: r.accountRange.to,\n      required: r.requiredDimension,\n    }));\n    return new DimensionRegistry(types, values, rules);\n  }\n\n  /**\n   * The mandatory-dimension rules in force, in the shape they arrived in.\n   *\n   * Not part of `toData()` on purpose — that method answers what gets *stored*, and the rules are\n   * the pack's, not the tenant's. This one answers what is *in force*, which is a different\n   * question with a different reader: an embedding that offers a cost-centre field has to know on\n   * which accounts leaving it empty will be refused, and until `tenantConfiguration` existed the\n   * only way to find out was to post and read `E_DIMENSION_INVALID`.\n   */\n  rulesData(): DimensionRuleData[] {\n    return this.rules.map((rule) => ({\n      accountRange: { from: rule.from, to: rule.to },\n      requiredDimension: rule.required,\n    }));\n  }\n\n  /**\n   * The same rules with different master data (SPEC-015).\n   *\n   * Reopening a tenant means combining two sources that are not the same kind of thing: the types\n   * and values are the tenant's, and come back from its record; the rules — which accounts may not\n   * be posted without a dimension — are the pack's, and come back from the pack. This is what keeps\n   * them apart without asking the adapter to know the difference.\n   */\n  withMasterData(\n    dimensionTypes: DimensionTypeData[],\n    dimensionValues: DimensionValueData[],\n  ): DimensionRegistry {\n    return new DimensionRegistry(\n      new Set(dimensionTypes.map((type) => type.code)),\n      new Set(dimensionValues.map((value) => `${value.typeCode}:${value.code}`)),\n      this.rules,\n    );\n  }\n\n  /**\n   * The registry as the data it was built from (SPEC-015) — `fromData(toData(r))` is `r`.\n   *\n   * Sorted, because this is what gets stored: two runs that declared the same types in a different\n   * order must produce the same stored bytes, or the cross-test would compare a set against an\n   * ordering accident. Rules are not included: which accounts require a dimension is the pack's\n   * answer, not the tenant's, and it comes back from the pack on every open.\n   */\n  toData(): { types: Array<{ code: string }>; values: Array<{ typeCode: string; code: string }> } {\n    const values = [...this.values].sort().map((entry) => {\n      const separator = entry.indexOf(':');\n      return { typeCode: entry.slice(0, separator), code: entry.slice(separator + 1) };\n    });\n    return { types: [...this.types].sort().map((code) => ({ code })), values };\n  }\n\n  /**\n   * Declares a dimension type (a cost centre axis, a project axis, …).\n   *\n   * Dimension types and values are the tenant's own master data, like accounts — not the pack's,\n   * because \"Materialstelle\" is a fact about one company and not about German law. They were\n   * declarable only through the in-memory construction path, which meant a tenant built FROM A PACK\n   * had an empty registry and every posting carrying a cost centre was rejected: cost accounting was\n   * unreachable on `de`, `us` and `default` alike, and nothing in the packs said so.\n   */\n  defineType(code: string): void {\n    if (code === '') {\n      throw new DomainError('E_DIMENSION_INVALID', 'A dimension type needs a code', { type: code });\n    }\n\n    if (this.types.has(code)) {\n      throw new DomainError('E_DIMENSION_INVALID', `Dimension type \"${code}\" is already defined`, { type: code });\n    }\n\n    this.types.add(code);\n  }\n\n  /**\n   * Declares a value of an existing type. Refused for an unknown type rather than creating it on the\n   * way: a typo in the type would otherwise open a second, near-identical axis in silence.\n   */\n  defineValue(typeCode: string, code: string): void {\n    if (!this.types.has(typeCode)) {\n      throw new DomainError('E_DIMENSION_INVALID', `Unknown dimension type \"${typeCode}\"`, { type: typeCode });\n    }\n\n    if (code === '') {\n      throw new DomainError('E_DIMENSION_INVALID', 'A dimension value needs a code', { type: typeCode });\n    }\n\n    if (this.values.has(`${typeCode}:${code}`)) {\n      throw new DomainError(\n        'E_DIMENSION_INVALID',\n        `Dimension value \"${code}\" of type \"${typeCode}\" is already defined`,\n        { type: typeCode, code },\n      );\n    }\n\n    this.values.add(`${typeCode}:${code}`);\n  }\n\n  validateLine(account: AccountNumber, dimensions: DimensionValue[]): void {\n    for (const dimension of dimensions) {\n      if (!this.types.has(dimension.type)) {\n        throw new DomainError('E_DIMENSION_INVALID', `Unknown dimension type \"${dimension.type}\"`, {\n          type: dimension.type,\n        });\n      }\n      if (!this.values.has(`${dimension.type}:${dimension.code}`)) {\n        throw new DomainError(\n          'E_DIMENSION_INVALID',\n          `Unknown dimension value \"${dimension.code}\" for type \"${dimension.type}\"`,\n          { type: dimension.type, code: dimension.code },\n        );\n      }\n    }\n\n    for (const rule of this.rules) {\n      const inRange = account.value >= rule.from && account.value <= rule.to;\n      if (!inRange) continue;\n      if (dimensions.some((d) => d.type === rule.required)) continue;\n      throw new DomainError(\n        'E_DIMENSION_INVALID',\n        `Mandatory dimension \"${rule.required}\" missing on account ${account.value}`,\n        { account: account.value, required: rule.required },\n      );\n    }\n  }\n}\n","import Big from 'big.js';\nimport { DomainError } from '../../../domain-error.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { Money } from '../../../substrate/money.js';\n\nexport interface BaseSplit {\n  /** What the tax is charged on, and what a reporting key receives. */\n  readonly base: Money;\n  /** The tax itself, rounded by the shared rule (half-up away from zero). */\n  readonly tax: Money;\n}\n\n/**\n * How a taxable amount splits into base and tax — the **second seam** of the tax expansion\n * (F-TAX-010).\n *\n * **Why this is its own socket and not a fifth mechanism.** The mechanism seam covers *line\n * assembly*: it receives an already-computed, already-rounded tax amount and decides which accounts\n * and reporting keys it lands on. `core/src/CLAUDE.md` has said since 2026-08-16 that the variance\n * which actually differs between jurisdictions sits **before** that and had no socket at all —\n * `base × rate / 100` was written twice inside `TaxService`, once per rounding granularity, and a\n * pack could not reach it. Every tax system that quotes prices with the tax already inside was\n * therefore inexpressible, and that is most of them.\n *\n * **The two kinds, and what separates them.**\n *\n * - `net` — the amount handed in is the base. `tax = amount × rate / 100`. What summae has always\n *   done, and the default when a tax code says nothing, so no shipped pack changes behaviour.\n * - `inclusive` — the amount handed in is the **gross**, tax already inside.\n *   `tax = amount × rate / (100 + rate)`, and the base is what remains. Rounding happens once, on\n *   the tax, and the base is derived by subtraction — the other order lets base and tax fail to add\n *   up to the amount the caller actually posted, which is the one property an inclusive régime\n *   cannot give up: the gross is a fact, the split is arithmetic.\n *\n * **What this seam deliberately does not reach**, because a socket's limits are part of its\n * contract. A *compound* base (Canadian PST computed on a GST-inclusive amount) needs the result of\n * another code and therefore an ordering between codes, which this function cannot see — it is\n * handed one amount and one rate. Tax at payment time (withholding, split payment) is not a base\n * question at all but a timing one, and margin schemes need the purchase price of the thing sold,\n * which is not in the posting. Those stay named and unbuilt; the repertoire question\n * (`core/src/CLAUDE.md`, \"what would reopen it\") is *not* settled by this change, because a\n * mechanism still is not describable as pure data.\n */\nexport type TaxBaseKind = 'net' | 'inclusive';\n\nconst KINDS: readonly TaxBaseKind[] = ['net', 'inclusive'];\n\nexport function isTaxBaseKind(value: unknown): value is TaxBaseKind {\n  return typeof value === 'string' && (KINDS as readonly string[]).includes(value);\n}\n\n/** The declared repertoire, for the contract test and for `tenantConfiguration`. */\nexport function allTaxBaseKinds(): readonly TaxBaseKind[] {\n  return KINDS;\n}\n\nexport function splitByBase(kind: TaxBaseKind, amount: Money, rate: string, currency: Currency): BaseSplit {\n  if (kind === 'net') {\n    return {\n      base: amount,\n      tax: Money.fromCalculation(new Big(amount.amountAsString()).times(rate).div(100), currency),\n    };\n  }\n\n  const divisor = new Big(100).plus(rate);\n  if (divisor.eq(0)) {\n    // A rate of −100 % would make the gross zero for any base, so no split exists. Refused rather\n    // than divided: a NaN reaching Money would surface far from the pack that caused it.\n    throw new DomainError('E_TAXCODE_INVALID', 'an inclusive tax base needs a rate other than -100', { rate });\n  }\n\n  const tax = Money.fromCalculation(new Big(amount.amountAsString()).times(rate).div(divisor), currency);\n  return { base: amount.subtract(tax), tax };\n}\n","import { DomainError } from '../../../domain-error.js';\nimport type { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { TaxCodeVersion } from './tax-code-version.js';\n\n/**\n * Tax code (tax-modell.md aggregate 1): bundled tax case as a list of rule\n * versions. Version selection follows the voucher date.\n */\nexport class TaxCode {\n  constructor(\n    readonly code: string,\n    readonly versions: TaxCodeVersion[],\n    readonly datevBu: string | null = null,\n  ) {}\n\n  versionFor(date: CalendarDate): TaxCodeVersion {\n    for (const version of this.versions) {\n      if (version.coversDate(date)) return version;\n    }\n    throw new DomainError(\n      'E_TAXCODE_NO_VALID_VERSION',\n      `tax code ${this.code} has no rule version valid for ${date.iso}`,\n      { code: this.code, date: date.iso },\n    );\n  }\n}\n","import type { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { TaxBaseKind } from './tax-bases.js';\n\n/**\n * Rule version of a tax code with validity period. Contents are\n * rule-module data — code cites no statute. mechanism `reverse_charge`:\n * VAT and input-tax line at once; `intra_community_supply`: tax-free.\n */\nexport class TaxCodeVersion {\n  constructor(\n    readonly validFrom: CalendarDate,\n    readonly validTo: CalendarDate | null,\n    readonly rate: string,\n    readonly taxAccount: string,\n    readonly reportingKey: string | null,\n    readonly mechanism: string = 'standard',\n    readonly inputTaxAccount: string | null = null,\n    readonly inputReportingKey: string | null = null,\n    readonly baseReportingKey: string | null = null,\n    /**\n     * How the amount handed in splits into base and tax (F-TAX-010) — the expansion's second seam.\n     *\n     * `net` is the default and what every shipped pack means today: the amount IS the base. A pack\n     * that quotes prices with the tax already inside says `inclusive`, and nothing else about the\n     * code changes — same account, same reporting key, same mechanism. See `tax-bases.ts` for why\n     * this is a socket of its own rather than a fifth mechanism.\n     */\n    readonly taxBase: TaxBaseKind = 'net',\n  ) {}\n\n  coversDate(date: CalendarDate): boolean {\n    if (date.isBefore(this.validFrom)) return false;\n    return this.validTo === null || !date.isAfter(this.validTo);\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport { isTaxBaseKind, type TaxBaseKind } from './tax-bases.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport { TaxCode } from './tax-code.js';\nimport { TaxCodeVersion } from './tax-code-version.js';\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/** Loaded, validated form of the tax-code rule-module data. */\nfunction parseTaxBase(value: unknown): TaxBaseKind {\n  if (value === undefined || value === null) return 'net';\n  if (isTaxBaseKind(value)) return value;\n  throw new DomainError('E_TAXCODE_INVALID', `unknown taxBase \"${String(value)}\"`, { taxBase: String(value) });\n}\n\nexport class TaxCodeRegistry {\n  private constructor(private readonly codes: ReadonlyMap<string, TaxCode>) {}\n\n  static empty(): TaxCodeRegistry {\n    return new TaxCodeRegistry(new Map());\n  }\n\n  static fromData(data: Array<Record<string, unknown>>): TaxCodeRegistry {\n    const codes = new Map<string, TaxCode>();\n\n    for (const codeData of data) {\n      const code = asString(codeData.code) ?? '';\n      const rawVersions = Array.isArray(codeData.versions) ? codeData.versions : [];\n      const versions: TaxCodeVersion[] = [];\n\n      for (const versionData of rawVersions) {\n        if (versionData === null || typeof versionData !== 'object') continue;\n        const v = versionData as Record<string, unknown>;\n        versions.push(\n          new TaxCodeVersion(\n            CalendarDate.of(asString(v.validFrom) ?? ''),\n            typeof v.validTo === 'string' ? CalendarDate.of(v.validTo) : null,\n            asString(v.rate) ?? '0',\n            asString(v.taxAccount) ?? '',\n            asString(v.reportingKey),\n            asString(v.mechanism) ?? 'standard',\n            asString(v.inputTaxAccount),\n            asString(v.inputReportingKey),\n            asString(v.baseReportingKey),\n            // Unknown values are refused rather than defaulted: a pack that misspells its base kind\n            // would otherwise silently get `net`, which is a wrong number in the books rather than a\n            // missing feature.\n            parseTaxBase(v.taxBase),\n          ),\n        );\n      }\n\n      codes.set(code, new TaxCode(code, versions, asString(codeData.datevBu)));\n    }\n\n    return new TaxCodeRegistry(codes);\n  }\n\n  allVersions(): TaxCodeVersion[] {\n    const versions: TaxCodeVersion[] = [];\n    for (const code of this.codes.values()) versions.push(...code.versions);\n    return versions;\n  }\n\n  datevBuFor(code: string): string | null {\n    return this.codes.get(code)?.datevBu ?? null;\n  }\n\n  get(code: string): TaxCode {\n    const found = this.codes.get(code);\n    if (found === undefined) {\n      throw new DomainError('E_TAXCODE_UNKNOWN', `tax code \"${code}\" is not defined`, { code });\n    }\n    return found;\n  }\n\n  versionFor(code: string, date: CalendarDate): TaxCodeVersion {\n    return this.get(code).versionFor(date);\n  }\n}\n","import { AuditRecord, type AuditChanges } from '../records/audit-record.js';\nimport type { AuditTrail } from '../port.js';\nimport type { Clock } from '../substrate/clock.js';\nimport type { IdGenerator } from '../substrate/id-generator.js';\nimport type { Uuid } from '../substrate/uuid.js';\n\n/**\n * Writes the audit trail for the ledger services.\n *\n * Extracted because `Ledger`, `SettlementService` and `ChartAdminService` all need the same three\n * things — who acted, what time it is, and the record itself — and sharing them through a base\n * class would tie services together that otherwise have nothing in common.\n */\nexport class AuditWriter {\n  constructor(\n    private readonly audit: AuditTrail,\n    private readonly clock: Clock,\n    private readonly ids: IdGenerator,\n  ) {}\n\n  /** The actor of an operation; absent or empty means the system itself. */\n  actorOf(input: Record<string, unknown>): string {\n    const actor = typeof input.actor === 'string' ? input.actor : null;\n    return actor !== null && actor !== '' ? actor : 'system';\n  }\n\n  now(): string {\n    return this.clock.now().toISOString();\n  }\n\n  record(\n    actor: string,\n    objectType: string,\n    objectId: Uuid,\n    action: string,\n    changes: AuditChanges = {},\n  ): void {\n    this.audit.append(new AuditRecord(this.ids.next(), this.now(), actor, objectType, objectId, action, changes));\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type { AccountRepository } from '../port.js';\nimport { Account } from '../substrate/account.js';\nimport { AccountNumber } from '../substrate/account-number.js';\nimport { CalendarDate } from '../substrate/calendar-date.js';\nimport type { IdGenerator } from '../substrate/id-generator.js';\nimport { ACCOUNT_SUBTYPES, isAccountSubtype, isAccountType } from '../substrate/types.js';\nimport type { DimensionRegistry } from '../policies/constraint/dimension-registry.js';\nimport type { Uuid } from '../substrate/uuid.js';\nimport type { AuditWriter } from './audit-writer.js';\nimport type { TenantConfigStore } from '../composition/tenant-config-store.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * Chart-of-accounts administration: creating, locking and bulk-importing accounts. Setup, not\n * bookkeeping — it touches no journal, no period and no open item, which is why it is the cleanest\n * cut out of the orchestrator.\n */\nexport class ChartAdminService {\n  constructor(\n    private readonly accounts: AccountRepository,\n    private readonly ids: IdGenerator,\n    private readonly audit: AuditWriter,\n    private readonly dimensions: DimensionRegistry | null = null,\n    // A dimension has no id of its own, so the audit record names the tenant — the same shape the tax\n    // profile and the allocation scheme use for configuration that exists once per tenant.\n    private readonly tenantId: Uuid | null = null,\n    /** Where a declared type or value is kept, so it outlives this object (SPEC-015). */\n    private readonly configStore: TenantConfigStore | null = null,\n  ) {}\n\n  /** Declares a dimension type. Master data, like an account: `costCenter`, `project`, `segment`. */\n  defineDimensionType(input: Record<string, unknown>): Record<string, unknown> {\n    const actor = this.audit.actorOf(input);\n    const code = asString(input.code) ?? '';\n\n    this.requireDimensions().defineType(code);\n\n    if (this.tenantId !== null) {\n      this.audit.record(actor, 'dimensionType', this.tenantId, 'created', { code: { from: null, to: code } });\n    }\n    this.persistDimensions();\n\n    return { code };\n  }\n\n  /** Declares a value of an existing dimension type. */\n  defineDimensionValue(input: Record<string, unknown>): Record<string, unknown> {\n    const actor = this.audit.actorOf(input);\n    const typeCode = asString(input.type) ?? '';\n    const code = asString(input.code) ?? '';\n\n    this.requireDimensions().defineValue(typeCode, code);\n\n    if (this.tenantId !== null) {\n      this.audit.record(actor, 'dimensionValue', this.tenantId, 'created', {\n        type: { from: null, to: typeCode },\n        code: { from: null, to: code },\n      });\n    }\n\n    this.persistDimensions();\n\n    return { type: typeCode, code };\n  }\n\n  /**\n   * The registry is stored whole rather than as a delta: it is a small set, and a whole-value write\n   * cannot drift from the object it describes the way an append log can.\n   */\n  private persistDimensions(): void {\n    if (this.configStore === null || this.dimensions === null) return;\n    const data = this.dimensions.toData();\n    this.configStore.rememberDimensions(data.types, data.values);\n  }\n\n  private requireDimensions(): DimensionRegistry {\n    if (this.dimensions === null) {\n      throw new DomainError('E_DIMENSION_INVALID', 'this tenant was built without a dimension registry', {\n        type: null,\n      });\n    }\n\n    return this.dimensions;\n  }\n\n  /**\n   * What an account's creation records (F-CORE-014).\n   *\n   * A creation is a change from nothing, so it is written as `from: null` rather than as an empty\n   * diff. That was already the idiom for vouchers, fiscal years, dimensions and costing runs;\n   * accounts, postings and partners recorded nothing at all, which made the published invariant\n   * (\"actor, timestamp, object and before/after values\") true of some records and not others. The\n   * identifying fields only — the account's current state is retrievable from `accounts`, and a\n   * trail that copies the object is a second source of truth, not a history.\n   */\n  private static creationDiff(account: Account): Record<string, { from: unknown; to: unknown }> {\n    const changes: Record<string, { from: unknown; to: unknown }> = {\n      number: { from: null, to: account.number.value },\n      name: { from: null, to: account.name },\n      type: { from: null, to: account.type },\n    };\n\n    if (account.subtype !== null) changes.subtype = { from: null, to: account.subtype };\n    // Only when set, like `subtype`: a window is the exception, and a trail that records two nulls\n    // on every account creation says nothing while costing every reader a line.\n    if (account.validFrom !== null) changes.validFrom = { from: null, to: account.validFrom.iso };\n    if (account.validTo !== null) changes.validTo = { from: null, to: account.validTo.iso };\n\n    return changes;\n  }\n\n  createAccount(input: Record<string, unknown>): Account {\n    const actor = this.audit.actorOf(input);\n    const account = this.buildAccount(input);\n\n    if (this.accounts.byNumber(account.number) !== null) {\n      throw new DomainError('E_ACCOUNT_NUMBER_TAKEN', `Account number ${account.number.value} is already taken`, {\n        number: account.number.value,\n      });\n    }\n\n    this.accounts.add(account);\n    this.audit.record(actor, 'account', account.id, 'created', ChartAdminService.creationDiff(account));\n    return account;\n  }\n\n  lockAccount(input: Record<string, unknown>): Account {\n    return this.setAccountStatus(input, 'locked');\n  }\n\n  /** The counterpart to `lockAccount` — see `Account.unlock` for why it is core mechanism. */\n  unlockAccount(input: Record<string, unknown>): Account {\n    return this.setAccountStatus(input, 'active');\n  }\n\n  /**\n   * Both directions in one place: the audit record is the whole point of the operation, and two\n   * copies of it would be two chances for one direction to record less than the other.\n   */\n  private setAccountStatus(input: Record<string, unknown>, target: 'locked' | 'active'): Account {\n    const actor = this.audit.actorOf(input);\n    const number = asString(input.number) ?? '';\n    const account = this.accounts.byNumber(AccountNumber.of(number));\n\n    if (account === null) {\n      throw new DomainError('E_ACCOUNT_UNKNOWN', `Account ${number} does not exist`, { number });\n    }\n\n    const before = account.status();\n    if (target === 'locked') account.lock();\n    else account.unlock();\n    this.accounts.save(account);\n    this.audit.record(actor, 'account', account.id, target === 'locked' ? 'locked' : 'unlocked', {\n      status: { from: before, to: account.status() },\n    });\n    return account;\n  }\n\n  importChartOfAccounts(input: Record<string, unknown>): number {\n    const actor = this.audit.actorOf(input);\n    const rows = input.rows;\n    if (!Array.isArray(rows) || rows.length === 0) {\n      throw new DomainError('E_COA_FORMAT_INVALID', 'Import without rows');\n    }\n\n    const accounts: Account[] = [];\n    const numbers = new Set<string>();\n\n    rows.forEach((row, index) => {\n      if (!isRecord(row)) {\n        throw new DomainError('E_COA_FORMAT_INVALID', `Row ${index} is not a structure`);\n      }\n      let account: Account;\n      try {\n        account = this.buildAccount(row);\n      } catch (error) {\n        if (error instanceof DomainError) {\n          throw new DomainError('E_COA_FORMAT_INVALID', `Row ${index} is not parsable`, { row: index });\n        }\n        throw error;\n      }\n      if (numbers.has(account.number.value) || this.accounts.byNumber(account.number) !== null) {\n        throw new DomainError('E_ACCOUNT_NUMBER_TAKEN', `Account number ${account.number.value} is already taken`, {\n          number: account.number.value,\n        });\n      }\n      numbers.add(account.number.value);\n      accounts.push(account);\n    });\n\n    for (const account of accounts) {\n      this.accounts.add(account);\n      this.audit.record(actor, 'account', account.id, 'created', ChartAdminService.creationDiff(account));\n    }\n    return accounts.length;\n  }\n\n  private buildAccount(input: Record<string, unknown>): Account {\n    const number = asString(input.number);\n    const name = asString(input.name);\n    const type = input.type;\n\n    if (number === null || number === '' || name === null || name === '' || !isAccountType(type)) {\n      throw new DomainError('E_COA_FORMAT_INVALID', 'Account needs number, name and a valid type');\n    }\n\n    const subtype = asString(input.subtype);\n    if (subtype !== null && !isAccountSubtype(subtype)) {\n      // Closed repertoire: an unknown subtype used to be stored and then read by nobody, so the\n      // account looked annotated and behaved like an unannotated one.\n      throw new DomainError('E_INPUT_INVALID', `Account ${number}: unknown subtype \"${subtype}\"`, {\n        number,\n        subtype,\n        known: [...ACCOUNT_SUBTYPES],\n      });\n    }\n    const status = input.status === 'locked' ? 'locked' : 'active';\n\n    const rawFrom = asString(input.validFrom);\n    const rawTo = asString(input.validTo);\n    const validFrom = rawFrom === null ? null : CalendarDate.of(rawFrom);\n    const validTo = rawTo === null ? null : CalendarDate.of(rawTo);\n    if (validFrom !== null && validTo !== null && validTo.isBefore(validFrom)) {\n      // A window that closes before it opens accepts no posting at all, so the account would be\n      // created dead and every later refusal would name the date rather than the cause.\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `Account ${number}: validTo ${validTo.iso} lies before validFrom ${validFrom.iso}`,\n        { number, validFrom: validFrom.iso, validTo: validTo.iso },\n      );\n    }\n\n    return new Account(\n      this.ids.next(),\n      AccountNumber.of(number),\n      name,\n      type,\n      subtype,\n      status,\n      validFrom,\n      validTo,\n    );\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type { JournalRepository } from '../port.js';\nimport { CalendarDate } from '../substrate/calendar-date.js';\nimport { InvalidValue } from '../substrate/errors.js';\nimport type { JournalEntry } from '../substrate/journal-entry.js';\nimport { Uuid } from '../substrate/uuid.js';\n\n/**\n * The two lookups every ledger service needs. They are free functions, not methods on a shared\n * base: both are stateless apart from the repository they read, so passing it in is cheaper than\n * inheritance — and it keeps `post`, `settle`, `correct` and `reverse` reporting the exact same\n * error for the exact same bad input, which is what the fixtures pin.\n */\n\n/** A posting date; anything unparsable is a period problem, not a format problem (api.md). */\nexport function parseEntryDate(entryDate: unknown): CalendarDate {\n  if (typeof entryDate !== 'string') {\n    throw new DomainError('E_PERIOD_UNKNOWN', 'entryDate missing');\n  }\n  try {\n    return CalendarDate.of(entryDate);\n  } catch (error) {\n    if (error instanceof InvalidValue) {\n      throw new DomainError('E_PERIOD_UNKNOWN', `Invalid posting date \"${entryDate}\"`);\n    }\n    throw error;\n  }\n}\n\n/** An existing journal entry by id — a malformed id is \"unknown\", never a crash. */\nexport function requireEntry(journal: JournalRepository, entryId: unknown): JournalEntry {\n  let entry: JournalEntry | null = null;\n  if (typeof entryId === 'string' && entryId !== '') {\n    try {\n      entry = journal.byId(Uuid.fromString(entryId));\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n    }\n  }\n  if (entry === null) {\n    throw new DomainError('E_ENTRY_UNKNOWN', `Posting ${typeof entryId === 'string' ? entryId : '?'} does not exist`);\n  }\n  return entry;\n}\n","import { DomainError, rejectedValue } from '../domain-error.js';\nimport type { FiscalYearRepository, JournalRepository } from '../port.js';\nimport { FiscalYear } from '../substrate/fiscal-year.js';\nimport type { IdGenerator } from '../substrate/id-generator.js';\nimport type { AuditWriter } from './audit-writer.js';\nimport { parseEntryDate } from './lookups.js';\n\n/**\n * Fiscal years and periods: creating a year, closing and reopening a period, closing the year.\n * The constraint side of the ledger — these operations write no postings, they only decide what\n * may still be posted.\n */\nexport class FiscalPeriodService {\n  constructor(\n    private readonly fiscalYears: FiscalYearRepository,\n    private readonly journal: JournalRepository,\n    private readonly ids: IdGenerator,\n    private readonly audit: AuditWriter,\n  ) {}\n\n  createFiscalYear(input: Record<string, unknown>): FiscalYear {\n    // Anything that was not a number became year 0 — a quoted `\"2027\"` from a JSON caller\n    // created a fiscal year nobody could address again: every later report for 2027 came back\n    // empty and correct-looking instead of saying the year does not exist. A fiscal year is a\n    // positive whole number; 2028.5 or -5 are caller mistakes, not values to round into shape.\n    const rawYear = input.year;\n    // Safe integer, not just integer: `1e21` passes Number.isInteger but is beyond what the\n    // PHP side can hold as an int, so it was accepted here and rejected there — same input,\n    // different answer, which is the one thing the equivalence policy does not allow.\n    if (typeof rawYear !== 'number' || !Number.isSafeInteger(rawYear) || rawYear <= 0) {\n      throw new DomainError('E_INPUT_INVALID', 'createFiscalYear requires \"year\" as a positive whole number', {\n        year: rejectedValue(rawYear),\n      });\n    }\n    const year = rawYear;\n    const start = parseEntryDate(input.start);\n    const end = parseEntryDate(input.end);\n\n    for (const existing of this.fiscalYears.all()) {\n      const overlaps = !existing.end.isBefore(start) && !existing.start.isAfter(end);\n      if (overlaps || existing.year === year) {\n        throw new DomainError(\n          'E_FISCALYEAR_OVERLAP',\n          `Fiscal year ${year} (${start.iso} to ${end.iso}) overlaps with ${existing.year}`,\n          { year, existing: existing.year },\n        );\n      }\n    }\n\n    const fiscalYear = FiscalYear.create(this.ids.next(), year, start, end);\n    this.fiscalYears.add(fiscalYear);\n    this.audit.record(this.audit.actorOf(input), 'fiscalYear', fiscalYear.id, 'created', {\n      year: { from: null, to: year },\n      start: { from: null, to: start.iso },\n      end: { from: null, to: end.iso },\n    });\n    return fiscalYear;\n  }\n\n  closePeriod(input: Record<string, unknown>): { fiscalYear: number; period: number; status: string } {\n    const fiscalYear = this.requireFiscalYear(input.fiscalYear);\n    const period = fiscalYear.closePeriod(this.periodNumber(input));\n    this.fiscalYears.save(fiscalYear);\n    this.audit.record(this.audit.actorOf(input), 'period', fiscalYear.id, 'closed', {\n      period: { from: null, to: `${fiscalYear.year}/${period.number}` },\n      status: { from: 'open', to: period.status() },\n    });\n    return { fiscalYear: fiscalYear.year, period: period.number, status: period.status() };\n  }\n\n  reopenPeriod(input: Record<string, unknown>): { fiscalYear: number; period: number; status: string } {\n    const fiscalYear = this.requireFiscalYear(input.fiscalYear);\n    const period = fiscalYear.reopenPeriod(this.periodNumber(input));\n    this.fiscalYears.save(fiscalYear);\n    this.audit.record(this.audit.actorOf(input), 'period', fiscalYear.id, 'reopened', {\n      period: { from: null, to: `${fiscalYear.year}/${period.number}` },\n      status: { from: 'closed', to: period.status() },\n    });\n    return { fiscalYear: fiscalYear.year, period: period.number, status: period.status() };\n  }\n\n  closeFiscalYear(input: Record<string, unknown>): FiscalYear {\n    const fiscalYear = this.requireFiscalYear(input.fiscalYear);\n    for (const entry of this.journal.forFiscalYear(fiscalYear.year)) {\n      if (!entry.isFinalized()) {\n        throw new DomainError(\n          'E_FISCALYEAR_UNFINALIZED_ENTRIES',\n          `Year-end close ${fiscalYear.year}: posting ${entry.sequenceNumber} is not finalized`,\n          { fiscalYear: fiscalYear.year, sequenceNumber: entry.sequenceNumber },\n        );\n      }\n    }\n    fiscalYear.close();\n    this.fiscalYears.save(fiscalYear);\n    this.audit.record(this.audit.actorOf(input), 'fiscalYear', fiscalYear.id, 'closed', {\n      status: { from: 'open', to: 'closed' },\n    });\n    return fiscalYear;\n  }\n\n  private requireFiscalYear(year: unknown): FiscalYear {\n    const fiscalYear = typeof year === 'number' ? this.fiscalYears.byYear(year) : null;\n    if (fiscalYear === null) {\n      throw new DomainError('E_PERIOD_UNKNOWN', `Fiscal year ${typeof year === 'number' ? year : '?'} is not created`);\n    }\n    return fiscalYear;\n  }\n\n  private periodNumber(input: Record<string, unknown>): number {\n    const period = input.period;\n    if (typeof period !== 'number' || !Number.isInteger(period)) {\n      throw new DomainError('E_PERIOD_UNKNOWN', 'Period number missing');\n    }\n    return period;\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type { AccountRepository, JournalRepository, OpenItemRepository } from '../port.js';\nimport type { Currency } from '../substrate/currency.js';\nimport { InvalidValue } from '../substrate/errors.js';\nimport type { JournalEntry } from '../substrate/journal-entry.js';\nimport { Money } from '../substrate/money.js';\nimport { Uuid } from '../substrate/uuid.js';\nimport { OpenItem } from '../records/open-item.js';\nimport { Settlement } from '../policies/expansion/settlement.js';\nimport { parseSettlementDifferenceKind, type SettlementDifferenceKind } from '../substrate/types.js';\nimport type { AuditWriter } from './audit-writer.js';\nimport { requireEntry } from './lookups.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * Settlement: allocation payment → open item(s), also partial; always\n * explicit, no FIFO (determinismus.md §3). Differences (cash discount/write-off/\n * small difference) per api.md G2. Validate fully first, then apply.\n *\n * **This service does not post.** It takes an entry the caller has already written, checks the\n * allocation is covered by what that entry moves on the item's account, and records it. So when a\n * difference reduces the consideration of an item that carried tax, nothing here demands that the\n * caller's entry also corrects that tax — and no projection can notice the omission afterwards,\n * because each one computes correctly from whatever is on the journal.\n *\n * That is a deliberate boundary, not an oversight: whether a given reduction changes the taxable\n * base is a question a jurisdiction answers, and the policy kind that would express it has no\n * socket in this core yet. Until it does, the caller owes the correction line. See the ➖ row in\n * docs/gobd-conformance.md §4 and A-13 in the app's obligation list.\n */\nexport class SettlementService {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly openItems: OpenItemRepository,\n    private readonly audit: AuditWriter,\n  ) {}\n\n  settle(input: Record<string, unknown>): OpenItem[] {\n    const actor = this.audit.actorOf(input);\n    const entry = requireEntry(this.journal, input.entryId);\n\n    const allocations = Array.isArray(input.allocations) ? input.allocations : [];\n    if (allocations.length === 0) {\n      throw new DomainError('E_OPENITEM_UNKNOWN', 'settle without allocations');\n    }\n\n    const plan: Array<{ item: OpenItem; settlement: Settlement }> = [];\n    const planned = new Map<string, Money>();\n\n    for (const allocation of allocations) {\n      if (!isRecord(allocation)) {\n        throw new DomainError('E_OPENITEM_UNKNOWN', 'Allocation is not a structure');\n      }\n      const openItemId = allocation.openItemId;\n      let item: OpenItem | null = null;\n      if (typeof openItemId === 'string') {\n        try {\n          item = this.openItems.byId(Uuid.fromString(openItemId));\n        } catch (error) {\n          if (!(error instanceof InvalidValue)) throw error;\n        }\n      }\n      if (item === null) {\n        throw new DomainError(\n          'E_OPENITEM_UNKNOWN',\n          `Open item ${typeof openItemId === 'string' ? openItemId : '?'} does not exist`,\n        );\n      }\n\n      const money = this.parseSettlementMoney(allocation.money, 'Allocation amount');\n      const [differenceMoney, differenceKind] = this.parseDifference(allocation.difference ?? null, item);\n\n      const alreadyPlanned = planned.get(item.id.value) ?? Money.zero(this.baseCurrency);\n      if (money.add(alreadyPlanned).compareTo(item.remaining()) > 0) {\n        throw new DomainError(\n          'E_SETTLEMENT_EXCEEDS_ITEM',\n          `Allocation ${money.amountAsString()} exceeds remaining amount ${item\n            .remaining()\n            .subtract(alreadyPlanned)\n            .amountAsString()} of item ${item.id.value}`,\n          { openItemId: item.id.value },\n        );\n      }\n\n      planned.set(item.id.value, money.add(alreadyPlanned));\n      plan.push({\n        item,\n        settlement: new Settlement(entry.id, money, entry.entryDate, differenceMoney, differenceKind),\n      });\n    }\n\n    this.assertEntryCoversAllocations(entry, plan);\n\n    const affected: OpenItem[] = [];\n    for (const step of plan) {\n      const before = step.item.remaining().amountAsString();\n      step.item.settle(step.settlement);\n      this.openItems.save(step.item);\n      this.audit.record(actor, 'openItem', step.item.id, 'settled', {\n        remaining: { from: before, to: step.item.remaining().amountAsString() },\n      });\n      affected.push(step.item);\n    }\n\n    return affected;\n  }\n\n  /**\n   * R-1: an allocation may not claim more than the settling entry actually books against the open\n   * item's account.\n   *\n   * The only bound used to be the item's remaining amount, so a 500.00 payment could close a\n   * 1190.00 receivable in full. The general ledger then carries a 690.00 receivable the subledger\n   * no longer knows about — permanently, and with nothing to point at it — and under cash-basis\n   * taxation the VAT return declares tax as collected that never arrived.\n   *\n   * The bound is the entry's NET REDUCING movement on that account, not its total: a payment with\n   * a discount books the full receivable against the receivables account and carries the\n   * difference as its own line, so those settlements stay valid. Settlements already recorded\n   * against this same entry count against the same budget — otherwise the check could be walked\n   * around by settling twice.\n   */\n  private assertEntryCoversAllocations(\n    entry: JournalEntry,\n    plan: Array<{ item: OpenItem; settlement: Settlement }>,\n  ): void {\n    const zero = Money.zero(this.baseCurrency);\n\n    // What this entry moves per account, signed so that a positive value reduces a receivable.\n    const movement = new Map<string, Money>();\n    for (const line of entry.lines()) {\n      const account = this.accounts.byId(line.accountId);\n      if (account === null) continue;\n      const key = account.number.value;\n      const signed = line.side === 'credit' ? line.money : line.money.negate();\n      movement.set(key, (movement.get(key) ?? zero).add(signed));\n    }\n\n    // Already claimed against this entry by an earlier settle call.\n    const claimed = new Map<string, Money>();\n    const addClaim = (item: OpenItem, amount: Money): void => {\n      const account = this.accountOfOpenItem(item);\n      if (account === null) return;\n      const asReduction = item.kind === 'payable' ? amount.negate() : amount;\n      claimed.set(account, (claimed.get(account) ?? zero).add(asReduction));\n    };\n\n    for (const item of this.openItems.all()) {\n      for (const settlement of item.settlements()) {\n        if (settlement.entryId.value === entry.id.value) addClaim(item, settlement.money);\n      }\n    }\n    for (const step of plan) {\n      addClaim(step.item, step.settlement.money);\n    }\n\n    for (const [account, needed] of claimed) {\n      const available = movement.get(account) ?? zero;\n      // Compared in the reducing direction: `needed` is already signed that way, and so is\n      // `available`, because a payable is reduced by a debit and a receivable by a credit.\n      if (needed.abs().compareTo(available.abs()) > 0 || needed.isPositive() !== available.isPositive()) {\n        throw new DomainError(\n          'E_SETTLEMENT_EXCEEDS_ENTRY',\n          `Allocations against account ${account} claim ${needed.abs().amountAsString()}, ` +\n            `but the entry moves ${available.abs().amountAsString()} there`,\n          { account, claimed: needed.abs().amountAsString(), available: available.abs().amountAsString() },\n        );\n      }\n    }\n  }\n\n  /** The account an open item sits on — its origin posting's line. */\n  private accountOfOpenItem(item: OpenItem): string | null {\n    const origin = this.journal.byId(item.originEntryId);\n    const line = origin?.lines()[item.originLineIndex];\n    if (line === undefined) return null;\n    return this.accounts.byId(line.accountId)?.number.value ?? null;\n  }\n\n  private parseSettlementMoney(raw: unknown, label: string): Money {\n    const amount = isRecord(raw) ? asString(raw.amount) : null;\n    const currency = isRecord(raw) ? asString(raw.currency) : null;\n    if (amount === null || currency !== this.baseCurrency.code) {\n      throw new InvalidValue(`${label} missing or wrong currency`);\n    }\n    const money = Money.of(amount, this.baseCurrency);\n    if (!money.isPositive()) {\n      throw new InvalidValue(`${label} must be > 0`);\n    }\n    return money;\n  }\n\n  private parseDifference(\n    raw: unknown,\n    item: OpenItem,\n  ): [Money | null, SettlementDifferenceKind | null] {\n    if (raw === null) return [null, null];\n    if (!isRecord(raw)) {\n      throw new DomainError('E_SETTLEMENT_DIFFERENCE_INVALID', 'difference is not a structure');\n    }\n    const kind = parseSettlementDifferenceKind(raw.kind);\n    if (kind === null) {\n      throw new DomainError(\n        'E_SETTLEMENT_DIFFERENCE_INVALID',\n        `Unknown difference kind \"${typeof raw.kind === 'string' ? raw.kind : '?'}\"`,\n      );\n    }\n    let money: Money;\n    try {\n      money = this.parseSettlementMoney(raw.money, 'Difference amount');\n    } catch (error) {\n      if (error instanceof InvalidValue) {\n        throw new DomainError('E_SETTLEMENT_DIFFERENCE_INVALID', 'Difference amount invalid (≤ 0 or format)');\n      }\n      throw error;\n    }\n    if (money.compareTo(item.remaining()) > 0) {\n      throw new DomainError(\n        'E_SETTLEMENT_DIFFERENCE_INVALID',\n        `Difference ${money.amountAsString()} exceeds remaining amount ${item.remaining().amountAsString()}`,\n      );\n    }\n    return [money, kind];\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport type {\n  AccountRepository,\n  AuditTrail,\n  FiscalYearRepository,\n  JournalRepository,\n  OpenItemRepository,\n  VoucherRepository,\n} from '../port.js';\nimport { AccountNumber } from '../substrate/account-number.js';\nimport type { CalendarDate } from '../substrate/calendar-date.js';\nimport type { Clock } from '../substrate/clock.js';\nimport type { Currency } from '../substrate/currency.js';\nimport { DimensionValue } from '../substrate/dimension-value.js';\nimport { InvalidValue } from '../substrate/errors.js';\nimport type { IdGenerator } from '../substrate/id-generator.js';\nimport { Money } from '../substrate/money.js';\nimport { PeriodRef } from '../substrate/period-ref.js';\nimport { Uuid } from '../substrate/uuid.js';\nimport type { Account } from '../substrate/account.js';\nimport type { AuditChanges } from '../records/audit-record.js';\nimport { TaxCodeRegistry } from '../policies/expansion/tax/tax-code-registry.js';\nimport { AccountCombinationRegistry, type ConstraintContext } from '../policies/constraint/account-combination-registry.js';\nimport type { LegalFormRegistry } from '../policies/projection/legal-forms.js';\nimport type { TaxProfile } from '../policies/expansion/tax/tax-profile.js';\nimport { DimensionRegistry } from '../policies/constraint/dimension-registry.js';\nimport { EntryLine } from '../substrate/entry-line.js';\nimport type { FiscalYear } from '../substrate/fiscal-year.js';\nimport { JournalEntry } from '../substrate/journal-entry.js';\nimport { OpenItem } from '../records/open-item.js';\nimport { PostResult } from '../substrate/post-result.js';\nimport { Settlement } from '../policies/expansion/settlement.js';\nimport { type OpenItemKind, type Side } from '../substrate/types.js';\nimport type { Voucher } from '../records/voucher.js';\nimport { AuditWriter } from './audit-writer.js';\nimport { ChartAdminService } from './chart-admin-service.js';\nimport type { TenantConfigStore } from '../composition/tenant-config-store.js';\nimport { FiscalPeriodService } from './fiscal-period-service.js';\nimport { SettlementService } from './settlement-service.js';\nimport { parseEntryDate, requireEntry } from './lookups.js';\n\ninterface ParsedLine {\n  readonly account: string;\n  readonly side: Side;\n  readonly money: Money;\n  readonly dimensions: DimensionValue[];\n  readonly taxTag: Record<string, unknown> | null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * Domain Service `post` and relatives (ledger-modell.md). Check order when\n * posting is part of the contract (api.md):\n *   1. Structure (E_ENTRY_TOO_FEW_LINES, E_ENTRY_INVALID_AMOUNT)\n *   2. References (E_ENTRY_NO_VOUCHER, E_VOUCHER_UNKNOWN, E_ACCOUNT_UNKNOWN,\n *      E_ACCOUNT_LOCKED, E_DIMENSION_INVALID)\n *   3. Balance equation (E_ENTRY_UNBALANCED)\n *   4. Temporal context (E_PERIOD_UNKNOWN, E_PERIOD_CLOSED)\n * Only the first error is reported.\n *\n * `Ledger` keeps the operations that write postings — `post`, `correct`, `finalize`, `reverse` —\n * together with the line parsing they share, and is a thin facade for the three areas that were\n * only ever neighbours of the journal, not part of it: settlement (`SettlementService`), chart of\n * accounts (`ChartAdminService`) and fiscal years/periods (`FiscalPeriodService`). The facade is\n * deliberate: `TenantOperations` and every adapter keep talking to one object, so the split is a\n * change of shape inside the core and of nothing else.\n */\nexport class Ledger {\n  private readonly auditWriter: AuditWriter;\n  private readonly settlements: SettlementService;\n  private readonly chart: ChartAdminService;\n  private readonly periods: FiscalPeriodService;\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly fiscalYears: FiscalYearRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly journal: JournalRepository,\n    private readonly openItems: OpenItemRepository,\n    audit: AuditTrail,\n    private readonly dimensions: DimensionRegistry,\n    clock: Clock,\n    private readonly ids: IdGenerator,\n    private readonly taxCodes: TaxCodeRegistry = TaxCodeRegistry.empty(),\n    // Only needed so that dimension declarations — which have no id of their own — can name their\n    // tenant in the audit trail, like the other per-tenant configuration does.\n    tenantId: Uuid | null = null,\n    /** Passed straight through to the chart service, which is where dimensions are declared. */\n    configStore: TenantConfigStore | null = null,\n    /** The constraint socket's second predicate (F-CORE-042), checked over the whole entry. */\n    private readonly combinations: AccountCombinationRegistry = AccountCombinationRegistry.empty(),\n    /**\n     * The two tenant facts a constraint rule may be conditioned on (`appliesWhen`, F-CORE-047).\n     * Held as the live registries rather than as copied values, because the legal form is set by\n     * `setEntityProfile` **after** the ledger exists — a snapshot taken here would leave every\n     * conditional rule dormant for the life of the tenant.\n     */\n    private readonly legalForms: LegalFormRegistry | null = null,\n    private readonly taxProfile: TaxProfile | null = null,\n  ) {\n    this.auditWriter = new AuditWriter(audit, clock, ids);\n    this.settlements = new SettlementService(baseCurrency, accounts, journal, openItems, this.auditWriter);\n    this.chart = new ChartAdminService(accounts, ids, this.auditWriter, dimensions, tenantId, configStore);\n    this.periods = new FiscalPeriodService(fiscalYears, journal, ids, this.auditWriter);\n  }\n\n  /**\n   * The dimension registry this ledger validates against — so `tenantConfiguration` can report what\n   * a posting will be measured by. Read-only access: declaring a type or a value goes through\n   * `defineDimensionType`/`defineDimensionValue`, which audit and store the change.\n   */\n  /** What `tenantConfiguration` reports, same reason as the dimension rules. */\n  /**\n   * The tenant facts a conditional constraint rule is measured against (`appliesWhen`).\n   *\n   * Read fresh on every posting, never cached: `setEntityProfile` may run at any point in a\n   * tenant's life, and a rule that only applies to tenants configured before the first posting\n   * would be a rule nobody could rely on. Absent stays absent — an unset fact makes a rule keyed on\n   * it dormant rather than failing the posting, which is argued where the matching is done.\n   */\n  private constraintContext(): ConstraintContext {\n    return {\n      legalForm: this.legalForms?.declared()?.legalForm ?? null,\n      taxationMethod: this.taxProfile?.taxationMethod() ?? null,\n    };\n  }\n\n  combinationRegistry(): AccountCombinationRegistry {\n    return this.combinations;\n  }\n\n  dimensionRegistry(): DimensionRegistry {\n    return this.dimensions;\n  }\n\n  /**\n   * What a posting's creation records (F-CORE-014).\n   *\n   * A creation is a change from nothing, written as `from: null` rather than as an empty diff — the\n   * idiom vouchers, fiscal years and dimensions already used, and which postings did not, so the\n   * published invariant held for some records and not for others.\n   *\n   * **The lines are deliberately not copied here.** A finalized entry cannot change and an entered\n   * one records its own change under `corrected`, so the journal already holds what the entry is;\n   * duplicating the lines would double the largest table in the system and create a second answer\n   * to what the posting says. What the trail adds is the frame a reader cannot reconstruct: when it\n   * was booked, against which voucher, under which text.\n   */\n  private static entryCreationDiff(entry: JournalEntry): Record<string, { from: unknown; to: unknown }> {\n    return {\n      entryDate: { from: null, to: entry.entryDate.iso },\n      voucherId: { from: null, to: entry.voucherId.value },\n      text: { from: null, to: entry.text() },\n    };\n  }\n\n  post(input: Record<string, unknown>): PostResult {\n    const actor = this.auditWriter.actorOf(input);\n\n    // 1. Structure\n    const rawLines = input.lines;\n    if (!Array.isArray(rawLines) || rawLines.length < 2) {\n      throw new DomainError('E_ENTRY_TOO_FEW_LINES', 'A posting needs at least two lines');\n    }\n    const parsed = rawLines.map((rawLine, index) => {\n      if (!isRecord(rawLine)) {\n        throw new DomainError('E_ENTRY_INVALID_AMOUNT', `Line ${index} is not a structure`);\n      }\n      return this.parseLine(rawLine, index);\n    });\n\n    // 2. References\n    const voucher = this.requireVoucher(input.voucherId);\n    const lines = this.resolveLines(parsed);\n\n    // 3. Balance equation\n    this.assertBalanced(lines);\n\n    // 4. Temporal context\n    const entryDate = parseEntryDate(input.entryDate);\n    const [fiscalYear, period] = this.openPeriodFor(entryDate);\n\n    // 4b. The accounts' validity window, which can only be judged once the date is known —\n    // deliberately AFTER the period check, so no input that is refused today changes its code.\n    this.assertAccountsValidOn(lines, entryDate);\n\n    const text = asString(input.text) ?? '';\n\n    const entry = new JournalEntry(\n      this.ids.next(),\n      this.journal.nextSequenceNumber(fiscalYear.year),\n      entryDate,\n      voucher.voucherDate,\n      this.auditWriter.now(),\n      new PeriodRef(fiscalYear.year, period.number),\n      voucher.id,\n      text,\n      lines,\n    );\n\n    this.journal.append(entry);\n    this.auditWriter.record(actor, 'journalEntry', entry.id, 'created', Ledger.entryCreationDiff(entry));\n\n    return new PostResult(entry, this.createOpenItems(entry));\n  }\n\n  /**\n   * AR/AP automation: debit on a receivable account → receivable, credit on a\n   * payable account → payable. Reversal postings create no items.\n   */\n  private createOpenItems(entry: JournalEntry): OpenItem[] {\n    if (entry.reverses !== null) return [];\n\n    const created: OpenItem[] = [];\n    const voucher = this.vouchers.byId(entry.voucherId);\n\n    entry.lines().forEach((line, index) => {\n      const account = this.accounts.byId(line.accountId);\n      let kind: OpenItemKind | null = null;\n      if (account?.subtype === 'ar' && line.side === 'debit') kind = 'receivable';\n      else if (account?.subtype === 'ap' && line.side === 'credit') kind = 'payable';\n      if (kind === null) return;\n\n      const item = new OpenItem(\n        this.ids.next(),\n        kind,\n        entry.id,\n        index,\n        line.money,\n        entry.voucherId,\n        entry.entryDate,\n        voucher?.partnerId ?? null,\n      );\n      this.openItems.add(item);\n      created.push(item);\n    });\n\n    return created;\n  }\n\n  correct(input: Record<string, unknown>): JournalEntry {\n    const actor = this.auditWriter.actorOf(input);\n    const entry = requireEntry(this.journal, input.entryId);\n    const changes: AuditChanges = {};\n\n    // Reading both fields leniently made every unrecognized field a silent no-op that still\n    // returned the entry as a SUCCESS payload: `txt` instead of `text` looked like a correction\n    // that had happened. A correction that changes nothing was never asked for — say so instead\n    // of confirming a change nobody made.\n    const hasText = input.text !== undefined && input.text !== null;\n    const hasLines = input.lines !== undefined && input.lines !== null;\n    if (!hasText && !hasLines) {\n      throw new DomainError('E_INPUT_INVALID', 'correct requires \"text\" or \"lines\" — nothing to change', {\n        fields: Object.keys(input).sort().join(','),\n      });\n    }\n    if (hasText && typeof input.text !== 'string') {\n      throw new DomainError('E_INPUT_INVALID', 'correct: \"text\" must be a string');\n    }\n    if (hasLines && !Array.isArray(input.lines)) {\n      throw new DomainError('E_INPUT_INVALID', 'correct: \"lines\" must be an array');\n    }\n\n    const text = asString(input.text);\n    if (text !== null && text !== entry.text()) {\n      changes.text = { from: entry.text(), to: text };\n      entry.changeText(text);\n    }\n\n    if (Array.isArray(input.lines)) {\n      // Rewriting the lines used to leave the open items derived from them untouched, so the\n      // subledger went on naming an amount, an account and a due date from a posting that no\n      // longer existed — the same silent split between ledger and subledger as R-1, from the\n      // other side. The text stays correctable; for amounts the GoBD-conform path is reversal\n      // and a fresh posting, which keeps both books together.\n      if (this.openItems.byOriginEntry(entry.id).length > 0) {\n        throw new DomainError(\n          'E_ENTRY_HAS_OPEN_ITEMS',\n          'correct: this entry produced open items — correct the text, or reverse and post anew',\n          { entryId: entry.id.value },\n        );\n      }\n\n      if (input.lines.length < 2) {\n        throw new DomainError('E_ENTRY_TOO_FEW_LINES', 'A posting needs at least two lines');\n      }\n      const parsed = input.lines.map((rawLine, index) => {\n        if (!isRecord(rawLine)) {\n          throw new DomainError('E_ENTRY_INVALID_AMOUNT', `Line ${index} is not a structure`);\n        }\n        return this.parseLine(rawLine, index);\n      });\n      const lines = this.resolveLines(parsed);\n      this.assertBalanced(lines);\n      // The corrected entry keeps its own date, so that is the date the window is judged against —\n      // a correction must not be able to move a posting onto an account that was not open for\n      // business when the posting happened.\n      this.assertAccountsValidOn(lines, entry.entryDate);\n\n      changes.lines = {\n        from: entry.lines().map((line) => line.toJSON()),\n        to: lines.map((line) => line.toJSON()),\n      };\n      entry.changeLines(lines);\n    }\n\n    if (Object.keys(changes).length > 0) {\n      this.journal.save(entry);\n      this.auditWriter.record(actor, 'journalEntry', entry.id, 'corrected', changes);\n    } else {\n      // Status check even without an effective change (E_ENTRY_FINALIZED).\n      entry.changeText(entry.text());\n    }\n\n    return entry;\n  }\n\n  finalize(input: Record<string, unknown>): number {\n    const actor = this.auditWriter.actorOf(input);\n\n    if (input.entryId !== undefined) {\n      const entry = requireEntry(this.journal, input.entryId);\n      if (entry.isFinalized()) return 0;\n      entry.finalize();\n      this.journal.save(entry);\n      this.auditWriter.record(actor, 'journalEntry', entry.id, 'finalized', {\n        status: { from: 'entered', to: 'finalized' },\n      });\n      return 1;\n    }\n\n    const until = input.finalizeUntil;\n    if (typeof until !== 'string') {\n      throw new DomainError('E_ENTRY_UNKNOWN', 'finalize needs entryId or finalizeUntil');\n    }\n    const untilDate = parseEntryDate(until);\n    let count = 0;\n\n    for (const entry of this.journal.all()) {\n      if (entry.isFinalized() || entry.entryDate.isAfter(untilDate)) continue;\n      entry.finalize();\n      this.journal.save(entry);\n      this.auditWriter.record(actor, 'journalEntry', entry.id, 'finalized', {\n        status: { from: 'entered', to: 'finalized' },\n      });\n      count++;\n    }\n    return count;\n  }\n\n  reverse(input: Record<string, unknown>): JournalEntry {\n    const actor = this.auditWriter.actorOf(input);\n    const original = requireEntry(this.journal, input.entryId);\n\n    if (original.reversedBy() !== null) {\n      throw new DomainError('E_ENTRY_ALREADY_REVERSED', `Posting ${original.id.value} is already reversed`, {\n        entryId: original.id.value,\n      });\n    }\n\n    // IMPL-008: a reversal clears the open items the reversed entry produced — but only while they\n    // are untouched. Once one carries a settlement, money has actually moved, and cancelling the\n    // item would drop that movement out of the open-item history while the ledger keeps it. The\n    // line SAP draws with F5308: undo the settlement first, or post a credit note.\n    const items = this.openItems.byOriginEntry(original.id);\n    const settled = items.filter((item) => item.settlements().length > 0);\n    if (settled.length > 0) {\n      throw new DomainError(\n        'E_ENTRY_HAS_SETTLED_ITEMS',\n        'reverse: an open item of this entry is already settled — undo the settlement or post a credit note instead',\n        { entryId: original.id.value, openItemId: settled[0]!.id.value },\n      );\n    }\n\n    const entryDate = parseEntryDate(input.entryDate);\n    const [fiscalYear, period] = this.openPeriodFor(entryDate);\n    const text = asString(input.text) ?? `Reversal ${original.sequenceNumber}`;\n\n    // A reversal may carry its own voucher. It used to inherit the reversed entry's one\n    // unconditionally and drop any `voucherId` in the input without a word — so a caller who\n    // supplied a cancellation document got no error, no hint, and a posting pointing at the wrong\n    // paper. Inheriting stays the default, because a reversal without its own document is a normal\n    // case and no posting may be voucher-less; supplying one is now honoured, and an unknown id\n    // fails like everywhere else (E_VOUCHER_UNKNOWN).\n    const reversalVoucherId =\n      input.voucherId === null || input.voucherId === undefined\n        ? original.voucherId\n        : this.requireVoucher(input.voucherId).id;\n\n    const reversal = new JournalEntry(\n      this.ids.next(),\n      this.journal.nextSequenceNumber(fiscalYear.year),\n      entryDate,\n      original.voucherDate,\n      this.auditWriter.now(),\n      new PeriodRef(fiscalYear.year, period.number),\n      reversalVoucherId,\n      text,\n      original.lines().map((line) => line.negated()),\n      original.id,\n    );\n\n    original.markReversed(reversal.id);\n    this.journal.append(reversal);\n    this.journal.save(original);\n\n    this.auditWriter.record(actor, 'journalEntry', reversal.id, 'created', Ledger.entryCreationDiff(reversal));\n    this.auditWriter.record(actor, 'journalEntry', original.id, 'reversed', {\n      reversedBy: { from: null, to: reversal.id.value },\n    });\n\n    // Clear each untouched open item against the reversal. Nothing is deleted — the item keeps its\n    // record and gains a settlement marked `cancellation`, which is what tells a reader (and the\n    // cash-basis VAT return) that this was a reversal and not an incoming payment.\n    for (const item of items) {\n      item.settle(new Settlement(reversal.id, item.remaining(), entryDate, null, null, 'cancellation'));\n      this.openItems.save(item);\n      this.auditWriter.record(actor, 'openItem', item.id, 'cancelled', {\n        cancelledBy: { from: null, to: reversal.id.value },\n      });\n    }\n\n    return reversal;\n  }\n\n  // ---- facade: settlement, chart of accounts, fiscal years -------------\n\n  settle(input: Record<string, unknown>): OpenItem[] {\n    return this.settlements.settle(input);\n  }\n\n  createAccount(input: Record<string, unknown>): Account {\n    return this.chart.createAccount(input);\n  }\n\n  defineDimensionType(input: Record<string, unknown>): Record<string, unknown> {\n    return this.chart.defineDimensionType(input);\n  }\n\n  defineDimensionValue(input: Record<string, unknown>): Record<string, unknown> {\n    return this.chart.defineDimensionValue(input);\n  }\n\n  lockAccount(input: Record<string, unknown>): Account {\n    return this.chart.lockAccount(input);\n  }\n\n  unlockAccount(input: Record<string, unknown>): Account {\n    return this.chart.unlockAccount(input);\n  }\n\n  importChartOfAccounts(input: Record<string, unknown>): number {\n    return this.chart.importChartOfAccounts(input);\n  }\n\n  createFiscalYear(input: Record<string, unknown>): FiscalYear {\n    return this.periods.createFiscalYear(input);\n  }\n\n  closePeriod(input: Record<string, unknown>): { fiscalYear: number; period: number; status: string } {\n    return this.periods.closePeriod(input);\n  }\n\n  reopenPeriod(input: Record<string, unknown>): { fiscalYear: number; period: number; status: string } {\n    return this.periods.reopenPeriod(input);\n  }\n\n  closeFiscalYear(input: Record<string, unknown>): FiscalYear {\n    return this.periods.closeFiscalYear(input);\n  }\n\n  // ---- internal --------------------------------------------------------\n\n  private parseLine(rawLine: Record<string, unknown>, index: number): ParsedLine {\n    const money = rawLine.money;\n    const amount = isRecord(money) ? asString(money.amount) : null;\n    const currency = isRecord(money) ? asString(money.currency) : null;\n\n    if (amount === null || currency === null) {\n      throw new DomainError('E_ENTRY_INVALID_AMOUNT', `Line ${index}: money missing or incomplete`);\n    }\n    if (currency !== this.baseCurrency.code) {\n      throw new DomainError(\n        'E_ENTRY_INVALID_AMOUNT',\n        `Line ${index}: foreign currency ${currency} — v1 posts only the tenant currency ${this.baseCurrency.code}`,\n        { currency },\n      );\n    }\n\n    let parsedMoney: Money;\n    try {\n      parsedMoney = Money.of(amount, this.baseCurrency);\n    } catch (error) {\n      if (error instanceof InvalidValue) {\n        throw new DomainError(\n          'E_ENTRY_INVALID_AMOUNT',\n          `Line ${index}: amount \"${amount}\" is not a valid ${this.baseCurrency.code} amount`,\n          { amount },\n        );\n      }\n      throw error;\n    }\n    if (!parsedMoney.isPositive()) {\n      throw new DomainError(\n        'E_ENTRY_INVALID_AMOUNT',\n        `Line ${index}: amount must be > 0 (negative amounts only on reversal)`,\n        { amount },\n      );\n    }\n\n    const side = rawLine.side;\n    if (side !== 'debit' && side !== 'credit') {\n      throw new DomainError('E_ENTRY_INVALID_AMOUNT', `Line ${index}: side must be debit or credit`);\n    }\n\n    const account = asString(rawLine.account);\n    if (account === null || account === '') {\n      throw new DomainError('E_ENTRY_INVALID_AMOUNT', `Line ${index}: account missing`);\n    }\n\n    const dimensions: DimensionValue[] = [];\n    const rawDimensions = Array.isArray(rawLine.dimensions) ? rawLine.dimensions : [];\n    for (const rawDimension of rawDimensions) {\n      if (!isRecord(rawDimension) || typeof rawDimension.type !== 'string' || typeof rawDimension.code !== 'string') {\n        throw new DomainError('E_DIMENSION_INVALID', `Line ${index}: dimension incomplete`);\n      }\n      dimensions.push(DimensionValue.of(rawDimension.type, rawDimension.code));\n    }\n\n    // A caller-supplied taxTag must name a REGISTERED tax code. The VAT return is built\n    // from these tags, never from account numbers, so an unvalidated tag writes straight\n    // into statutory output: `post` used to accept `{\"code\":\"MADEUP\",\"reportingKey\":\"4711\"}`\n    // and the invented key showed up as a line of the return. `postVoucher` always went\n    // through the registry; the direct `post` path did not.\n    const taxTag = isRecord(rawLine.taxTag) ? rawLine.taxTag : null;\n    if (taxTag !== null && typeof taxTag.code === 'string' && taxTag.code !== '') {\n      this.taxCodes.get(taxTag.code);\n    }\n\n    return { account, side, money: parsedMoney, dimensions, taxTag };\n  }\n\n  private requireVoucher(voucherId: unknown): Voucher {\n    if (typeof voucherId !== 'string' || voucherId === '') {\n      throw new DomainError('E_ENTRY_NO_VOUCHER', 'No posting without a voucher (F-CORE-003)');\n    }\n    let voucher: Voucher | null = null;\n    try {\n      voucher = this.vouchers.byId(Uuid.fromString(voucherId));\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n    }\n    if (voucher === null) {\n      throw new DomainError('E_VOUCHER_UNKNOWN', `Voucher ${voucherId} does not exist`, { voucherId });\n    }\n    return voucher;\n  }\n\n  private resolveLines(parsed: ParsedLine[]): EntryLine[] {\n    const lines = parsed.map((line) => {\n      const number = AccountNumber.of(line.account);\n      const account = this.accounts.byNumber(number);\n      if (account === null) {\n        throw new DomainError('E_ACCOUNT_UNKNOWN', `Account ${number.value} does not exist`, { number: number.value });\n      }\n      if (account.isLocked()) {\n        throw new DomainError('E_ACCOUNT_LOCKED', `Account ${number.value} is locked`, { number: number.value });\n      }\n      return new EntryLine(account.id, account.number, line.side, line.money, line.dimensions, line.taxTag);\n    });\n\n    for (const line of lines) {\n      this.dimensions.validateLine(line.account, line.dimensions);\n    }\n    // Over the whole entry, after the per-line checks: a combination is not a property of any one\n    // line, which is why it could not have been a second rule inside the dimension registry.\n    this.combinations.validateEntry(lines.map((line) => line.account), this.constraintContext());\n    return lines;\n  }\n\n  /**\n   * An account may be posted to only inside its validity window (F-CORE-045).\n   *\n   * Judged against the ENTRY DATE, not against today: that is the whole difference from a lock. An\n   * account retired at a year end keeps taking a late correction for December and refuses January,\n   * which is what retiring an account actually means; a lock would refuse both.\n   */\n  private assertAccountsValidOn(lines: EntryLine[], entryDate: CalendarDate): void {\n    for (const line of lines) {\n      const account = this.accounts.byId(line.accountId);\n      if (account === null || account.isValidOn(entryDate)) continue;\n\n      throw new DomainError(\n        'E_ACCOUNT_NOT_VALID_AT_DATE',\n        `Account ${account.number.value} may not be posted to on ${entryDate.iso}`,\n        {\n          number: account.number.value,\n          entryDate: entryDate.iso,\n          validFrom: account.validFrom?.iso ?? null,\n          validTo: account.validTo?.iso ?? null,\n        },\n      );\n    }\n  }\n\n  private assertBalanced(lines: EntryLine[]): void {\n    let debit = Money.zero(this.baseCurrency);\n    let credit = Money.zero(this.baseCurrency);\n    for (const line of lines) {\n      if (line.side === 'debit') debit = debit.add(line.money);\n      else credit = credit.add(line.money);\n    }\n    if (!debit.equals(credit)) {\n      throw new DomainError(\n        'E_ENTRY_UNBALANCED',\n        `Σ debit (${debit.amountAsString()}) ≠ Σ credit (${credit.amountAsString()})`,\n        { debit: debit.amountAsString(), credit: credit.amountAsString() },\n      );\n    }\n  }\n\n  private openPeriodFor(entryDate: CalendarDate): [FiscalYear, ReturnType<FiscalYear['periodForDate']>] {\n    const fiscalYear = this.fiscalYears.forDate(entryDate);\n    if (fiscalYear === null) {\n      throw new DomainError(\n        'E_PERIOD_UNKNOWN',\n        `Posting date ${entryDate.iso} lies outside any created fiscal year`,\n        { date: entryDate.iso },\n      );\n    }\n    const period = fiscalYear.periodForDate(entryDate);\n    if (fiscalYear.isClosed() || !period.isOpen()) {\n      throw new DomainError('E_PERIOD_CLOSED', `Period ${fiscalYear.year}/${period.number} is closed`, {\n        fiscalYear: fiscalYear.year,\n        period: period.number,\n      });\n    }\n    return [fiscalYear, period];\n  }\n}\n","import type {\n  AccountRepository,\n  AssetRepository,\n  AuditCriteria,\n  AuditTrail,\n  CostingRunRepository,\n  InventoryValuationRepository,\n  DeferralRepository,\n  ProvisionRepository,\n  FiscalYearRepository,\n  JournalRepository,\n  OpenItemRepository,\n  PartnerRepository,\n  TenantRecordData,\n  TenantRecordRepository,\n  VoucherRepository,\n} from './port.js';\nimport { applyAuditCriteria } from './records/audit-filter.js';\nimport type { Asset } from './policies/expansion/assets/asset.js';\nimport type { CostingRun } from './policies/expansion/costing/costing-run.js';\nimport type { InventoryValuation } from './policies/expansion/inventory/inventory-valuation.js';\nimport type { Deferral } from './policies/expansion/deferrals/deferral.js';\nimport type { Provision } from './policies/expansion/provisions/provision.js';\nimport type { Partner } from './partner/partner.js';\nimport type { AccountNumber } from './substrate/account-number.js';\nimport type { CalendarDate } from './substrate/calendar-date.js';\nimport type { Uuid } from './substrate/uuid.js';\nimport type { Account } from './substrate/account.js';\nimport type { AuditRecord } from './records/audit-record.js';\nimport type { FiscalYear } from './substrate/fiscal-year.js';\nimport type { JournalEntry } from './substrate/journal-entry.js';\nimport type { OpenItem } from './records/open-item.js';\nimport type { Voucher } from './records/voucher.js';\n\nexport class InMemoryAccountRepository implements AccountRepository {\n  private readonly byNumberMap = new Map<string, Account>();\n  private readonly byIdMap = new Map<string, Account>();\n\n  add(account: Account): void {\n    if (this.byNumberMap.has(account.number.value)) {\n      throw new Error(`Repository contract violated: account number ${account.number.value} duplicated`);\n    }\n    this.byNumberMap.set(account.number.value, account);\n    this.byIdMap.set(account.id.value, account);\n  }\n\n  save(_account: Account): void {\n    // In-memory: object identity suffices.\n  }\n\n  byNumber(number: AccountNumber): Account | null {\n    return this.byNumberMap.get(number.value) ?? null;\n  }\n\n  byId(id: Uuid): Account | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  all(): Account[] {\n    return [...this.byNumberMap.values()].sort((a, b) => a.number.compareTo(b.number));\n  }\n}\n\nexport class InMemoryFiscalYearRepository implements FiscalYearRepository {\n  private readonly byYearMap = new Map<number, FiscalYear>();\n\n  add(fiscalYear: FiscalYear): void {\n    this.byYearMap.set(fiscalYear.year, fiscalYear);\n  }\n\n  save(_fiscalYear: FiscalYear): void {}\n\n  byYear(year: number): FiscalYear | null {\n    return this.byYearMap.get(year) ?? null;\n  }\n\n  forDate(date: CalendarDate): FiscalYear | null {\n    for (const fiscalYear of this.byYearMap.values()) {\n      if (fiscalYear.contains(date)) return fiscalYear;\n    }\n    return null;\n  }\n\n  all(): FiscalYear[] {\n    return [...this.byYearMap.values()].sort((a, b) => a.year - b.year);\n  }\n}\n\nexport class InMemoryJournalRepository implements JournalRepository {\n  private readonly entries: JournalEntry[] = [];\n  private readonly byIdMap = new Map<string, JournalEntry>();\n  private readonly sequences = new Map<number, number>();\n\n  append(entry: JournalEntry): void {\n    this.entries.push(entry);\n    this.byIdMap.set(entry.id.value, entry);\n    this.sequences.set(entry.periodRef.fiscalYear, entry.sequenceNumber);\n  }\n\n  save(_entry: JournalEntry): void {}\n\n  byId(id: Uuid): JournalEntry | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  nextSequenceNumber(fiscalYear: number): number {\n    return (this.sequences.get(fiscalYear) ?? 0) + 1;\n  }\n\n  all(): JournalEntry[] {\n    return [...this.entries].sort((a, b) =>\n      a.periodRef.fiscalYear !== b.periodRef.fiscalYear\n        ? a.periodRef.fiscalYear - b.periodRef.fiscalYear\n        : a.sequenceNumber - b.sequenceNumber,\n    );\n  }\n\n  forFiscalYear(fiscalYear: number): JournalEntry[] {\n    return this.entries\n      .filter((entry) => entry.periodRef.fiscalYear === fiscalYear)\n      .sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n  }\n}\n\nexport class InMemoryVoucherRepository implements VoucherRepository {\n  private readonly byIdMap = new Map<string, Voucher>();\n\n  add(voucher: Voucher): void {\n    this.byIdMap.set(voucher.id.value, voucher);\n  }\n\n  byId(id: Uuid): Voucher | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  all(): Voucher[] {\n    return [...this.byIdMap.values()].sort((a, b) =>\n      a.id.value < b.id.value ? -1 : a.id.value > b.id.value ? 1 : 0,\n    );\n  }\n}\n\nexport class InMemoryOpenItemRepository implements OpenItemRepository {\n  private readonly items: OpenItem[] = [];\n  private readonly byIdMap = new Map<string, OpenItem>();\n\n  add(item: OpenItem): void {\n    this.items.push(item);\n    this.byIdMap.set(item.id.value, item);\n  }\n\n  save(_item: OpenItem): void {}\n\n  byId(id: Uuid): OpenItem | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  byOriginEntry(entryId: Uuid): OpenItem[] {\n    return this.items.filter((item) => item.originEntryId.equals(entryId));\n  }\n\n  all(): OpenItem[] {\n    return [...this.items];\n  }\n}\n\nexport class InMemoryAuditTrail implements AuditTrail {\n  private readonly records: AuditRecord[] = [];\n\n  append(record: AuditRecord): void {\n    // The head is the last record's hash — a redacted shell keeps its own, so an erasure does not\n    // move the chain's tip and every later link still resolves.\n    const head = this.records.at(-1)?.recordHash ?? null;\n    this.records.push(record.chainedTo(head));\n  }\n\n  all(): AuditRecord[] {\n    return [...this.records];\n  }\n\n  eraseFor(objectType: string, objectId: Uuid): number {\n    let erased = 0;\n    for (let i = 0; i < this.records.length; i += 1) {\n      const record = this.records[i]!;\n      if (record.objectType === objectType && record.objectId.value === objectId.value) {\n        // Replaced by its shell, not removed: a deleted row would break the chain at the successor\n        // and leave every later verification reporting a manipulation that never happened.\n        this.records[i] = record.redactedShell();\n        erased += 1;\n      }\n    }\n    return erased;\n  }\n\n  find(criteria: AuditCriteria): { records: AuditRecord[]; count: number } {\n    return applyAuditCriteria(this.records, criteria);\n  }\n}\n\nexport class InMemoryPartnerRepository implements PartnerRepository {\n  private readonly byIdMap = new Map<string, Partner>();\n\n  add(partner: Partner): void {\n    this.byIdMap.set(partner.id.value, partner);\n  }\n\n  save(_partner: Partner): void {}\n\n  byId(id: Uuid): Partner | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  remove(id: Uuid): void {\n    this.byIdMap.delete(id.value);\n  }\n\n  all(): Partner[] {\n    return [...this.byIdMap.values()].sort((a, b) => {\n      const byName = a.name() < b.name() ? -1 : a.name() > b.name() ? 1 : 0;\n      return byName !== 0 ? byName : a.id.value < b.id.value ? -1 : a.id.value > b.id.value ? 1 : 0;\n    });\n  }\n}\n\n/**\n * The tenant record, in memory — the fake behind `TenantRecordRepository`.\n *\n * It stores a copy rather than the object it was handed, so a caller that keeps mutating its own\n * record cannot change what \"has been saved\" retroactively. That matters here more than in the\n * other fakes: this is the repository whose whole point is that a change outlives the object that\n * made it, and a fake that shares the reference would prove nothing.\n */\nexport class InMemoryTenantRecordRepository implements TenantRecordRepository {\n  private stored: TenantRecordData | null = null;\n\n  load(): TenantRecordData | null {\n    return this.stored === null ? null : (JSON.parse(JSON.stringify(this.stored)) as TenantRecordData);\n  }\n\n  save(record: TenantRecordData): void {\n    this.stored = JSON.parse(JSON.stringify(record)) as TenantRecordData;\n  }\n}\n\n/** Costing runs, in memory — the fake behind `CostingRunRepository`. */\nexport class InMemoryCostingRunRepository implements CostingRunRepository {\n  private readonly byIdMap = new Map<string, CostingRun>();\n\n  add(run: CostingRun): void {\n    this.byIdMap.set(run.id.value, run);\n  }\n\n  save(_run: CostingRun): void {}\n\n  byId(id: Uuid): CostingRun | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  all(): CostingRun[] {\n    return [...this.byIdMap.values()].sort((a, b) => {\n      const byYear = a.period.fiscalYear - b.period.fiscalYear;\n      if (byYear !== 0) return byYear;\n      const byPeriod = a.period.period - b.period.period;\n      return byPeriod !== 0 ? byPeriod : a.version - b.version;\n    });\n  }\n}\n\nexport class InMemoryInventoryValuationRepository implements InventoryValuationRepository {\n  private readonly items: InventoryValuation[] = [];\n\n  add(valuation: InventoryValuation): void {\n    this.items.push(valuation);\n  }\n\n  all(): InventoryValuation[] {\n    return [...this.items].sort((a, b) => {\n      const byYear = a.period.fiscalYear - b.period.fiscalYear;\n      if (byYear !== 0) return byYear;\n      const byPeriod = a.period.period - b.period.period;\n      return byPeriod !== 0 ? byPeriod : a.version - b.version;\n    });\n  }\n}\n\nexport class InMemoryDeferralRepository implements DeferralRepository {\n  private readonly items: Deferral[] = [];\n\n  add(deferral: Deferral): void {\n    this.items.push(deferral);\n  }\n\n  save(_deferral: Deferral): void {}\n\n  all(): Deferral[] {\n    return this.items;\n  }\n}\n\nexport class InMemoryProvisionRepository implements ProvisionRepository {\n  private readonly items: Provision[] = [];\n  private readonly byIdMap = new Map<string, Provision>();\n\n  add(provision: Provision): void {\n    this.items.push(provision);\n    this.byIdMap.set(provision.id.value, provision);\n  }\n\n  save(_provision: Provision): void {}\n\n  byId(id: Uuid): Provision | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  all(): Provision[] {\n    return this.items;\n  }\n}\n\nexport class InMemoryAssetRepository implements AssetRepository {\n  private readonly items: Asset[] = [];\n  private readonly byIdMap = new Map<string, Asset>();\n\n  add(asset: Asset): void {\n    this.items.push(asset);\n    this.byIdMap.set(asset.id.value, asset);\n  }\n\n  save(_asset: Asset): void {}\n\n  byId(id: Uuid): Asset | null {\n    return this.byIdMap.get(id.value) ?? null;\n  }\n\n  all(): Asset[] {\n    return [...this.items];\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport type { AccountNumber } from '../../../substrate/account-number.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Money } from '../../../substrate/money.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\nimport type { AssetRoute } from './asset-route.js';\n\ninterface Depreciation {\n  planMonth: number;\n  date: CalendarDate;\n  amount: Money;\n  entryId: Uuid;\n  kind: string;\n}\n\n/** Last day of the month `monthsToAdd` after `base` (1-based plan months). */\nfunction lastDayOfMonthAfter(base: CalendarDate, monthsToAdd: number): CalendarDate {\n  const totalMonth0 = base.month() - 1 + monthsToAdd;\n  const year = base.year() + Math.floor(totalMonth0 / 12);\n  const month0 = ((totalMonth0 % 12) + 12) % 12;\n  const lastDay = new Date(Date.UTC(year, month0 + 1, 0)).getUTCDate();\n  return CalendarDate.of(\n    `${String(year).padStart(4, '0')}-${String(month0 + 1).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`,\n  );\n}\n\n/**\n * Asset (assets-modell.md): master data + depreciation schedule + history. Invariants:\n * book value = acquisition cost − Σ depreciations, never < 0; no depreciation before acquisition/after disposal.\n */\nexport class Asset {\n  private readonly depreciations: Depreciation[] = [];\n\n  /**\n   * True once an unplanned write-down has rewritten the remaining plan. From then on the schedule IS\n   * the plan and may not be re-derived from the acquisition cost — the whole point of the write-down\n   * is that the cost is no longer the basis.\n   */\n  private scheduleRevised = false;\n\n  private reportedUnitsValue = 0;\n\n  /**\n   * The schedule as it stood before any write-down rebased it — the *shadow* plan.\n   *\n   * It exists for one purpose: the write-up ceiling. A write-down does not only reduce the book\n   * value, it lowers every remaining planned instalment, so the book value drifts *above* what it\n   * would have been without the write-down as the plan runs on. Reversing the write-down in full\n   * would therefore carry the asset higher than its amortised acquisition cost, which no write-up\n   * may do. The ceiling is `cost − Σ original shares of the booked months`, and the original shares\n   * are recoverable from nothing else once a rebase has happened: for a declining-balance or\n   * units-of-production plan they were never a flat allocate to begin with.\n   */\n  private originalSchedule: Money[] = [];\n\n  private disposed = false;\n  private disposedOn: CalendarDate | null = null;\n\n  constructor(\n    readonly id: Uuid,\n    readonly name: string,\n    readonly assetClass: string,\n    readonly assetAccount: AccountNumber,\n    readonly acquisitionCost: Money,\n    readonly acquiredOn: CalendarDate,\n    readonly route: AssetRoute,\n    readonly usefulLifeMonths: number | null,\n    public monthlySchedule: Money[],\n    readonly voucherId: Uuid,\n    /**\n     * Cost centre and friends, carried by the asset itself (IMPL-023). Depreciation is booked by the\n     * machine, month after month, for years — nobody is there to name a dimension at that moment,\n     * and a mandatory one on the depreciation account would otherwise make the run impossible. The\n     * master record answering it once is also how it works in practice: an asset belongs to a cost\n     * centre, and its depreciation belongs there with it.\n     */\n    readonly dimensions: ReadonlyArray<{ type: string; code: string }> = [],\n    /**\n     * First month of the depreciation plan. Normally the month of acquisition — pro rata temporis,\n     * which is what linear depreciation asks for in most jurisdictions.\n     *\n     * A pooled asset can be different: where a jurisdiction dissolves its pool in equal *fiscal-year*\n     * fractions, the first year is not shortened by the acquisition month, so the plan starts at the\n     * beginning of the fiscal year the asset was acquired in. Which of the two applies is pack data\n     * (`poolProRataInFirstYear`), never a decision of this class — the asset is simply told where its\n     * plan begins.\n     *\n     * Null means \"same as acquisition\", so persisted assets written before this field existed\n     * rehydrate to exactly the behaviour they had.\n     */\n    readonly depreciationStart: CalendarDate | null = null,\n    /**\n     * How the schedule was built. Straight line spreads the cost flat, so the yearly run can\n     * re-derive a year's share from the month counts; declining balance cannot, because each year\n     * depends on what is left after the one before. The schedule then IS the plan and has to be read\n     * rather than recomputed — that is the only thing this field decides.\n     *\n     * Null means straight line, so assets written before the field existed rehydrate unchanged.\n     */\n    readonly depreciationMethod: string | null = null,\n    /**\n     * An additional allowance running ALONGSIDE the plan, not instead of it.\n     *\n     * Some jurisdictions let a business deduct an extra share of the cost within the first few years,\n     * freely distributed over them. It is not a depreciation method — the ordinary plan carries on\n     * untouched on the original basis while the window is open — so it cannot be expressed as a\n     * different schedule. It is a budget: this much may still be taken, until this fiscal year. Both\n     * numbers come from the pack; the asset only remembers them.\n     *\n     * Null means no such allowance was elected, which is every asset written before this existed.\n     */\n    readonly specialDepreciationBudget: Money | null = null,\n    readonly specialDepreciationWindowEnd: number | null = null,\n    /**\n     * Total expected output of the asset, where depreciation follows use rather than time —\n     * kilometres for a lorry, operating hours for a press, copies for a machine.\n     *\n     * It changes what \"a year\" means. Time-based depreciation knows at acquisition what every future\n     * period will take; output-based depreciation cannot, because the number comes from outside the\n     * books. So there is no schedule to build and the yearly run has nothing to do here: usage is\n     * reported as it happens, and each report books the difference between what the asset has now\n     * given and what has already been written off.\n     */\n    readonly totalUnits: number | null = null,\n  ) {\n    // The shadow plan starts as the plan. It only diverges when a write-down rebases the live one,\n    // which is exactly when the write-up ceiling starts to need it.\n    this.originalSchedule = [...monthlySchedule];\n  }\n\n  /** Units reported so far — never more than `totalUnits`, which is what caps the last booking. */\n  reportedUnits(): number {\n    return this.reportedUnitsValue;\n  }\n\n  recordUsage(date: CalendarDate, amount: Money, entryId: Uuid, unitsAfter: number): void {\n    this.reportedUnitsValue = unitsAfter;\n    this.depreciations.push({ planMonth: 0, date, amount, entryId, kind: 'usage' });\n  }\n\n  /** What is left of the additional allowance. */\n  specialDepreciationRemaining(): Money | null {\n    if (this.specialDepreciationBudget === null) return null;\n\n    let used = this.specialDepreciationBudget.subtract(this.specialDepreciationBudget);\n    for (const booking of this.depreciations) {\n      if (booking.kind === 'special') used = used.add(booking.amount);\n    }\n\n    return this.specialDepreciationBudget.subtract(used);\n  }\n\n  hasSpecialDepreciation(): boolean {\n    if (this.specialDepreciationBudget === null) return false;\n    return this.depreciations.some((booking) => booking.kind === 'special');\n  }\n\n  recordSpecialDepreciation(date: CalendarDate, amount: Money, entryId: Uuid): void {\n    // No re-spreading here, unlike a write-down. While the window is open the ordinary plan runs on\n    // the original basis — that is what \"alongside\" means, and lowering it now would quietly take back\n    // part of the allowance the same year it was granted. The plan is re-based once, after the window\n    // closes.\n    this.depreciations.push({ planMonth: 0, date, amount, entryId, kind: 'special' });\n  }\n\n  /**\n   * Spreads whatever book value is left over the plan months not yet booked.\n   *\n   * Two occasions need exactly this: an unplanned write-down, where the basis fell; and the end of an\n   * additional allowance's window, where part of the cost has already been deducted outside the plan\n   * and the rest has to last for the remaining life. Same arithmetic, and it should stay the same\n   * arithmetic — two spreadings that drifted apart would be two different answers to one question.\n   */\n  rebaseRemainingPlan(openPlanMonths: number[]): void {\n    this.scheduleRevised = true;\n\n    if (openPlanMonths.length === 0) return;\n\n    const remaining = this.acquisitionCost.subtract(this.accumulatedDepreciationAt(null));\n    const shares = remaining.allocate(...openPlanMonths.map(() => 1));\n\n    openPlanMonths.forEach((planMonth, index) => {\n      this.monthlySchedule[planMonth - 1] = shares[index]!;\n    });\n  }\n\n  /** Straight line unless the pack offered, and the caller chose, something else. */\n  method(): string {\n    return this.depreciationMethod ?? 'straight_line';\n  }\n\n  /** A schedule that cannot be re-derived from month counts and must be read as it stands. */\n  scheduleIsAuthoritative(): boolean {\n    return this.method() !== 'straight_line' || this.scheduleRevised;\n  }\n\n  scheduleWasRevised(): boolean {\n    return this.scheduleRevised;\n  }\n\n  /** Where the depreciation plan begins — the acquisition month unless the pack moved it. */\n  planStart(): CalendarDate {\n    return this.depreciationStart ?? this.acquiredOn;\n  }\n\n  /** When it left, or null while it is still there — read by the movement schedule (F-CORE-055). */\n  disposedOnDate(): CalendarDate | null {\n    return this.disposedOn;\n  }\n\n  isDisposed(): boolean {\n    return this.disposed;\n  }\n\n  assertActive(): void {\n    if (this.disposed) {\n      throw new DomainError(\n        'E_ASSET_DISPOSED',\n        `asset ${this.id.value} is already disposed (${this.disposedOn?.iso ?? '?'})`,\n        { assetId: this.id.value },\n      );\n    }\n  }\n\n  dispose(disposedOn: CalendarDate): void {\n    this.assertActive();\n    this.disposed = true;\n    this.disposedOn = disposedOn;\n  }\n\n  planMonthDate(planMonth: number): CalendarDate {\n    return lastDayOfMonthAfter(this.planStart(), planMonth - 1);\n  }\n\n  isMonthBooked(planMonth: number): boolean {\n    return this.depreciations.some((booking) => booking.planMonth === planMonth);\n  }\n\n  recordDepreciation(planMonth: number, date: CalendarDate, amount: Money, entryId: Uuid, kind = 'planned'): void {\n    this.depreciations.push({ planMonth, date, amount, entryId, kind });\n  }\n\n  /**\n   * An unplanned write-down: the amount lowers the book value at once, and what is left is spread over\n   * the plan months that have not been booked yet.\n   *\n   * Re-spreading is the part that is easy to leave out and wrong to leave out. Continuing the old plan\n   * after a write-down would depreciate more than the asset is still worth — the invariant says the\n   * book value never goes below zero — and stopping early instead would finish the asset before its\n   * life is over. Neither is what a lasting impairment means: the reduced value is carried on over the\n   * REMAINING life, which is exactly what this does.\n   *\n   * `planMonth: 0` marks it as belonging to no plan month; plan months are 1-based, so nothing reads\n   * it as one, while the accumulated depreciation picks it up like any other booking.\n   */\n  recordWriteDown(date: CalendarDate, amount: Money, entryId: Uuid, openPlanMonths: number[]): void {\n    this.depreciations.push({ planMonth: 0, date, amount, entryId, kind: 'unplanned' });\n    this.rebaseRemainingPlan(openPlanMonths);\n  }\n\n  /**\n   * A write-up reverses part of an earlier write-down. It is recorded as a negative \"unplanned\"\n   * booking, so every existing reader — accumulated depreciation, the book value, the register —\n   * picks it up without a special case, and the plan is rebased upward the same way a write-down\n   * rebases it downward.\n   */\n  recordWriteUp(date: CalendarDate, amount: Money, entryId: Uuid, openPlanMonths: number[]): void {\n    this.depreciations.push({ planMonth: 0, date, amount: amount.negate(), entryId, kind: 'writeUp' });\n    this.rebaseRemainingPlan(openPlanMonths);\n  }\n\n  /**\n   * What the book value would be if no write-down had ever happened — the ceiling a write-up may\n   * not cross.\n   *\n   * Every month the live plan has booked is charged at its **original** share instead of the reduced\n   * one. An asset that was never written down has an identical shadow, so this equals the ordinary\n   * book value and the ceiling binds nothing.\n   */\n  amortisedCostCeiling(): Money {\n    let shadowAccumulated = this.acquisitionCost.subtract(this.acquisitionCost);\n\n    for (const booking of this.depreciations) {\n      // A write-down or a usage report is not part of any plan — the shadow ignores it, which is\n      // the whole point: the shadow is the plan that never saw the write-down.\n      if (booking.planMonth < 1) continue;\n      const share = this.originalSchedule[booking.planMonth - 1];\n      if (share !== undefined) shadowAccumulated = shadowAccumulated.add(share);\n    }\n\n    return this.acquisitionCost.subtract(shadowAccumulated);\n  }\n\n  /** What has been written down and not yet written back — nothing may be reversed twice. */\n  unreversedWriteDowns(): Money {\n    let sum = this.acquisitionCost.subtract(this.acquisitionCost);\n\n    for (const booking of this.depreciations) {\n      // A write-up booking is already negative, so adding it subtracts.\n      if (booking.kind === 'unplanned' || booking.kind === 'writeUp') sum = sum.add(booking.amount);\n    }\n\n    return sum;\n  }\n\n  originalScheduleShares(): Money[] {\n    return this.originalSchedule;\n  }\n\n  /** Depreciation history in persistable form — counterpart to PHP's `depreciationsForPersistence`. */\n  depreciationsForPersistence(): Array<{\n    planMonth: number;\n    date: string;\n    amount: { amount: string; currency: string };\n    entryId: string;\n    kind: string;\n  }> {\n    return this.depreciations.map((booking) => ({\n      planMonth: booking.planMonth,\n      date: booking.date.iso,\n      amount: booking.amount.toJSON(),\n      entryId: booking.entryId.value,\n      kind: booking.kind,\n    }));\n  }\n\n  /**\n   * Restore from persistence: set master data + depreciation history + disposal\n   * status directly (no re-validation) — counterpart to PHP's `Asset::restore`.\n   */\n  static restore(\n    id: Uuid,\n    name: string,\n    assetClass: string,\n    assetAccount: AccountNumber,\n    acquisitionCost: Money,\n    acquiredOn: CalendarDate,\n    route: AssetRoute,\n    usefulLifeMonths: number | null,\n    monthlySchedule: Money[],\n    voucherId: Uuid,\n    depreciations: ReadonlyArray<{ planMonth: number; date: CalendarDate; amount: Money; entryId: Uuid; kind?: string }>,\n    disposed: boolean,\n    disposedOn: CalendarDate | null,\n    dimensions: ReadonlyArray<{ type: string; code: string }> = [],\n    depreciationStart: CalendarDate | null = null,\n    depreciationMethod: string | null = null,\n    scheduleRevised = false,\n    specialDepreciationBudget: Money | null = null,\n    specialDepreciationWindowEnd: number | null = null,\n    totalUnits: number | null = null,\n    reportedUnits = 0,\n    // Null for an asset written before the shadow plan existed — and that is the right answer rather\n    // than a fallback: such an asset either has no write-down (so the shadow IS the live plan) or one\n    // booked before a write-up was possible at all.\n    originalSchedule: Money[] | null = null,\n  ): Asset {\n    const asset = new Asset(\n      id,\n      name,\n      assetClass,\n      assetAccount,\n      acquisitionCost,\n      acquiredOn,\n      route,\n      usefulLifeMonths,\n      monthlySchedule,\n      voucherId,\n      dimensions,\n      depreciationStart,\n      depreciationMethod,\n      specialDepreciationBudget,\n      specialDepreciationWindowEnd,\n      totalUnits,\n    );\n    asset.reportedUnitsValue = reportedUnits;\n    for (const booking of depreciations) {\n      asset.depreciations.push({\n        planMonth: booking.planMonth,\n        date: booking.date,\n        amount: booking.amount,\n        entryId: booking.entryId,\n        // A booking written before write-downs existed is a planned one — that is what it was.\n        kind: booking.kind ?? 'planned',\n      });\n    }\n    asset.scheduleRevised = scheduleRevised;\n    asset.originalSchedule = originalSchedule ?? [...monthlySchedule];\n    asset.disposed = disposed;\n    asset.disposedOn = disposedOn;\n    return asset;\n  }\n\n  accumulatedDepreciationAt(asOf: CalendarDate | null): Money {\n    let sum = this.acquisitionCost.subtract(this.acquisitionCost); // 0 in tenant currency\n    for (const booking of this.depreciations) {\n      if (asOf !== null && booking.date.isAfter(asOf)) continue;\n      sum = sum.add(booking.amount);\n    }\n    return sum;\n  }\n\n  /**\n   * Carrying amount = cost less what has been depreciated (IMPL-024).\n   *\n   * Only an immediately expensed asset has no carrying amount — it was never capitalised. A\n   * *pooled* one was: it sits on the pool account and is written down over the pack's term, so\n   * reporting zero for it made the fixed-asset schedule (F-AST-005) understate the balance sheet\n   * it is supposed to explain. The old shortcut was invisible while nothing consumed the value\n   * for pooled assets; the disposal write-off does now.\n   */\n  bookValueAt(asOf: CalendarDate | null): Money {\n    if (this.route === 'immediate_expense') return this.acquisitionCost.subtract(this.acquisitionCost);\n    return this.acquisitionCost.subtract(this.accumulatedDepreciationAt(asOf));\n  }\n\n  scheduleSummary(): Record<string, string> {\n    if (this.monthlySchedule.length === 0) return {};\n\n    const summary: Record<string, string> = {};\n    let total = this.acquisitionCost.subtract(this.acquisitionCost);\n    let runStart = 1;\n\n    this.monthlySchedule.forEach((amount, index) => {\n      total = total.add(amount);\n      const isLast = index === this.monthlySchedule.length - 1;\n      const next = isLast ? null : this.monthlySchedule[index + 1]!;\n      if (next !== null && next.equals(amount)) return;\n      summary[`months${runStart}to${index + 1}`] = amount.amountAsString();\n      runStart = index + 2;\n    });\n\n    summary.total = total.amountAsString();\n    return summary;\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      name: this.name,\n      assetClass: this.assetClass,\n      assetAccount: this.assetAccount.value,\n      route: this.route,\n      acquisitionCost: this.acquisitionCost.toJSON(),\n      acquiredOn: this.acquiredOn.iso,\n      usefulLifeMonths: this.usefulLifeMonths,\n      status: this.disposed ? 'disposed' : 'active',\n      disposedOn: this.disposedOn?.iso ?? null,\n      voucherId: this.voucherId.value,\n      dimensions: this.dimensions.map((d) => ({ type: d.type, code: d.code })),\n      depreciationMethod: this.method(),\n    };\n  }\n}\n","/** Low-value-asset switch (SF-05): three routes; the thresholds are rule-module data. */\nexport type AssetRoute = 'capitalize' | 'immediate_expense' | 'pool';\n\nexport function parseAssetRoute(value: unknown): AssetRoute | null {\n  return value === 'capitalize' || value === 'immediate_expense' || value === 'pool' ? value : null;\n}\n","import { DomainError, rejectedValue } from '../../../domain-error.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { Ledger } from '../../../ledger/ledger.js';\nimport { Voucher } from '../../../records/voucher.js';\nimport type { AssetRepository, FiscalYearRepository, VoucherRepository } from '../../../port.js';\nimport { AccountNumber } from '../../../substrate/account-number.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport type { IdGenerator } from '../../../substrate/id-generator.js';\nimport { Money } from '../../../substrate/money.js';\nimport { Uuid } from '../../../substrate/uuid.js';\nimport { Asset } from './asset.js';\nimport { type AssetRoute, parseAssetRoute } from './asset-route.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\ninterface Threshold {\n  validFrom: string;\n  validTo: string | null;\n  immediateMax: string;\n  poolMin: string | null;\n  poolMax: string | null;\n  poolYears: number | null;\n  poolReducedOnDisposal: boolean | null;\n  poolProRataInFirstYear: boolean | null;\n}\n\n/**\n * Asset subledger (assets-modell.md): low-value-asset switch at acquisition,\n * depreciation run idempotent per run target, postings through the ledger (finalized immediately).\n * Depreciation distribution: monthly values = allocate of the acquisition cost over the useful life (flat).\n */\nexport class AssetService {\n  private ruleModule: Record<string, unknown> = {};\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly assets: AssetRepository,\n    private readonly fiscalYears: FiscalYearRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly ledger: Ledger,\n    private readonly ids: IdGenerator,\n    // An asset run posts through the ledger, so `journalEntry/created` records exist — but\n    // nothing in them says *an asset was acquired*. These records carry the asset event\n    // itself (F-CORE-014); the depreciation run has no object of its own, so it names the\n    // tenant, like the configuration singletons.\n    private readonly tenantId: Uuid | null = null,\n    private readonly audit: AuditWriter | null = null,\n  ) {}\n\n  private trace(\n    input: Record<string, unknown>,\n    objectType: string,\n    objectId: Uuid,\n    action: string,\n    changes: Record<string, { from: unknown; to: unknown }>,\n  ): void {\n    if (this.audit === null) return;\n    this.audit.record(this.audit.actorOf(input), objectType, objectId, action, changes);\n  }\n\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  acquire(input: Record<string, unknown>): Record<string, unknown> {\n    const name = asString(input.name) ?? '';\n    const assetClass = asString(input.assetClass) ?? '';\n    const assetAccount = AccountNumber.of(asString(input.assetAccount) ?? '0');\n    const cost = this.parseMoney(input.acquisitionCost);\n    const acquiredOn = CalendarDate.of(asString(input.acquiredOn) ?? '');\n    const voucherIdRaw = asString(input.voucherId);\n    if (voucherIdRaw === null) throw new InvalidValue('acquireAsset requires voucherId');\n    const voucherId = Uuid.fromString(voucherIdRaw);\n    const choice = asString(input.gwgChoice) ?? 'auto';\n    const dimensions = AssetService.parseDimensions(input.dimensions);\n\n    const special = input.specialDepreciation === true;\n    const totalUnits = AssetService.parseTotalUnits(input.totalUnits);\n    const route = this.resolveRoute(choice, cost, acquiredOn);\n    const explicitLife = AssetService.parseUsefulLifeMonths(input.usefulLifeMonths);\n    const method = AssetService.parseMethod(input.depreciationMethod);\n\n    // Same again: an additional allowance is a share of a capitalised asset's cost, and there is\n    // nothing for it to attach to on a route that expenses the whole cost at once.\n    if (special && route !== 'capitalize') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `acquireAsset: \"specialDepreciation\" applies to a capitalised asset, not to route \"${route}\"`,\n        { route },\n      );\n    }\n\n    // Refused, not ignored. A pooled asset takes its term from the pack's poolYears and an\n    // immediately expensed one has no schedule at all, so a life given with either route cannot be\n    // honoured — and dropping it in silence would let a caller believe a number took effect that\n    // never did.\n    if (explicitLife !== null && route !== 'capitalize') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `acquireAsset: \"usefulLifeMonths\" applies to a capitalised asset, not to route \"${route}\"`,\n        { usefulLifeMonths: explicitLife, route },\n      );\n    }\n\n    // Same reasoning as the useful life: a method cannot apply to a route that has no schedule of\n    // its own, and accepting it in silence would suggest it took effect.\n    if (method !== 'straight_line' && route !== 'capitalize') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `acquireAsset: \"depreciationMethod\" applies to a capitalised asset, not to route \"${route}\"`,\n        { depreciationMethod: method, route },\n      );\n    }\n\n    let usefulLifeMonths: number | null = null;\n    const schedule: Money[] = [];\n    if (route === 'capitalize') {\n      // The caller's own figure wins over the class average. A table of class averages cannot serve a\n      // jurisdiction that lets a taxpayer prove a shorter life for an individual asset, however\n      // complete the table is — and without this parameter an asset class missing from the pack was\n      // simply unusable.\n      usefulLifeMonths = explicitLife ?? this.usefulLifeMonths(assetClass);\n      // No schedule for output-based depreciation, on purpose. It cannot know at acquisition what any\n      // future period will take — the number comes from outside the books — so there is nothing to\n      // plan and the yearly run has nothing to do for this asset.\n      if (method !== 'units_of_production') {\n        schedule.push(\n          ...(method === 'declining_balance'\n            ? this.decliningBalanceSchedule(cost, usefulLifeMonths, acquiredOn, assetClass)\n            : cost.allocateEvenly(usefulLifeMonths)),\n        );\n      }\n    } else if (route === 'pool') {\n      // Pool period comes from the pack (SPEC-004): a fixed five years used to sit here, which is one\n      // jurisdiction's rule, so every other jurisdiction with a pooled de-minimis regime would have\n      // inherited it silently. The pack says over how long; the core only spreads it evenly.\n      const poolYears = this.poolYears(acquiredOn);\n      usefulLifeMonths = poolYears * 12;\n      for (const yearAmount of cost.allocateEvenly(poolYears)) {\n        schedule.push(...yearAmount.allocateEvenly(12));\n      }\n    }\n\n    if (method === 'units_of_production' && totalUnits === null) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'acquireAsset: \"units_of_production\" needs \"totalUnits\" — the expected output is what replaces the schedule',\n        { depreciationMethod: method },\n      );\n    }\n\n    if (totalUnits !== null && method !== 'units_of_production') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'acquireAsset: \"totalUnits\" applies to \"units_of_production\", and would have no effect otherwise',\n        { depreciationMethod: method },\n      );\n    }\n\n    const [specialBudget, specialWindowEnd] = special\n      ? this.specialDepreciationTerms(cost, acquiredOn, assetClass)\n      : [null, null];\n\n    const asset = new Asset(\n      this.ids.next(),\n      name,\n      assetClass,\n      assetAccount,\n      cost,\n      acquiredOn,\n      route,\n      usefulLifeMonths,\n      schedule,\n      voucherId,\n      dimensions,\n      this.planStartFor(route, acquiredOn),\n      method,\n      specialBudget,\n      specialWindowEnd,\n      totalUnits,\n    );\n    this.assets.add(asset);\n\n    const targetAccount = route === 'immediate_expense' ? this.gwgExpenseAccount() : assetAccount.value;\n    this.postMachineEntry(acquiredOn, voucherId, `Asset acquisition ${name}`, this.withDimensions(asset, [\n      { account: targetAccount, side: 'debit', money: cost.toJSON() },\n      { account: this.counterAccount(), side: 'credit', money: cost.toJSON() },\n    ]));\n\n    this.trace(input, 'asset', asset.id, 'acquired', {\n      name: { from: null, to: name },\n      assetClass: { from: null, to: assetClass },\n      acquiredOn: { from: null, to: acquiredOn.iso },\n      route: { from: null, to: route },\n    });\n\n    const result = asset.toJSON();\n    result.route = route;\n    if (route === 'immediate_expense') result.expenseAccount = targetAccount;\n    return result;\n  }\n\n  dispose(input: Record<string, unknown>): Record<string, unknown> {\n    const asset = this.requireAsset(input.assetId);\n    asset.assertActive();\n\n    const disposedOn = CalendarDate.of(asString(input.disposedOn) ?? '');\n    asset.dispose(disposedOn);\n    this.assets.save(asset);\n\n    const proceeds = isRecord(input.proceeds) ? this.parseMoney(input.proceeds) : null;\n    const bankAccount = asString(input.bankAccount) ?? this.counterAccount();\n    const voucherId = asString(input.voucherId) ? Uuid.fromString(asString(input.voucherId)!) : asset.voucherId;\n\n    // Where the pack keeps a disposed item in the pool (F-AST-006, see runDepreciation), the pool\n    // keeps running its term and there is no carrying amount of its own to clear — only the\n    // proceeds are booked. Where the pack takes it out, it is written off like any other asset.\n    const staysPooled = this.staysInPool(asset);\n    if (!staysPooled) this.catchUpDepreciation(asset, disposedOn, voucherId);\n    // What is written off is what stands on the account, not what an as-of query says stood there\n    // on the disposal date (IMPL-026). The two are not the same: a yearly run books the whole year\n    // in one entry dated 31 December, so a disposal on 30 September read the carrying amount, saw\n    // that entry as later than itself, ignored it, and wrote off the full acquisition cost — of\n    // which the run had already written off a part. The asset account was left at a credit balance\n    // that nothing clears, while the entry balanced and every invariant held. Every other reader of\n    // the accumulated depreciation in this service already asks the whole ledger; the disposal was\n    // the only as-of query, and it is the one place an as-of query cannot be right, because what\n    // leaves the account must equal what stands on it (F-AST-004).\n    const carrying = staysPooled ? Money.zero(this.baseCurrency) : asset.bookValueAt(null);\n    const lines = this.disposalLines(asset, carrying, proceeds, bankAccount, asString(input.proceedsAccount));\n\n    if (lines.length > 0) {\n      this.postMachineEntry(disposedOn, voucherId, `Asset disposal ${asset.name}`, this.withDimensions(asset, lines));\n    }\n\n    this.trace(input, 'asset', asset.id, 'disposed', {\n      status: { from: 'active', to: 'disposed' },\n      disposedOn: { from: null, to: disposedOn.iso },\n    });\n\n    return asset.toJSON();\n  }\n\n  /**\n   * Reports what the asset has produced, and writes off what that use consumed.\n   *\n   * Where a jurisdiction allows it, an asset that wears by use rather than by time may be depreciated\n   * by output — kilometres, operating hours, copies. There is nothing to plan: the number comes from\n   * goods movements, meter readings, job cards, none of which are in the books. So the caller reports\n   * the meter and the core does the arithmetic.\n   *\n   * The arithmetic is cumulative on purpose. Each report splits the acquisition cost between what the\n   * asset has now given and what it has not, and books the difference against what is already written\n   * off. Computing each period on its own would let rounding drift, and the last report would leave a\n   * stray cent behind on an asset that is fully used up. This way the final report, the one that\n   * reaches the total output, lands on the cost exactly.\n   *\n   * More output than expected is not an error — a lorry can outlive its estimate — but there is no\n   * more cost to write off, so the booking is capped at the book value and the answer says so.\n   */\n  reportAssetUsage(input: Record<string, unknown>): Record<string, unknown> {\n    const asset = this.requireAsset(input.assetId);\n    asset.assertActive();\n\n    if (asset.totalUnits === null) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `asset ${asset.id.value} is not depreciated by output — \"units_of_production\" has to be chosen on acquisition`,\n        { assetId: asset.id.value },\n      );\n    }\n\n    const units = AssetService.parseTotalUnits(input.units);\n    if (units === null) {\n      throw new DomainError('E_INPUT_INVALID', 'reportAssetUsage: \"units\" is required', {\n        assetId: asset.id.value,\n      });\n    }\n\n    const fiscalYear = typeof input.fiscalYear === 'number' ? input.fiscalYear : 0;\n    const bookValue = asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null));\n\n    if (bookValue.isZero()) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `asset ${asset.id.value} is already fully depreciated — further output has nothing left to write off`,\n        { assetId: asset.id.value },\n      );\n    }\n\n    const cumulative = asset.reportedUnits() + units;\n    const capped = cumulative > asset.totalUnits;\n    const effective = capped ? asset.totalUnits : cumulative;\n\n    const target =\n      effective === asset.totalUnits\n        ? asset.acquisitionCost\n        : asset.acquisitionCost.allocate(effective, asset.totalUnits - effective)[0]!;\n\n    const written = asset.accumulatedDepreciationAt(null);\n    const amount = target.subtract(written);\n\n    if (amount.isNegative() || amount.isZero()) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `reported output for asset ${asset.id.value} writes off nothing — ${asset.reportedUnits()} of ${asset.totalUnits} units are already accounted for`,\n        { assetId: asset.id.value },\n      );\n    }\n\n    const date = CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-12-31`);\n\n    const voucherId =\n      typeof input.voucherId === 'string' && input.voucherId !== ''\n        ? this.requireVoucherId(input.voucherId)\n        : this.usageVoucher(asset, fiscalYear);\n\n    const entry = this.postMachineEntry(\n      date,\n      voucherId,\n      `Output depreciation ${asset.name} ${fiscalYear} (${units} units)`,\n      this.withDimensions(asset, [\n        { account: this.depreciationExpenseAccount(), side: 'debit', money: amount.toJSON() },\n        { account: asset.assetAccount.value, side: 'credit', money: amount.toJSON() },\n      ]),\n    );\n\n    const before = asset.reportedUnits();\n    asset.recordUsage(date, amount, entry, effective);\n    this.assets.save(asset);\n\n    this.trace(input, 'asset', asset.id, 'usageReported', {\n      reportedUnits: { from: String(before), to: String(effective) },\n      bookValue: {\n        from: bookValue.amountAsString(),\n        to: asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null)).amountAsString(),\n      },\n    });\n\n    return {\n      assetId: asset.id.value,\n      entryId: entry.value,\n      amount: amount.amountAsString(),\n      reportedUnits: effective,\n      totalUnits: asset.totalUnits,\n      capped,\n      bookValue: asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null)).amountAsString(),\n    };\n  }\n\n  private usageVoucher(asset: Asset, fiscalYear: number): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `LAFA-${fiscalYear}-${asset.id.value.slice(-6)}`,\n      voucherDate: CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-12-31`),\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n    return voucher.id;\n  }\n\n  /**\n   * Books part of an additional allowance (see `Asset.specialDepreciationBudget`).\n   *\n   * Two things make this an operation rather than a plan. The amount is the taxpayer's to choose — a\n   * jurisdiction that grants \"up to 40 % over five years\" grants exactly that, and any split is as\n   * valid as any other — and the entitlement itself is a question about the business (a profit limit,\n   * a share of business use) that summae has no way to check and does not pretend to. So the caller\n   * says how much and when, and the core enforces only what it can know: not more than the budget,\n   * not outside the window, not on an asset that has none.\n   */\n  bookSpecialDepreciation(input: Record<string, unknown>): Record<string, unknown> {\n    const asset = this.requireAsset(input.assetId);\n    asset.assertActive();\n\n    const remaining = asset.specialDepreciationRemaining();\n    if (remaining === null || asset.specialDepreciationWindowEnd === null) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `asset ${asset.id.value} carries no special depreciation — it has to be elected on acquisition`,\n        { assetId: asset.id.value },\n      );\n    }\n\n    const fiscalYear = typeof input.fiscalYear === 'number' ? input.fiscalYear : 0;\n    const firstYear = this.planMonthYear(asset, 1);\n\n    if (fiscalYear < firstYear || fiscalYear > asset.specialDepreciationWindowEnd) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `special depreciation for asset ${asset.id.value} is available in ${firstYear} through ${asset.specialDepreciationWindowEnd}, not in ${fiscalYear}`,\n        { fiscalYear },\n      );\n    }\n\n    const amount = this.parseMoney(input.amount);\n    if (amount.isNegative() || amount.isZero()) {\n      throw new DomainError('E_INPUT_INVALID', 'bookSpecialDepreciation: \"amount\" must be greater than zero', {\n        amount: amount.amountAsString(),\n      });\n    }\n\n    if (amount.compareTo(remaining) > 0) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `special depreciation of ${amount.amountAsString()} exceeds the remaining allowance of ${remaining.amountAsString()}`,\n        { amount: amount.amountAsString(), remaining: remaining.amountAsString() },\n      );\n    }\n\n    const date = CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-12-31`);\n\n    const voucherId =\n      typeof input.voucherId === 'string' && input.voucherId !== ''\n        ? this.requireVoucherId(input.voucherId)\n        : this.specialDepreciationVoucher(asset, fiscalYear);\n\n    const entry = this.postMachineEntry(\n      date,\n      voucherId,\n      `Special depreciation ${asset.name} ${fiscalYear}`,\n      this.withDimensions(asset, [\n        { account: this.depreciationExpenseAccount(), side: 'debit', money: amount.toJSON() },\n        { account: asset.assetAccount.value, side: 'credit', money: amount.toJSON() },\n      ]),\n    );\n\n    asset.recordSpecialDepreciation(date, amount, entry);\n    this.assets.save(asset);\n\n    const left = asset.specialDepreciationRemaining();\n\n    this.trace(input, 'asset', asset.id, 'specialDepreciationBooked', {\n      remainingAllowance: { from: remaining.amountAsString(), to: left?.amountAsString() ?? null },\n      fiscalYear: { from: null, to: String(fiscalYear) },\n    });\n\n    return {\n      assetId: asset.id.value,\n      entryId: entry.value,\n      amount: amount.amountAsString(),\n      remainingAllowance: left?.amountAsString() ?? null,\n      bookValue: asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null)).amountAsString(),\n    };\n  }\n\n  private specialDepreciationVoucher(asset: Asset, fiscalYear: number): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `SAFA-${fiscalYear}-${asset.id.value.slice(-6)}`,\n      voucherDate: CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-12-31`),\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n    return voucher.id;\n  }\n\n  /**\n   * Rate and window of the additional allowance, from the pack. Refused rather than defaulted, like\n   * every other pack question here: a core that invents \"40 % over five years\" has one jurisdiction's\n   * tax policy in the substrate.\n   */\n  private specialDepreciationTerms(cost: Money, acquiredOn: CalendarDate, assetClass: string): [Money, number] {\n    const raw = Array.isArray(this.ruleModule.specialDepreciation) ? this.ruleModule.specialDepreciation : [];\n\n    for (const item of raw) {\n      if (!isRecord(item) || typeof item.validFrom !== 'string') continue;\n\n      const validFrom = CalendarDate.of(item.validFrom);\n      const validTo = typeof item.validTo === 'string' ? CalendarDate.of(item.validTo) : null;\n      if (acquiredOn.isBefore(validFrom) || (validTo !== null && acquiredOn.isAfter(validTo))) continue;\n\n      const rate = typeof item.rate === 'string' ? item.rate : null;\n      const years = typeof item.years === 'number' && Number.isSafeInteger(item.years) ? item.years : null;\n      if (rate === null || years === null || years < 1) continue;\n\n      const rest = String(Math.round((100 - Number(rate)) * 10000) / 10000);\n      const budget = cost.allocate(rate, rest)[0]!;\n\n      return [budget, acquiredOn.year() + years - 1];\n    }\n\n    throw new DomainError(\n      'E_PACK_INCOHERENT',\n      `special depreciation was elected, but the pack declares no allowance in force on ${acquiredOn.iso}`,\n      { field: 'specialDepreciation', acquiredOn: acquiredOn.iso, assetClass },\n    );\n  }\n\n  /**\n   * An unplanned write-down — the value fell, and not because time passed.\n   *\n   * The planned schedule answers wear and tear; it has nothing to say about a machine damaged in March\n   * or a building whose neighbourhood lost its factory. Where the loss is expected to last, writing\n   * the asset down is not an option a preparer takes but an obligation, and until now the only ways to\n   * express it were disposing of the asset (wrong — it still exists) or posting by hand past the asset\n   * register (wrong — the register then disagrees with the ledger about what the asset is worth).\n   *\n   * A reason is required. An unplanned write-down that does not say why is not auditable, and \"why\" is\n   * the whole difference between an impairment and a mistake.\n   *\n   * The remaining plan is rewritten: what is left after the write-down is spread over the plan months\n   * still open. Leaving the plan alone would depreciate past zero; stopping the plan would finish the\n   * asset early. Carrying the reduced value over the remaining life is what a lasting impairment means.\n   */\n  writeDownAsset(input: Record<string, unknown>): Record<string, unknown> {\n    const asset = this.requireAsset(input.assetId);\n    asset.assertActive();\n\n    const reason = typeof input.reason === 'string' ? input.reason.trim() : '';\n    if (reason === '') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'writeDownAsset: \"reason\" is required — an unplanned write-down that does not say why is not auditable',\n        { assetId: asset.id.value },\n      );\n    }\n\n    const amount = this.parseMoney(input.amount);\n    if (amount.isNegative() || amount.isZero()) {\n      throw new DomainError('E_INPUT_INVALID', 'writeDownAsset: \"amount\" must be greater than zero', {\n        amount: amount.amountAsString(),\n      });\n    }\n\n    const bookValue = asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null));\n    if (amount.compareTo(bookValue) > 0) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `writeDownAsset: ${amount.amountAsString()} exceeds the book value of ${bookValue.amountAsString()} — an asset cannot be written below zero`,\n        { amount: amount.amountAsString(), bookValue: bookValue.amountAsString() },\n      );\n    }\n\n    const date = CalendarDate.of(typeof input.date === 'string' ? input.date : '');\n\n    const openPlanMonths: number[] = [];\n    for (let planMonth = 1; planMonth <= asset.monthlySchedule.length; planMonth++) {\n      if (!asset.isMonthBooked(planMonth)) openPlanMonths.push(planMonth);\n    }\n\n    const voucherId =\n      typeof input.voucherId === 'string' && input.voucherId !== ''\n        ? this.requireVoucherId(input.voucherId)\n        : this.writeDownVoucher(asset, date);\n\n    const entry = this.postMachineEntry(\n      date,\n      voucherId,\n      `Write-down ${asset.name}: ${reason}`,\n      this.withDimensions(asset, [\n        { account: this.impairmentExpenseAccount(), side: 'debit', money: amount.toJSON() },\n        { account: asset.assetAccount.value, side: 'credit', money: amount.toJSON() },\n      ]),\n    );\n\n    asset.recordWriteDown(date, amount, entry, openPlanMonths);\n    this.assets.save(asset);\n\n    const newBookValue = asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null));\n\n    this.trace(input, 'asset', asset.id, 'writtenDown', {\n      bookValue: { from: bookValue.amountAsString(), to: newBookValue.amountAsString() },\n      reason: { from: null, to: reason },\n    });\n\n    return {\n      assetId: asset.id.value,\n      entryId: entry.value,\n      amount: amount.amountAsString(),\n      bookValue: newBookValue.amountAsString(),\n      remainingPlanMonths: openPlanMonths.length,\n    };\n  }\n\n  /**\n   * Reverse an earlier write-down when its reason has ceased (`writeUpAsset`, F-CORE-052).\n   *\n   * **This is a duty, not an option, and its absence was the smallest of the real legal gaps.**\n   * `writeDownAsset` has existed for a long time with no counterpart, so an asset written down in a\n   * bad year stayed down for ever — which understates equity and the result exactly as permanently\n   * as the write-down was meant to state them prudently for one year.\n   *\n   * **Two caps, and the second is the one that needs the shadow plan.** Nothing may be written back\n   * that was not written down (`unreversedWriteDowns`), and the book value may not exceed what it\n   * would have been had the write-down never happened (`amortisedCostCeiling`). The second is\n   * stricter than the first and is easy to get wrong: a write-down also lowers every remaining\n   * planned instalment, so the book value climbs *above* the untouched plan as the years run on.\n   * Reversing in full would then carry the asset over its amortised cost.\n   *\n   * **What the caller decides and what the core decides.** Whether the reason has ceased, and by how\n   * much the value has recovered, is an appraisal — a judgement about the world, which no library\n   * makes. The amount is therefore an input. The ceiling is arithmetic, and that is the part that is\n   * enforced.\n   */\n  writeUpAsset(input: Record<string, unknown>): Record<string, unknown> {\n    const asset = this.requireAsset(input.assetId);\n    asset.assertActive();\n\n    const reason = typeof input.reason === 'string' ? input.reason.trim() : '';\n    if (reason === '') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'writeUpAsset: \"reason\" is required — a write-up that does not say why the impairment ceased is not auditable',\n        { assetId: asset.id.value },\n      );\n    }\n\n    const amount = this.parseMoney(input.amount);\n    if (amount.isNegative() || amount.isZero()) {\n      throw new DomainError('E_INPUT_INVALID', 'writeUpAsset: \"amount\" must be greater than zero', {\n        amount: amount.amountAsString(),\n      });\n    }\n\n    const reversible = asset.unreversedWriteDowns();\n    if (amount.compareTo(reversible) > 0) {\n      throw new DomainError(\n        'E_ASSET_WRITE_UP_EXCEEDS_WRITE_DOWN',\n        `writeUpAsset: ${amount.amountAsString()} exceeds the ${reversible.amountAsString()} still written down on this asset`,\n        { amount: amount.amountAsString(), reversible: reversible.amountAsString() },\n      );\n    }\n\n    const bookValue = asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null));\n    const ceiling = asset.amortisedCostCeiling();\n    if (bookValue.add(amount).compareTo(ceiling) > 0) {\n      throw new DomainError(\n        'E_ASSET_WRITE_UP_EXCEEDS_CEILING',\n        `writeUpAsset: ${amount.amountAsString()} would carry the asset to ` +\n          `${bookValue.add(amount).amountAsString()}, above the amortised cost of ${ceiling.amountAsString()}`,\n        {\n          amount: amount.amountAsString(),\n          bookValue: bookValue.amountAsString(),\n          ceiling: ceiling.amountAsString(),\n        },\n      );\n    }\n\n    const date = CalendarDate.of(typeof input.date === 'string' ? input.date : '');\n\n    const openPlanMonths: number[] = [];\n    for (let planMonth = 1; planMonth <= asset.monthlySchedule.length; planMonth++) {\n      if (!asset.isMonthBooked(planMonth)) openPlanMonths.push(planMonth);\n    }\n\n    const voucherId =\n      typeof input.voucherId === 'string' && input.voucherId !== ''\n        ? this.requireVoucherId(input.voucherId)\n        : this.writeUpVoucher(asset, date);\n\n    const entry = this.postMachineEntry(\n      date,\n      voucherId,\n      `Write-up ${asset.name}: ${reason}`,\n      this.withDimensions(asset, [\n        { account: asset.assetAccount.value, side: 'debit', money: amount.toJSON() },\n        { account: this.writeUpIncomeAccount(), side: 'credit', money: amount.toJSON() },\n      ]),\n    );\n\n    asset.recordWriteUp(date, amount, entry, openPlanMonths);\n    this.assets.save(asset);\n\n    const newBookValue = asset.acquisitionCost.subtract(asset.accumulatedDepreciationAt(null));\n\n    this.trace(input, 'asset', asset.id, 'writtenUp', {\n      bookValue: { from: bookValue.amountAsString(), to: newBookValue.amountAsString() },\n      reason: { from: null, to: reason },\n    });\n\n    return {\n      assetId: asset.id.value,\n      entryId: entry.value,\n      amount: amount.amountAsString(),\n      bookValue: newBookValue.amountAsString(),\n      ceiling: ceiling.amountAsString(),\n      stillReversible: asset.unreversedWriteDowns().amountAsString(),\n    };\n  }\n\n  /**\n   * Where a write-up is booked. **Required from the pack**, and the asymmetry with the impairment\n   * account is deliberate rather than an oversight.\n   *\n   * A write-down that names no account falls back to ordinary depreciation, which is not wrong —\n   * only less informative, because both are a charge against the same asset. There is no equivalent\n   * on the income side: the disposal-proceeds account is specifically a *gain on disposal*, and a\n   * write-up is not one. Borrowing it would put a figure under a heading that says something untrue\n   * about it, which is worse than asking the pack to say where it goes.\n   */\n  private writeUpIncomeAccount(): string {\n    const block = isRecord(this.ruleModule.assetAccounts) ? this.ruleModule.assetAccounts : {};\n    const value = block.writeUpIncomeAccount;\n\n    if (typeof value !== 'string' || value === '') {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'assetAccounts.writeUpIncomeAccount is not set in the rule module — a write-up needs an ' +\n          'income account of its own; the disposal account would name it something it is not',\n        { field: 'assetAccounts.writeUpIncomeAccount' },\n      );\n    }\n\n    return value;\n  }\n\n  private writeUpVoucher(asset: Asset, date: CalendarDate): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `ZUSCHR-${date.iso.replaceAll('-', '')}-${asset.id.value.slice(-6)}`,\n      voucherDate: date,\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n    return voucher.id;\n  }\n\n  private rebaseAfterSpecialWindow(asset: Asset, fiscalYear: number): void {\n    if (\n      asset.specialDepreciationWindowEnd === null ||\n      fiscalYear <= asset.specialDepreciationWindowEnd ||\n      asset.scheduleWasRevised() ||\n      !asset.hasSpecialDepreciation()\n    ) {\n      return;\n    }\n\n    const openPlanMonths: number[] = [];\n    for (let planMonth = 1; planMonth <= asset.monthlySchedule.length; planMonth++) {\n      if (!asset.isMonthBooked(planMonth)) openPlanMonths.push(planMonth);\n    }\n\n    asset.rebaseRemainingPlan(openPlanMonths);\n    this.assets.save(asset);\n  }\n\n  private writeDownVoucher(asset: Asset, date: CalendarDate): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `AFAA-${date.iso.replace(/-/g, '')}-${asset.id.value.slice(-6)}`,\n      voucherDate: date,\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n    return voucher.id;\n  }\n\n  private requireVoucherId(voucherId: string): Uuid {\n    const voucher = this.vouchers.byId(Uuid.fromString(voucherId));\n\n    if (voucher === null) {\n      throw new DomainError('E_VOUCHER_UNKNOWN', `voucher ${voucherId} does not exist`, { voucherId });\n    }\n\n    return voucher.id;\n  }\n\n  /**\n   * Where an unplanned write-down is booked. A pack that separates it from ordinary depreciation says\n   * so; one that does not gets the depreciation account, which is what it had before this operation\n   * existed and is not wrong, only less informative.\n   */\n  private impairmentExpenseAccount(): string {\n    const block = isRecord(this.ruleModule.assetAccounts) ? this.ruleModule.assetAccounts : {};\n    const value = block.impairmentExpenseAccount;\n\n    return typeof value === 'string' && value !== '' ? value : this.depreciationExpenseAccount();\n  }\n\n  runDepreciation(input: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = typeof input.fiscalYear === 'number' ? input.fiscalYear : 0;\n    const period = typeof input.period === 'number' ? input.period : null;\n\n    let entriesCreated = 0;\n    let total = Money.zero(this.baseCurrency);\n\n    for (const asset of this.assets.all()) {\n      if (asset.route !== 'capitalize' && asset.route !== 'pool') continue;\n      // A disposed asset stops depreciating — unless its pack keeps it in the pool. Whether a\n      // disposal reduces the pool is declared per jurisdiction (`poolReducedOnDisposal`); where it\n      // does not, the pool runs its fixed term no matter what happened to the individual items\n      // (F-AST-006). Stopping unconditionally understated depreciation and overstated profit for\n      // every remaining year of the term.\n      if (asset.isDisposed() && !this.staysInPool(asset)) continue;\n\n      // The window closed, and part of the cost left the plan while it was open. What is left has\n      // to last the remaining life — otherwise the plan keeps asking for the original yearly amount\n      // and runs the book value below zero. Once, and only once, per asset.\n      this.rebaseAfterSpecialWindow(asset, fiscalYear);\n\n      const [months, amount] =\n        period === null ? this.yearTarget(asset, fiscalYear) : this.monthTarget(asset, fiscalYear, period);\n      if (months.length === 0 || amount.isZero()) continue;\n\n      const bookingDate = this.bookingDate(asset, fiscalYear, period, months);\n      const periodLabel = period === null ? '' : `/${String(period).padStart(2, '0')}`;\n      const entry = this.postMachineEntry(\n        bookingDate,\n        this.depreciationVoucher(asset, fiscalYear, period),\n        `Depreciation ${asset.name} ${fiscalYear}${periodLabel}`,\n        this.withDimensions(asset, [\n          { account: this.depreciationExpenseAccount(), side: 'debit', money: amount.toJSON() },\n          { account: asset.assetAccount.value, side: 'credit', money: amount.toJSON() },\n        ]),\n      );\n\n      const monthAmounts = months.length === 1 ? [amount] : this.monthAmounts(asset, months, amount);\n      months.forEach((planMonth, index) => {\n        asset.recordDepreciation(planMonth, bookingDate, monthAmounts[index]!, entry);\n      });\n\n      this.assets.save(asset);\n      entriesCreated++;\n      total = total.add(amount);\n    }\n\n    // A run that created nothing is still an event: \"someone ran depreciation for this\n    // period and it was already done\" is exactly what an auditor reconstructing a timeline\n    // wants to see, and leaving it out would make repeated runs invisible.\n    if (this.tenantId !== null) {\n      this.trace(input, 'depreciationRun', this.tenantId, 'completed', {\n        fiscalYear: { from: null, to: fiscalYear },\n        period: { from: null, to: period },\n        entriesCreated: { from: null, to: entriesCreated },\n      });\n    }\n\n    if (entriesCreated === 0) return { alreadyRun: true, entriesCreated: 0 };\n    return { entriesCreated, totalDepreciation: total.toJSON() };\n  }\n\n  requireAsset(assetId: unknown): Asset {\n    let asset: Asset | null = null;\n    if (typeof assetId === 'string' && assetId !== '') {\n      try {\n        asset = this.assets.byId(Uuid.fromString(assetId));\n      } catch (error) {\n        if (!(error instanceof InvalidValue)) throw error;\n      }\n    }\n    if (asset === null) {\n      throw new DomainError('E_ASSET_UNKNOWN', `asset ${typeof assetId === 'string' ? assetId : '?'} does not exist`);\n    }\n    return asset;\n  }\n\n  // ---- internal --------------------------------------------------------\n\n  private yearTarget(asset: Asset, fiscalYear: number): [number[], Money] {\n    const zero = Money.zero(this.baseCurrency);\n    const monthsByYear = new Map<number, number[]>();\n    const life = asset.monthlySchedule.length;\n    for (let planMonth = 1; planMonth <= life; planMonth++) {\n      const year = this.planMonthYear(asset, planMonth);\n      const list = monthsByYear.get(year) ?? [];\n      list.push(planMonth);\n      monthsByYear.set(year, list);\n    }\n    const months = monthsByYear.get(fiscalYear);\n    if (months === undefined) return [[], zero];\n\n    let yearAmount: Money;\n    if (asset.scheduleIsAuthoritative()) {\n      // A declining-balance plan cannot be re-derived from month counts — each year depends on what\n      // the previous one left. The schedule IS the plan, so the year's target is simply the sum of\n      // its months. Straight line keeps re-allocating, which is what pins its rounding to the values\n      // every existing fixture expects.\n      yearAmount = zero;\n      for (const planMonth of months) {\n        yearAmount = yearAmount.add(asset.monthlySchedule[planMonth - 1]!);\n      }\n    } else {\n      const years = [...monthsByYear.keys()];\n      const weights = years.map((year) => monthsByYear.get(year)!.length);\n      const yearAmounts = asset.acquisitionCost.allocate(...weights);\n      const yearIndex = years.indexOf(fiscalYear);\n      if (yearIndex === -1) return [[], zero];\n      yearAmount = yearAmounts[yearIndex]!;\n    }\n\n    const openMonths: number[] = [];\n    let bookedAmount = zero;\n    for (const planMonth of months) {\n      if (asset.isMonthBooked(planMonth)) {\n        bookedAmount = bookedAmount.add(asset.monthlySchedule[planMonth - 1]!);\n        continue;\n      }\n      openMonths.push(planMonth);\n    }\n\n    const amount = yearAmount.subtract(bookedAmount);\n    if (openMonths.length === 0 || !amount.isPositive()) return [[], zero];\n    return [openMonths, amount];\n  }\n\n  private monthTarget(asset: Asset, fiscalYear: number, period: number): [number[], Money] {\n    const zero = Money.zero(this.baseCurrency);\n    const year = this.fiscalYears.byYear(fiscalYear);\n    if (year === null) {\n      throw new DomainError('E_PERIOD_UNKNOWN', `fiscal year ${fiscalYear} is not set up`);\n    }\n    const periodEntity = year.period(period);\n    const life = asset.monthlySchedule.length;\n    for (let planMonth = 1; planMonth <= life; planMonth++) {\n      const date = asset.planMonthDate(planMonth);\n      if (!periodEntity.contains(date)) continue;\n      if (asset.isMonthBooked(planMonth)) return [[], zero];\n      return [[planMonth], asset.monthlySchedule[planMonth - 1]!];\n    }\n    return [[], zero];\n  }\n\n  private monthAmounts(asset: Asset, months: number[], total: Money): Money[] {\n    const planned = months.map((planMonth) => asset.monthlySchedule[planMonth - 1]!);\n    let plannedSum = Money.zero(this.baseCurrency);\n    for (const amount of planned) plannedSum = plannedSum.add(amount);\n    if (plannedSum.equals(total)) return planned;\n    return total.allocateEvenly(months.length);\n  }\n\n  private bookingDate(asset: Asset, fiscalYear: number, period: number | null, months: number[]): CalendarDate {\n    const year = this.fiscalYears.byYear(fiscalYear);\n    if (period !== null && year !== null) return year.period(period).end;\n    if (year !== null) return year.end;\n    return asset.planMonthDate(months[months.length - 1]!);\n  }\n\n  /**\n   * Dimensions the asset carries, in the shape a posting line expects (IMPL-023). Every machine\n   * entry about an asset gets them on every line: the whole event belongs to that cost centre, and\n   * a line without them would be refused wherever the pack makes a dimension mandatory — which is\n   * precisely the case that used to make depreciation impossible to run.\n   */\n  private static parseDimensions(raw: unknown): Array<{ type: string; code: string }> {\n    if (!Array.isArray(raw)) return [];\n    const parsed: Array<{ type: string; code: string }> = [];\n    for (const item of raw) {\n      if (!isRecord(item)) continue;\n      const type = asString(item.type);\n      const code = asString(item.code);\n      if (type !== null && code !== null) parsed.push({ type, code });\n    }\n    return parsed;\n  }\n\n  private withDimensions(\n    asset: Asset,\n    lines: Array<Record<string, unknown>>,\n  ): Array<Record<string, unknown>> {\n    if (asset.dimensions.length === 0) return lines;\n    return lines.map((line) => ({ ...line, dimensions: asset.dimensions.map((d) => ({ ...d })) }));\n  }\n\n  private postMachineEntry(\n    date: CalendarDate,\n    voucherId: Uuid,\n    text: string,\n    lines: Array<Record<string, unknown>>,\n  ): Uuid {\n    const result = this.ledger.post({ entryDate: date.iso, voucherId: voucherId.value, text, lines });\n    // Machine-generated entry: finalize immediately (machine entries are not hand-correctable).\n    this.ledger.finalize({ entryId: result.entry.id.value });\n    return result.entry.id;\n  }\n\n  private depreciationVoucher(asset: Asset, fiscalYear: number, period: number | null): Uuid {\n    const periodLabel = period === null ? '' : `-${String(period).padStart(2, '0')}`;\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `AFA-${fiscalYear}${periodLabel}-${asset.id.value.slice(-6)}`,\n      voucherDate: CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-12-31`),\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n    return voucher.id;\n  }\n\n  private resolveRoute(choice: string, cost: Money, acquiredOn: CalendarDate): AssetRoute {\n    if (choice !== 'auto') return parseAssetRoute(choice) ?? 'capitalize';\n\n    const threshold = this.applicableThreshold(acquiredOn);\n    if (threshold === null) return 'capitalize';\n\n    if (cost.compareTo(Money.of(threshold.immediateMax, this.baseCurrency)) <= 0) return 'immediate_expense';\n    if (\n      threshold.poolMin !== null &&\n      threshold.poolMax !== null &&\n      cost.compareTo(Money.of(threshold.poolMin, this.baseCurrency)) >= 0 &&\n      cost.compareTo(Money.of(threshold.poolMax, this.baseCurrency)) <= 0\n    ) {\n      return 'pool';\n    }\n    return 'capitalize';\n  }\n\n  /** The threshold row in force on the acquisition date — the first whose validity window contains it. */\n  private applicableThreshold(acquiredOn: CalendarDate): Threshold | null {\n    for (const threshold of this.thresholds()) {\n      const validFrom = CalendarDate.of(threshold.validFrom);\n      const validTo = threshold.validTo === null ? null : CalendarDate.of(threshold.validTo);\n      if (acquiredOn.isBefore(validFrom) || (validTo !== null && acquiredOn.isAfter(validTo))) continue;\n      return threshold;\n    }\n    return null;\n  }\n\n  /**\n   * How long a pooled asset is written off. Refused rather than defaulted: a pack that opens a pool\n   * range without saying over how long is incomplete, and picking a number here would put a statute\n   * back into the core — the exact thing SPEC-004 is about. The schema requires the field alongside\n   * `poolMax`, so this fires only for hand-fed rule data that never went through a pack.\n   */\n  private poolYears(acquiredOn: CalendarDate): number {\n    const threshold = this.applicableThreshold(acquiredOn);\n    if (threshold === null || threshold.poolYears === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'gwgThresholds: a pool range (poolMin/poolMax) without poolYears — the pack must say over how many years the pool is written off',\n        { field: 'poolYears', acquiredOn: acquiredOn.iso },\n      );\n    }\n    return threshold.poolYears;\n  }\n\n  /**\n   * Whether a disposal takes the item out of the pool. Same reasoning as `poolYears`, and the same\n   * refusal: this is a jurisdiction's answer, not a property of pooling. Germany does not reduce\n   * the pool when an item leaves (the yearly fraction runs to the end of the term regardless);\n   * the UK and Australia take disposals out of their pools. Deciding it here would have put a\n   * statute back into the core — which is exactly what IMPL-019 accidentally did before this.\n   */\n  /**\n   * Does the pool's first year get shortened by the acquisition month?\n   *\n   * Germany says no: the pool is dissolved in the fiscal year it is formed and the following ones by\n   * equal fractions, so an asset bought in November still carries a full fraction in that year, and\n   * the term ends after `poolYears` fiscal years. Treating a pool like ordinary linear depreciation —\n   * pro rata from the month of acquisition — understated the first year and invented a last one.\n   *\n   * Other pool regimes answer this differently, which is why the pack has to say it rather than the\n   * core assuming it — the same reason `poolYears` (SPEC-004) and `poolReducedOnDisposal` (IMPL-019)\n   * are pack data.\n   */\n  private poolProRataInFirstYear(acquiredOn: CalendarDate): boolean {\n    const threshold = this.applicableThreshold(acquiredOn);\n    if (threshold === null || threshold.poolProRataInFirstYear === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'gwgThresholds: a pool range (poolMin/poolMax) without poolProRataInFirstYear — the pack must say whether the first year is shortened by the acquisition month',\n        { field: 'poolProRataInFirstYear', acquiredOn: acquiredOn.iso },\n      );\n    }\n    return threshold.poolProRataInFirstYear;\n  }\n\n  /**\n   * Where the depreciation plan starts. Capitalised assets start in the month of acquisition (pro rata\n   * temporis). A pooled asset whose pack dissolves the pool in whole fiscal-year fractions starts at\n   * the beginning of the fiscal year it was acquired in — that, and nothing else, is what makes the\n   * first year full and the term end after `poolYears` years.\n   */\n  private planStartFor(route: AssetRoute, acquiredOn: CalendarDate): CalendarDate | null {\n    if (route !== 'pool') return null;\n\n    const year = this.fiscalYears.forDate(acquiredOn);\n\n    // Acquired on the first day of the fiscal year? Then both answers produce the same plan, and the\n    // pack is not asked. That is deliberate and mirrors `poolReducedOnDisposal`, which is only demanded\n    // when something is actually disposed: a pack owes an answer where the answer changes the books,\n    // not everywhere. The guarantee that a *pack* carries the field is the schema's job.\n    if (year !== null && acquiredOn.iso === year.start.iso) return null;\n\n    if (this.poolProRataInFirstYear(acquiredOn)) return null;\n\n    if (year === null) {\n      throw new DomainError(\n        'E_PERIOD_UNKNOWN',\n        `the pool for an asset acquired on ${acquiredOn.iso} is dissolved in whole fiscal-year fractions, but no fiscal year contains that date`,\n        { acquiredOn: acquiredOn.iso },\n      );\n    }\n\n    return year.start;\n  }\n\n  private poolReducedOnDisposal(acquiredOn: CalendarDate): boolean {\n    const threshold = this.applicableThreshold(acquiredOn);\n    if (threshold === null || threshold.poolReducedOnDisposal === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'gwgThresholds: a pool range (poolMin/poolMax) without poolReducedOnDisposal — the pack must say whether a disposal reduces the pool',\n        { field: 'poolReducedOnDisposal', acquiredOn: acquiredOn.iso },\n      );\n    }\n    return threshold.poolReducedOnDisposal;\n  }\n\n  /** A pooled asset that its pack keeps in the pool after disposal — the write-off does not apply. */\n  private staysInPool(asset: Asset): boolean {\n    return asset.route === 'pool' && !this.poolReducedOnDisposal(asset.acquiredOn);\n  }\n\n  private thresholds(): Threshold[] {\n    const raw = Array.isArray(this.ruleModule.gwgThresholds) ? this.ruleModule.gwgThresholds : [];\n    const thresholds: Threshold[] = [];\n    for (const item of raw) {\n      if (!isRecord(item) || typeof item.validFrom !== 'string' || typeof item.immediateMax !== 'string') continue;\n      thresholds.push({\n        validFrom: item.validFrom,\n        validTo: typeof item.validTo === 'string' ? item.validTo : null,\n        immediateMax: item.immediateMax,\n        poolMin: typeof item.poolMin === 'string' ? item.poolMin : null,\n        poolMax: typeof item.poolMax === 'string' ? item.poolMax : null,\n        poolYears: typeof item.poolYears === 'number' && Number.isSafeInteger(item.poolYears) && item.poolYears >= 1\n          ? item.poolYears\n          : null,\n        poolReducedOnDisposal: typeof item.poolReducedOnDisposal === 'boolean' ? item.poolReducedOnDisposal : null,\n        poolProRataInFirstYear:\n          typeof item.poolProRataInFirstYear === 'boolean' ? item.poolProRataInFirstYear : null,\n      });\n    }\n    return thresholds;\n  }\n\n  /**\n   * Which yearly bucket a plan month belongs to.\n   *\n   * The fiscal year that contains the month, when one is set up — NOT its calendar year. Where the\n   * two differ the old shortcut came apart badly: for a fiscal year 07/2026–06/2027 (labelled by its\n   * end year) an asset acquired in September 2026 had its September-to-December months filed under\n   * \"2026\", a label no fiscal year carries, so no run ever booked them, while months belonging to the\n   * following fiscal year were pulled into this one. Which months belong to a fiscal year is what a\n   * fiscal year is; reading it off the calendar was simply wrong.\n   *\n   * Falls back to the calendar year for a month beyond every fiscal year that has been set up. That is\n   * not a second opinion about the boundary — it keeps the weighting COMPLETE. The yearly amount comes\n   * from allocating the cost across all buckets by month count, so dropping the months that reach past\n   * the last configured year would push their share into the years that remain and write the asset off\n   * too fast. With calendar-year fiscal years the fallback is identical to the answer above; with\n   * deviating ones it is the old behaviour, and it corrects itself as soon as the year is created. The\n   * honest limit: set up the fiscal years an asset runs through.\n   */\n  private planMonthYear(asset: Asset, planMonth: number): number {\n    const date = asset.planMonthDate(planMonth);\n    return this.fiscalYears.forDate(date)?.year ?? date.year();\n  }\n\n  /**\n   * The depreciation method the caller asked for. Straight line when absent — the method every\n   * jurisdiction allows and the only one this core knew until 2026-08-23.\n   */\n  /**\n   * Expected total output. A whole number, at least one — JSON has no int/float split, so 100000.0 is\n   * the same value as 100000, but 100000.5 is a caller's mistake and not half a kilometre.\n   */\n  private static parseTotalUnits(value: unknown): number | null {\n    if (value === null || value === undefined) return null;\n\n    if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value)) {\n      throw new DomainError('E_INPUT_INVALID', 'acquireAsset: \"totalUnits\" must be a whole number', {\n        totalUnits: rejectedValue(value),\n      });\n    }\n\n    if (value < 1) {\n      throw new DomainError('E_INPUT_INVALID', 'acquireAsset: \"totalUnits\" must be at least 1', {\n        totalUnits: value,\n      });\n    }\n\n    return value;\n  }\n\n  private static parseMethod(value: unknown): string {\n    if (value === null || value === undefined) return 'straight_line';\n\n    if (value !== 'straight_line' && value !== 'declining_balance' && value !== 'units_of_production') {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'acquireAsset: \"depreciationMethod\" must be \"straight_line\", \"declining_balance\" or \"units_of_production\"',\n        { depreciationMethod: rejectedValue(value) },\n      );\n    }\n\n    return value;\n  }\n\n  /**\n   * A declining-balance plan, with the switch to straight line built in.\n   *\n   * Each year takes a fixed percentage of what is LEFT, so the amounts fall and never quite reach\n   * zero on their own — which is why every declining-balance regime pairs the method with a switch to\n   * straight line over the remaining life, and why the final year simply takes the remainder. Without\n   * that last step an asset would keep a residue forever.\n   *\n   * The switch is taken automatically at the first year where straight line over the remaining life\n   * yields more. It is a permission rather than a duty, but no one entitled to it declines it — an\n   * option nobody ever sets differently is better expressed as the behaviour.\n   *\n   * Rate, factor and the window come from the pack: the mechanism is shared (Germany applies it both\n   * to movables and, at a different rate, to new residential buildings), the numbers are not. Both the\n   * percentage and the remaining-life figure go through allocate, so the cents fall where the rest of\n   * the core puts them.\n   */\n  private decliningBalanceSchedule(\n    cost: Money,\n    usefulLifeMonths: number,\n    acquiredOn: CalendarDate,\n    assetClass: string,\n  ): Money[] {\n    const rule = this.decliningBalanceRule(acquiredOn, assetClass);\n    const years = Math.ceil(usefulLifeMonths / 12);\n\n    // min(factor x straight-line rate, cap) — expressed on the cost, not per year, because the rate is\n    // a property of the asset's life and does not change as the balance falls.\n    const straightLineRate = 100 / years;\n    const rate = Math.min(rule.factor * straightLineRate, Number(rule.maxRate));\n    const rateWeight = String(Math.round(rate * 10000) / 10000);\n    const restWeight = String(Math.round((100 - rate) * 10000) / 10000);\n\n    const schedule: Money[] = [];\n    let remaining = cost;\n\n    for (let year = 1; year <= years; year++) {\n      const remainingYears = years - year + 1;\n\n      let amount: Money;\n      if (year === years) {\n        amount = remaining;\n      } else {\n        const declining = remaining.allocate(rateWeight, restWeight)[0]!;\n        const straightLine = remaining.allocate(...Array.from({ length: remainingYears }, () => 1))[0]!;\n        amount = declining.compareTo(straightLine) >= 0 ? declining : straightLine;\n      }\n\n      remaining = remaining.subtract(amount);\n      schedule.push(...amount.allocateEvenly(12));\n    }\n\n    return schedule.slice(0, usefulLifeMonths);\n  }\n\n  /**\n   * The declining-balance rule in force on the acquisition date, for this kind of asset. Refused\n   * rather than defaulted, like every other pack question here: a core that invents a rate has one\n   * jurisdiction's tax policy in the substrate, and these rates are the most short-lived numbers in\n   * the whole pack — Germany's current one applies to a window of two and a half years.\n   *\n   * Two entries can be in force at once, because a jurisdiction may run one declining-balance regime\n   * for movables and another for buildings over overlapping windows — Germany does exactly that. So\n   * an entry may name the asset classes it covers, and **a class-specific entry wins over a general\n   * one no matter which comes first in the file.** Order-independence is the point: a rule that\n   * changed meaning when someone appended a line above it would be a trap, and the general entry is\n   * the one a pack author is most likely to add later.\n   *\n   * An entry without `assetClasses` covers every class, which is what a pack written before this\n   * distinction existed says — those keep computing what they always did.\n   */\n  private decliningBalanceRule(acquiredOn: CalendarDate, assetClass: string): { factor: number; maxRate: string } {\n    const raw = Array.isArray(this.ruleModule.decliningBalance) ? this.ruleModule.decliningBalance : [];\n    let general: { factor: number; maxRate: string } | null = null;\n\n    for (const item of raw) {\n      if (!isRecord(item) || typeof item.validFrom !== 'string') continue;\n\n      const validFrom = CalendarDate.of(item.validFrom);\n      const validTo = typeof item.validTo === 'string' ? CalendarDate.of(item.validTo) : null;\n      if (acquiredOn.isBefore(validFrom) || (validTo !== null && acquiredOn.isAfter(validTo))) continue;\n\n      const factor = typeof item.factor === 'number' && Number.isSafeInteger(item.factor) ? item.factor : null;\n      const maxRate = typeof item.maxRate === 'string' ? item.maxRate : null;\n      if (factor === null || factor < 1 || maxRate === null) continue;\n\n      const classes = Array.isArray(item.assetClasses) ? item.assetClasses : null;\n\n      if (classes === null) {\n        general ??= { factor, maxRate };\n        continue;\n      }\n\n      if (classes.includes(assetClass)) return { factor, maxRate };\n    }\n\n    if (general !== null) return general;\n\n    throw new DomainError(\n      'E_PACK_INCOHERENT',\n      `declining-balance depreciation was asked for, but the pack declares no rule in force on ${acquiredOn.iso} for asset class \"${assetClass}\"`,\n      { field: 'decliningBalance', acquiredOn: acquiredOn.iso, assetClass },\n    );\n  }\n\n  /**\n   * A useful life given per acquisition: a whole number of months, at least one. JSON has no\n   * int/float split, so 60.0 is the same value as 60 — but 60.4 is a caller's mistake and not a\n   * number to round into shape.\n   */\n  private static parseUsefulLifeMonths(value: unknown): number | null {\n    if (value === null || value === undefined) return null;\n\n    if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'acquireAsset: \"usefulLifeMonths\" must be a whole number of months, at least 1',\n        { usefulLifeMonths: rejectedValue(value) },\n      );\n    }\n\n    return value;\n  }\n\n  private usefulLifeMonths(assetClass: string): number {\n    const raw = Array.isArray(this.ruleModule.usefulLife) ? this.ruleModule.usefulLife : [];\n    for (const item of raw) {\n      if (isRecord(item) && item.assetClass === assetClass && typeof item.months === 'number') {\n        return item.months;\n      }\n    }\n    throw new DomainError(\n      'E_ASSET_UNKNOWN',\n      `No useful life for asset class \"${assetClass}\" in the rule module (see FINDINGS-CLOSED.md)`,\n    );\n  }\n\n  private counterAccount(): string {\n    return this.assetAccount('acquisitionCounterAccount');\n  }\n  private depreciationExpenseAccount(): string {\n    return this.assetAccount('depreciationExpenseAccount');\n  }\n  private gwgExpenseAccount(): string {\n    return this.assetAccount('gwgExpenseAccount');\n  }\n  /**\n   * Depreciation owed up to the disposal, booked before the write-off (IMPL-022).\n   *\n   * Without this the disposal wrote off whatever carrying amount happened to be booked, and the\n   * asset's last months of depreciation never happened at all: `runDepreciation` skips disposed\n   * assets, so nobody would book them afterwards either. The expense landed in the disposal\n   * account as an inflated loss instead of in depreciation — the total hit the income statement\n   * correctly, the split did not, and the depreciation figure the fixed-asset schedule reports\n   * was short.\n   *\n   * Which months are owed follows the schedule's own due-date convention — a plan month falls due\n   * on its last day, exactly as `monthTarget` reads it for the regular run. No new rule is\n   * invented here, and deliberately so: whether the month an asset leaves in counts as a whole\n   * month is a *jurisdiction's* answer (Germany grants it, US conventions are half-year or\n   * mid-quarter), so it belongs in a pack, not in this code. Consequence today: an asset disposed\n   * mid-month gets no depreciation for that month. Recorded as a follow-up.\n   */\n  private catchUpDepreciation(asset: Asset, disposedOn: CalendarDate, voucherId: Uuid): void {\n    const due: number[] = [];\n    for (let planMonth = 1; planMonth <= asset.monthlySchedule.length; planMonth++) {\n      if (asset.planMonthDate(planMonth).isAfter(disposedOn)) break;\n      if (!asset.isMonthBooked(planMonth)) due.push(planMonth);\n    }\n    if (due.length === 0) return;\n\n    let amount = Money.zero(this.baseCurrency);\n    for (const planMonth of due) amount = amount.add(asset.monthlySchedule[planMonth - 1]!);\n    if (amount.isZero()) return;\n\n    const entry = this.postMachineEntry(\n      disposedOn,\n      voucherId,\n      `Depreciation up to disposal ${asset.name}`,\n      this.withDimensions(asset, [\n        { account: this.depreciationExpenseAccount(), side: 'debit', money: amount.toJSON() },\n        { account: asset.assetAccount.value, side: 'credit', money: amount.toJSON() },\n      ]),\n    );\n\n    const amounts = this.monthAmounts(asset, due, amount);\n    due.forEach((planMonth, index) => {\n      asset.recordDepreciation(planMonth, disposedOn, amounts[index]!, entry);\n    });\n    this.assets.save(asset);\n  }\n\n  private disposalProceedsAccount(): string {\n    return this.assetAccount('disposalProceedsAccount');\n  }\n  private disposalLossAccount(): string {\n    return this.assetAccount('disposalLossAccount');\n  }\n\n  /**\n   * The disposal entry (F-AST-004). Two things leave the books at once: the asset's carrying\n   * amount, and the difference between that and what the sale brought in.\n   *\n   * This core depreciates *net* — `runDepreciation` credits the asset account directly, there is\n   * no accumulated-depreciation account — so the write-off is a single credit of the carrying\n   * amount against that same account, not the gross form with an offsetting contra account.\n   *\n   * The difference is a gain (proceeds above book value) or a loss (below, including a scrapping\n   * with no proceeds at all), and it goes to the account the pack names for it. Before this,\n   * `dispose` booked only `bank → proceedsAccount`: the asset stayed in the balance sheet at its\n   * carrying amount and the proceeds counted as income in full, overstating profit by exactly\n   * that amount.\n   *\n   * The `proceedsAccount` input parameter still wins over the pack's account — it is documented\n   * and fixtures pass it — but is no longer required for the entry to happen.\n   */\n  private disposalLines(\n    asset: Asset,\n    carrying: Money,\n    proceeds: Money | null,\n    bankAccount: string,\n    proceedsAccountOverride: string | null,\n  ): Array<Record<string, unknown>> {\n    const lines: Array<Record<string, unknown>> = [];\n    const received = proceeds ?? Money.zero(this.baseCurrency);\n\n    if (received.isPositive()) {\n      lines.push({ account: bankAccount, side: 'debit', money: received.toJSON() });\n    }\n    if (carrying.isPositive()) {\n      lines.push({ account: asset.assetAccount.value, side: 'credit', money: carrying.toJSON() });\n    }\n\n    const difference = received.subtract(carrying);\n    if (difference.isPositive()) {\n      const gainAccount = proceedsAccountOverride ?? this.disposalProceedsAccount();\n      lines.push({ account: gainAccount, side: 'credit', money: difference.toJSON() });\n    } else if (!difference.isZero()) {\n      lines.push({ account: this.disposalLossAccount(), side: 'debit', money: difference.negate().toJSON() });\n    }\n\n    // Nothing moved: a fully depreciated asset scrapped without proceeds. Booking a zero entry\n    // would put an empty voucher in the journal for no reason.\n    return lines.length > 1 ? lines : [];\n  }\n\n  private assetAccount(key: string): string {\n    const block = isRecord(this.ruleModule.assetAccounts) ? this.ruleModule.assetAccounts : {};\n    const value = block[key];\n    if (typeof value === 'string' && value !== '') return value;\n    throw new DomainError('E_ACCOUNT_UNKNOWN', `assetAccounts.${key} is not set in the rule module`, { key });\n  }\n\n  private parseMoney(raw: unknown): Money {\n    const amount = isRecord(raw) ? asString(raw.amount) : null;\n    if (amount === null) throw new InvalidValue('amount missing');\n    return Money.of(amount, this.baseCurrency);\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport type { OverheadRate, ProductionCostResult, RateWarning } from './costing-service.js';\nimport type { Money } from '../../../substrate/money.js';\nimport type { PeriodRef } from '../../../substrate/period-ref.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\n\n/**\n * Costing run (costing-modell.md aggregate 1): unique per period + version;\n * repetition creates a new version. draft → released.\n */\nexport class CostingRun {\n  private runStatus = 'draft';\n\n  constructor(\n    readonly id: Uuid,\n    readonly period: PeriodRef,\n    readonly version: number,\n    readonly primary: Map<string, Money>,\n    readonly afterAllocation: Map<string, Money>,\n    readonly grandTotal: Money,\n    // Which procedure produced these numbers. It belongs in the run because the two answer the same\n    // question differently, and a sheet that does not say how it was allocated cannot be checked\n    // against anything.\n    readonly method: string = 'step_ladder',\n    // Frozen with the run, not recomputed on read: the configuration can change after a release, and\n    // a released run that answers differently tomorrow is not released.\n    readonly rates: OverheadRate[] = [],\n    readonly rateWarnings: RateWarning[] = [],\n    readonly productionCost: ProductionCostResult | null = null,\n  ) {}\n\n  status(): string {\n    return this.runStatus;\n  }\n\n  release(): void {\n    if (this.runStatus === 'released') {\n      throw new DomainError(\n        'E_COSTING_RUN_RELEASED',\n        `run ${this.id.value} is already released — changes create a new version`,\n        { runId: this.id.value },\n      );\n    }\n    this.runStatus = 'released';\n  }\n\n  /**\n   * Persistable form (F-KLR-001/004).\n   *\n   * A run used to live in a `Map` inside the service, which meant a released run was gone with the\n   * process that made it. The requirements had said otherwise all along — runs are versioned per\n   * period, and the BAB and the rates are a projection *of a released run* — so a run no later\n   * process can read satisfies neither. Everything the three projections read is in here, and\n   * nothing else is: what a run answers must not depend on configuration that has moved since.\n   */\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      period: this.period.toJSON(),\n      version: this.version,\n      status: this.runStatus,\n      method: this.method,\n      primary: CostingRun.totalsToJSON(this.primary),\n      afterAllocation: CostingRun.totalsToJSON(this.afterAllocation),\n      grandTotal: this.grandTotal.toJSON(),\n      rates: this.rates,\n      rateWarnings: this.rateWarnings,\n      productionCost: this.productionCost,\n    };\n  }\n\n  /** Restore from persistence — status taken over directly, no re-validation. */\n  static restore(\n    id: Uuid,\n    period: PeriodRef,\n    version: number,\n    status: string,\n    primary: Map<string, Money>,\n    afterAllocation: Map<string, Money>,\n    grandTotal: Money,\n    method: string,\n    rates: OverheadRate[],\n    rateWarnings: RateWarning[],\n    productionCost: ProductionCostResult | null,\n  ): CostingRun {\n    const run = new CostingRun(\n      id,\n      period,\n      version,\n      primary,\n      afterAllocation,\n      grandTotal,\n      method,\n      rates,\n      rateWarnings,\n      productionCost,\n    );\n    run.runStatus = status;\n    return run;\n  }\n\n  /**\n   * Cost-centre totals as an object, keys sorted by code point.\n   *\n   * A JSON object preserves insertion order, so writing the map as it happens to be iterated would\n   * make the stored bytes depend on the order the postings arrived in — and the export has to be\n   * byte-identical across implementations (SF-15).\n   */\n  private static totalsToJSON(totals: Map<string, Money>): Record<string, unknown> {\n    const out: Record<string, unknown> = {};\n    for (const code of [...totals.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n      out[code] = totals.get(code)!.toJSON();\n    }\n    return out;\n  }\n}\n","import type { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Money } from '../../../substrate/money.js';\nimport type { PeriodRef } from '../../../substrate/period-ref.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\n\nexport interface InventoryCategoryRow {\n  account: string;\n  quantity: string;\n  unitCost: string;\n  marketValue: string | null;\n  unitValue: string;\n  source: string;\n  openingValue: string;\n  closingValue: string;\n  change: string;\n  changeAccount: string;\n  writtenDownToMarket: boolean;\n}\n\n/**\n * One act of valuing stock, recorded (F-CORE-050).\n *\n * **What this is not, first, because that is the whole design.** It is not a stock ledger. summae\n * does not know what is in the warehouse and never claims to: quantities arrive as *input* to a\n * valuation and are not carried forward, there are no goods movements, no bills of material and no\n * product master. Those are the embedding application's data.\n *\n * **What it is** is the same thing `Asset` is one layer over: summae does not own the machine, it\n * owns the register and the postings. Here it owns the *act of valuing* — which accounts, which\n * quantities, at what unit value, where that value came from, what the comparison with a market\n * value did, and which entry it produced. Keeping that is not optional bookkeeping tidiness: an\n * engine that posts a change in stock and keeps no record of how it reached the number has done\n * exactly what this project refuses to let an embedder do, one level down.\n *\n * **Versioned per period, like a costing run, and for the same reason.** Repetition creates a new\n * version rather than overwriting one. The posting is always the *difference* to what the accounts\n * already carry, so a second valuation of an unchanged period books nothing and records that it\n * booked nothing (`entryId: null`) — self-correcting rather than duplicating, without an\n * idempotency key to get wrong.\n *\n * Every figure is a string at the currency's scale. The quantity is a string too: it is not Money,\n * it is not rounded, and it must survive a round trip through JSON byte-identically in both\n * languages.\n */\nexport class InventoryValuation {\n  constructor(\n    readonly id: Uuid,\n    readonly period: PeriodRef,\n    readonly version: number,\n    readonly valuationDate: CalendarDate,\n    readonly runId: Uuid | null,\n    readonly categories: InventoryCategoryRow[],\n    readonly closingTotal: Money,\n    readonly change: Money,\n    readonly entryId: Uuid | null,\n  ) {}\n\n  /**\n   * Persistable form.\n   *\n   * Frozen, like a released costing run: the categories carry the unit values the act used, not the\n   * ones the configuration would produce today. A valuation that answers differently tomorrow is\n   * not a valuation of anything.\n   */\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      period: this.period.toJSON(),\n      version: this.version,\n      valuationDate: this.valuationDate.iso,\n      runId: this.runId?.value ?? null,\n      categories: this.categories,\n      closingTotal: this.closingTotal.toJSON(),\n      change: this.change.toJSON(),\n      entryId: this.entryId?.value ?? null,\n    };\n  }\n\n  static restore(\n    id: Uuid,\n    period: PeriodRef,\n    version: number,\n    valuationDate: CalendarDate,\n    runId: Uuid | null,\n    categories: InventoryCategoryRow[],\n    closingTotal: Money,\n    change: Money,\n    entryId: Uuid | null,\n  ): InventoryValuation {\n    return new InventoryValuation(\n      id,\n      period,\n      version,\n      valuationDate,\n      runId,\n      categories,\n      closingTotal,\n      change,\n      entryId,\n    );\n  }\n}\n","import { InvalidValue } from './errors.js';\n\n/**\n * An exact fraction of two integers, always in lowest terms with a positive denominator.\n *\n * It exists for one reason: the simultaneous-equation method of internal cost allocation solves a\n * linear system, and solving one means dividing. Every other number in this core either divides\n * evenly or is distributed with `Money.allocate`, so decimals with a fixed scale have been enough —\n * here they are not. 1/3 has no decimal form, and a solver that rounds mid-computation gives answers\n * that depend on the rounding, which is precisely what byte-identical results across two languages\n * cannot tolerate. Rationals have no such freedom: the arithmetic is exact, so PHP and TypeScript\n * cannot drift even in principle.\n *\n * Money never becomes a Rational and a Rational never becomes Money by rounding on its own — the\n * conversion back happens once, at the end, under the same largest-remainder rule the rest of the\n * core uses. PHP twin: `Substrate/Rational.php`.\n */\n\nconst DECIMAL_FORMAT = /^-?\\d+(\\.\\d+)?$/;\n\nfunction gcd(a: bigint, b: bigint): bigint {\n  let x = a < 0n ? -a : a;\n  let y = b < 0n ? -b : b;\n  while (y !== 0n) {\n    [x, y] = [y, x % y];\n  }\n  return x;\n}\n\nexport class Rational {\n  private constructor(\n    readonly numerator: bigint,\n    readonly denominator: bigint,\n  ) {}\n\n  static of(numerator: bigint | number, denominator: bigint | number = 1n): Rational {\n    let num = BigInt(numerator);\n    let den = BigInt(denominator);\n\n    if (den === 0n) throw new InvalidValue('Rational: denominator must not be zero');\n\n    if (den < 0n) {\n      num = -num;\n      den = -den;\n    }\n\n    if (num === 0n) return new Rational(0n, 1n);\n\n    const divisor = gcd(num, den);\n    return new Rational(num / divisor, den / divisor);\n  }\n\n  static zero(): Rational {\n    return new Rational(0n, 1n);\n  }\n\n  /**\n   * A decimal string (\"0.25\", \"-3\", \"1.5\") as an exact fraction. Weights arrive as strings because\n   * that is how the data format carries them; nothing here rounds.\n   */\n  static fromDecimalString(value: string): Rational {\n    if (!DECIMAL_FORMAT.test(value)) {\n      throw new InvalidValue(`Rational: \"${value}\" is not a decimal number`);\n    }\n\n    const dot = value.indexOf('.');\n    if (dot === -1) return Rational.of(BigInt(value));\n\n    const decimals = value.length - dot - 1;\n    return Rational.of(BigInt(value.replace('.', '')), 10n ** BigInt(decimals));\n  }\n\n  add(other: Rational): Rational {\n    return Rational.of(\n      this.numerator * other.denominator + other.numerator * this.denominator,\n      this.denominator * other.denominator,\n    );\n  }\n\n  subtract(other: Rational): Rational {\n    return this.add(other.negate());\n  }\n\n  multiply(other: Rational): Rational {\n    return Rational.of(this.numerator * other.numerator, this.denominator * other.denominator);\n  }\n\n  divide(other: Rational): Rational {\n    if (other.isZero()) throw new InvalidValue('Rational: division by zero');\n    return Rational.of(this.numerator * other.denominator, this.denominator * other.numerator);\n  }\n\n  negate(): Rational {\n    return new Rational(-this.numerator, this.denominator);\n  }\n\n  isZero(): boolean {\n    return this.numerator === 0n;\n  }\n\n  isNegative(): boolean {\n    return this.numerator < 0n;\n  }\n\n  compareTo(other: Rational): number {\n    const left = this.numerator * other.denominator;\n    const right = other.numerator * this.denominator;\n    return left < right ? -1 : left > right ? 1 : 0;\n  }\n\n  /**\n   * The largest integer not greater than this fraction — floor, not truncation, so that -0.5 becomes\n   * -1 and the fractional remainder stays in [0, 1) on both sides of zero. That property is what lets\n   * largest-remainder rounding work unchanged for negative amounts, and cost centres do carry\n   * negative balances (a credit note, a correction).\n   */\n  floorToBigInt(): bigint {\n    const quotient = this.numerator / this.denominator;\n    const remainder = this.numerator % this.denominator;\n    return remainder < 0n ? quotient - 1n : quotient;\n  }\n\n  /** This fraction minus its floor: always in [0, 1). */\n  fractionalPart(): Rational {\n    return this.subtract(Rational.of(this.floorToBigInt()));\n  }\n}\n","import Big from 'big.js';\nimport { DomainError } from '../../../domain-error.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { Ledger } from '../../../ledger/ledger.js';\nimport type {\n  AccountRepository,\n  CostingRunRepository,\n  InventoryValuationRepository,\n  JournalRepository,\n  VoucherRepository,\n} from '../../../port.js';\nimport { Voucher } from '../../../records/voucher.js';\nimport { AccountNumber } from '../../../substrate/account-number.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport type { IdGenerator } from '../../../substrate/id-generator.js';\nimport { Money } from '../../../substrate/money.js';\nimport { PeriodRef } from '../../../substrate/period-ref.js';\nimport { Rational } from '../../../substrate/rational.js';\nimport { Uuid } from '../../../substrate/uuid.js';\nimport type { CostingRun } from '../costing/costing-run.js';\nimport { InventoryValuation, type InventoryCategoryRow } from './inventory-valuation.js';\n\n/** Digits after the decimal point a derived unit value is carried at, before the product is rounded. */\nconst UNIT_SCALE = 6;\n\n/**\n * A decimal string echoed with **its own** scale.\n *\n * The PHP side gets this for free — `BigDecimal::of(\"12.00\")` prints `12.00` — while `Big(\"12.00\")`\n * normalises to `12`. A quantity that reads back as a different string in the two languages breaks\n * byte parity at the first export, which is why the scale of the input is carried rather than\n * inferred from the value.\n */\nfunction decimalString(value: Big, raw: string): string {\n  const dot = raw.indexOf('.');\n  return value.toFixed(dot === -1 ? 0 : raw.length - dot - 1);\n}\n\n/** Half-up away from zero at `UNIT_SCALE`, done exactly — the same rounding brick/math applies. */\nfunction unitValueString(value: Rational): string {\n  const scaled = value.multiply(Rational.of(10n ** BigInt(UNIT_SCALE)));\n  const negative = scaled.isNegative();\n  const magnitude = negative ? scaled.negate() : scaled;\n  const rounded = magnitude.add(Rational.of(1n, 2n)).floorToBigInt();\n  const digits = rounded.toString().padStart(UNIT_SCALE + 1, '0');\n  const decimal = `${digits.slice(0, digits.length - UNIT_SCALE)}.${digits.slice(digits.length - UNIT_SCALE)}`;\n  return negative ? `-${decimal}` : decimal;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Stock: measurement and posting (F-CORE-050).\n *\n * **The link that was missing.** Cost accounting justifies itself through a chain — cost centres →\n * allocation → overhead rates → production cost → *inventory valuation* → balance sheet — and only\n * the last link makes it bookkeeping rather than controlling. The middle was built and good; both\n * ends were missing. This is the outer one: the production cost the costing run computes now\n * reaches an account, and that account now reaches a balance-sheet position.\n *\n * **Socket and plug, as everywhere else.** The core knows *that* stock is carried at the lower of\n * its cost and a value the caller supplies, that the difference against what the books already\n * carry is booked, and that the counter-account is whatever the pack names for that category. It\n * knows nothing about *which* accounts, which categories a jurisdiction distinguishes, or whether\n * a change in raw materials belongs with material expense while a change in finished goods is its\n * own line — all of that is the `inventory` module.\n *\n * **The division the costing service refuses to do.** `computeProductionCost` deliberately does not\n * divide by a quantity, on the ground that the core carries no quantities. That is still true: it\n * carries none. Here a quantity is *handed in*, together with the produced quantity the run's total\n * relates to, and the division happens where both are declared inputs of one call. Nothing is\n * stored as a stock and nothing is carried forward.\n *\n * **Lower of cost or market, and why the mechanism is jurisdiction-free while the duty is not.**\n * Given a `marketValue` per unit, the lower of it and the unit cost is used, and the row says so.\n * Whether comparing is a duty, an option or forbidden is the pack's business; the arithmetic of\n * \"take the lower of two numbers and say which one you took\" is not. A row that only showed its\n * result would be unauditable, exactly as a production cost showing only its total would be.\n */\nexport class InventoryService {\n  private ruleModule: Record<string, unknown>;\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly runs: CostingRunRepository,\n    private readonly valuations: InventoryValuationRepository,\n    private readonly ledger: Ledger,\n    private readonly ids: IdGenerator,\n    ruleModule: Record<string, unknown> = {},\n    private readonly tenantId: Uuid | null = null,\n    private readonly audit: AuditWriter | null = null,\n  ) {\n    this.ruleModule = ruleModule;\n  }\n\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  /** Value the stock of one period and book the change (`valuateInventory`). */\n  valuate(input: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = typeof input.fiscalYear === 'number' ? input.fiscalYear : null;\n    const period = typeof input.period === 'number' ? input.period : null;\n\n    if (fiscalYear === null || period === null) {\n      throw new DomainError('E_INPUT_INVALID', 'valuateInventory: fiscalYear and period are required', {\n        field: 'fiscalYear',\n      });\n    }\n\n    const periodRef = new PeriodRef(fiscalYear, period);\n    const valuationDate = this.requireDate(input.valuationDate);\n    const categoryAccounts = this.packCategories();\n    const run = this.releasedRun(input.runId);\n    const producedQuantity = this.optionalDecimal(input.producedQuantity, 'producedQuantity');\n\n    const rows: InventoryCategoryRow[] = [];\n    const lines: Array<Record<string, unknown>> = [];\n    let closingTotal = Money.zero(this.baseCurrency);\n    let change = Money.zero(this.baseCurrency);\n\n    const categories = this.requireCategories(input.categories);\n    for (let index = 0; index < categories.length; index += 1) {\n      const row = this.valuateCategory(\n        categories[index] as Record<string, unknown>,\n        index,\n        categoryAccounts,\n        run,\n        producedQuantity,\n        periodRef,\n      );\n      rows.push(row);\n\n      closingTotal = closingTotal.add(Money.of(row.closingValue, this.baseCurrency));\n      const rowChange = Money.of(row.change, this.baseCurrency);\n      change = change.add(rowChange);\n\n      if (rowChange.isZero()) continue;\n\n      // An increase debits the stock account and credits the account the pack names; a decrease\n      // does the reverse. One entry for the whole valuation, because it is one act: splitting it\n      // per category would produce a set of entries an auditor has to recognise as belonging\n      // together from their dates.\n      const stockSide = rowChange.isPositive() ? 'debit' : 'credit';\n      const counterSide = rowChange.isPositive() ? 'credit' : 'debit';\n      const absolute = rowChange.abs().toJSON();\n\n      lines.push({ account: row.account, side: stockSide, money: absolute });\n      lines.push({ account: row.changeAccount, side: counterSide, money: absolute });\n    }\n\n    const entryId = lines.length === 0 ? null : this.postMachineEntry(valuationDate, periodRef, lines);\n\n    const valuation = new InventoryValuation(\n      this.ids.next(),\n      periodRef,\n      this.nextVersion(periodRef),\n      valuationDate,\n      run === null ? null : run.id,\n      rows,\n      closingTotal,\n      change,\n      entryId,\n    );\n    this.valuations.add(valuation);\n\n    if (this.audit !== null && this.tenantId !== null) {\n      this.audit.record(this.audit.actorOf(input), 'inventoryValuation', valuation.id, 'valued', {\n        fiscalYear: { from: null, to: fiscalYear },\n        period: { from: null, to: period },\n        closingTotal: { from: null, to: closingTotal.amountAsString() },\n        change: { from: null, to: change.amountAsString() },\n      });\n    }\n\n    return {\n      valuationId: valuation.id.value,\n      version: valuation.version,\n      closingTotal: closingTotal.toJSON(),\n      change: change.toJSON(),\n      // `false` is an answer, not a failure: a second valuation of an unchanged period books\n      // nothing, which is what makes repeating one harmless.\n      posted: entryId !== null,\n      entryId: entryId?.value ?? null,\n    };\n  }\n\n  /** What was valued, how, and out of what (`inventoryValuation`). */\n  valuationReport(params: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = typeof params.fiscalYear === 'number' ? params.fiscalYear : null;\n    const period = typeof params.period === 'number' ? params.period : null;\n\n    const rows = this.valuations\n      .all()\n      .filter((valuation) => fiscalYear === null || valuation.period.fiscalYear === fiscalYear)\n      .filter((valuation) => period === null || valuation.period.period === period)\n      .map((valuation) => ({\n        valuationId: valuation.id.value,\n        fiscalYear: valuation.period.fiscalYear,\n        period: valuation.period.period,\n        version: valuation.version,\n        valuationDate: valuation.valuationDate.iso,\n        runId: valuation.runId?.value ?? null,\n        categories: valuation.categories,\n        closingTotal: valuation.closingTotal.amountAsString(),\n        change: valuation.change.amountAsString(),\n        entryId: valuation.entryId?.value ?? null,\n      }));\n\n    return { valuations: rows };\n  }\n\n  private valuateCategory(\n    raw: Record<string, unknown>,\n    index: number,\n    categoryAccounts: Map<string, string>,\n    run: CostingRun | null,\n    producedQuantity: Big | null,\n    periodRef: PeriodRef,\n  ): InventoryCategoryRow {\n    const number = typeof raw.account === 'string' ? raw.account : '';\n    if (number === '') {\n      throw new DomainError('E_INPUT_INVALID', `valuateInventory: categories[${index}] requires \"account\"`, {\n        field: 'categories',\n      });\n    }\n\n    const account = this.accounts.byNumber(AccountNumber.of(number));\n    if (account === null) {\n      throw new DomainError('E_ACCOUNT_UNKNOWN', `valuateInventory: account ${number} does not exist`, {\n        account: number,\n      });\n    }\n\n    // The reader that earns `inventory` its place in the closed subtype repertoire. Valuing stock\n    // onto an account that is not a stock account would balance, satisfy every invariant and put\n    // the figure in the wrong balance-sheet position — the inert-annotation defect the repertoire\n    // was closed for, with a wrong number instead of a missing one.\n    if (account.subtype !== 'inventory') {\n      throw new DomainError(\n        'E_INVENTORY_ACCOUNT_INVALID',\n        `valuateInventory: account ${number} is not a stock account (subtype \"inventory\")`,\n        { account: number, subtype: account.subtype },\n      );\n    }\n\n    const changeAccount = categoryAccounts.get(number);\n    if (changeAccount === undefined) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        `the pack declares no change account for stock account ${number}`,\n        { account: number },\n      );\n    }\n\n    const quantityRaw = this.requireRawString(raw.quantity, `categories[${index}].quantity`);\n    const quantity = this.requireDecimal(quantityRaw, `categories[${index}].quantity`);\n    if (quantity.lt(0)) {\n      throw new DomainError('E_INPUT_INVALID', `valuateInventory: categories[${index}] has a negative quantity`, {\n        field: 'categories',\n        account: number,\n      });\n    }\n\n    const [unitCost, unitCostText, source] = this.unitCost(raw, index, run, producedQuantity);\n    const marketRaw = raw.marketValue === null || raw.marketValue === undefined\n      ? null\n      : this.requireRawString(raw.marketValue, `categories[${index}].marketValue`);\n    const marketValue = marketRaw === null ? null : this.requireDecimal(marketRaw, `categories[${index}].marketValue`);\n    const marketText = marketValue === null || marketRaw === null ? null : decimalString(marketValue, marketRaw);\n\n    const writtenDown = marketValue !== null && marketValue.lt(unitCost);\n    const unitValue = writtenDown && marketValue !== null ? marketValue : unitCost;\n    const unitValueText = writtenDown && marketText !== null ? marketText : unitCostText;\n\n    // One rounding, on the product — not a rounded unit value multiplied by a quantity. With 3,000\n    // units the two differ by up to fifteen euros, and the difference lands in the balance sheet.\n    const closingValue = Money.fromCalculation(quantity.times(unitValue), this.baseCurrency);\n    const openingValue = this.carryingAmount(number, periodRef);\n\n    return {\n      account: number,\n      quantity: decimalString(quantity, quantityRaw),\n      unitCost: unitCostText,\n      marketValue: marketText,\n      unitValue: unitValueText,\n      source,\n      openingValue: openingValue.amountAsString(),\n      closingValue: closingValue.amountAsString(),\n      change: closingValue.subtract(openingValue).amountAsString(),\n      changeAccount,\n      writtenDownToMarket: writtenDown,\n    };\n  }\n\n  /** Where a unit value comes from, and it is never guessed. */\n  private unitCost(\n    raw: Record<string, unknown>,\n    index: number,\n    run: CostingRun | null,\n    producedQuantity: Big | null,\n  ): [Big, string, string] {\n    if (raw.unitCost !== null && raw.unitCost !== undefined) {\n      const text = this.requireRawString(raw.unitCost, `categories[${index}].unitCost`);\n      const value = this.requireDecimal(text, `categories[${index}].unitCost`);\n      return [value, decimalString(value, text), 'input'];\n    }\n\n    if (run === null) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `valuateInventory: categories[${index}] has no unitCost and no released costing run to derive one from`,\n        { field: 'categories' },\n      );\n    }\n\n    if (run.productionCost === null) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `costing run ${run.id.value} carries no production cost — declare the components in setAllocationScheme before the run`,\n        { runId: run.id.value },\n      );\n    }\n\n    if (producedQuantity === null || producedQuantity.lte(0)) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'valuateInventory: deriving a unit cost from a costing run needs a positive producedQuantity',\n        { field: 'producedQuantity' },\n      );\n    }\n\n    // Exact division and one exact rounding, via Rational rather than Big: a unit cost is not Money\n    // — it is an intermediate — and rounding it to cents here would be the error the comment on\n    // `closingValue` avoids, moved one line up. Rational is what keeps the result bit-for-bit\n    // identical to the PHP side's `dividedBy(q, 6, HalfUp)`.\n    const total = Rational.fromDecimalString(run.productionCost.total);\n    const divisor = Rational.fromDecimalString(producedQuantity.toFixed());\n    const text = unitValueString(total.divide(divisor));\n\n    return [new Big(text), text, 'productionCost'];\n  }\n\n  /**\n   * What the books already carry on this account, up to and including the valuation period.\n   *\n   * Cumulative across fiscal years, because a stock account is a balance-carrying account and\n   * carries forward implicitly (F-CORE-021) — there is no opening entry to read instead.\n   */\n  private carryingAmount(number: string, periodRef: PeriodRef): Money {\n    let total = Money.zero(this.baseCurrency);\n\n    for (const entry of this.journal.all()) {\n      const entryYear = entry.periodRef.fiscalYear;\n      if (entryYear > periodRef.fiscalYear) continue;\n      if (entryYear === periodRef.fiscalYear && entry.periodRef.period > periodRef.period) continue;\n\n      for (const line of entry.lines()) {\n        const account = this.accounts.byId(line.accountId);\n        if (account === null || account.number.toString() !== number) continue;\n        total = line.side === 'debit' ? total.add(line.money) : total.subtract(line.money);\n      }\n    }\n\n    return total;\n  }\n\n  /** stock account -> change account */\n  private packCategories(): Map<string, string> {\n    const module = isRecord(this.ruleModule.inventory) ? this.ruleModule.inventory : null;\n    if (module === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'inventory was valued, but the pack declares no inventory categories',\n        { field: 'inventory' },\n      );\n    }\n\n    const map = new Map<string, string>();\n    for (const category of Array.isArray(module.categories) ? module.categories : []) {\n      if (!isRecord(category)) continue;\n      if (typeof category.account === 'string' && typeof category.changeAccount === 'string') {\n        map.set(category.account, category.changeAccount);\n      }\n    }\n\n    return map;\n  }\n\n  private releasedRun(runId: unknown): CostingRun | null {\n    if (typeof runId !== 'string' || runId === '') return null;\n\n    let run: CostingRun | null;\n    try {\n      run = this.runs.byId(Uuid.fromString(runId));\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      run = null;\n    }\n\n    if (run === null) {\n      throw new DomainError('E_COSTING_RUN_UNKNOWN', `costing run ${runId} does not exist`, { runId });\n    }\n\n    // A draft is a working figure. Valuing the balance sheet out of one would put a number in the\n    // books that its own producer has not stood behind, and the two conditions need opposite\n    // corrections — release it, or name a different run — which is why this is not\n    // E_COSTING_RUN_UNKNOWN.\n    if (run.status() !== 'released') {\n      throw new DomainError(\n        'E_COSTING_RUN_NOT_RELEASED',\n        `costing run ${runId} is a draft — release it before valuing stock from it`,\n        { runId, status: run.status() },\n      );\n    }\n\n    return run;\n  }\n\n  private requireCategories(raw: unknown): Array<Record<string, unknown>> {\n    if (!Array.isArray(raw) || raw.length === 0) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'valuateInventory: at least one category is required — a valuation of nothing is not a valuation of zero',\n        { field: 'categories' },\n      );\n    }\n\n    return raw.map((entry) => {\n      if (!isRecord(entry)) {\n        throw new DomainError('E_INPUT_INVALID', 'valuateInventory: every category must be an object', {\n          field: 'categories',\n        });\n      }\n      return entry;\n    });\n  }\n\n  private requireDate(raw: unknown): CalendarDate {\n    if (typeof raw !== 'string' || raw === '') {\n      throw new DomainError('E_INPUT_INVALID', 'valuateInventory: valuationDate is required', {\n        field: 'valuationDate',\n      });\n    }\n\n    try {\n      return CalendarDate.of(raw);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', 'valuateInventory: valuationDate is not a calendar date', {\n        field: 'valuationDate',\n      });\n    }\n  }\n\n  /**\n   * Strings only, exactly as Money takes strings only. A JSON number has already lost the argument\n   * before it arrives: 0.1 is not 0.1, and a quantity that reads back differently in the two\n   * languages breaks byte parity at the first export.\n   */\n  private requireRawString(raw: unknown, field: string): string {\n    if (typeof raw !== 'string' || raw === '') {\n      throw new DomainError('E_INPUT_INVALID', `valuateInventory: ${field} must be a decimal string`, { field });\n    }\n    return raw;\n  }\n\n  private requireDecimal(raw: string, field: string): Big {\n    try {\n      return new Big(raw);\n    } catch {\n      throw new DomainError('E_INPUT_INVALID', `valuateInventory: ${field} is not a decimal number`, { field });\n    }\n  }\n\n  private optionalDecimal(raw: unknown, field: string): Big | null {\n    if (raw === null || raw === undefined) return null;\n    return this.requireDecimal(this.requireRawString(raw, field), field);\n  }\n\n  private nextVersion(periodRef: PeriodRef): number {\n    let version = 0;\n    for (const valuation of this.valuations.all()) {\n      if (\n        valuation.period.fiscalYear === periodRef.fiscalYear &&\n        valuation.period.period === periodRef.period\n      ) {\n        version = Math.max(version, valuation.version);\n      }\n    }\n    return version + 1;\n  }\n\n  private postMachineEntry(\n    date: CalendarDate,\n    periodRef: PeriodRef,\n    lines: Array<Record<string, unknown>>,\n  ): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `INV-${periodRef.fiscalYear}-${String(periodRef.period).padStart(2, '0')}`,\n      voucherDate: date,\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n\n    const result = this.ledger.post({\n      entryDate: date.iso,\n      voucherId: voucher.id.value,\n      text: `Inventory valuation ${periodRef.fiscalYear}/${String(periodRef.period).padStart(2, '0')}`,\n      lines,\n    });\n\n    // Machine-generated, like a depreciation run: finalized immediately, because a hand correction\n    // of a valuation posting would leave the record and the books disagreeing.\n    this.ledger.finalize({ entryId: result.entry.id.value });\n\n    return result.entry.id;\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport type { AccountNumber } from '../../../substrate/account-number.js';\nimport type { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Money } from '../../../substrate/money.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\n\nexport interface ProvisionMovement {\n  kind: string;\n  date: CalendarDate;\n  amount: Money;\n  entryId: Uuid | null;\n  note: string | null;\n}\n\n/**\n * A provision, with its history (F-CORE-051).\n *\n * **Why this is an aggregate and not just a balance.** The balance of a provision account answers\n * almost nothing an auditor asks. What was set aside, for what, when, at what estimate — and then\n * what happened to it: was it *used* because the obligation materialised, *released* because the\n * reason ceased, or *re-measured* because the estimate moved? Those are three different events with\n * three different postings and three different meanings, and a netted balance shows none of them.\n * Same reason the asset register exists next to the asset accounts.\n *\n * **The movement list is the point, and it is append-only.** Every step names the entry it produced,\n * so the register and the journal can be walked against each other in both directions. Nothing here\n * is ever edited: a re-measurement is a new movement, not a corrected old one.\n *\n * **`settled` is not `released`.** A provision reaches `settled` when its carrying amount is zero,\n * however it got there. *How* it got there is in the movements, and the difference matters: a\n * release is income the business never had to pay, a use is an obligation that came true. A status\n * field that collapsed the two would be the same kind of lie as a netted balance.\n */\nexport class Provision {\n  private movementList: ProvisionMovement[] = [];\n\n  private carrying: Money;\n\n  constructor(\n    readonly id: Uuid,\n    readonly reason: string,\n    readonly account: AccountNumber,\n    readonly expenseAccount: AccountNumber,\n    readonly releaseAccount: AccountNumber,\n    readonly recognizedOn: CalendarDate,\n    readonly dueDate: CalendarDate | null,\n    /** The undiscounted best estimate of the amount needed to settle (the *Erfüllungsbetrag*). */\n    readonly settlementAmount: Money,\n    /** What was actually recognised — the present value where discounting applied. */\n    recognizedAmount: Money,\n    /** The rate the discount used, as a percentage string, or null where nothing was discounted. */\n    readonly discountRate: string | null,\n  ) {\n    this.carrying = recognizedAmount;\n  }\n\n  carryingAmount(): Money {\n    return this.carrying;\n  }\n\n  isSettled(): boolean {\n    return this.carrying.isZero();\n  }\n\n  status(): string {\n    return this.isSettled() ? 'settled' : 'open';\n  }\n\n  movements(): ProvisionMovement[] {\n    return this.movementList;\n  }\n\n  record(kind: string, date: CalendarDate, amount: Money, entryId: Uuid | null, note: string | null = null): void {\n    this.movementList.push({ kind, date, amount, entryId, note });\n  }\n\n  /**\n   * Move the carrying amount. Never below zero — a provision that has given back more than it held\n   * would be income invented out of a sign error, and the operations that call this each cap their\n   * own amount, so reaching here is a bug rather than a user mistake.\n   */\n  moveCarryingAmount(delta: Money): void {\n    const next = this.carrying.add(delta);\n\n    if (next.isNegative()) {\n      throw new DomainError(\n        'E_PROVISION_EXCEEDS_CARRYING',\n        `provision ${this.id.value} carries ${this.carrying.amountAsString()} — ` +\n          `${delta.abs().amountAsString()} cannot be taken from it`,\n        { provisionId: this.id.value, carryingAmount: this.carrying.amountAsString() },\n      );\n    }\n\n    this.carrying = next;\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      reason: this.reason,\n      account: this.account.toString(),\n      expenseAccount: this.expenseAccount.toString(),\n      releaseAccount: this.releaseAccount.toString(),\n      recognizedOn: this.recognizedOn.iso,\n      dueDate: this.dueDate?.iso ?? null,\n      settlementAmount: this.settlementAmount.toJSON(),\n      carryingAmount: this.carrying.toJSON(),\n      discountRate: this.discountRate,\n      movements: this.movementList.map((movement) => ({\n        kind: movement.kind,\n        date: movement.date.iso,\n        amount: movement.amount.toJSON(),\n        entryId: movement.entryId?.value ?? null,\n        note: movement.note,\n      })),\n    };\n  }\n\n  /**\n   * Restore from persistence — the carrying amount and the movements are taken over directly, no\n   * replay. Replaying them would recompute a history that is already a fact.\n   */\n  static restore(\n    id: Uuid,\n    reason: string,\n    account: AccountNumber,\n    expenseAccount: AccountNumber,\n    releaseAccount: AccountNumber,\n    recognizedOn: CalendarDate,\n    dueDate: CalendarDate | null,\n    settlementAmount: Money,\n    carryingAmount: Money,\n    discountRate: string | null,\n    movements: ProvisionMovement[],\n  ): Provision {\n    const provision = new Provision(\n      id,\n      reason,\n      account,\n      expenseAccount,\n      releaseAccount,\n      recognizedOn,\n      dueDate,\n      settlementAmount,\n      carryingAmount,\n      discountRate,\n    );\n    provision.movementList = movements;\n    return provision;\n  }\n}\n","import Big from 'big.js';\nimport { DomainError } from '../../../domain-error.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { Ledger } from '../../../ledger/ledger.js';\nimport type { AccountRepository, ProvisionRepository, VoucherRepository } from '../../../port.js';\nimport { Voucher } from '../../../records/voucher.js';\nimport { AccountNumber } from '../../../substrate/account-number.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport type { IdGenerator } from '../../../substrate/id-generator.js';\nimport { Money } from '../../../substrate/money.js';\nimport { Uuid } from '../../../substrate/uuid.js';\nimport { Provision } from './provision.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Provisions: formation, use, release, re-measurement (F-CORE-051).\n *\n * **Why this is a duty and not a feature.** A provision is the one balance-sheet item a business\n * must recognise for something that has *not yet happened* — an obligation whose amount or timing\n * is uncertain. Leaving it out overstates the result and the equity, which is why the law makes it\n * mandatory rather than optional. summae had nothing: no account, no position, no operation, zero\n * occurrences in either core. A balance sheet without it is not merely incomplete, it is wrong in a\n * direction that flatters.\n *\n * **Four operations, because there are four events and they mean different things.** Recognising is\n * an expense for a future obligation. *Using* it is that obligation coming true. *Releasing* it is\n * the obligation going away — income the business never had to pay. *Re-measuring* is the estimate\n * moving while the obligation stands. A design with one \"adjust\" would net these into a number that\n * answers none of the questions an auditor asks, which is the same defect as reading a provision\n * off an account balance.\n *\n * **Socket and plug.** The core knows *that* a provision is recognised as an expense against a\n * liability account, that using it settles against something else, that releasing it is income, and\n * that a long-dated one is discounted. Which accounts, whether discounting applies at all and from\n * what remaining term — all pack.\n *\n * **The discount rate is deliberately not shipped, and that is a decision rather than a gap.** The\n * pack declares the *rule* (discount from a remaining term of n months, compounded annually) and\n * cites its basis; the *rate* arrives per act as an input. In Germany it is an average of the last\n * seven years' market rates, published **monthly** — a number that would be stale in a pack file\n * before anybody upgraded, and a stale legal rate that looks authoritative is worse than an absent\n * one. So a provision that must be discounted and carries no rate is refused, by name, rather than\n * recognised undiscounted.\n */\nexport class ProvisionService {\n  private ruleModule: Record<string, unknown>;\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly provisions: ProvisionRepository,\n    private readonly ledger: Ledger,\n    private readonly ids: IdGenerator,\n    ruleModule: Record<string, unknown> = {},\n    private readonly audit: AuditWriter | null = null,\n  ) {\n    this.ruleModule = ruleModule;\n  }\n\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  /** Recognise a provision (`recognizeProvision`). */\n  recognize(input: Record<string, unknown>): Record<string, unknown> {\n    const module = this.packModule();\n    const number = this.requireString(input.account, 'account');\n    const declared = this.declaredAccount(module, number);\n\n    const reason = this.requireString(input.reason, 'reason');\n    const recognizedOn = this.requireDate(input.recognizedOn, 'recognizedOn');\n    const dueDate = this.optionalDate(input.dueDate, 'dueDate');\n    const settlementAmount = this.requireMoney(input.amount, 'amount');\n\n    if (!settlementAmount.isPositive()) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'recognizeProvision: amount must be positive — a provision of nothing is not a provision',\n        { field: 'amount' },\n      );\n    }\n\n    const [recognized, rate] = this.discount(module, settlementAmount, recognizedOn, dueDate, input);\n\n    const provision = new Provision(\n      this.ids.next(),\n      reason,\n      AccountNumber.of(number),\n      AccountNumber.of(declared.expenseAccount),\n      AccountNumber.of(declared.releaseAccount),\n      recognizedOn,\n      dueDate,\n      settlementAmount,\n      recognized,\n      rate,\n    );\n\n    const entryId = this.post(recognizedOn, `Provision ${reason}`, 'RST', [\n      { account: declared.expenseAccount, side: 'debit', money: recognized.toJSON() },\n      { account: number, side: 'credit', money: recognized.toJSON() },\n    ]);\n\n    provision.record('recognized', recognizedOn, recognized, entryId);\n    this.provisions.add(provision);\n    this.trace(input, provision, 'recognized', {\n      reason: { from: null, to: reason },\n      amount: { from: null, to: recognized.amountAsString() },\n    });\n\n    return {\n      provisionId: provision.id.value,\n      settlementAmount: settlementAmount.toJSON(),\n      carryingAmount: recognized.toJSON(),\n      discounted: rate !== null,\n      discountRate: rate,\n      entryId: entryId.value,\n    };\n  }\n\n  /** The obligation came true (`useProvision`). */\n  use(input: Record<string, unknown>): Record<string, unknown> {\n    const provision = this.require(input.provisionId);\n    const date = this.requireDate(input.date, 'date');\n    const amount = this.requireMoney(input.amount, 'amount');\n    const settlementAccount = this.requireExistingAccount(input.settlementAccount, 'settlementAccount');\n\n    if (!amount.isPositive()) {\n      throw new DomainError('E_INPUT_INVALID', 'useProvision: amount must be positive', { field: 'amount' });\n    }\n\n    const carrying = provision.carryingAmount();\n    // The overshoot is the case worth getting right, and it is common: the invoice arrives larger\n    // than the estimate. What was provided for is taken out of the provision; the rest is an expense\n    // of the year the invoice arrived, NOT a retroactive correction of the year the provision was\n    // formed. Netting the two would move an expense across a closed year.\n    const fromProvision = amount.compareTo(carrying) > 0 ? carrying : amount;\n    const excess = amount.subtract(fromProvision);\n\n    const lines: Array<Record<string, unknown>> = [];\n    if (!fromProvision.isZero()) {\n      lines.push({ account: provision.account.toString(), side: 'debit', money: fromProvision.toJSON() });\n    }\n    if (!excess.isZero()) {\n      lines.push({ account: provision.expenseAccount.toString(), side: 'debit', money: excess.toJSON() });\n    }\n    lines.push({ account: settlementAccount, side: 'credit', money: amount.toJSON() });\n\n    const entryId = this.post(date, `Provision used: ${provision.reason}`, 'RST-V', lines);\n\n    provision.moveCarryingAmount(fromProvision.negate());\n    provision.record(\n      'used',\n      date,\n      fromProvision,\n      entryId,\n      excess.isZero()\n        ? null\n        : `settled at ${amount.amountAsString()}, ${excess.amountAsString()} more than provided for`,\n    );\n    this.provisions.save(provision);\n    this.trace(input, provision, 'used', {\n      carryingAmount: { from: carrying.amountAsString(), to: provision.carryingAmount().amountAsString() },\n    });\n\n    return {\n      provisionId: provision.id.value,\n      usedFromProvision: fromProvision.toJSON(),\n      excessExpense: excess.toJSON(),\n      carryingAmount: provision.carryingAmount().toJSON(),\n      status: provision.status(),\n      entryId: entryId.value,\n    };\n  }\n\n  /** The reason ceased (`releaseProvision`). */\n  release(input: Record<string, unknown>): Record<string, unknown> {\n    const provision = this.require(input.provisionId);\n    const date = this.requireDate(input.date, 'date');\n    const carrying = provision.carryingAmount();\n    const amount =\n      input.amount === null || input.amount === undefined ? carrying : this.requireMoney(input.amount, 'amount');\n\n    if (amount.isNegative()) {\n      throw new DomainError('E_INPUT_INVALID', 'releaseProvision: amount must not be negative', { field: 'amount' });\n    }\n\n    if (amount.compareTo(carrying) > 0) {\n      throw new DomainError(\n        'E_PROVISION_EXCEEDS_CARRYING',\n        `provision ${provision.id.value} carries ${carrying.amountAsString()} — ` +\n          `${amount.amountAsString()} cannot be released from it`,\n        { provisionId: provision.id.value, carryingAmount: carrying.amountAsString() },\n      );\n    }\n\n    let entryId: Uuid | null = null;\n    if (!amount.isZero()) {\n      entryId = this.post(date, `Provision released: ${provision.reason}`, 'RST-A', [\n        { account: provision.account.toString(), side: 'debit', money: amount.toJSON() },\n        { account: provision.releaseAccount.toString(), side: 'credit', money: amount.toJSON() },\n      ]);\n      provision.moveCarryingAmount(amount.negate());\n    }\n\n    provision.record('released', date, amount, entryId);\n    this.provisions.save(provision);\n    this.trace(input, provision, 'released', {\n      carryingAmount: { from: carrying.amountAsString(), to: provision.carryingAmount().amountAsString() },\n    });\n\n    return {\n      provisionId: provision.id.value,\n      released: amount.toJSON(),\n      carryingAmount: provision.carryingAmount().toJSON(),\n      status: provision.status(),\n      entryId: entryId?.value ?? null,\n    };\n  }\n\n  /** The estimate moved while the obligation stands (`remeasureProvision`). */\n  remeasure(input: Record<string, unknown>): Record<string, unknown> {\n    const provision = this.require(input.provisionId);\n    const date = this.requireDate(input.date, 'date');\n    const target = this.requireMoney(input.amount, 'amount');\n\n    if (target.isNegative()) {\n      throw new DomainError('E_INPUT_INVALID', 'remeasureProvision: amount must not be negative', { field: 'amount' });\n    }\n\n    const [targetCarrying, rate] = this.discount(this.packModule(), target, date, provision.dueDate, input);\n\n    const carrying = provision.carryingAmount();\n    const delta = targetCarrying.subtract(carrying);\n\n    let entryId: Uuid | null = null;\n    if (!delta.isZero()) {\n      // An increase is a further expense; a decrease is income under the release account, because\n      // that is what a partial reversal of a provision IS — the same account a full release books\n      // to, so the two cannot be told apart in the accounts by accident.\n      const lines = delta.isPositive()\n        ? [\n            { account: provision.expenseAccount.toString(), side: 'debit', money: delta.toJSON() },\n            { account: provision.account.toString(), side: 'credit', money: delta.toJSON() },\n          ]\n        : [\n            { account: provision.account.toString(), side: 'debit', money: delta.abs().toJSON() },\n            { account: provision.releaseAccount.toString(), side: 'credit', money: delta.abs().toJSON() },\n          ];\n\n      entryId = this.post(date, `Provision remeasured: ${provision.reason}`, 'RST-B', lines);\n      provision.moveCarryingAmount(delta);\n    }\n\n    provision.record('remeasured', date, delta, entryId, rate === null ? null : `discounted at ${rate}%`);\n    this.provisions.save(provision);\n    this.trace(input, provision, 'remeasured', {\n      carryingAmount: { from: carrying.amountAsString(), to: provision.carryingAmount().amountAsString() },\n    });\n\n    return {\n      provisionId: provision.id.value,\n      change: delta.toJSON(),\n      carryingAmount: provision.carryingAmount().toJSON(),\n      discounted: rate !== null,\n      discountRate: rate,\n      status: provision.status(),\n      entryId: entryId?.value ?? null,\n    };\n  }\n\n  /** The register (`provisionRegister`). */\n  register(params: Record<string, unknown>): Record<string, unknown> {\n    const status = typeof params.status === 'string' ? params.status : null;\n    const asOf = this.optionalDate(params.asOf, 'asOf');\n\n    const rows: Array<Record<string, unknown>> = [];\n    let total = Money.zero(this.baseCurrency);\n\n    for (const provision of this.provisions.all()) {\n      if (status !== null && provision.status() !== status) continue;\n      if (asOf !== null && provision.recognizedOn.iso > asOf.iso) continue;\n\n      const movements = provision\n        .movements()\n        .filter((movement) => asOf === null || movement.date.iso <= asOf.iso)\n        .map((movement) => ({\n          kind: movement.kind,\n          date: movement.date.iso,\n          amount: movement.amount.amountAsString(),\n          entryId: movement.entryId?.value ?? null,\n          note: movement.note,\n        }));\n\n      rows.push({\n        provisionId: provision.id.value,\n        reason: provision.reason,\n        account: provision.account.toString(),\n        recognizedOn: provision.recognizedOn.iso,\n        dueDate: provision.dueDate?.iso ?? null,\n        settlementAmount: provision.settlementAmount.amountAsString(),\n        carryingAmount: provision.carryingAmount().amountAsString(),\n        discountRate: provision.discountRate,\n        status: provision.status(),\n        movements,\n      });\n      total = total.add(provision.carryingAmount());\n    }\n\n    return { provisions: rows, total: total.amountAsString() };\n  }\n\n  /** Discounting: mechanism here, everything jurisdictional in the pack. */\n  private discount(\n    module: Record<string, unknown>,\n    amount: Money,\n    from: CalendarDate,\n    dueDate: CalendarDate | null,\n    input: Record<string, unknown>,\n  ): [Money, string | null] {\n    const rule = isRecord(module.discounting) ? module.discounting : null;\n    if (rule === null || dueDate === null) return [amount, null];\n\n    const fromMonths = typeof rule.fromMonths === 'number' ? rule.fromMonths : 12;\n    const months = monthsBetween(from, dueDate);\n\n    if (months <= fromMonths) return [amount, null];\n\n    const rate = input.discountRate;\n    if (typeof rate !== 'string' || rate === '') {\n      // Refused rather than recognised undiscounted, and the message says what is needed. The rate\n      // is published periodically and is not a pack constant — a stale legal rate that looks\n      // authoritative is worse than an absent one.\n      throw new DomainError(\n        'E_PROVISION_DISCOUNT_RATE_REQUIRED',\n        `this provision runs ${months} months and must be discounted — supply discountRate ` +\n          `(${typeof rule.basis === 'string' ? rule.basis : 'see the pack'})`,\n        { months, fromMonths },\n      );\n    }\n\n    let percent: Big;\n    try {\n      percent = new Big(rate);\n    } catch {\n      throw new DomainError('E_INPUT_INVALID', 'discountRate is not a decimal number', { field: 'discountRate' });\n    }\n\n    if (percent.lt(0)) {\n      throw new DomainError('E_INPUT_INVALID', 'discountRate must not be negative', { field: 'discountRate' });\n    }\n\n    // **The compounding convention, and why it is this one.** Whole years compound; the remaining\n    // months of the stub period accrue simple interest:\n    //\n    //     PV = amount / ( (1 + r)^years x (1 + r x months/12) )\n    //\n    // The statute prescribes a rate, not a convention, so this is a choice — and it is made for a\n    // reason a shared oracle forces: a genuine fractional power (1+r)^(n/12) is a transcendental,\n    // and computing one here and in PHP would put the two a cent apart on some inputs. Everything\n    // here is exact decimal arithmetic — an integer power, one multiplication, one division — so\n    // both languages reach the same cent by construction. The mixed convention is ordinary practice\n    // for a stub period and errs on the small side of the discount, which is the prudent direction\n    // for a liability.\n    const years = Math.trunc(months / 12);\n    const stubMonths = months % 12;\n\n    const r = percent.div(100).round(12, Big.roundHalfUp);\n    const factor = new Big(1).plus(r).pow(Math.max(0, years));\n    const stub = new Big(1).plus(r.times(stubMonths).div(12).round(12, Big.roundHalfUp));\n\n    // `div` runs at big.js's default 20 decimal places, which is the scale the PHP side divides at\n    // for exactly this reason. Rounding twice at the same two scales in both languages is what\n    // makes the last cent equal; rounding at different intermediate scales would not.\n    const value = Money.fromCalculation(new Big(amount.amountAsString()).div(factor.times(stub)), this.baseCurrency);\n\n    // The rate is reported back exactly as it was given, not re-serialised from the parsed number.\n    // `BigDecimal` keeps the scale of its input and `Big` does not, so `2.00` would come back as\n    // `2` here — a difference that reaches the export and breaks byte parity for no gain at all.\n    return [value, rate];\n  }\n\n  private declaredAccount(\n    module: Record<string, unknown>,\n    number: string,\n  ): { expenseAccount: string; releaseAccount: string } {\n    for (const declared of Array.isArray(module.accounts) ? module.accounts : []) {\n      if (!isRecord(declared) || declared.account !== number) continue;\n\n      const expense = declared.expenseAccount;\n      const release = declared.releaseAccount;\n      if (typeof expense !== 'string' || typeof release !== 'string') {\n        throw new DomainError(\n          'E_PACK_INCOHERENT',\n          `the pack declares provision account ${number} without an expense or release account`,\n          { account: number },\n        );\n      }\n\n      return { expenseAccount: expense, releaseAccount: release };\n    }\n\n    // Two guards, and this is the one that blames the right party. The subtype check below says\n    // \"you named the wrong account\"; this one says \"your pack has nothing to say about this\n    // account\", which needs a different fix.\n    const account = this.accounts.byNumber(AccountNumber.of(number));\n    if (account === null) {\n      throw new DomainError('E_ACCOUNT_UNKNOWN', `recognizeProvision: account ${number} does not exist`, {\n        account: number,\n      });\n    }\n\n    if (account.subtype !== 'provision') {\n      throw new DomainError(\n        'E_PROVISION_ACCOUNT_INVALID',\n        `recognizeProvision: account ${number} is not a provision account (subtype \"provision\")`,\n        { account: number, subtype: account.subtype },\n      );\n    }\n\n    throw new DomainError(\n      'E_PACK_INCOHERENT',\n      `the pack declares no expense and release account for provision account ${number}`,\n      { account: number },\n    );\n  }\n\n  private packModule(): Record<string, unknown> {\n    const module = isRecord(this.ruleModule.provisions) ? this.ruleModule.provisions : null;\n    if (module === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'a provision was recognised, but the pack declares no provision accounts',\n        { field: 'provisions' },\n      );\n    }\n    return module;\n  }\n\n  require(provisionId: unknown): Provision {\n    let provision: Provision | null = null;\n\n    if (typeof provisionId === 'string' && provisionId !== '') {\n      try {\n        provision = this.provisions.byId(Uuid.fromString(provisionId));\n      } catch (error) {\n        if (!(error instanceof InvalidValue)) throw error;\n        provision = null;\n      }\n    }\n\n    if (provision === null) {\n      throw new DomainError(\n        'E_PROVISION_UNKNOWN',\n        `provision ${typeof provisionId === 'string' ? provisionId : ''} does not exist`,\n        { provisionId },\n      );\n    }\n\n    return provision;\n  }\n\n  private trace(\n    input: Record<string, unknown>,\n    provision: Provision,\n    action: string,\n    changes: Record<string, { from: unknown; to: unknown }>,\n  ): void {\n    this.audit?.record(this.audit.actorOf(input), 'provision', provision.id, action, changes);\n  }\n\n  private post(\n    date: CalendarDate,\n    text: string,\n    voucherPrefix: string,\n    lines: Array<Record<string, unknown>>,\n  ): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `${voucherPrefix}-${date.iso.replaceAll('-', '')}`,\n      voucherDate: date,\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n\n    const result = this.ledger.post({\n      entryDate: date.iso,\n      voucherId: voucher.id.value,\n      text,\n      lines,\n    });\n    // Machine-generated, like a depreciation run and a stock valuation: finalized immediately,\n    // because a hand correction would leave the register and the books disagreeing.\n    this.ledger.finalize({ entryId: result.entry.id.value });\n\n    return result.entry.id;\n  }\n\n  private requireString(raw: unknown, field: string): string {\n    if (typeof raw !== 'string' || raw.trim() === '') {\n      throw new DomainError('E_INPUT_INVALID', `${field} is required`, { field });\n    }\n    return raw;\n  }\n\n  private requireExistingAccount(raw: unknown, field: string): string {\n    const number = this.requireString(raw, field);\n\n    if (this.accounts.byNumber(AccountNumber.of(number)) === null) {\n      throw new DomainError('E_ACCOUNT_UNKNOWN', `account ${number} does not exist`, { account: number });\n    }\n\n    return number;\n  }\n\n  private requireDate(raw: unknown, field: string): CalendarDate {\n    const date = this.optionalDate(raw, field);\n    if (date === null) {\n      throw new DomainError('E_INPUT_INVALID', `${field} is required`, { field });\n    }\n    return date;\n  }\n\n  private optionalDate(raw: unknown, field: string): CalendarDate | null {\n    if (raw === null || raw === undefined) return null;\n\n    if (typeof raw !== 'string' || raw === '') {\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a calendar date`, { field });\n    }\n\n    try {\n      return CalendarDate.of(raw);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a calendar date`, { field });\n    }\n  }\n\n  private requireMoney(raw: unknown, field: string): Money {\n    if (!isRecord(raw) || typeof raw.amount !== 'string') {\n      throw new DomainError('E_INPUT_INVALID', `${field} must be a money object`, { field });\n    }\n\n    const currency = typeof raw.currency === 'string' ? raw.currency : this.baseCurrency.code;\n\n    try {\n      return Money.of(raw.amount, currency);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a valid amount`, { field });\n    }\n  }\n}\n\nfunction monthsBetween(from: CalendarDate, to: CalendarDate): number {\n  const fromYear = Number(from.iso.slice(0, 4));\n  const fromMonth = Number(from.iso.slice(5, 7));\n  const fromDay = Number(from.iso.slice(8, 10));\n  const toYear = Number(to.iso.slice(0, 4));\n  const toMonth = Number(to.iso.slice(5, 7));\n  const toDay = Number(to.iso.slice(8, 10));\n\n  let months = (toYear - fromYear) * 12 + (toMonth - fromMonth);\n  if (toDay < fromDay) months -= 1;\n\n  return months;\n}\n","import type { AccountNumber } from '../../../substrate/account-number.js';\nimport type { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Money } from '../../../substrate/money.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\n\nexport interface DeferralInstalment {\n  fiscalYear: number;\n  period: number;\n  amount: Money;\n}\n\nexport interface DeferralRelease extends DeferralInstalment {\n  date: CalendarDate;\n  entryId: Uuid;\n}\n\nexport const PREPAID_EXPENSE = 'prepaidExpense';\nexport const DEFERRED_INCOME = 'deferredIncome';\n\n/** The closed vocabulary — a third kind would be a third direction of posting. */\nexport const DEFERRAL_KINDS: readonly string[] = [PREPAID_EXPENSE, DEFERRED_INCOME];\n\nfunction key(fiscalYear: number, period: number): string {\n  return `${String(fiscalYear).padStart(4, '0')}-${String(period).padStart(2, '0')}`;\n}\n\n/**\n * A prepaid or deferred item and its release plan (F-CORE-053).\n *\n * **What was missing was never the accounts.** Both of them have existed in the shipped German chart\n * from the beginning, and both have had a balance-sheet position. What was missing is the *plan*: an\n * insurance premium paid in December for the following year could be deferred and then had to be\n * released by hand, month after month, from memory. That is precisely the failure mode\n * `runDepreciation` exists to prevent for arithmetic that is identical — an amount spread evenly\n * over a known number of periods — and the two ought not to differ in whether the machine remembers.\n *\n * **The plan is fixed at recognition and never recomputed.** `allocate` distributes the amount over\n * the periods with largest-remainder, so the instalments sum to the amount exactly and the last one\n * carries no drift. Storing the plan rather than re-deriving it is the same decision the asset\n * schedule makes, for the same reason: a plan that is recomputed on read answers differently after a\n * rounding rule moves.\n *\n * **Two kinds, and they are opposites rather than variants.** A *prepaid expense* is money already\n * paid for a service still to come — an asset. A *deferred income* is money already received for a\n * service still to be rendered — a liability. Both defer, in opposite directions, and every posting\n * this class produces flips with the kind.\n */\nexport class Deferral {\n  private released = new Map<string, DeferralRelease>();\n\n  constructor(\n    readonly id: Uuid,\n    readonly kind: string,\n    readonly reason: string,\n    readonly account: AccountNumber,\n    readonly counterAccount: AccountNumber,\n    readonly recognizedOn: CalendarDate,\n    readonly amount: Money,\n    readonly plan: DeferralInstalment[],\n    readonly recognitionEntryId: Uuid | null = null,\n  ) {}\n\n  isReleased(fiscalYear: number, period: number): boolean {\n    return this.released.has(key(fiscalYear, period));\n  }\n\n  recordRelease(fiscalYear: number, period: number, amount: Money, date: CalendarDate, entryId: Uuid): void {\n    this.released.set(key(fiscalYear, period), { fiscalYear, period, amount, date, entryId });\n  }\n\n  releasedTotal(): Money {\n    let sum = this.amount.subtract(this.amount);\n    for (const release of this.released.values()) sum = sum.add(release.amount);\n    return sum;\n  }\n\n  outstanding(): Money {\n    return this.amount.subtract(this.releasedTotal());\n  }\n\n  isSettled(): boolean {\n    return this.outstanding().isZero();\n  }\n\n  /** The instalment due for a period, or null where the plan has none. */\n  instalmentFor(fiscalYear: number, period: number): Money | null {\n    for (const entry of this.plan) {\n      if (entry.fiscalYear === fiscalYear && entry.period === period) return entry.amount;\n    }\n    return null;\n  }\n\n  releases(): DeferralRelease[] {\n    // Sorted, because a map keyed by period has whatever order the releases happened in and the\n    // register must read the same after a restart as before one.\n    return [...this.released.values()].sort((a, b) =>\n      a.fiscalYear !== b.fiscalYear ? a.fiscalYear - b.fiscalYear : a.period - b.period,\n    );\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      kind: this.kind,\n      reason: this.reason,\n      account: this.account.toString(),\n      counterAccount: this.counterAccount.toString(),\n      recognizedOn: this.recognizedOn.iso,\n      amount: this.amount.toJSON(),\n      recognitionEntryId: this.recognitionEntryId?.value ?? null,\n      plan: this.plan.map((entry) => ({\n        fiscalYear: entry.fiscalYear,\n        period: entry.period,\n        amount: entry.amount.toJSON(),\n      })),\n      released: this.releases().map((release) => ({\n        fiscalYear: release.fiscalYear,\n        period: release.period,\n        amount: release.amount.toJSON(),\n        date: release.date.iso,\n        entryId: release.entryId.value,\n      })),\n    };\n  }\n\n  static restore(\n    id: Uuid,\n    kind: string,\n    reason: string,\n    account: AccountNumber,\n    counterAccount: AccountNumber,\n    recognizedOn: CalendarDate,\n    amount: Money,\n    plan: DeferralInstalment[],\n    released: DeferralRelease[],\n    recognitionEntryId: Uuid | null,\n  ): Deferral {\n    const deferral = new Deferral(\n      id,\n      kind,\n      reason,\n      account,\n      counterAccount,\n      recognizedOn,\n      amount,\n      plan,\n      recognitionEntryId,\n    );\n    for (const release of released) {\n      deferral.released.set(key(release.fiscalYear, release.period), release);\n    }\n    return deferral;\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { Ledger } from '../../../ledger/ledger.js';\nimport type {\n  AccountRepository,\n  DeferralRepository,\n  FiscalYearRepository,\n  VoucherRepository,\n} from '../../../port.js';\nimport { Voucher } from '../../../records/voucher.js';\nimport { AccountNumber } from '../../../substrate/account-number.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport type { IdGenerator } from '../../../substrate/id-generator.js';\nimport { Money } from '../../../substrate/money.js';\nimport { Uuid } from '../../../substrate/uuid.js';\nimport { Deferral, DEFERRAL_KINDS, PREPAID_EXPENSE, type DeferralInstalment } from './deferral.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Prepaid and deferred items: recognition and the release schedule (F-CORE-053).\n *\n * **The accounts were never the gap.** The shipped German chart has carried both from the start and\n * both have had a balance-sheet position. What was missing is the *plan*. An insurance premium paid\n * in December for the following year could be deferred and then had to be released by hand, month\n * after month, from memory — which is exactly the failure `runDepreciation` exists to prevent for\n * arithmetic that is identical: an amount spread evenly over a known number of periods. Two\n * mechanisms that differ only in whether the machine remembers is not a design, it is an omission.\n *\n * **Two kinds, opposites rather than variants.** A *prepaid expense* is money already paid for a\n * service still to come, so it is an asset and its release is an expense. A *deferred income* is\n * money already received for a service still to be rendered, so it is a liability and its release is\n * revenue. Every posting here flips with the kind; nothing else does.\n *\n * **The release run mirrors the depreciation run, deliberately and down to the answer shape.** One\n * period at a time, idempotent because each deferral records which periods it has released,\n * `alreadyRun` where there was nothing left to do. Somebody who has closed a period with\n * `runDepreciation` should not have to learn a second vocabulary for the same act.\n *\n * **Socket and plug.** Which account holds each kind is the pack's; which expense or revenue the\n * amount belongs to is the caller's, because it is a fact about the transaction rather than about\n * the jurisdiction.\n */\nexport class DeferralService {\n  private ruleModule: Record<string, unknown>;\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly fiscalYears: FiscalYearRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly deferrals: DeferralRepository,\n    private readonly ledger: Ledger,\n    private readonly ids: IdGenerator,\n    ruleModule: Record<string, unknown> = {},\n    private readonly tenantId: Uuid | null = null,\n    private readonly audit: AuditWriter | null = null,\n  ) {\n    this.ruleModule = ruleModule;\n  }\n\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  /** Defer an amount and fix its release plan (`recognizeDeferral`). */\n  recognize(input: Record<string, unknown>): Record<string, unknown> {\n    const kind = typeof input.kind === 'string' ? input.kind : '';\n    if (!DEFERRAL_KINDS.includes(kind)) {\n      throw new DomainError('E_INPUT_INVALID', `recognizeDeferral: \"${kind}\" is not a deferral kind`, {\n        field: 'kind',\n        known: [...DEFERRAL_KINDS],\n      });\n    }\n\n    const account = AccountNumber.of(this.packAccount(kind));\n    const counterAccount = AccountNumber.of(this.requireExistingAccount(input.counterAccount, 'counterAccount'));\n    const reason = this.requireString(input.reason, 'reason');\n    const recognizedOn = this.requireDate(input.recognizedOn, 'recognizedOn');\n    const amount = this.requireMoney(input.amount, 'amount');\n\n    if (!amount.isPositive()) {\n      throw new DomainError('E_INPUT_INVALID', 'recognizeDeferral: amount must be positive', { field: 'amount' });\n    }\n\n    const periods = typeof input.periods === 'number' ? input.periods : 0;\n    if (periods < 1) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'recognizeDeferral: \"periods\" must be at least 1 — a deferral with no release plan is the ' +\n          'hand-kept schedule this operation exists to replace',\n        { field: 'periods' },\n      );\n    }\n\n    const firstYear = typeof input.firstFiscalYear === 'number' ? input.firstFiscalYear : 0;\n    const firstPeriod = typeof input.firstPeriod === 'number' ? input.firstPeriod : 0;\n    if (firstYear < 1 || firstPeriod < 1) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'recognizeDeferral: firstFiscalYear and firstPeriod say when the release starts and are required',\n        { field: 'firstFiscalYear' },\n      );\n    }\n\n    // Largest-remainder, like every other distribution in this library: the instalments sum to the\n    // amount exactly, and the drift lands in the earliest periods rather than in the last one, where\n    // it would look like a correction.\n    const shares = amount.allocate(...Array.from({ length: periods }, () => 1));\n    const plan: DeferralInstalment[] = shares.map((share, index) => ({\n      ...this.periodAt(firstYear, firstPeriod, index),\n      amount: share,\n    }));\n\n    // Recognition: a prepaid expense moves value OUT of the expense account and onto the asset; a\n    // deferred income moves it out of revenue and onto the liability. The release, later, runs each\n    // of these backwards.\n    const lines =\n      kind === PREPAID_EXPENSE\n        ? [\n            { account: account.toString(), side: 'debit', money: amount.toJSON() },\n            { account: counterAccount.toString(), side: 'credit', money: amount.toJSON() },\n          ]\n        : [\n            { account: counterAccount.toString(), side: 'debit', money: amount.toJSON() },\n            { account: account.toString(), side: 'credit', money: amount.toJSON() },\n          ];\n\n    const entryId = this.post(recognizedOn, `Deferral ${reason}`, 'RAP', lines);\n\n    const deferral = new Deferral(\n      this.ids.next(),\n      kind,\n      reason,\n      account,\n      counterAccount,\n      recognizedOn,\n      amount,\n      plan,\n      entryId,\n    );\n    this.deferrals.add(deferral);\n\n    this.audit?.record(this.audit.actorOf(input), 'deferral', deferral.id, 'recognized', {\n      kind: { from: null, to: kind },\n      amount: { from: null, to: amount.amountAsString() },\n      periods: { from: null, to: periods },\n    });\n\n    return {\n      deferralId: deferral.id.value,\n      kind,\n      amount: amount.toJSON(),\n      periods,\n      entryId: entryId.value,\n    };\n  }\n\n  /**\n   * Release what a period owes, for every deferral (`runDeferralRelease`).\n   *\n   * The depreciation run's shape, on purpose: one period, idempotent, `alreadyRun` when there is\n   * nothing left. A period that was already released books nothing a second time, because each\n   * deferral records what it has released rather than deriving it from a balance.\n   */\n  runRelease(input: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = typeof input.fiscalYear === 'number' ? input.fiscalYear : 0;\n    const period = typeof input.period === 'number' ? input.period : 0;\n\n    if (fiscalYear < 1 || period < 1) {\n      throw new DomainError('E_INPUT_INVALID', 'runDeferralRelease: fiscalYear and period are required', {\n        field: 'fiscalYear',\n      });\n    }\n\n    const date = this.periodEnd(fiscalYear, period);\n    let entriesCreated = 0;\n    let total = Money.zero(this.baseCurrency);\n\n    for (const deferral of this.deferrals.all()) {\n      if (deferral.isReleased(fiscalYear, period)) continue;\n\n      const instalment = deferral.instalmentFor(fiscalYear, period);\n      if (instalment === null || instalment.isZero()) continue;\n\n      const lines =\n        deferral.kind === PREPAID_EXPENSE\n          ? [\n              { account: deferral.counterAccount.toString(), side: 'debit', money: instalment.toJSON() },\n              { account: deferral.account.toString(), side: 'credit', money: instalment.toJSON() },\n            ]\n          : [\n              { account: deferral.account.toString(), side: 'debit', money: instalment.toJSON() },\n              { account: deferral.counterAccount.toString(), side: 'credit', money: instalment.toJSON() },\n            ];\n\n      const entryId = this.post(\n        date,\n        `Deferral release ${deferral.reason} ${fiscalYear}/${String(period).padStart(2, '0')}`,\n        'RAP-A',\n        lines,\n      );\n\n      deferral.recordRelease(fiscalYear, period, instalment, date, entryId);\n      this.deferrals.save(deferral);\n      entriesCreated += 1;\n      total = total.add(instalment);\n    }\n\n    // A run that created nothing is still an event, exactly as it is for depreciation: \"somebody ran\n    // the release for this period and it was already done\" is what an auditor reconstructing a\n    // timeline wants to see.\n    if (this.tenantId !== null) {\n      this.audit?.record(this.audit.actorOf(input), 'deferralRelease', this.tenantId, 'completed', {\n        fiscalYear: { from: null, to: fiscalYear },\n        period: { from: null, to: period },\n        entriesCreated: { from: null, to: entriesCreated },\n      });\n    }\n\n    if (entriesCreated === 0) return { alreadyRun: true, entriesCreated: 0 };\n\n    return { entriesCreated, totalReleased: total.toJSON() };\n  }\n\n  /** What is deferred, over what, and how far it has run (`deferralRegister`). */\n  register(params: Record<string, unknown>): Record<string, unknown> {\n    const kind = typeof params.kind === 'string' ? params.kind : null;\n    const status = typeof params.status === 'string' ? params.status : null;\n\n    const rows: Array<Record<string, unknown>> = [];\n    let outstanding = Money.zero(this.baseCurrency);\n\n    for (const deferral of this.deferrals.all()) {\n      const deferralStatus = deferral.isSettled() ? 'settled' : 'open';\n      if (kind !== null && deferral.kind !== kind) continue;\n      if (status !== null && deferralStatus !== status) continue;\n\n      rows.push({\n        deferralId: deferral.id.value,\n        kind: deferral.kind,\n        reason: deferral.reason,\n        account: deferral.account.toString(),\n        counterAccount: deferral.counterAccount.toString(),\n        recognizedOn: deferral.recognizedOn.iso,\n        amount: deferral.amount.amountAsString(),\n        released: deferral.releasedTotal().amountAsString(),\n        outstanding: deferral.outstanding().amountAsString(),\n        status: deferralStatus,\n        plan: deferral.plan.map((entry) => ({\n          fiscalYear: entry.fiscalYear,\n          period: entry.period,\n          amount: entry.amount.amountAsString(),\n          // The plan is the answer to \"when will this be gone\" and the releases are the answer to\n          // \"what has actually happened\". Reporting them as one flag per instalment keeps both in\n          // one place without a second list to line up.\n          released: deferral.isReleased(entry.fiscalYear, entry.period),\n        })),\n      });\n      outstanding = outstanding.add(deferral.outstanding());\n    }\n\n    return { deferrals: rows, outstandingTotal: outstanding.amountAsString() };\n  }\n\n  private periodAt(firstYear: number, firstPeriod: number, offset: number): { fiscalYear: number; period: number } {\n    const periodsPerYear = this.periodsPerYear(firstYear);\n    const zeroBased = firstPeriod - 1 + offset;\n\n    return {\n      fiscalYear: firstYear + Math.floor(zeroBased / periodsPerYear),\n      period: (zeroBased % periodsPerYear) + 1,\n    };\n  }\n\n  /**\n   * How many periods a year has — read from the fiscal year where there is one, twelve otherwise.\n   *\n   * A release plan that ran off the end of a year has to know where the next one starts, and\n   * assuming twelve for a tenant whose year is divided differently would put instalments in periods\n   * that do not exist.\n   */\n  private periodsPerYear(fiscalYear: number): number {\n    const year = this.fiscalYears.byYear(fiscalYear);\n    const count = year === null ? 0 : year.periods().length;\n    return count > 0 ? count : 12;\n  }\n\n  private periodEnd(fiscalYear: number, period: number): CalendarDate {\n    const year = this.fiscalYears.byYear(fiscalYear);\n    if (year !== null) {\n      for (const candidate of year.periods()) {\n        if (candidate.number === period) return candidate.end;\n      }\n    }\n\n    throw new DomainError('E_PERIOD_UNKNOWN', `period ${period} of fiscal year ${fiscalYear} does not exist`, {\n      fiscalYear,\n      period,\n    });\n  }\n\n  private packAccount(kind: string): string {\n    const module = isRecord(this.ruleModule.deferrals) ? this.ruleModule.deferrals : null;\n    if (module === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'a deferral was recognised, but the pack declares no prepaid or deferred accounts',\n        { field: 'deferrals' },\n      );\n    }\n\n    for (const declared of Array.isArray(module.kinds) ? module.kinds : []) {\n      if (isRecord(declared) && declared.kind === kind && typeof declared.account === 'string') {\n        return declared.account;\n      }\n    }\n\n    throw new DomainError('E_PACK_INCOHERENT', `the pack declares no account for deferral kind \"${kind}\"`, {\n      kind,\n    });\n  }\n\n  private post(\n    date: CalendarDate,\n    text: string,\n    voucherPrefix: string,\n    lines: Array<Record<string, unknown>>,\n  ): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `${voucherPrefix}-${date.iso.replaceAll('-', '')}`,\n      voucherDate: date,\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n\n    const result = this.ledger.post({ entryDate: date.iso, voucherId: voucher.id.value, text, lines });\n    this.ledger.finalize({ entryId: result.entry.id.value });\n\n    return result.entry.id;\n  }\n\n  private requireString(raw: unknown, field: string): string {\n    if (typeof raw !== 'string' || raw.trim() === '') {\n      throw new DomainError('E_INPUT_INVALID', `${field} is required`, { field });\n    }\n    return raw;\n  }\n\n  private requireExistingAccount(raw: unknown, field: string): string {\n    const number = this.requireString(raw, field);\n\n    if (this.accounts.byNumber(AccountNumber.of(number)) === null) {\n      throw new DomainError('E_ACCOUNT_UNKNOWN', `account ${number} does not exist`, { account: number });\n    }\n\n    return number;\n  }\n\n  private requireDate(raw: unknown, field: string): CalendarDate {\n    if (typeof raw !== 'string' || raw === '') {\n      throw new DomainError('E_INPUT_INVALID', `${field} is required`, { field });\n    }\n\n    try {\n      return CalendarDate.of(raw);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a calendar date`, { field });\n    }\n  }\n\n  private requireMoney(raw: unknown, field: string): Money {\n    if (!isRecord(raw) || typeof raw.amount !== 'string') {\n      throw new DomainError('E_INPUT_INVALID', `${field} must be a money object`, { field });\n    }\n\n    const currency = typeof raw.currency === 'string' ? raw.currency : this.baseCurrency.code;\n\n    try {\n      return Money.of(raw.amount, currency);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a valid amount`, { field });\n    }\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport { Rational } from '../../../substrate/rational.js';\n\nexport interface Receiver {\n  code: string;\n  share: string;\n}\n\nexport interface Step {\n  sender: string;\n  receivers: Receiver[];\n}\n\n/**\n * The simultaneous-equation method of internal cost allocation.\n *\n * The step ladder allocates in one pass and therefore cannot describe cost centres that serve each\n * other — the power plant heats the workshop, the workshop maintains the power plant. Ordering the\n * two is not a modelling choice, it is a wrong answer: whichever goes first sends cost the other has\n * not received yet. That is why the step ladder refuses a cycle outright (`E_COSTING_CYCLE`) rather\n * than picking an order.\n *\n * Mutual service is not a special case, it is the general one, and it has an exact answer. Let x_i be\n * everything that passes through centre i, p_i its own primary cost and A[j][i] the fraction of centre\n * j that goes to i. Then x = p + A^T x for all centres at once — n equations, n unknowns, one\n * solution. Solving it is Gaussian elimination, nothing more exotic.\n *\n * Two properties this had to have and did not come for free:\n *\n * - **Exact.** The elimination runs on `Rational`, not on decimals. A solved share is routinely a\n *   fraction with no decimal form, and a solver that rounded on the way would make the result depend\n *   on where it rounded — which two implementations cannot agree on by construction.\n * - **Deterministic.** The pivot is the FIRST row with a non-zero coefficient, never the largest.\n *   Choosing by magnitude is the numerically sensible thing to do in floating point and is exactly\n *   what would make the two languages diverge; with exact arithmetic there is nothing to stabilise,\n *   so the cheap rule is also the correct one.\n *\n * PHP twin: `Policies/Expansion/Costing/SimultaneousAllocation.php`.\n */\nexport function solveSimultaneously(\n  codes: string[],\n  primary: Map<string, Rational>,\n  steps: Step[],\n): { totals: Map<string, Rational>; senders: string[] } {\n  const index = new Map(codes.map((code, position) => [code, position]));\n  const n = codes.length;\n\n  // A sender may be named by more than one step; the receivers add up rather than the later step\n  // replacing the earlier. Weights are per sender, so they are summed before normalising.\n  const weights = new Map<string, Map<string, Rational>>();\n  const senders: string[] = [];\n\n  for (const step of steps) {\n    let byReceiver = weights.get(step.sender);\n    if (byReceiver === undefined) {\n      byReceiver = new Map<string, Rational>();\n      weights.set(step.sender, byReceiver);\n      senders.push(step.sender);\n    }\n\n    for (const receiver of step.receivers) {\n      const share = Rational.fromDecimalString(receiver.share);\n\n      if (share.isNegative()) {\n        throw new DomainError(\n          'E_INPUT_INVALID',\n          `allocation share for cost center \"${receiver.code}\" must not be negative`,\n          { costCenter: receiver.code, share: receiver.share },\n        );\n      }\n\n      byReceiver.set(receiver.code, (byReceiver.get(receiver.code) ?? Rational.zero()).add(share));\n    }\n  }\n\n  // M = I - A^T, augmented with p in the last column.\n  const m: Rational[][] = codes.map((code, row) => {\n    const line = Array.from({ length: n + 1 }, () => Rational.zero());\n    line[row] = Rational.of(1);\n    line[n] = primary.get(code) ?? Rational.zero();\n    return line;\n  });\n\n  for (const sender of senders) {\n    const byReceiver = weights.get(sender)!;\n    let total = Rational.zero();\n    for (const share of byReceiver.values()) total = total.add(share);\n\n    if (total.isZero()) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `cost center \"${sender}\" allocates to receivers whose shares add up to zero`,\n        { costCenter: sender },\n      );\n    }\n\n    const senderColumn = index.get(sender)!;\n    for (const [code, share] of byReceiver) {\n      const receiverRow = index.get(code)!;\n      m[receiverRow]![senderColumn] = m[receiverRow]![senderColumn]!.subtract(share.divide(total));\n    }\n  }\n\n  // Gauss-Jordan. First non-zero pivot, not the largest — see the doc comment.\n  for (let col = 0; col < n; col++) {\n    let pivot: number | null = null;\n    for (let row = col; row < n; row++) {\n      if (!m[row]![col]!.isZero()) {\n        pivot = row;\n        break;\n      }\n    }\n\n    if (pivot === null) {\n      throw new DomainError(\n        'E_COSTING_UNSOLVABLE',\n        `the allocation scheme has no solution: cost held by \"${codes[col]}\" never reaches a cost center that keeps it`,\n        { costCenter: codes[col]! },\n      );\n    }\n\n    [m[col], m[pivot]] = [m[pivot]!, m[col]!];\n\n    const divisor = m[col]![col]!;\n    for (let c = col; c <= n; c++) m[col]![c] = m[col]![c]!.divide(divisor);\n\n    for (let row = 0; row < n; row++) {\n      if (row === col || m[row]![col]!.isZero()) continue;\n      const factor = m[row]![col]!;\n      for (let c = col; c <= n; c++) {\n        m[row]![c] = m[row]![c]!.subtract(factor.multiply(m[col]![c]!));\n      }\n    }\n  }\n\n  // A sender passes everything on, so it keeps nothing — the same invariant the step ladder has,\n  // reached by solving instead of by ordering.\n  const senderSet = new Set(senders);\n  const totals = new Map<string, Rational>();\n  codes.forEach((code, row) => {\n    totals.set(code, senderSet.has(code) ? Rational.zero() : m[row]![n]!);\n  });\n\n  return { totals, senders };\n}\n","import { DomainError, rejectedValue } from '../../../domain-error.js';\nimport type { AccountRepository,\n  CostingRunRepository, JournalRepository } from '../../../port.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { TenantConfigStore } from '../../../composition/tenant-config-store.js';\nimport type { IdGenerator } from '../../../substrate/id-generator.js';\nimport { Money } from '../../../substrate/money.js';\nimport { PeriodRef } from '../../../substrate/period-ref.js';\nimport { Uuid } from '../../../substrate/uuid.js';\nimport { AccountNumber } from '../../../substrate/account-number.js';\nimport { Rational } from '../../../substrate/rational.js';\nimport { CostingRun } from './costing-run.js';\nimport { solveSimultaneously } from './simultaneous-allocation.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\ninterface Receiver {\n  code: string;\n  share: string;\n}\ninterface Step {\n  sender: string;\n  receivers: Receiver[];\n}\n\ninterface RateDefinition {\n  costCenter: string;\n  label: string;\n  accounts: string[];\n  costCenters: string[];\n}\n\nexport interface OverheadRate {\n  costCenter: string;\n  label: string;\n  overhead: string;\n  base: string;\n  rate: string | null;\n}\n\nexport interface RateWarning {\n  costCenter: string;\n  reason: string;\n}\n\ninterface ComponentDefinition {\n  id: string;\n  treatment: string;\n  included: boolean;\n  accounts: string[];\n  costCenters: string[];\n}\n\nexport interface ProductionCostComponent {\n  id: string;\n  amount: string;\n  treatment: string;\n  included: boolean;\n}\n\nexport interface ProductionCostResult {\n  total: string;\n  components: ProductionCostComponent[];\n}\n\n/** A percentage with four decimals, commercial half-up (away from zero), like everything else here. */\nfunction formatRate(value: Rational): string {\n  const scaled = value.multiply(Rational.of(10n ** 4n));\n  const negative = scaled.isNegative();\n  const magnitude = negative ? scaled.negate() : scaled;\n  const rounded = magnitude.add(Rational.of(1, 2)).floorToBigInt();\n  const digits = rounded.toString().padStart(5, '0');\n  const decimal = `${digits.slice(0, digits.length - 4)}.${digits.slice(digits.length - 4)}`;\n\n  return `${negative && rounded !== 0n ? '-' : ''}${decimal}`;\n}\n\nfunction stringList(value: unknown): string[] {\n  return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\n/**\n * Cost accounting (costing-modell.md): own accounting circle — the financial-accounting\n * journal stays untouched. Primary-cost intake via the costCenter dimension, allocation by\n * step ladder (acyclic, E_COSTING_CYCLE), distribution by Money.allocate.\n */\n/**\n * The two ways this core allocates internal services. A method it cannot perform is refused rather\n * than approximated: until now `method` was read, echoed back in the answer and then ignored, so\n * asking for the simultaneous method returned step-ladder numbers under the name of a different\n * procedure — the worst shape a defect can take, because the answer asserts it did what was asked.\n */\nconst METHODS = ['step_ladder', 'simultaneous'];\n\nexport class CostingService {\n  private schemeSteps: Step[] = [];\n  private method = 'step_ladder';\n\n  /**\n   * The pack's answer to \"what may enter production cost\". Data, never code — which components a\n   * jurisdiction requires, permits or forbids is the part that differs, and the summation is not.\n   */\n  private ruleModule: Record<string, unknown> = {};\n\n  /**\n   * Production-cost component definitions and the tenant's election among the optional ones, frozen\n   * into each run for the same reason the rates are.\n   */\n  private productionCostConfig: ComponentDefinition[] | null = null;\n\n  /**\n   * Overhead rate definitions, part of the same tenant-level configuration as the scheme.\n   *\n   * They sit on `setAllocationScheme` rather than on an operation of their own because a rate is\n   * computed FROM an allocation and frozen INTO the run: a second operation would need its own\n   * freezing rule against the same run, and two rules for one moment is how they drift apart.\n   */\n  private rateDefinitions: RateDefinition[] = [];\n  /** A stored scheme waiting for its first use — see `restoreAllocationScheme`. */\n  private pendingScheme: Record<string, unknown> | null = null;\n  /**\n   * The scheme as it was given, kept for `tenantConfiguration` to report.\n   *\n   * The raw input rather than the parsed fields, for the same reason the store keeps the raw input:\n   * it is exactly what `setAllocationScheme` accepts, so what comes out can be put back in and no\n   * second serializer can drift from the first one.\n   */\n  private schemeData: Record<string, unknown> | null = null;\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    /**\n     * Where the runs live (F-KLR-001/004).\n     *\n     * They used to live in two private `Map`s in this class — the runs themselves and a per-period\n     * version counter — which meant a released run was gone with the process that produced it and\n     * the version restarted at 1 after every restart. The requirements had said otherwise all\n     * along: runs are versioned per period, and the BAB and the rates are a projection *of a\n     * released run*. A run no later process can read satisfies neither; it satisfies them inside\n     * one process, which is not what a repository port is for.\n     */\n    private readonly runs: CostingRunRepository,\n    private readonly ids: IdGenerator,\n    // The allocation scheme is a tenant-level singleton — see TaxService for why the\n    // audit record names the tenant as its object (F-CORE-014 \"Profile\").\n    private readonly tenantId: Uuid | null = null,\n    private readonly audit: AuditWriter | null = null,\n    /** Where the scheme is kept, so it outlives this object (SPEC-015). */\n    private readonly configStore: TenantConfigStore | null = null,\n  ) {}\n\n  /** The resolved pack bundle (`productionCost` is read here). */\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  /**\n   * Hands back a stored scheme when a tenant is opened (SPEC-015).\n   *\n   * **Deferred on purpose.** A scheme can reference production-cost treatments, which only the pack\n   * answers — and the pack arrives through `setRuleModule`, *after* the factory has built the\n   * tenant. Applying it here would make opening the books fail on a scheme that was perfectly valid\n   * when it was set, which is the wrong moment to find out and the wrong thing to block: reading a\n   * journal does not need an allocation scheme.\n   *\n   * So it is applied on first use — `setAllocationScheme` and `run` are the only entry points that\n   * read it. A stored scheme that the *current* pack no longer accepts then fails when somebody runs\n   * a costing, with the error the operation itself would have given.\n   */\n  restoreAllocationScheme(input: Record<string, unknown>): void {\n    this.pendingScheme = input;\n  }\n\n  /** Applies what `restoreAllocationScheme` handed back, once, at the moment it is first needed. */\n  private applyPendingScheme(): void {\n    if (this.pendingScheme === null) return;\n    const pending = this.pendingScheme;\n    this.pendingScheme = null;\n    this.applyAllocationScheme(pending);\n  }\n\n  setAllocationScheme(input: Record<string, unknown>): Record<string, unknown> {\n    this.applyPendingScheme();\n    const previousStepCount = this.schemeSteps.length;\n    const previousRateCount = this.rateDefinitions.length;\n    const result = this.applyAllocationScheme(input);\n\n    if (this.audit !== null && this.tenantId !== null) {\n      this.audit.record(this.audit.actorOf(input), 'allocationScheme', this.tenantId, 'changed', {\n        method: { from: null, to: result.method },\n        stepCount: { from: previousStepCount, to: result.stepCount },\n        rateCount: { from: previousRateCount, to: result.rateCount },\n      });\n    }\n    // The raw input, not the parsed fields: it is exactly what this method accepts, so reloading it\n    // on the next open runs the same validation again rather than a second, drifting reader.\n    this.configStore?.rememberAllocationScheme(input);\n\n    return result;\n  }\n\n  /**\n   * The allocation scheme in force, as it was set — what `tenantConfiguration` reports, or null when\n   * none was ever set.\n   *\n   * Reads the *pending* scheme first and deliberately does not apply it. A stored scheme may name\n   * production-cost treatments only the current pack answers, so applying it is what\n   * `restoreAllocationScheme` defers to first use — and a projection is the wrong place to find out:\n   * reporting what a tenant is configured as must not fail on a scheme that was valid when it was\n   * set. Reporting it unapplied is the honest answer, because unapplied is what it is.\n   */\n  allocationScheme(): Record<string, unknown> | null {\n    return this.pendingScheme ?? this.schemeData;\n  }\n\n  private applyAllocationScheme(input: Record<string, unknown>): {\n    valid: boolean;\n    method: string;\n    stepCount: number;\n    rateCount: number;\n    productionCostComponents: number;\n  } {\n    const method = typeof input.method === 'string' ? input.method : 'step_ladder';\n\n    if (!METHODS.includes(method)) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `setAllocationScheme: unknown allocation method \"${method}\" — this core allocates by ${METHODS.join(' or ')}`,\n        { method: rejectedValue(method) },\n      );\n    }\n\n    const steps: Step[] = [];\n    const edges = new Map<string, string[]>();\n\n    for (const rawStep of Array.isArray(input.steps) ? input.steps : []) {\n      if (!isRecord(rawStep) || typeof rawStep.sender !== 'string') {\n        throw new InvalidValue('allocation step requires sender');\n      }\n      const sender = rawStep.sender;\n      const receivers: Receiver[] = [];\n      for (const rawReceiver of Array.isArray(rawStep.receivers) ? rawStep.receivers : []) {\n        if (!isRecord(rawReceiver) || typeof rawReceiver.code !== 'string') continue;\n        receivers.push({ code: rawReceiver.code, share: typeof rawReceiver.share === 'string' ? rawReceiver.share : '1' });\n        const list = edges.get(sender) ?? [];\n        list.push(rawReceiver.code);\n        edges.set(sender, list);\n      }\n      steps.push({ sender, receivers });\n    }\n\n    const rates: RateDefinition[] = [];\n    for (const rawRate of Array.isArray(input.rates) ? input.rates : []) {\n      if (!isRecord(rawRate) || typeof rawRate.costCenter !== 'string') {\n        throw new DomainError('E_INPUT_INVALID', 'setAllocationScheme: an overhead rate requires \"costCenter\"', {\n          field: 'rates',\n        });\n      }\n\n      const base = isRecord(rawRate.base) ? rawRate.base : {};\n      rates.push({\n        costCenter: rawRate.costCenter,\n        label: typeof rawRate.label === 'string' ? rawRate.label : rawRate.costCenter,\n        accounts: stringList(base.accounts),\n        costCenters: stringList(base.costCenters),\n      });\n    }\n\n    let productionCost: ComponentDefinition[] | null = null;\n    if (isRecord(input.productionCost)) {\n      productionCost = this.resolveProductionCost(input.productionCost);\n    }\n\n    if (method === 'step_ladder') this.assertAcyclic(edges);\n    this.schemeSteps = steps;\n    this.method = method;\n    this.rateDefinitions = rates;\n    this.productionCostConfig = productionCost;\n    this.schemeData = input;\n\n    return {\n      valid: true,\n      method,\n      stepCount: steps.length,\n      rateCount: rates.length,\n      productionCostComponents: productionCost === null ? 0 : productionCost.length,\n    };\n  }\n\n  run(input: Record<string, unknown>): CostingRun {\n    this.applyPendingScheme();\n    const fiscalYear = typeof input.fiscalYear === 'number' ? input.fiscalYear : 0;\n    const period = typeof input.period === 'number' ? input.period : 0;\n    const periodRef = new PeriodRef(fiscalYear, period);\n\n    const zero = Money.zero(this.baseCurrency);\n    const primary = new Map<string, Money>();\n    const accountTotals = new Map<string, Money>();\n\n    for (const entry of this.journal.forFiscalYear(fiscalYear)) {\n      if (entry.periodRef.period !== period) continue;\n      for (const line of entry.lines()) {\n        const account = this.accounts.byId(line.accountId);\n        if (account === null) continue;\n\n        // Direct costs — the denominator of an overhead rate — are booked WITHOUT a cost centre:\n        // they belong to the product, not to a department. So they are collected per account here,\n        // in the same pass, and not through the costCenter dimension.\n        const number = account.number.toString();\n        const signedLine = line.side === 'debit' ? line.money : line.money.negate();\n        accountTotals.set(number, (accountTotals.get(number) ?? zero).add(signedLine));\n\n        if (account.type !== 'expense') continue;\n        for (const dimension of line.dimensions) {\n          if (dimension.type !== 'costCenter') continue;\n          const signed = line.side === 'debit' ? line.money : line.money.negate();\n          primary.set(dimension.code, (primary.get(dimension.code) ?? zero).add(signed));\n        }\n      }\n    }\n\n    // Allocation: distribute, never create — by either method.\n    const after =\n      this.method === 'simultaneous'\n        ? this.allocateSimultaneously(primary)\n        : this.allocateByStepLadder(primary);\n\n    let grandTotal = zero;\n    for (const total of after.values()) grandTotal = grandTotal.add(total);\n\n    const computed = this.computeRates(after, accountTotals);\n    const productionCost = this.computeProductionCost(after, accountTotals);\n\n    // The next version comes from what is stored, not from a counter in this object: a counter\n    // starts at zero in every new process, so the second run of a period would have claimed to be\n    // its first.\n    const version = this.nextVersionFor(fiscalYear, period);\n\n    const run = new CostingRun(\n      this.ids.next(),\n      periodRef,\n      version,\n      primary,\n      after,\n      grandTotal,\n      this.method,\n      computed.rates,\n      computed.warnings,\n      productionCost,\n    );\n    this.runs.add(run);\n    if (this.audit !== null) {\n      this.audit.record(this.audit.actorOf(input), 'costingRun', run.id, 'created', {\n        period: { from: null, to: `${periodRef.fiscalYear}/${periodRef.period}` },\n        method: { from: null, to: this.method },\n        version: { from: null, to: version },\n        status: { from: null, to: run.status() },\n      });\n    }\n\n    return run;\n  }\n\n  release(input: Record<string, unknown>): CostingRun {\n    const run = this.requireRun(input.runId);\n    const before = run.status();\n    run.release();\n    this.runs.save(run);\n    if (this.audit !== null) {\n      this.audit.record(this.audit.actorOf(input), 'costingRun', run.id, 'released', {\n        status: { from: before, to: run.status() },\n      });\n    }\n\n    return run;\n  }\n\n  costAllocationSheet(params: Record<string, unknown>): Record<string, unknown> {\n    const run = this.requireRun(params.runId);\n\n    // The run already fixes fiscal year and period. Passing them alongside was accepted and\n    // ignored, so a caller could ask for period 2, receive period 1's numbers, and have nothing\n    // in the answer to contradict them. If they are given, they have to agree.\n    if (params.fiscalYear !== undefined && params.fiscalYear !== null && params.fiscalYear !== run.period.fiscalYear) {\n      throw new DomainError('E_INPUT_INVALID', `costAllocationSheet: the run belongs to fiscal year ${run.period.fiscalYear}`, {\n        fiscalYear: rejectedValue(params.fiscalYear),\n      });\n    }\n    if (params.period !== undefined && params.period !== null && params.period !== run.period.period) {\n      throw new DomainError('E_INPUT_INVALID', `costAllocationSheet: the run belongs to period ${run.period.period}`, {\n        period: rejectedValue(params.period),\n      });\n    }\n\n    return {\n      runId: run.id.value,\n      status: run.status(),\n      version: run.version,\n      method: run.method,\n      primary: this.serializeTotals(run.primary),\n      afterAllocation: this.serializeTotals(run.afterAllocation),\n      grandTotal: run.grandTotal.amountAsString(),\n    };\n  }\n\n  /**\n   * Overhead rates of a run (F-KLR-004: \"BAB *und Kalkulationssätze*\").\n   *\n   * A rate answers the question the allocation sheet cannot: the sheet says what a cost centre ended\n   * up carrying, a rate says how that attaches to a product. Numerator is the centre after allocation,\n   * denominator is a base the scheme declares — direct-cost ACCOUNTS, other cost CENTRES, or both. The\n   * classic four fall straight out of that: material and production overhead over their direct costs,\n   * administration and sales overhead over cost of production, which is \"the direct-cost accounts plus\n   * the two centres\" and needs no special case.\n   *\n   * Rounded to four decimals, half-up away from zero — a rate is a published figure, not money, and\n   * four places is where the pack schema already puts a percentage.\n   *\n   * Note what this deliberately does NOT do: refuse a draft run. F-KLR-001 says evaluations read\n   * released runs only, and the fixture `parameter-effect` reads a draft sheet — an append-only\n   * contract that says otherwise. Bending the fixture would rewrite what the contract always said, so\n   * the rule is followed as the contract has it and the contradiction is recorded (FINDINGS-CLOSED.md).\n   * `status` is in the answer, so nobody has to guess which they got.\n   */\n  overheadRates(params: Record<string, unknown>): Record<string, unknown> {\n    const run = this.requireRun(params.runId);\n\n    return {\n      runId: run.id.value,\n      status: run.status(),\n      version: run.version,\n      method: run.method,\n      rates: run.rates,\n      warnings: run.rateWarnings,\n    };\n  }\n\n  /**\n   * Production cost of a run, component by component (F-KLR-004's balance-sheet neighbour).\n   *\n   * Every configured component appears, whether it was counted or not, with the pack's treatment next\n   * to it — `mandatory`, `optional` or `forbidden` — and whether it went in. A valuation that shows\n   * only its own total is unauditable; this one shows what it left out and on whose authority.\n   */\n  productionCost(params: Record<string, unknown>): Record<string, unknown> {\n    const run = this.requireRun(params.runId);\n\n    if (run.productionCost === null) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        `run ${run.id.value} has no production-cost components — declare them in setAllocationScheme before the run`,\n        { runId: run.id.value },\n      );\n    }\n\n    return {\n      runId: run.id.value,\n      status: run.status(),\n      version: run.version,\n      total: run.productionCost.total,\n      components: run.productionCost.components,\n    };\n  }\n\n  /**\n   * Production cost of the period — the figure inventory is carried at.\n   *\n   * This is the one piece of cost accounting with balance-sheet effect, so what may be counted into it\n   * is law rather than preference. The split falls exactly along the socket/plug line the rest of the\n   * core uses — **this method sums, the pack says what may enter.** One jurisdiction requires material\n   * and production cost with their overhead and the production-related depreciation, leaves general\n   * administration to the preparer, and forbids research and distribution; another treats general\n   * administration as a period charge and so reaches a different inventory value from identical books.\n   * None of that is written here, and none of it should be: which of the three treatments a component\n   * gets is a row in the pack, not a branch in this method.\n   *\n   * Three rules, and each refuses rather than guesses:\n   *\n   * - a component the pack does not declare is `E_PACK_INCOHERENT` — an unknown component silently\n   *   counted or silently dropped would move the balance sheet either way;\n   * - electing a component the pack forbids is `E_INPUT_INVALID`, not a quiet exclusion, because the\n   *   caller has said something about their books that is not allowed;\n   * - asking for the figure without configuring the components is `E_INPUT_INVALID` rather than 0.00,\n   *   since a valuation nobody set up is not a valuation of zero.\n   *\n   * What this deliberately does NOT do is divide by a quantity. Production cost per unit needs produced\n   * quantities, and the core carries no quantities at all — goods movements and production orders are\n   * the embedding application's data. summae answers what the components add up to and why; the\n   * division is arithmetic on top of that.\n   */\n  private computeProductionCost(\n    after: Map<string, Money>,\n    accountTotals: Map<string, Money>,\n  ): ProductionCostResult | null {\n    if (this.productionCostConfig === null) return null;\n\n    const zero = Money.zero(this.baseCurrency);\n    let total = zero;\n    const components: ProductionCostComponent[] = [];\n\n    for (const component of this.productionCostConfig) {\n      let amount = zero;\n\n      for (const number of component.accounts) {\n        if (this.accounts.byNumber(AccountNumber.of(number)) === null) {\n          throw new DomainError(\n            'E_ACCOUNT_UNKNOWN',\n            `production-cost component \"${component.id}\" names account ${number}, which does not exist`,\n            { account: number },\n          );\n        }\n        amount = amount.add(accountTotals.get(number) ?? zero);\n      }\n\n      for (const code of component.costCenters) amount = amount.add(after.get(code) ?? zero);\n\n      if (component.included) total = total.add(amount);\n\n      // Excluded components stay in the answer with their amount and the reason. A valuation that\n      // shows only what it counted cannot be checked against the law it claims to follow.\n      components.push({\n        id: component.id,\n        amount: amount.amountAsString(),\n        treatment: component.treatment,\n        included: component.included,\n      });\n    }\n\n    return { total: total.amountAsString(), components };\n  }\n\n  /**\n   * Applies the pack's treatment table to a production-cost configuration — at the moment the\n   * configuration is set, not at the moment the run happens, so a caller learns about a refusal where\n   * they can still do something about it.\n   */\n  private resolveProductionCost(raw: Record<string, unknown>): ComponentDefinition[] {\n    const treatments = this.treatmentTable();\n    const elected = stringList(raw.include);\n\n    for (const componentId of elected) {\n      const treatment = treatments.get(componentId);\n\n      if (treatment === undefined) {\n        throw new DomainError(\n          'E_PACK_INCOHERENT',\n          `production-cost component \"${componentId}\" was elected, but the pack declares no treatment for it`,\n          { component: componentId },\n        );\n      }\n\n      if (treatment === 'forbidden') {\n        throw new DomainError(\n          'E_INPUT_INVALID',\n          `production-cost component \"${componentId}\" may not be capitalised under this pack`,\n          { component: componentId },\n        );\n      }\n    }\n\n    const components: ComponentDefinition[] = [];\n    for (const rawComponent of Array.isArray(raw.components) ? raw.components : []) {\n      if (!isRecord(rawComponent) || typeof rawComponent.id !== 'string') {\n        throw new DomainError('E_INPUT_INVALID', 'setAllocationScheme: a production-cost component requires \"id\"', {\n          field: 'productionCost.components',\n        });\n      }\n\n      const treatment = treatments.get(rawComponent.id);\n\n      if (treatment === undefined) {\n        throw new DomainError(\n          'E_PACK_INCOHERENT',\n          `production-cost component \"${rawComponent.id}\" is not declared by the pack`,\n          { component: rawComponent.id },\n        );\n      }\n\n      const base = isRecord(rawComponent.base) ? rawComponent.base : {};\n      components.push({\n        id: rawComponent.id,\n        treatment,\n        included: treatment === 'mandatory' || (treatment === 'optional' && elected.includes(rawComponent.id)),\n        accounts: stringList(base.accounts),\n        costCenters: stringList(base.costCenters),\n      });\n    }\n\n    // An election that names a component with no base configured does NOTHING, and until now it did\n    // nothing quietly. `include: [\"administration\"]` without an `administration` entry in\n    // `components` passed every check above — the component exists in the pack, it is not forbidden\n    // — and then never appeared in the run at all. The caller has asserted a measurement election\n    // and got no election; worse, the consistency report would show the basis as unchanged, which is\n    // true and useless. Same shape as the third rule above, one step later.\n    const configured = new Set(components.map((component) => component.id));\n    for (const componentId of elected) {\n      if (!configured.has(componentId)) {\n        throw new DomainError(\n          'E_INPUT_INVALID',\n          `production-cost component \"${componentId}\" was elected, but no base is configured for it — ` +\n            'give it accounts or cost centres, or drop the election',\n          { component: componentId },\n        );\n      }\n    }\n\n    return components;\n  }\n\n  /** component id -> mandatory | optional | forbidden */\n  private treatmentTable(): Map<string, string> {\n    const module = isRecord(this.ruleModule.productionCost) ? this.ruleModule.productionCost : null;\n\n    if (module === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'production cost was asked for, but the pack declares no production-cost treatments',\n        { field: 'productionCost' },\n      );\n    }\n\n    const table = new Map<string, string>();\n    for (const row of Array.isArray(module.treatments) ? module.treatments : []) {\n      if (!isRecord(row) || typeof row.component !== 'string' || typeof row.treatment !== 'string') continue;\n      table.set(row.component, row.treatment);\n    }\n\n    return table;\n  }\n\n  private computeRates(\n    after: Map<string, Money>,\n    accountTotals: Map<string, Money>,\n  ): { rates: OverheadRate[]; warnings: RateWarning[] } {\n    const zero = Money.zero(this.baseCurrency);\n    const rates: OverheadRate[] = [];\n    const warnings: RateWarning[] = [];\n\n    // Definition order, not alphabetical: an administration rate takes cost of production as its base,\n    // so the order the caller wrote is the order that reads correctly. It is deterministic for the\n    // same reason the steps are — it comes from the input.\n    for (const definition of this.rateDefinitions) {\n      const overhead = after.get(definition.costCenter) ?? zero;\n      let base = zero;\n\n      for (const number of definition.accounts) {\n        if (this.accounts.byNumber(AccountNumber.of(number)) === null) {\n          throw new DomainError(\n            'E_ACCOUNT_UNKNOWN',\n            `overhead rate for cost center \"${definition.costCenter}\" names account ${number}, which does not exist`,\n            { account: number },\n          );\n        }\n        base = base.add(accountTotals.get(number) ?? zero);\n      }\n\n      for (const code of definition.costCenters) base = base.add(after.get(code) ?? zero);\n\n      let rate: string | null = null;\n      if (base.isZero()) {\n        // A rate over an empty base is not zero and not infinite, it is undefined — and an undefined\n        // number returned as 0.00 would be applied to products as if it meant something. Named\n        // instead, in the same shape the cash-basis report uses for its gaps.\n        warnings.push({\n          costCenter: definition.costCenter,\n          reason: 'the base is zero, so no rate can be computed',\n        });\n      } else {\n        rate = formatRate(\n          Rational.fromDecimalString(overhead.amountAsString())\n            .divide(Rational.fromDecimalString(base.amountAsString()))\n            .multiply(Rational.of(100)),\n        );\n      }\n\n      rates.push({\n        costCenter: definition.costCenter,\n        label: definition.label,\n        overhead: overhead.amountAsString(),\n        base: base.amountAsString(),\n        rate,\n      });\n    }\n\n    return { rates, warnings };\n  }\n\n  /**\n   * One pass in step order. Cheap, and wrong the moment two centres serve each other — which is why a\n   * cycle is refused here rather than resolved by picking an order.\n   */\n  private allocateByStepLadder(primary: Map<string, Money>): Map<string, Money> {\n    const zero = Money.zero(this.baseCurrency);\n    const after = new Map(primary);\n\n    for (const step of this.schemeSteps) {\n      const senderTotal = after.get(step.sender) ?? zero;\n      if (senderTotal.isZero() || step.receivers.length === 0) continue;\n      const weights = step.receivers.map((receiver) => receiver.share);\n      const parts = senderTotal.allocate(...weights);\n      step.receivers.forEach((receiver, index) => {\n        after.set(receiver.code, (after.get(receiver.code) ?? zero).add(parts[index]!));\n      });\n      after.set(step.sender, zero);\n    }\n\n    return after;\n  }\n\n  /**\n   * All centres at once, solved exactly (solveSimultaneously) and only then turned back into money.\n   *\n   * The order matters and is the reason this is not simply \"solve and round\": the solution is a vector\n   * of exact fractions whose sum is the primary total to the last cent, and rounding each one on its\n   * own would break that — a cent appears or vanishes, and the sheet no longer says that allocation\n   * distributes rather than creates. So the fractions are floored and the difference handed out by\n   * largest remainder, ties to the earlier cost centre, which is `Money.allocate`'s rule applied to a\n   * vector instead of a single amount.\n   */\n  private allocateSimultaneously(primary: Map<string, Money>): Map<string, Money> {\n    const seen = new Set<string>(primary.keys());\n    for (const step of this.schemeSteps) {\n      seen.add(step.sender);\n      for (const receiver of step.receivers) seen.add(receiver.code);\n    }\n\n    const codes = [...seen].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    if (codes.length === 0) return new Map();\n\n    // Minor units throughout: the solver knows nothing about currencies, and an integer count of\n    // cents is the one representation in which \"the total is preserved\" is checkable.\n    const scale = this.baseCurrency.scale;\n    const toMinor = Rational.of(10n ** BigInt(scale));\n\n    const primaryMinor = new Map<string, Rational>();\n    let totalMinor = 0n;\n    for (const [code, money] of primary) {\n      const value = Rational.fromDecimalString(money.amountAsString()).multiply(toMinor);\n      primaryMinor.set(code, value);\n      totalMinor += value.floorToBigInt();\n    }\n\n    const solved = solveSimultaneously(codes, primaryMinor, this.schemeSteps);\n    const senderSet = new Set(solved.senders);\n    const keepers = codes.filter((code) => !senderSet.has(code));\n\n    const floors = keepers.map((code) => solved.totals.get(code)!.floorToBigInt());\n    const assigned = floors.reduce((sum, value) => sum + value, 0n);\n\n    const order = keepers.map((_, position) => position);\n    order.sort((a, b) => {\n      const byRemainder = solved.totals\n        .get(keepers[b]!)!\n        .fractionalPart()\n        .compareTo(solved.totals.get(keepers[a]!)!.fractionalPart());\n      return byRemainder !== 0 ? byRemainder : a - b;\n    });\n\n    const leftover = Number(totalMinor - assigned);\n    for (let i = 0; i < leftover; i++) floors[order[i]!] = floors[order[i]!]! + 1n;\n\n    const zero = Money.zero(this.baseCurrency);\n    const after = new Map<string, Money>();\n    for (const code of codes) after.set(code, zero);\n    keepers.forEach((code, position) => {\n      after.set(code, this.moneyFromMinor(floors[position]!, scale));\n    });\n\n    return after;\n  }\n\n  /** Minor units back to Money, exactly — no rounding is left to do at this point. */\n  private moneyFromMinor(minor: bigint, scale: number): Money {\n    const negative = minor < 0n;\n    const digits = (negative ? -minor : minor).toString().padStart(scale + 1, '0');\n    const decimal =\n      scale === 0 ? digits : `${digits.slice(0, digits.length - scale)}.${digits.slice(digits.length - scale)}`;\n\n    return Money.of(`${negative ? '-' : ''}${decimal}`, this.baseCurrency);\n  }\n\n  private serializeTotals(totals: Map<string, Money>): Array<{ costCenter: string; total: string }> {\n    const codes = [...totals.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    return codes.map((code) => ({ costCenter: code, total: totals.get(code)!.amountAsString() }));\n  }\n\n  /**\n   * The next version for a period: one more than the highest stored for it.\n   *\n   * Derived rather than counted, because a counter in this object starts at zero in every new\n   * process — the second run of a period would have claimed to be its first, and F-KLR-001's\n   * \"versioned per period\" would have held only until a restart.\n   */\n  private nextVersionFor(fiscalYear: number, period: number): number {\n    let highest = 0;\n    for (const run of this.runs.all()) {\n      if (run.period.fiscalYear !== fiscalYear || run.period.period !== period) continue;\n      if (run.version > highest) highest = run.version;\n    }\n    return highest + 1;\n  }\n\n  private requireRun(runId: unknown): CostingRun {\n    let run: CostingRun | null = null;\n    if (typeof runId === 'string' && runId !== '') {\n      try {\n        run = this.runs.byId(Uuid.fromString(runId));\n      } catch (error) {\n        if (!(error instanceof InvalidValue)) throw error;\n      }\n    }\n    if (run === null) {\n      throw new DomainError('E_COSTING_RUN_UNKNOWN', `costing run ${typeof runId === 'string' ? runId : '?'} does not exist`);\n    }\n    return run;\n  }\n\n  private assertAcyclic(edges: Map<string, string[]>): void {\n    const visiting = new Set<string>();\n    const done = new Set<string>();\n\n    const visit = (node: string): void => {\n      if (done.has(node)) return;\n      if (visiting.has(node)) {\n        throw new DomainError(\n          'E_COSTING_CYCLE',\n          `allocation cycle via cost center \"${node}\" — step ladder requires acyclicity`,\n          { costCenter: node },\n        );\n      }\n      visiting.add(node);\n      for (const next of edges.get(node) ?? []) visit(next);\n      visiting.delete(node);\n      done.add(node);\n    };\n\n    for (const node of edges.keys()) visit(node);\n  }\n}\n","import { canonicalJson } from '../substrate/canonical-json.js';\nimport type { AuditChanges } from '../records/audit-record.js';\nimport type { Uuid } from '../substrate/uuid.js';\n\n/**\n * Business partner (datenformat.md v0.4) — deliberately lean: OP-per-partner,\n * intra-community supply proof (VAT ID), EC sales list basis, DATEV master data.\n */\nexport class Partner {\n  private partnerName: string;\n  private partnerKind: string;\n  private partnerVatId: string | null;\n  private partnerPaymentTermsDays: number | null;\n\n  constructor(\n    readonly id: Uuid,\n    name: string,\n    kind: string,\n    vatId: string | null,\n    paymentTermsDays: number | null,\n    private accountNumbers: string[] = [],\n    private address: Record<string, unknown> = {},\n    /**\n     * Whether the partner is still in use (F-CORE-034).\n     *\n     * There is no `deletePartner` and there should not be: the books keep what they referenced,\n     * and an id that open items point at must not vanish. But a partner nobody trades with any\n     * more has to be sayable somewhere, or every application invents its own list beside the\n     * ledger — which is the state that made this a finding.\n     *\n     * It is a **state, not a control**. An inactive partner refuses nothing: old items still\n     * settle, old vouchers still read, and a posting that names one is not rejected. Whether a\n     * picker still offers it is the application's workflow, and summae's own scope rule puts\n     * \"the user must…\" on that side. Compare `Account.lock`, which does have teeth — the\n     * difference is deliberate and the two words are different on purpose.\n     */\n    private partnerStatus: 'active' | 'inactive' = 'active',\n  ) {\n    this.partnerName = name;\n    this.partnerKind = kind;\n    this.partnerVatId = vatId;\n    this.partnerPaymentTermsDays = paymentTermsDays;\n  }\n\n  name(): string {\n    return this.partnerName;\n  }\n\n  status(): 'active' | 'inactive' {\n    return this.partnerStatus;\n  }\n\n  isActive(): boolean {\n    return this.partnerStatus === 'active';\n  }\n\n  deactivate(): void {\n    this.partnerStatus = 'inactive';\n  }\n\n  reactivate(): void {\n    this.partnerStatus = 'active';\n  }\n\n  vatId(): string | null {\n    return this.partnerVatId;\n  }\n\n  update(input: Record<string, unknown>): AuditChanges {\n    const changes: AuditChanges = {};\n\n    if (typeof input.name === 'string' && input.name !== this.partnerName) {\n      changes.name = { from: this.partnerName, to: input.name };\n      this.partnerName = input.name;\n    }\n    if (\n      'vatId' in input &&\n      input.vatId !== this.partnerVatId &&\n      (typeof input.vatId === 'string' || input.vatId === null)\n    ) {\n      changes.vatId = { from: this.partnerVatId, to: input.vatId };\n      this.partnerVatId = input.vatId;\n    }\n    if (typeof input.kind === 'string' && input.kind !== this.partnerKind) {\n      changes.kind = { from: this.partnerKind, to: input.kind };\n      this.partnerKind = input.kind;\n    }\n    // `null` clears the term, the way `vatId: null` above already did. Reading it with a\n    // `typeof === 'number'` check meant an agreed payment term could be set and never taken back:\n    // neither null nor an absent field removed it, and the two fields behaved differently with\n    // nothing saying so.\n    if (\n      'paymentTermsDays' in input &&\n      (typeof input.paymentTermsDays === 'number' || input.paymentTermsDays === null) &&\n      input.paymentTermsDays !== this.partnerPaymentTermsDays\n    ) {\n      changes.paymentTermsDays = { from: this.partnerPaymentTermsDays, to: input.paymentTermsDays };\n      this.partnerPaymentTermsDays = input.paymentTermsDays;\n    }\n    // Create-only until now, which made a wrong account link permanent: the partner had to be\n    // abandoned and created again under a new id, and every open item stayed on the old one. Both\n    // replace wholesale rather than merging — \"these are the accounts now\" is a statement an\n    // application can make from a form, while a merge would need a way to say \"remove this one\".\n    if (Array.isArray(input.accountNumbers)) {\n      const next = input.accountNumbers.filter((value): value is string => typeof value === 'string');\n      if (canonicalJson(next) !== canonicalJson(this.accountNumbers)) {\n        changes.accountNumbers = { from: [...this.accountNumbers], to: next };\n        this.accountNumbers = next;\n      }\n    }\n    if (input.address !== undefined && input.address !== null && typeof input.address === 'object') {\n      const next = Array.isArray(input.address) ? {} : (input.address as Record<string, unknown>);\n      if (canonicalJson(next) !== canonicalJson(this.address)) {\n        changes.address = { from: { ...this.address }, to: next };\n        this.address = next;\n      }\n    }\n\n    return changes;\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      id: this.id.value,\n      name: this.partnerName,\n      kind: this.partnerKind,\n      vatId: this.partnerVatId,\n      paymentTermsDays: this.partnerPaymentTermsDays,\n      accountNumbers: this.accountNumbers,\n      address: Object.keys(this.address).length === 0 ? null : this.address,\n      status: this.partnerStatus,\n    };\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport { AuditRecord, type AuditChanges } from '../records/audit-record.js';\nimport type {\n  AccountRepository,\n  AuditTrail,\n  OpenItemRepository,\n  PartnerRepository,\n  VoucherRepository,\n} from '../port.js';\nimport { AccountNumber } from '../substrate/account-number.js';\nimport type { Clock } from '../substrate/clock.js';\nimport { InvalidValue } from '../substrate/errors.js';\nimport type { IdGenerator } from '../substrate/id-generator.js';\nimport { parsePartnerKind } from '../substrate/types.js';\nimport { Uuid } from '../substrate/uuid.js';\nimport { Partner } from './partner.js';\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/** Partner operations (api.md v0.4): createPartner / updatePartner with audit. */\nexport class PartnerService {\n  constructor(\n    private readonly partners: PartnerRepository,\n    private readonly audit: AuditTrail,\n    private readonly clock: Clock,\n    private readonly ids: IdGenerator,\n    /**\n     * The chart, so an account link can be checked against it (F-CORE-032).\n     *\n     * Not optional: a service built without it would validate nothing and say nothing, which is the\n     * state this check was added to end.\n     */\n    private readonly accounts: AccountRepository,\n    /**\n     * The two places a partner is reachable from the books (F-CORE-040) — needed only by `erase`,\n     * which must refuse while either still names it.\n     *\n     * A journal entry never names a partner directly; it reaches one through its voucher, which is\n     * why the journal is not consulted here and why an entry cannot orphan a reference this check\n     * would miss.\n     */\n    private readonly vouchers: VoucherRepository,\n    private readonly openItems: OpenItemRepository,\n  ) {}\n\n  /**\n   * A partner may only be linked to accounts the books actually carry.\n   *\n   * Without this a partner could be linked to 9999 in a chart that stops at 3110: the operation\n   * succeeded, the link was stored as a list of strings on the aggregate, and nothing ever reported\n   * it. That is master data wrong for every reader of the books, not only for the screen that\n   * entered it — the same argument that pulled `name` and `kind` in here rather than leaving them\n   * to the embedding. The account link was made updatable in that pass and its check was not.\n   *\n   * Whole-list semantics are untouched: an empty list still clears the link.\n   */\n  private validateAccountNumbers(input: Record<string, unknown>): void {\n    if (!Array.isArray(input.accountNumbers)) return;\n    for (const value of input.accountNumbers) {\n      if (typeof value !== 'string') continue;\n      if (this.accounts.byNumber(AccountNumber.of(value)) === null) {\n        throw new DomainError('E_ACCOUNT_UNKNOWN', `Account ${value} does not exist in this chart`, {\n          account: value,\n        });\n      }\n    }\n  }\n\n  /**\n   * A partner needs a name, and the kinds are the three the manual names (F-CORE-032).\n   *\n   * Both used to be optional in the widest sense: `name` defaulted to `\"\"`, so a request that\n   * forgot it created a nameless partner indistinguishable from the next one and impossible to\n   * pick out of a list; `kind` was a plain string, so `custommer` was a partner kind like any\n   * other and only surfaced as a category nothing could filter on. An embedding application ended\n   * up validating both itself, which is the wrong place: master data that is wrong here is wrong\n   * for every reader of the books, not just for the screen that entered it.\n   */\n  private validateMasterData(input: Record<string, unknown>, nameRequired: boolean): void {\n    const name = asString(input.name);\n    if (nameRequired ? name === null || name.trim() === '' : 'name' in input && (name === null || name.trim() === '')) {\n      throw new DomainError('E_INPUT_INVALID', 'createPartner: \"name\" must not be empty', {\n        name: input.name === undefined ? null : input.name,\n      });\n    }\n    if (input.kind !== undefined && input.kind !== null && parsePartnerKind(input.kind) === null) {\n      throw new DomainError('E_INPUT_INVALID', 'partner \"kind\" must be \"customer\", \"supplier\" or \"both\"', {\n        kind: input.kind,\n      });\n    }\n  }\n\n  create(input: Record<string, unknown>): Partner {\n    this.validateMasterData(input, true);\n    this.validateAccountNumbers(input);\n    const accountNumbers = (Array.isArray(input.accountNumbers) ? input.accountNumbers : []).filter(\n      (value): value is string => typeof value === 'string',\n    );\n    const address =\n      input.address !== null && typeof input.address === 'object' && !Array.isArray(input.address)\n        ? (input.address as Record<string, unknown>)\n        : {};\n\n    const name = asString(input.name) ?? '';\n    const kind = asString(input.kind) ?? 'both';\n\n    const partner = new Partner(\n      this.ids.next(),\n      name,\n      kind,\n      asString(input.vatId),\n      typeof input.paymentTermsDays === 'number' ? input.paymentTermsDays : null,\n      accountNumbers,\n      address,\n    );\n\n    this.partners.add(partner);\n    // A creation is a change from nothing, written as `from: null` rather than as an empty diff —\n    // the idiom vouchers and fiscal years already used. The identifying fields only: the partner's\n    // current state is retrievable from the master data, and a trail that copies the object is a\n    // second source of truth rather than a history.\n    this.recordAudit(input, 'created', partner.id, {\n      name: { from: null, to: name },\n      kind: { from: null, to: kind },\n    });\n    return partner;\n  }\n\n  update(input: Record<string, unknown>): Partner {\n    const partner = this.require(input.partnerId);\n    // Absent leaves the name alone; present and empty is the same mistake as creating without one.\n    this.validateMasterData(input, false);\n    this.validateAccountNumbers(input);\n    const changes = partner.update(input);\n    if (Object.keys(changes).length > 0) {\n      this.partners.save(partner);\n      this.recordAudit(input, 'updated', partner.id, changes);\n    }\n    return partner;\n  }\n\n  /**\n   * Marks a partner as no longer in use, and takes it back (F-CORE-034).\n   *\n   * Both directions in one place, like the account lock, because the audit record is the point of\n   * the operation and two copies of it would be two chances for one direction to record less.\n   */\n  setStatus(input: Record<string, unknown>, target: 'active' | 'inactive'): Partner {\n    const partner = this.require(input.partnerId);\n    const before = partner.status();\n    if (target === 'inactive') partner.deactivate();\n    else partner.reactivate();\n\n    if (before !== partner.status()) {\n      this.partners.save(partner);\n      this.recordAudit(input, target === 'inactive' ? 'deactivated' : 'reactivated', partner.id, {\n        status: { from: before, to: partner.status() },\n      });\n    }\n    return partner;\n  }\n\n  /**\n   * Erase a partner and the trail's records about it (F-CORE-040).\n   *\n   * **Why this exists next to `deactivate`, which reads like it should be enough.** It is not the\n   * same question. `inactive` says *we no longer trade with them* and is a state the books keep;\n   * erasure says *this record must not be here at all*. The mechanism is the same in every\n   * jurisdiction and the reason is not: wherever a retention rule applies it applies to what the\n   * books reference, and a partner the books have never referenced falls outside it. So the line\n   * this operation draws — referenced or not — is the only line the core knows. Which rule puts a\n   * record on which side of it, and under what name, is documented outside the core\n   * (`docs/gdpr-conformance.md`) and never asserted here.\n   *\n   * **Why it also erases the audit records about the partner.** `createPartner` writes the name\n   * and, if given, the address into `changes`. Removing the partner row while that record stands\n   * erases nothing — the personal data simply moves to the place nobody looks. So the records\n   * *about this partner* go with it, and a single new record is appended in their place naming the\n   * id, the actor and the moment, and carrying **no personal payload**. The trail keeps the fact\n   * that an erasure happened, which is what an audit asks of it, and stops keeping what the law\n   * says must go.\n   *\n   * **What it will not touch.** A voucher or an open item naming the partner is a bookkeeping\n   * record under retention, and the refusal is unconditional — `E_PARTNER_IN_USE`, with the counts,\n   * so a caller can say *why* rather than only *no*. Nothing here can reach a journal entry.\n   */\n  erase(input: Record<string, unknown>): { id: string; erasedAuditRecords: number } {\n    const partner = this.require(input.partnerId);\n\n    const vouchers = this.vouchers.all().filter((voucher) => voucher.partnerId?.value === partner.id.value).length;\n    const openItems = this.openItems.all().filter((item) => item.partnerId?.value === partner.id.value).length;\n\n    if (vouchers > 0 || openItems > 0) {\n      throw new DomainError(\n        'E_PARTNER_IN_USE',\n        `Business partner ${partner.id.value} is referenced by the books and is kept under the retention duty`,\n        { partnerId: partner.id.value, vouchers, openItems },\n      );\n    }\n\n    const erasedAuditRecords = this.audit.eraseFor('partner', partner.id);\n    this.partners.remove(partner.id);\n    // Appended after the erasure, never before: the record that documents it must not be one of\n    // the records it removes.\n    // `existed`, not an empty diff. The published invariant says every record carries before/after\n    // values, and the contract test enforces it — which is the right pressure here rather than an\n    // exception: what changed IS the existence of the record, and saying so costs nothing and\n    // reveals nothing. A diff naming the erased fields would put the name back into the trail,\n    // which is the one thing this operation exists to prevent.\n    this.recordAudit(input, 'erased', partner.id, { existed: { from: true, to: false } });\n\n    return { id: partner.id.value, erasedAuditRecords };\n  }\n\n  require(partnerId: unknown): Partner {\n    let partner: Partner | null = null;\n    if (typeof partnerId === 'string' && partnerId !== '') {\n      try {\n        partner = this.partners.byId(Uuid.fromString(partnerId));\n      } catch (error) {\n        if (!(error instanceof InvalidValue)) throw error;\n      }\n    }\n    if (partner === null) {\n      throw new DomainError('E_PARTNER_UNKNOWN', `Business partner ${typeof partnerId === 'string' ? partnerId : '?'} does not exist`);\n    }\n    return partner;\n  }\n\n  private recordAudit(\n    input: Record<string, unknown>,\n    action: string,\n    objectId: Uuid,\n    changes: AuditChanges,\n  ): void {\n    const actor = asString(input.actor);\n    this.audit.append(\n      new AuditRecord(\n        this.ids.next(),\n        this.clock.now().toISOString(),\n        actor !== null && actor !== '' ? actor : 'system',\n        'partner',\n        objectId,\n        action,\n        changes,\n      ),\n    );\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport type { Money } from '../../../substrate/money.js';\nimport type { TaxCodeVersion } from './tax-code-version.js';\n\n/**\n * Tax mechanism = the law-free strategy that turns one tax code's net base into tax line(s),\n * a base tag, and a gross delta. The repertoire used to be an inline switch in TaxService\n * (`reverse_charge` / `intra_community_supply` / else); it is now an addressable registry —\n * the \"socket\" the architecture calls for (substrate → policy kinds → pack). Each mechanism is\n * a small strategy here in the policy layer; the pack only *selects* one per tax code via\n * `version.mechanism`, it carries no code.\n *\n * The repertoire is CLOSED (decided 2026-08-16): mechanisms are registered here, inside the core,\n * in both languages — never from outside. A mechanism plugged in by the embedder would be\n * different code in PHP than in Node, and \"same input → same result regardless of language\" is the\n * project's top rule; the shared fixtures could not check such a mechanism at all. The reasoning\n * and what would reopen the question: `core/src/CLAUDE.md`.\n *\n * The unknown-mechanism fallback is still lenient (`mechanismFor` returns the standard mechanism\n * for any unrecognized name, exactly as the old `else` branch did), so a typo in a pack books\n * standard VAT silently. Tightening that to an error is a separate hardening, not done.\n */\nexport interface MechanismContext {\n  readonly version: TaxCodeVersion;\n  /** Tax already computed for this code (rounded once per voucher) — mechanisms only assemble. */\n  readonly tax: Money;\n  /** Posting side for an output/input voucher (`credit`/`debit`). */\n  readonly outputSide: 'credit' | 'debit';\n  /** Builds a tax tag for this code/version/base with the given reporting key. */\n  readonly tag: (reportingKey: string | null) => Record<string, unknown>;\n  /** Zero in the base currency — the gross delta of a mechanism that does not raise gross. */\n  readonly zero: Money;\n}\n\nexport interface MechanismContribution {\n  readonly taxLines: Array<Record<string, unknown>>;\n  readonly baseTag: Record<string, unknown>;\n  readonly grossDelta: Money;\n}\n\nexport interface TaxMechanism {\n  /** The resolver must check `inputTaxAccount` exists for this mechanism (reverse charge). */\n  readonly requiresInputTaxAccount: boolean;\n  /** This mechanism's reporting keys feed the EC sales list (intra-community supply). */\n  readonly affectsEcSalesList: boolean;\n  /** Fixed VAT-return direction, or `null` to derive it from the tax account. */\n  readonly vatReturnDirection: 'input' | null;\n  contribute(ctx: MechanismContext): MechanismContribution;\n}\n\n/** Standard VAT: one tax line on the output/input side; gross = net + tax. */\nclass StandardMechanism implements TaxMechanism {\n  readonly requiresInputTaxAccount = false;\n  readonly affectsEcSalesList = false;\n  readonly vatReturnDirection: 'input' | null = null;\n  contribute({ version, tax, outputSide, tag }: MechanismContext): MechanismContribution {\n    return {\n      taxLines: [{ account: version.taxAccount, side: outputSide, money: tax.toJSON(), taxTag: tag(version.reportingKey) }],\n      baseTag: tag(version.reportingKey),\n      grossDelta: tax,\n    };\n  }\n}\n\n/** Reverse charge: VAT and input tax at once (credit + debit), each its own key; payable = net. */\nclass ReverseChargeMechanism implements TaxMechanism {\n  readonly requiresInputTaxAccount = true;\n  readonly affectsEcSalesList = false;\n  readonly vatReturnDirection: 'input' | null = 'input';\n  contribute({ version, tax, tag, zero }: MechanismContext): MechanismContribution {\n    return {\n      taxLines: [\n        { account: version.taxAccount, side: 'credit', money: tax.toJSON(), taxTag: tag(version.reportingKey) },\n        {\n          account: version.inputTaxAccount ?? version.taxAccount,\n          side: 'debit',\n          money: tax.toJSON(),\n          taxTag: tag(version.inputReportingKey),\n        },\n      ],\n      baseTag: tag(version.baseReportingKey ?? version.reportingKey),\n      grossDelta: zero,\n    };\n  }\n}\n\n/** Intra-community supply: tax-free — no tax line, just the reporting-key tag on the base. */\nclass IntraCommunitySupplyMechanism implements TaxMechanism {\n  readonly requiresInputTaxAccount = false;\n  readonly affectsEcSalesList = true;\n  readonly vatReturnDirection: 'input' | null = null;\n  contribute({ version, tag, zero }: MechanismContext): MechanismContribution {\n    return { taxLines: [], baseTag: tag(version.reportingKey), grossDelta: zero };\n  }\n}\n\n/**\n * Exempt supply: tax-free — no tax line, base tagged for reporting. Mechanically like an\n * intra-community supply but a distinct mechanism, so projections that single out IC supplies\n * (the EC sales list) do not pick it up. Lets an exempt code post without a rejected 0.00 tax\n * line (the reason a plain rate-0 standard code could not — IMPL-004/SPEC-010).\n */\nclass ExemptMechanism implements TaxMechanism {\n  readonly requiresInputTaxAccount = false;\n  readonly affectsEcSalesList = false;\n  readonly vatReturnDirection: 'input' | null = null;\n  contribute({ version, tag, zero }: MechanismContext): MechanismContribution {\n    return { taxLines: [], baseTag: tag(version.reportingKey), grossDelta: zero };\n  }\n}\n\nconst REGISTRY: Record<string, TaxMechanism> = {\n  standard: new StandardMechanism(),\n  reverse_charge: new ReverseChargeMechanism(),\n  intra_community_supply: new IntraCommunitySupplyMechanism(),\n  exempt: new ExemptMechanism(),\n};\n\n/**\n * An unregistered name is refused, not quietly standardised. The repertoire is closed (decided\n * 2026-08-16): a pack names one of these four and carries no code, so a name that is not here is a\n * typo or a pack built against a newer core — and both used to book plain VAT without a word.\n * `reverse_charge` misspelled as `reverse-charge` produced a normal tax line, on the normal\n * account, in the normal VAT return box. Nothing about the output said the mechanism had been\n * dropped.\n *\n * `E_PACK_INCOHERENT` because that is what it is: the modules resolve, but the bundle asks for a\n * mechanism that does not exist. The resolver calls this too, so a composed pack fails at\n * `resolvePack`/`init` rather than at the first posting.\n */\n/**\n * The registered repertoire, in registration order. Published because a *document* that names the\n * mechanisms — `docs/gobd-conformance.md` does — is making a checkable claim, and a claim nothing\n * checks is how that census came to describe a pack that had already moved on.\n */\nexport function allTaxMechanisms(): readonly string[] {\n  return Object.keys(REGISTRY);\n}\n\nexport function mechanismFor(name: string): TaxMechanism {\n  const mechanism = REGISTRY[name];\n  if (mechanism === undefined) {\n    throw new DomainError('E_PACK_INCOHERENT', `Unknown tax mechanism: ${name}`, {\n      mechanism: name,\n      known: allTaxMechanisms(),\n    });\n  }\n\n  return mechanism;\n}\n","import type { JournalRepository, PartnerRepository, VoucherRepository } from '../../port.js';\nimport { Money } from '../../substrate/money.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport type { TaxCodeRegistry } from '../expansion/tax/tax-code-registry.js';\nimport { mechanismFor } from '../expansion/tax/tax-mechanisms.js';\nimport { integerOr } from './parameters.js';\n\n/**\n * EC sales list basis (v0.4, SF-21): intra-community supplies per VAT ID and\n * period — from reporting-key tags of the intra-community-supply codes, partner via the voucher.\n *\n * **A supply that cannot be reported is reported as unreportable** (F-IO-011). The list is keyed by\n * VAT ID, so a supply whose partner has none used to fall out of it silently: two postings, one\n * with a VAT ID and one without, and the answer was one row and nothing else. That is the dangerous\n * direction — in the jurisdictions that have this report, a supply without the recipient's\n * registration number is typically not exempt at all, so what\n * dropped out was exactly the case where something is wrong. Same shape as `vatReturn.gapWarnings`,\n * and for the same reason: the warning belongs at the figures, next to what is filed, rather than\n * in a projection of its own that whoever files may never open.\n *\n * Not a refusal. Whether a missing VAT ID makes a supply taxable is jurisdiction law and the\n * embedding's call; the library's job is to make sure the case is never invisible.\n */\nexport class EcSalesListProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly journal: JournalRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly partners: PartnerRepository,\n    private readonly registry: TaxCodeRegistry,\n  ) {}\n\n  compute(params: Record<string, unknown>): {\n    rows: Array<Record<string, string>>;\n    gapWarnings: Array<Record<string, unknown>>;\n  } {\n    const year = integerOr(params.year, 0);\n    const quarter = integerOr(params.quarter, 0);\n\n    const intraCommunityKeys = new Set<string>();\n    for (const version of this.registry.allVersions()) {\n      if (mechanismFor(version.mechanism).affectsEcSalesList && version.reportingKey !== null) {\n        intraCommunityKeys.add(version.reportingKey);\n      }\n    }\n\n    const byVatId = new Map<string, Money>();\n    const gapWarnings: Array<Record<string, unknown>> = [];\n\n    for (const entry of this.journal.all()) {\n      const voucher = this.vouchers.byId(entry.voucherId);\n      const taxDate = voucher === null ? entry.entryDate : voucher.taxDate();\n      if (taxDate.year() !== year) continue;\n      if (quarter !== 0 && Math.floor((taxDate.month() - 1) / 3) + 1 !== quarter) continue;\n\n      const partner = voucher?.partnerId == null ? null : this.partners.byId(voucher.partnerId);\n      const vatId = partner?.vatId() ?? null;\n\n      for (const line of entry.lines()) {\n        const rawKey = line.taxTag?.reportingKey;\n        if (typeof rawKey !== 'string' && typeof rawKey !== 'number') continue;\n        if (!intraCommunityKeys.has(String(rawKey))) continue;\n\n        // The line IS an intra-community supply — decided before the partner is looked at, which is\n        // the whole change. Deciding it afterwards is what made a missing VAT ID look like a\n        // posting that was never an intra-community supply to begin with.\n        if (vatId === null) {\n          gapWarnings.push({\n            reason: partner === null ? 'supply_without_partner' : 'partner_without_vat_id',\n            sequenceNumber: entry.sequenceNumber,\n            entryDate: entry.entryDate.iso,\n            reportingKey: String(rawKey),\n            money: line.money.toJSON(),\n            partnerId: partner?.id.value ?? null,\n          });\n          continue;\n        }\n\n        const signed = line.side === 'credit' ? line.money : line.money.negate();\n        byVatId.set(vatId, (byVatId.get(vatId) ?? Money.zero(this.baseCurrency)).add(signed));\n      }\n    }\n\n    // Journal order: the order the postings happened in is the order somebody checking them will\n    // work through. Same rule as vatReturn's warnings.\n    gapWarnings.sort((a, b) => Number(a.sequenceNumber) - Number(b.sequenceNumber));\n\n    const vatIds = [...byVatId.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    const rows: Array<Record<string, string>> = [];\n    for (const vatId of vatIds) {\n      const amount = byVatId.get(vatId)!;\n      if (amount.isZero()) continue;\n      rows.push({ vatId, amount: amount.amountAsString(), kind: 'supply' });\n    }\n    return { rows, gapWarnings };\n  }\n}\n","import type { AccountRepository, JournalRepository } from '../../port.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { isBalanceCarrying } from '../../substrate/types.js';\nimport { integerOr } from './parameters.js';\n\ninterface Totals {\n  opening: Money;\n  debit: Money;\n  credit: Money;\n  touched: boolean;\n}\n\n/**\n * Trial balance (SuSa) — columns binding (api.md v0.4):\n * - openingBalance: cumulative balance BEFORE the FY (0 for income accounts)\n * - debitTotal/creditTotal: turnover figures of the period (FY up to period)\n * - balance = openingBalance + debitTotal − creditTotal (debit balances positive)\n * Sorting: account number by codepoints (determinismus.md §3).\n */\nexport class TrialBalanceProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n  ) {}\n\n  compute(params: Record<string, unknown>): { rows: Array<Record<string, string>> } {\n    const fiscalYear = integerOr(params.fiscalYear, 0);\n    const throughPeriod = integerOr(params.throughPeriod, Number.MAX_SAFE_INTEGER);\n    const includeZeroBalances = params.includeZeroBalances === true;\n\n    const zero = Money.zero(this.baseCurrency);\n    const totals = new Map<string, Totals>();\n\n    for (const entry of this.journal.all()) {\n      const entryYear = entry.periodRef.fiscalYear;\n      const entryPeriod = entry.periodRef.period;\n      const isPriorYear = entryYear < fiscalYear;\n      const isCurrentScope = entryYear === fiscalYear && entryPeriod <= throughPeriod;\n      if (!isPriorYear && !isCurrentScope) continue;\n\n      for (const line of entry.lines()) {\n        const account = this.accounts.byId(line.accountId);\n        if (account === null) continue;\n        // Income accounts start at zero each fiscal year (G1).\n        if (isPriorYear && !isBalanceCarrying(account.type)) continue;\n\n        const key = account.number.value;\n        let total = totals.get(key);\n        if (total === undefined) {\n          total = { opening: zero, debit: zero, credit: zero, touched: false };\n          totals.set(key, total);\n        }\n\n        if (isPriorYear) {\n          total.opening =\n            line.side === 'debit' ? total.opening.add(line.money) : total.opening.subtract(line.money);\n          continue;\n        }\n\n        if (line.side === 'debit') total.debit = total.debit.add(line.money);\n        else total.credit = total.credit.add(line.money);\n        total.touched = true;\n      }\n    }\n\n    if (includeZeroBalances) {\n      for (const account of this.accounts.all()) {\n        if (!totals.has(account.number.value)) {\n          totals.set(account.number.value, { opening: zero, debit: zero, credit: zero, touched: false });\n        }\n      }\n    }\n\n    const numbers = [...totals.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    const rows: Array<Record<string, string>> = [];\n    for (const number of numbers) {\n      const total = totals.get(number)!;\n      const balance = total.opening.add(total.debit).subtract(total.credit);\n      if (!includeZeroBalances && balance.isZero() && !total.touched) continue;\n      rows.push({\n        account: number,\n        openingBalance: total.opening.amountAsString(),\n        debitTotal: total.debit.amountAsString(),\n        creditTotal: total.credit.amountAsString(),\n        balance: balance.amountAsString(),\n      });\n    }\n    return { rows };\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type {\n  JournalRepository,\n  OpenItemRepository,\n  PartnerRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { OpenItem } from '../../records/open-item.js';\nimport { parseOpenItemKind } from '../../substrate/types.js';\n\n/**\n * Open items list: deterministic, asOf-capable (time travel via settledAt). Sorting:\n * voucherDate, then sequenceNumber (determinismus.md §3).\n */\nexport class OpenItemsProjection {\n  constructor(\n    private readonly openItems: OpenItemRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly journal: JournalRepository,\n    private readonly partners: PartnerRepository,\n  ) {}\n\n  compute(params: Record<string, unknown>): { items: Array<Record<string, unknown>> } {\n    const asOf = typeof params.asOf === 'string' ? CalendarDate.of(params.asOf) : null;\n    // An unparseable kind used to fall back to \"no filter\", so a mistyped filter widened the\n    // result instead of narrowing it: a payment run asking for payables got receivables mixed\n    // in and would have paid them out. Absent still means \"no filter\" — a wrong value must not.\n    let kind = null;\n    if (params.kind !== undefined && params.kind !== null) {\n      kind = parseOpenItemKind(params.kind);\n      if (kind === null) {\n        throw new DomainError('E_INPUT_INVALID', 'openItems: \"kind\" must be \"receivable\" or \"payable\"', {\n          kind: rejectedValue(params.kind),\n        });\n      }\n    }\n    const partnerId = typeof params.partnerId === 'string' ? params.partnerId : null;\n\n    const open = this.openItems.all().filter((item) => {\n      if (kind !== null && item.kind !== kind) return false;\n      if (partnerId !== null && (item.partnerId?.value ?? null) !== partnerId) return false;\n      if (asOf !== null && item.openedAt.isAfter(asOf)) return false;\n      if (item.remainingAt(asOf).isZero()) return false;\n      return true;\n    });\n\n    open.sort((a, b) => {\n      const byDate = this.voucherDate(a).compareTo(this.voucherDate(b));\n      return byDate !== 0 ? byDate : this.sequenceNumber(a) - this.sequenceNumber(b);\n    });\n\n    return { items: open.map((item) => this.serializeItem(item, asOf)) };\n  }\n\n  private voucherDate(item: OpenItem): CalendarDate {\n    return this.vouchers.byId(item.voucherId)?.voucherDate ?? item.openedAt;\n  }\n\n  private sequenceNumber(item: OpenItem): number {\n    return this.journal.byId(item.originEntryId)?.sequenceNumber ?? 0;\n  }\n\n  /**\n   * Both `partnerId` and `due` were known here and neither was published.\n   *\n   * The partner was accepted as a FILTER and dropped from the result, so a list could be narrowed to\n   * one debtor and then could not say which. The due date sits on the voucher — which this method\n   * already loads, for the voucher number — and without it the list cannot be aged at all, which is\n   * what a maturity disclosure is built from.\n   *\n   * Null where the voucher names no date: present and null, so \"no date agreed\" stays\n   * distinguishable from \"this view does not say\".\n   *\n   * `partnerName` joined the same way and for the same reason (F-CORE-030). The list could name\n   * the invoice but not the customer, and resolving the id meant a second projection inside one\n   * view — which is exactly the mixing an application's read layer is supposed to avoid. A dunning\n   * notice without a recipient is not a notice. Null where the partner is unknown or was never\n   * recorded, so a deleted-from-view partner does not turn into an empty string that reads like a\n   * name.\n   */\n  private serializeItem(item: OpenItem, asOf: CalendarDate | null): Record<string, unknown> {\n    const voucher = this.vouchers.byId(item.voucherId);\n    return {\n      id: item.id.value,\n      kind: item.kind,\n      voucherNumber: voucher?.voucherNumber ?? null,\n      partnerId: item.partnerId?.value ?? null,\n      partnerName: this.partnerName(item),\n      due: voucher?.due?.iso ?? null,\n      money: item.money.toJSON(),\n      remaining: item.remainingAt(asOf).toJSON(),\n      status: item.statusAt(asOf),\n    };\n  }\n\n  private partnerName(item: OpenItem): string | null {\n    if (item.partnerId === null) return null;\n    return this.partners.byId(item.partnerId)?.name() ?? null;\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type { AccountRepository, JournalRepository } from '../../port.js';\nimport { ReversalIndex } from './reversal-index.js';\nimport { AccountNumber } from '../../substrate/account-number.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { isBalanceCarrying } from '../../substrate/types.js';\nimport { integerOr, isIntegerParam } from './parameters.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport type { Side } from '../../substrate/types.js';\n\n/**\n * Account sheet: all movements of an account in the fiscal year with a running balance.\n * Opening balance = cumulative prior years for balance-carrying accounts, null for income accounts.\n * Order: sequenceNumber (determinismus.md §3).\n *\n * Each line carries the **identity of its entry** and the accounts on the other side of it\n * (SPEC-021, reported by an embedding app as its F-31). Without the first, a screen that shows a\n * sheet and lets the reader open a line had to go looking: `journal` with `fromDate` and `toDate`\n * set to the same day, then filter the day's entries by `sequenceNumber` — a search where a lookup\n * belongs, for an entry whose identity the caller had two fields ago. Without the second, a\n * T-account cannot answer the question it raises on every line: *6000 in debit, against what?*\n *\n * `contraAccounts` is a **list** on purpose. For a plain entry it holds one account; as soon as a\n * tax code is involved it holds two or more, and a field called \"the counter account\" would have to\n * pick one and thereby invent a fact. Forming it is also the one part only the library can do: the\n * sheet is an extract of ONE account and the other lines are not in it, so an embedding combining\n * figures itself is exactly what a bookkeeping API should make unnecessary.\n */\nexport class AccountSheetProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    // Both are documented as required. Defaulting them produced an authoritative-looking\n    // empty ledger — the resolved account name next to \"0.00\" reads as a verified statement\n    // about the account, not as \"you forgot a parameter\".\n    if (typeof params.account !== 'string' || params.account === '') {\n      throw new DomainError('E_INPUT_INVALID', 'accountSheet requires the parameter \"account\"', {\n        account: rejectedValue(params.account),\n      });\n    }\n    if (!isIntegerParam(params.fiscalYear)) {\n      throw new DomainError('E_INPUT_INVALID', 'accountSheet requires the parameter \"fiscalYear\"', {\n        fiscalYear: rejectedValue(params.fiscalYear),\n      });\n    }\n    const number = params.account;\n    const fiscalYear = params.fiscalYear;\n    const throughPeriod = integerOr(params.throughPeriod, Number.MAX_SAFE_INTEGER);\n\n    const account = this.accounts.byNumber(AccountNumber.of(number));\n    if (account === null) {\n      throw new DomainError('E_ACCOUNT_UNKNOWN', `Account ${number} does not exist`);\n    }\n\n    let opening = Money.zero(this.baseCurrency);\n    if (isBalanceCarrying(account.type)) {\n      for (const entry of this.journal.all()) {\n        if (entry.periodRef.fiscalYear >= fiscalYear) continue;\n        for (const line of entry.lines()) {\n          if (!line.accountId.equals(account.id)) continue;\n          opening = line.side === 'debit' ? opening.add(line.money) : opening.subtract(line.money);\n        }\n      }\n    }\n\n    let running = opening;\n    const lines: Array<Record<string, unknown>> = [];\n    // See cash-journal: a sheet that shows a reversal as an ordinary opposite movement leaves the\n    // reader unable to tell a correction from a removal.\n    const reversals = ReversalIndex.of(this.journal);\n    for (const entry of this.journal.forFiscalYear(fiscalYear)) {\n      if (entry.periodRef.period > throughPeriod) continue;\n      for (const line of entry.lines()) {\n        if (!line.accountId.equals(account.id)) continue;\n        running = line.side === 'debit' ? running.add(line.money) : running.subtract(line.money);\n        lines.push({\n          sequenceNumber: entry.sequenceNumber,\n          entryId: entry.id.value,\n          entryDate: entry.entryDate.iso,\n          text: entry.text(),\n          side: line.side,\n          money: line.money.toJSON(),\n          runningBalance: running.amountAsString(),\n          contraAccounts: this.contraAccounts(entry, line.side),\n          ...reversals.forEntry(entry),\n        });\n      }\n    }\n\n    return {\n      account: account.number.value,\n      name: account.name,\n      openingBalance: opening.amountAsString(),\n      lines,\n      closingBalance: running.amountAsString(),\n    };\n  }\n\n  /**\n   * The accounts on the other side of one entry, by number, deduplicated and sorted.\n   *\n   * \"Other side\" is decided per line, not per sheet: on a debit line the credit accounts answer the\n   * question, and the other way round. An entry that touches the same account on both sides — a\n   * correction within one account — therefore names it here too, which is the honest answer rather\n   * than an empty list.\n   */\n  private contraAccounts(entry: JournalEntry, side: Side): Array<Record<string, string>> {\n    const seen = new Map<string, string>();\n    for (const line of entry.lines()) {\n      if (line.side === side) continue;\n      const account = this.accounts.byId(line.accountId);\n      if (account === null) continue;\n      seen.set(account.number.value, account.name);\n    }\n    return [...seen.entries()]\n      .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n      .map(([number, name]) => ({ account: number, name }));\n  }\n}\n","import type { AccountRepository } from '../../port.js';\n\n/**\n * The chart of accounts as a screen can afford to read it (F-CORE-028).\n *\n * Every field here was already published somewhere, and nowhere a caller could use. `subtype`\n * and `status` live in `journalExport.data.accounts` — behind five streams with a SHA-256 each,\n * an archive format answering a question a list view asks on every page load. `datevExport({\n * kind: 'accounts' })` is cheap but DATEV-shaped: number, name, type, and by definition nothing\n * else, because it is master data for an export format rather than the chart itself.\n *\n * So the two facts an application needs most were the two it could not get. `subtype` is what\n * identifies an account's *role* — which one is the bank, which the cash box, which receivables\n * and payables — and without it an app preselecting a counter account has to read the pack it was\n * created from, which is the chart the tenant *started* with and not the chart it has. `status`\n * is the read side of `lockAccount`: the operation exists, and nothing a screen could afford\n * reported whether it had been used, so the only honest test was to post into the account and\n * read the refusal.\n *\n * Deliberately small: no balances (that is `trialBalance`), no movements (`accountSheet`), no\n * hashes. Sorted by account number over Unicode code points, like every other ordering here.\n */\nexport class AccountsProjection {\n  constructor(private readonly accounts: AccountRepository) {}\n\n  compute(_params: Record<string, unknown>): { accounts: Array<Record<string, unknown>> } {\n    const sorted = [...this.accounts.all()].sort((a, b) =>\n      a.number.value < b.number.value ? -1 : a.number.value > b.number.value ? 1 : 0,\n    );\n\n    return {\n      accounts: sorted.map((account) => ({\n        number: account.number.value,\n        name: account.name,\n        type: account.type,\n        subtype: account.subtype,\n        status: account.status(),\n        // The read side of the validity window (F-CORE-045), and for the same reason `status` is\n        // here: a screen offering an account picker has to be able to grey out what the posting\n        // date does not allow, rather than letting the user post and then translating\n        // `E_ACCOUNT_NOT_VALID_AT_DATE` back into a sentence.\n        validFrom: account.validFrom?.iso ?? null,\n        validTo: account.validTo?.iso ?? null,\n      })),\n    };\n  }\n}\n","import type { FiscalYearRepository } from '../../port.js';\nimport { integerOrNull } from './parameters.js';\n\n/**\n * Fiscal years and their periods, with the status of each (F-CORE-029).\n *\n * `closePeriod`, `reopenPeriod` and `closeFiscalYear` decide what may still be posted, and until\n * this projection nothing on the read side said what they had decided. `systemDescription` names\n * the invariant — \"a closed period accepts no further postings\" — without naming the periods.\n *\n * What was left was `auditLog`, which records every close and reopen. That is a **trail, not a\n * state**: replaying it into \"period 3 is open\" makes the application rebuild library state from a\n * log, and it is wrong the moment a period is closed by anything that did not pass through that\n * application. The same shape as the account status — the write side owning state the read side\n * does not publish.\n *\n * `start` and `end` come out with it, and they are not decoration: without them an application\n * cannot offer a period *list* at all. Twelve months is a guess that a fiscal year running\n * February to January does not share, and a form that invents them asks for input the ledger will\n * refuse.\n *\n * Ordered by year, periods by their number — the order they fall due in.\n */\nexport class FiscalYearsProjection {\n  constructor(private readonly fiscalYears: FiscalYearRepository) {}\n\n  compute(params: Record<string, unknown>): { fiscalYears: Array<Record<string, unknown>> } {\n    const wanted = integerOrNull(params.fiscalYear);\n\n    const years = [...this.fiscalYears.all()]\n      .filter((year) => wanted === null || year.year === wanted)\n      .sort((a, b) => a.year - b.year);\n\n    return {\n      fiscalYears: years.map((year) => ({\n        year: year.year,\n        start: year.start.iso,\n        end: year.end.iso,\n        status: year.status(),\n        periods: [...year.periods()]\n          .sort((a, b) => a.number - b.number)\n          .map((period) => ({\n            period: period.number,\n            start: period.start.iso,\n            end: period.end.iso,\n            status: period.status(),\n          })),\n      })),\n    };\n  }\n}\n","import type { AccountRepository, AuditTrail, JournalRepository, VoucherRepository } from '../../port.js';\nimport { entryAuthors } from './entry-authors.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport { integerOr, integerOrNull } from './parameters.js';\n\n/**\n * The journal as a screen reads it (F-CORE-031).\n *\n * The plainest view a bookkeeping application has, and until now it had two bad ways to fill it.\n * `journalExport` is lossless and builds five streams with a SHA-256 each, has no window and no\n * paging — an archive format answering a list view's question, paid for on every page load.\n * `datevExport` has the window and the weight but is DATEV-shaped, and therefore **lossy for split\n * entries**: `6000 75.00 + 1500 14.25 against 1200 89.25` collapses into one row and the input-tax\n * line disappears. Filling a journal view from it would quietly hide every tax line in the books.\n *\n * So: `datevExport`'s cost with `journalExport`'s completeness. Every line of every entry, account\n * numbers resolved, no hashes, no streams.\n *\n * **Paging counts entries, not lines**, which is the whole point — a page boundary that fell inside\n * a split entry would reproduce exactly the defect this projection exists to avoid. `count` is the\n * number of entries in the window *before* paging, so a page header can say \"51–100 of 3,204\"\n * without a second call that costs an export.\n *\n * Ordered by `sequenceNumber`, which is already the journal's total order: paging needs a stable\n * one, and inventing a tie-break where the ledger already has none would be a second answer to a\n * question that has one.\n *\n * Each entry carries `actor` (F-CORE-037): who recorded it. The entry itself has no author — the\n * fact lives in the audit trail and nowhere else, so a screen showing the journal could show\n * everything about a posting except who made it. See `entryAuthors`.\n */\nexport class JournalProjection {\n  constructor(\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly vouchers: VoucherRepository,\n    /** Where the author of a posting lives — required for the same reason as everywhere else. */\n    private readonly audit: AuditTrail,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = integerOr(params.fiscalYear, 0);\n    const fromDate = typeof params.fromDate === 'string' ? CalendarDate.of(params.fromDate) : null;\n    const toDate = typeof params.toDate === 'string' ? CalendarDate.of(params.toDate) : null;\n    const offset = Math.max(0, integerOr(params.offset, 0));\n    const limit = integerOrNull(params.limit);\n\n    const matching = this.journal\n      .forFiscalYear(fiscalYear)\n      .filter((entry) => {\n        if (fromDate !== null && entry.entryDate.isBefore(fromDate)) return false;\n        if (toDate !== null && entry.entryDate.isAfter(toDate)) return false;\n        return true;\n      })\n      .sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n\n    // A limit that is absent means \"everything from the offset on\" — a projection that invented a\n    // default page size would silently truncate a caller that never asked for pages.\n    const page = limit === null || limit < 0 ? matching.slice(offset) : matching.slice(offset, offset + limit);\n    const authors = entryAuthors(\n      this.audit,\n      page.map((entry) => entry.id.value),\n    );\n\n    return {\n      fiscalYear,\n      count: matching.length,\n      offset,\n      limit,\n      entries: page.map((entry) => this.serialize(entry, authors)),\n    };\n  }\n\n  private serialize(entry: JournalEntry, authors: Map<string, string>): Record<string, unknown> {\n    const voucher = this.vouchers.byId(entry.voucherId);\n\n    return {\n      sequenceNumber: entry.sequenceNumber,\n      entryId: entry.id.value,\n      actor: authors.get(entry.id.value) ?? null,\n      status: entry.isFinalized() ? 'finalized' : 'entered',\n      entryDate: entry.entryDate.iso,\n      voucherNumber: voucher?.voucherNumber ?? null,\n      voucherDate: voucher?.voucherDate.iso ?? null,\n      text: entry.text(),\n      reverses: entry.reverses?.value ?? null,\n      reversedBy: entry.reversedBy()?.value ?? null,\n      lines: entry.lines().map((line) => ({\n        account: line.account.value,\n        // The name is why this is not just a cheaper export: a journal view showing \"6000\" and\n        // nothing else makes the reader look every number up somewhere for every row.\n        accountName: this.accounts.byId(line.accountId)?.name ?? null,\n        side: line.side,\n        money: line.money.toJSON(),\n        dimensions: line.dimensions.map((dimension) => dimension.toJSON()),\n        taxTag: line.taxTag,\n      })),\n    };\n  }\n}\n","import type { AuditRecord } from '../../records/audit-record.js';\nimport type { AuditTrail } from '../../port.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport { integerOr, integerOrNull } from './parameters.js';\n\n/**\n * Change history as a projection (F-CORE-014, F-CORE-036; GoBD Rz. 107 ff.).\n *\n * Order = recording order of the audit trail, which is already its total order (the sequence in the\n * store, insertion order in memory). Paging needs a stable one, and inventing a tie-break where the\n * trail already has none would be a second answer to a question that has one.\n *\n * **Filters, because the auditor's question is about one thing.** Until 0.13.0 the only parameters\n * were `from`/`to`, so \"who touched this account\", \"what happened to this posting\" and \"what did\n * this user do\" were not askable: the caller had to fetch the whole trail and filter outside. That\n * is the wrong place twice over — it moves the fastest-growing table in the system across a\n * boundary to discard most of it, and it makes progressive and retrograde traceability a property\n * of the embedding rather than of the books.\n *\n * All filters combine with AND, and an absent one filters nothing. `count` is the number of records\n * matching the filters *before* paging, so a page header can say \"51–100 of 3,204\" without a second\n * call — the same contract `journal` publishes, and deliberately the same words.\n */\nexport class AuditLogProjection {\n  constructor(private readonly audit: AuditTrail) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const from = typeof params.from === 'string' ? CalendarDate.of(params.from) : null;\n    const to = typeof params.to === 'string' ? CalendarDate.of(params.to) : null;\n    const objectType = typeof params.objectType === 'string' ? params.objectType : null;\n    const objectId = typeof params.objectId === 'string' ? params.objectId : null;\n    const actor = typeof params.actor === 'string' ? params.actor : null;\n    const action = typeof params.action === 'string' ? params.action : null;\n    const offset = Math.max(0, integerOr(params.offset, 0));\n    const limit = integerOrNull(params.limit);\n\n    const matching: Array<Record<string, unknown>> = [];\n    for (const record of this.audit.all()) {\n      if (!matches(record, from, to, objectType, objectId, actor, action)) continue;\n      matching.push(record.toJSON());\n    }\n\n    // A limit that is absent means \"everything from the offset on\" — a projection that invented a\n    // default page size would silently truncate a caller that never asked for pages.\n    const page = limit === null || limit < 0 ? matching.slice(offset) : matching.slice(offset, offset + limit);\n\n    return { count: matching.length, offset, limit, records: page };\n  }\n}\n\nfunction matches(\n  record: AuditRecord,\n  from: CalendarDate | null,\n  to: CalendarDate | null,\n  objectType: string | null,\n  objectId: string | null,\n  actor: string | null,\n  action: string | null,\n): boolean {\n  const date = CalendarDate.of(record.at.slice(0, 10));\n\n  if (from !== null && date.isBefore(from)) return false;\n  if (to !== null && date.isAfter(to)) return false;\n  if (objectType !== null && record.objectType !== objectType) return false;\n  if (objectId !== null && record.objectId.value !== objectId) return false;\n  if (actor !== null && record.actor !== actor) return false;\n\n  return !(action !== null && record.action !== action);\n}\n","import Big from 'big.js';\nimport type {\n  AccountRepository,\n  JournalRepository,\n  OpenItemRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport { AccountNumber } from '../../substrate/account-number.js';\nimport { mechanismFor } from '../expansion/tax/tax-mechanisms.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport type { OpenItem } from '../../records/open-item.js';\nimport type { TaxCodeRegistry } from '../expansion/tax/tax-code-registry.js';\nimport type { TaxProfile } from '../expansion/tax/tax-profile.js';\nimport { integerOr } from './parameters.js';\nimport { DomainError, rejectedValue } from '../../domain-error.js';\n\n/**\n * Does a date fall in the requested filing period?\n *\n * Three windows, and which one applies is the caller's to say: a month, a quarter, or — when neither\n * is given — the whole year. The month matters more than it looks: for a business above the threshold\n * the monthly period is not a convenience but the prescribed one, and the only alternative an app had\n * was to call twice cumulatively and subtract. That difference is not the period's figure once\n * cash-basis taxation or a reversal is involved, which is why it had to become a window here rather\n * than arithmetic there.\n */\nfunction inPeriod(date: CalendarDate, year: number, quarter: number, month: number): boolean {\n  if (date.year() !== year) return false;\n  if (month !== 0) return date.month() === month;\n  return quarter === 0 || Math.floor((date.month() - 1) / 3) + 1 === quarter;\n}\n\n\ninterface KeyAmount {\n  base: Money;\n  tax: Money;\n}\ninterface Share {\n  key: string;\n  base: Money;\n  tax: Money;\n  settledAt: CalendarDate;\n}\n\n/**\n * VAT return reporting keys via taxTags (SF-09). Accrual: posting/supply date; cash:\n * follows OP settlements (proportional half-up, final remainder exact). Tax bases\n * per reporting key rounded down to full euros, tax to the cent (api.md v0.3).\n */\nexport class VatReturnProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly journal: JournalRepository,\n    private readonly openItems: OpenItemRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly accounts: AccountRepository,\n    private readonly registry: TaxCodeRegistry,\n    private readonly profile: TaxProfile,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const year = integerOr(params.year, 0);\n    const quarter = integerOr(params.quarter, 0);\n    const month = integerOr(params.month, 0);\n\n    // Both would describe two different windows, and picking one silently is how a return gets filed\n    // for the wrong period. Absent is still \"the whole year\".\n    if (quarter !== 0 && month !== 0) {\n      throw new DomainError('E_INPUT_INVALID', 'vatReturn: give either \"quarter\" or \"month\", not both', {\n        quarter,\n        month,\n      });\n    }\n\n    if (month !== 0 && (month < 1 || month > 12)) {\n      throw new DomainError('E_INPUT_INVALID', 'vatReturn: \"month\" must be between 1 and 12', {\n        month: rejectedValue(params.month),\n      });\n    }\n    const asOf = typeof params.asOf === 'string' ? CalendarDate.of(params.asOf) : null;\n\n    const zero = Money.zero(this.baseCurrency);\n    const keys = new Map<string, KeyAmount>();\n    const directions = this.registryDirections();\n\n    const add = (key: string, base: Money, tax: Money): void => {\n      const current = keys.get(key) ?? { base: zero, tax: zero };\n      keys.set(key, { base: current.base.add(base), tax: current.tax.add(tax) });\n    };\n\n    if (this.profile.isCashBasis()) {\n      for (const item of this.openItems.all()) {\n        const origin = this.journal.byId(item.originEntryId);\n        if (origin === null || (asOf !== null && origin.entryDate.isAfter(asOf))) continue;\n        const contributions = this.entryContributions(origin, directions);\n        if (contributions.size === 0) continue;\n        for (const share of this.allocateToSettlements(item, contributions)) {\n          if (asOf !== null && share.settledAt.isAfter(asOf)) continue;\n          if (inPeriod(share.settledAt, year, quarter, month)) add(share.key, share.base, share.tax);\n        }\n      }\n\n      for (const entry of this.journal.all()) {\n        if (!inPeriod(entry.entryDate, year, quarter, month)) continue;\n        if (asOf !== null && entry.entryDate.isAfter(asOf)) continue;\n        if (this.openItems.byOriginEntry(entry.id).length > 0) continue;\n        // IMPL-005: this loop's premise is \"no open item ⇒ the money moved at posting time\"\n        // (a cash sale). A reversal has no open item of its own, but it is not a cash\n        // movement either. When the entry it reverses carries open items, its tax already\n        // follows those items' settlements above — counting it here would declare a\n        // correction for money that never moved: reversing an unpaid invoice would claim\n        // back tax that was never due. Reversals of genuinely cash-effective entries\n        // (target without open items) still count here, at their own posting date.\n        if (entry.reverses !== null && this.openItems.byOriginEntry(entry.reverses).length > 0) {\n          continue;\n        }\n        for (const [key, contribution] of this.entryContributions(entry, directions)) {\n          add(key, contribution.base, contribution.tax);\n        }\n      }\n    } else {\n      for (const entry of this.journal.all()) {\n        let taxDate: CalendarDate;\n        if (entry.reverses !== null) {\n          // SPEC-011: a tax correction counts by its own posting date.\n          taxDate = entry.entryDate;\n        } else {\n          const voucher = this.vouchers.byId(entry.voucherId);\n          taxDate = voucher === null ? entry.entryDate : voucher.taxDate();\n        }\n        if (!inPeriod(taxDate, year, quarter, month)) continue;\n        if (asOf !== null && entry.entryDate.isAfter(asOf)) continue;\n        for (const [key, contribution] of this.entryContributions(entry, directions)) {\n          add(key, contribution.base, contribution.tax);\n        }\n      }\n    }\n\n    const sortedKeys = [...keys.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    const result: Record<string, { base: string; tax: string }> = {};\n    let payload = zero;\n\n    for (const key of sortedKeys) {\n      const amounts = keys.get(key)!;\n      // Official VAT-return convention: round base down to full euros.\n      const flooredBase = Money.fromCalculation(\n        new Big(amounts.base.amountAsString()).round(0, Big.roundDown),\n        this.baseCurrency,\n      );\n      result[key] = { base: flooredBase.amountAsString(), tax: amounts.tax.amountAsString() };\n      const direction = directions.get(key) ?? 'output';\n      payload = direction === 'input' ? payload.subtract(amounts.tax) : payload.add(amounts.tax);\n    }\n\n    return { keys: result, payload: payload.toJSON(), gapWarnings: this.gapWarnings(year, quarter, month, asOf) };\n  }\n\n  /**\n   * Postings that touch a tax account without a tax code (F-TAX-013).\n   *\n   * The return is built from tax-*coded* postings — `line.taxTag` is what carries the reporting key\n   * and the base. That is a defensible design and it is silent: posting expense / input tax / bank\n   * by hand balances, satisfies every invariant, and shows correct figures on the accounts and in\n   * the trial balance. Only `vatReturn` reports zero, because nothing told it which key the amount\n   * belongs to. The books look right everywhere except the one place that decides what is filed,\n   * and an application's seed script fell into it on the first attempt.\n   *\n   * So the warning lives here, at the figures, rather than in a projection of its own that whoever\n   * files the return may not open. It is **not** a refusal: correction postings legitimately touch\n   * these accounts, and a library that blocked them would be wrong more often than the caller.\n   *\n   * Which accounts count is the pack's answer, not this code's: `tax_in` and `tax_out` are subtypes\n   * the chart assigns, so a jurisdiction without input-tax deduction simply has no `tax_in` account\n   * and produces no such warning.\n   *\n   * The window is the posting's tax date in both taxation methods. An untagged line has nothing to\n   * attach it to a settlement, so the cash-basis question \"when did the money move\" has no answer\n   * for it — which is part of what makes it worth reporting.\n   */\n  private gapWarnings(\n    year: number,\n    quarter: number,\n    month: number,\n    asOf: CalendarDate | null,\n  ): Array<Record<string, unknown>> {\n    const warnings: Array<Record<string, unknown>> = [];\n\n    for (const entry of this.journal.all()) {\n      const voucher = this.vouchers.byId(entry.voucherId);\n      const taxDate = entry.reverses !== null || voucher === null ? entry.entryDate : voucher.taxDate();\n      if (!inPeriod(taxDate, year, quarter, month)) continue;\n      if (asOf !== null && entry.entryDate.isAfter(asOf)) continue;\n\n      for (const line of entry.lines()) {\n        if (line.taxTag !== null) continue;\n        const account = this.accounts.byId(line.accountId);\n        const subtype = account?.subtype ?? null;\n        if (subtype !== 'tax_in' && subtype !== 'tax_out') continue;\n\n        warnings.push({\n          reason: 'tax_account_without_tax_code',\n          sequenceNumber: entry.sequenceNumber,\n          entryDate: entry.entryDate.iso,\n          account: account?.number.value ?? null,\n          side: line.side,\n          money: line.money.toJSON(),\n        });\n      }\n    }\n\n    // Journal order, then account: the order the postings happened in is the order somebody\n    // checking them will work through.\n    warnings.sort((a, b) => {\n      const bySeq = (a.sequenceNumber as number) - (b.sequenceNumber as number);\n      if (bySeq !== 0) return bySeq;\n      const left = String(a.account ?? '');\n      const right = String(b.account ?? '');\n      return left < right ? -1 : left > right ? 1 : 0;\n    });\n    return warnings;\n  }\n\n  private registryDirections(): Map<string, string> {\n    const directions = new Map<string, string>();\n    for (const version of this.registry.allVersions()) {\n      if (version.reportingKey !== null) {\n        directions.set(version.reportingKey, this.accountDirection(version.taxAccount));\n      }\n      if (version.inputReportingKey !== null) {\n        directions.set(version.inputReportingKey, 'input');\n      }\n      if (version.baseReportingKey !== null) {\n        directions.set(\n          version.baseReportingKey,\n          mechanismFor(version.mechanism).vatReturnDirection ?? this.accountDirection(version.taxAccount),\n        );\n      }\n    }\n    return directions;\n  }\n\n  private accountDirection(accountNumber: string): string {\n    if (accountNumber === '') return 'output';\n    const account = this.accounts.byNumber(AccountNumber.of(accountNumber));\n    return account?.subtype === 'tax_in' ? 'input' : 'output';\n  }\n\n  private entryContributions(entry: JournalEntry, directions: Map<string, string>): Map<string, KeyAmount> {\n    const zero = Money.zero(this.baseCurrency);\n    interface Collected {\n      baseFromTax: Money;\n      hasTaxBase: boolean;\n      baseFallback: Money;\n      tax: Money;\n    }\n    const collected = new Map<string, Collected>();\n\n    for (const line of entry.lines()) {\n      const tag = line.taxTag;\n      if (tag === null) continue;\n      const rawKey = tag.reportingKey;\n      if (typeof rawKey !== 'string' && typeof rawKey !== 'number') continue;\n      const key = String(rawKey);\n\n      const account = this.accounts.byId(line.accountId);\n      const subtype = account?.subtype ?? null;\n      const entryFor = collected.get(key) ?? {\n        baseFromTax: zero,\n        hasTaxBase: false,\n        baseFallback: zero,\n        tax: zero,\n      };\n\n      if (subtype === 'tax_out' || subtype === 'tax_in') {\n        const positiveSide = subtype === 'tax_out' ? 'credit' : 'debit';\n        const signed = line.side === positiveSide ? line.money : line.money.negate();\n        entryFor.tax = entryFor.tax.add(signed);\n\n        let baseMoney = this.tagBaseMoney(tag);\n        if (baseMoney !== null) {\n          if (line.money.isNegative()) baseMoney = baseMoney.negate();\n          entryFor.baseFromTax = entryFor.baseFromTax.add(baseMoney);\n          entryFor.hasTaxBase = true;\n        }\n      } else {\n        const direction = directions.get(key) ?? 'output';\n        const positiveSide = direction === 'input' ? 'debit' : 'credit';\n        const signed = line.side === positiveSide ? line.money : line.money.negate();\n        entryFor.baseFallback = entryFor.baseFallback.add(signed);\n      }\n      collected.set(key, entryFor);\n    }\n\n    const contributions = new Map<string, KeyAmount>();\n    for (const [key, parts] of collected) {\n      const base = parts.hasTaxBase ? parts.baseFromTax : parts.baseFallback;\n      if (base.isZero() && parts.tax.isZero()) continue;\n      contributions.set(key, { base, tax: parts.tax });\n    }\n    return contributions;\n  }\n\n  private tagBaseMoney(tag: Record<string, unknown>): Money | null {\n    const baseMoney = tag.baseMoney;\n    const amount =\n      baseMoney !== null && typeof baseMoney === 'object' && typeof (baseMoney as Record<string, unknown>).amount === 'string'\n        ? ((baseMoney as Record<string, unknown>).amount as string)\n        : null;\n    return amount === null ? null : Money.of(amount, this.baseCurrency);\n  }\n\n  private allocateToSettlements(item: OpenItem, contributions: Map<string, KeyAmount>): Share[] {\n    const shares: Share[] = [];\n    const allocated = new Map<string, KeyAmount>();\n    let remaining = item.money;\n    const total = new Big(item.money.amountAsString());\n\n    for (const settlement of item.settlements()) {\n      // IMPL-008: a cancellation closes the item without any money moving. Counting it here would\n      // declare cash-basis VAT for a reversed invoice that was never paid — the exact opposite of\n      // what the reversal means. Skipped before `remaining` is touched, so the proportional split\n      // of any real payments is unaffected.\n      if (settlement.cause === 'cancellation') continue;\n      remaining = remaining.subtract(settlement.money);\n      const isFinal = remaining.isZero();\n      const ratio = new Big(settlement.money.amountAsString());\n\n      for (const [key, contribution] of contributions) {\n        const current = allocated.get(key) ?? {\n          base: Money.zero(this.baseCurrency),\n          tax: Money.zero(this.baseCurrency),\n        };\n\n        let base: Money;\n        let tax: Money;\n        if (isFinal) {\n          base = contribution.base.subtract(current.base);\n          tax = contribution.tax.subtract(current.tax);\n        } else {\n          base = this.proportional(contribution.base, ratio, total);\n          tax = this.proportional(contribution.tax, ratio, total);\n        }\n\n        allocated.set(key, { base: current.base.add(base), tax: current.tax.add(tax) });\n        shares.push({ key, base, tax, settledAt: settlement.settledAt });\n      }\n    }\n    return shares;\n  }\n\n  private proportional(total: Money, part: Big, whole: Big): Money {\n    if (whole.eq(0)) return Money.zero(this.baseCurrency);\n    return Money.fromCalculation(\n      new Big(total.amountAsString()).times(part).div(whole),\n      this.baseCurrency,\n    );\n  }\n\n}\n","/**\n * The catch-all a mapping gap falls into.\n *\n * The error catalogue settles the treatment: a gap is not an error but `gapWarnings[]` plus this\n * position. Three places need to agree on the key — the importer, which reports gaps at import\n * time, and both statements, which have to keep the money visible at report time — so it lives\n * here rather than as three string literals that would eventually disagree.\n */\nexport const UNASSIGNED = '_unassigned';\n\n/**\n * Label for the catch-all. Neutral and jurisdiction-free on purpose: there is no mapping entry to\n * take a label from, and the core carries no statute language (see the no-jurisdiction-text guard).\n */\nexport const UNASSIGNED_LABEL = 'Unassigned';\n","import { DomainError } from '../../domain-error.js';\nimport type { MappingRegistry } from './mapping/mapping-registry.js';\nimport type { AccountRepository, JournalRepository } from '../../port.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { isBalanceCarrying } from '../../substrate/types.js';\nimport { integerOr } from './parameters.js';\nimport { UNASSIGNED, UNASSIGNED_LABEL } from './mapping/unassigned.js';\n\n/**\n * Income statement as a projection over a mapping (SF-09). Sign: credit − debit\n * (revenue positive, expense negative); netIncome = sum of the positions.\n * fromPeriod/throughPeriod restrict the range (monthly income statement as BWA basis).\n */\nexport class IncomeStatementProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly mappings: MappingRegistry,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = integerOr(params.fiscalYear, 0);\n    const fromPeriod = integerOr(params.fromPeriod, 1);\n    const throughPeriod = integerOr(params.throughPeriod, Number.MAX_SAFE_INTEGER);\n    const mappingId = typeof params.mapping === 'string' ? params.mapping : '';\n\n    // A missing or unknown mapping is a caller mistake, not an overlap: reporting it as\n    // E_MAPPING_OVERLAP (the code for two positions claiming the same account) sent operators\n    // hunting the wrong thing, and an omitted parameter produced `Mapping \"\" is not loaded`.\n    const mapping = this.mappings.byId(mappingId);\n    if (mapping === null) {\n      throw this.mappingRefusal('incomeStatement', mappingId);\n    }\n\n    const zero = Money.zero(this.baseCurrency);\n    const amounts = new Map<string, Money>();\n    const touched = new Set<string>();\n    // Accounts the mapping does not cover. A gap is not an error (error catalogue: gapWarnings[]\n    // + catch-all, the same treatment importMapping gives it) — but it must not be silence\n    // either: the amount used to be dropped here while the balance sheet, which sums income\n    // accounts by type, kept counting it. Two reports, same money, different answers, no hint.\n    const gapAccounts = new Set<string>();\n\n    for (const entry of this.journal.forFiscalYear(fiscalYear)) {\n      const period = entry.periodRef.period;\n      if (period < fromPeriod || period > throughPeriod) continue;\n\n      for (const line of entry.lines()) {\n        const account = this.accounts.byId(line.accountId);\n        if (account === null || isBalanceCarrying(account.type)) continue;\n        const leaf = mapping.leafFor(account.number.value);\n        const key = leaf?.key ?? UNASSIGNED;\n        if (leaf === null) gapAccounts.add(account.number.value);\n        const signed = line.side === 'credit' ? line.money : line.money.negate();\n        amounts.set(key, (amounts.get(key) ?? zero).add(signed));\n        touched.add(key);\n      }\n    }\n\n    const positions: Array<Record<string, string>> = [];\n    let netIncome = zero;\n\n    for (const leaf of mapping.leaves) {\n      const amount = amounts.get(leaf.key) ?? zero;\n      netIncome = netIncome.add(amount);\n      if (amount.isZero() && !touched.has(leaf.key)) continue;\n      positions.push({ key: leaf.key, label: leaf.label, amount: amount.amountAsString() });\n    }\n\n    // The catch-all comes last and only when it carries something — an empty one would put a\n    // \"nothing is missing\" line into every report, which is noise rather than information.\n    const unassigned = amounts.get(UNASSIGNED) ?? zero;\n    if (touched.has(UNASSIGNED)) {\n      netIncome = netIncome.add(unassigned);\n      positions.push({ key: UNASSIGNED, label: UNASSIGNED_LABEL, amount: unassigned.amountAsString() });\n    }\n\n    // Sorted by account number (code points) so the list is deterministic; it names the accounts\n    // that actually contributed, which is what a reader of THIS report needs. Whether a mapping\n    // covers every account regardless of postings is importMapping's question, and it answers it.\n    const gapWarnings = [...gapAccounts]\n      .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n      .map((account) => ({ account, assignedTo: UNASSIGNED }));\n\n    return { positions, netIncome: netIncome.amountAsString(), gapWarnings };\n  }\n\n  /**\n   * Which mappings this tenant could use — part of the refusal, because the refusal is the only\n   * place a caller learns it. A `default` tenant has none at all: the neutral pack ships no mapping\n   * module, since a jurisdiction-free chart has no lawful statement layout to ship (IMPL-032). That\n   * is a legitimate answer and used to arrive as \"requires the parameter mapping\", which reads as\n   * *you forgot something* rather than *this pack cannot do this*.\n   */\n  private mappingRefusal(projection: string, mappingId: string): DomainError {\n    const available = this.mappings.summaries().map((summary) => summary.id);\n    if (available.length === 0) {\n      return new DomainError(\n        'E_INPUT_INVALID',\n        `${projection} needs a mapping and this tenant has none: its pack ships no mapping module, so one has to be loaded with importMapping`,\n        { mapping: mappingId, available },\n      );\n    }\n    return new DomainError(\n      'E_INPUT_INVALID',\n      mappingId === ''\n        ? `${projection} requires the parameter \"mapping\"`\n        : `mapping \"${mappingId}\" is not loaded`,\n      { mapping: mappingId, available },\n    );\n  }\n}\n","export interface MappingLeaf {\n  key: string;\n  label: string;\n  side: string | null;\n  ranges: Array<{ from: string; to: string }>;\n  numbers: string[];\n  includeNonCash: boolean;\n  includesNetIncome: boolean;\n  parents: string[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/** Does a leaf match an account number? (Individual numbers or codepoint ranges.) */\nexport function leafMatches(leaf: MappingLeaf, accountNumber: string): boolean {\n  if (leaf.numbers.includes(accountNumber)) return true;\n  for (const range of leaf.ranges) {\n    if (accountNumber >= range.from && accountNumber <= range.to) return true;\n  }\n  return false;\n}\n\n/**\n * Structure mapping (datenformat.md v0.2): assigns accounts to positions —\n * same structure for balance sheet, income statement, cash-basis lines and VAT-return reporting keys.\n */\nexport class Mapping {\n  constructor(\n    readonly id: string,\n    readonly kind: string,\n    readonly version: string,\n    readonly leaves: MappingLeaf[],\n  ) {}\n\n  static fromData(data: Record<string, unknown>): Mapping {\n    const leaves: MappingLeaf[] = [];\n    Mapping.collectLeaves(Array.isArray(data.positions) ? data.positions : [], [], leaves, null);\n    return new Mapping(asString(data.id) ?? '', asString(data.kind) ?? '', asString(data.version) ?? '', leaves);\n  }\n\n  private static collectLeaves(\n    positions: unknown[],\n    parents: string[],\n    leaves: MappingLeaf[],\n    side: string | null,\n  ): void {\n    for (const position of positions) {\n      if (!isRecord(position)) continue;\n      const key = asString(position.key) ?? '';\n      // side is set at the root node and inherited by the leaves (v0.5/SPEC-007).\n      const nodeSide = asString(position.side) ?? side;\n      const children = Array.isArray(position.children) ? position.children : [];\n\n      if (children.length > 0) {\n        Mapping.collectLeaves(children, [...parents, key], leaves, nodeSide);\n        continue;\n      }\n\n      const ranges: Array<{ from: string; to: string }> = [];\n      const numbers: string[] = [];\n      for (const selector of Array.isArray(position.accounts) ? position.accounts : []) {\n        if (!isRecord(selector)) continue;\n        if (typeof selector.from === 'string' && typeof selector.to === 'string') {\n          ranges.push({ from: selector.from, to: selector.to });\n        }\n        for (const number of Array.isArray(selector.numbers) ? selector.numbers : []) {\n          if (typeof number === 'string') numbers.push(number);\n        }\n      }\n\n      leaves.push({\n        key,\n        label: asString(position.label) ?? key,\n        side: nodeSide,\n        ranges,\n        numbers,\n        includeNonCash: position.includeNonCash === true,\n        includesNetIncome: position.includesNetIncome === true,\n        parents,\n      });\n    }\n  }\n\n  leafFor(accountNumber: string): MappingLeaf | null {\n    for (const leaf of this.leaves) {\n      if (leafMatches(leaf, accountNumber)) return leaf;\n    }\n    return null;\n  }\n}\n","import { DomainError } from '../../domain-error.js';\nimport { UNASSIGNED, UNASSIGNED_LABEL } from './mapping/unassigned.js';\nimport { leafMatches } from './mapping/mapping.js';\nimport type { MappingRegistry } from './mapping/mapping-registry.js';\nimport type { AccountRepository, JournalRepository } from '../../port.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { isBalanceCarrying } from '../../substrate/types.js';\nimport { integerOrNull } from './parameters.js';\n\ntype Section = 'assets' | 'liabilitiesAndEquity';\n\n/**\n * Balance sheet as a projection (SF-10): cumulative as of the reporting date. A position with\n * includesNetIncome contains the cumulative net income + its own balance.\n * Side (v0.5/SPEC-007): `side` at the root node; assets = debit−credit,\n * liabilitiesAndEquity = credit−debit. Default: assets.\n */\nexport class BalanceSheetProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly mappings: MappingRegistry,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const asOf = typeof params.asOf === 'string' ? CalendarDate.of(params.asOf) : null;\n    const mappingId = typeof params.mapping === 'string' ? params.mapping : '';\n    // `fiscalYear` used to be read by nobody here: the handbook, the cheat sheet and the\n    // gated scenarios all passed it, and the projection silently reported the whole journal\n    // instead — two different years returned byte-identical balance sheets.\n    //\n    // It scopes CUMULATIVELY (everything up to and including that year), i.e. \"as at the end\n    // of fiscal year N\", not \"movements of year N\". A balance sheet is a snapshot and must\n    // balance; applying trialBalance's G1 rule here (income accounts restart each year) tears\n    // a hole exactly the size of the prior year's result, because summae deliberately writes\n    // no closing entries (`closeFiscalYear` is a pure status change), so that result was never\n    // carried into equity. Cumulative keeps assets == liabilities+equity in every year.\n    const fiscalYear = integerOrNull(params.fiscalYear);\n\n    const mapping = this.mappings.byId(mappingId);\n    if (mapping === null) {\n      throw this.mappingRefusal('balanceSheet', mappingId);\n    }\n\n    const zero = Money.zero(this.baseCurrency);\n    const debits = new Map<string, Money>();\n    const credits = new Map<string, Money>();\n    const touchedAccounts = new Set<string>();\n    // Which side an account belongs on when no position claims it. Taken from the account TYPE,\n    // which is jurisdiction-free and always present — the mapping cannot answer it, since the\n    // whole problem is that the mapping says nothing about this account.\n    const sectionOf = new Map<string, Section>();\n    let netIncome = zero;\n\n    for (const entry of this.journal.all()) {\n      if (asOf !== null && entry.entryDate.isAfter(asOf)) continue;\n      const entryYear = entry.periodRef.fiscalYear;\n      if (fiscalYear !== null && entryYear > fiscalYear) continue;\n\n      for (const line of entry.lines()) {\n        const account = this.accounts.byId(line.accountId);\n        if (account === null) continue;\n\n        if (!isBalanceCarrying(account.type)) {\n          netIncome = line.side === 'credit' ? netIncome.add(line.money) : netIncome.subtract(line.money);\n          continue;\n        }\n\n        const key = account.number.value;\n        sectionOf.set(key, account.type === 'asset' ? 'assets' : 'liabilitiesAndEquity');\n        if (line.side === 'debit') debits.set(key, (debits.get(key) ?? zero).add(line.money));\n        else credits.set(key, (credits.get(key) ?? zero).add(line.money));\n        touchedAccounts.add(key);\n      }\n    }\n\n    const allNumbers = new Set<string>([...debits.keys(), ...credits.keys()]);\n    const sections: Record<Section, Array<Record<string, string>>> = { assets: [], liabilitiesAndEquity: [] };\n    const totals: Record<Section, Money> = { assets: zero, liabilitiesAndEquity: zero };\n\n    // An account no position matches used to be visited by nobody: the loop below runs over the\n    // POSITIONS and pulls what each one matches, so an unmatched account landed in neither total\n    // and the sheet stopped balancing without saying so.\n    const unmatched = [...allNumbers].filter((number) => !mapping.leaves.some((leaf) => leafMatches(leaf, number)));\n\n    for (const leaf of mapping.leaves) {\n      const section: Section = leaf.side === 'liabilitiesAndEquity' ? 'liabilitiesAndEquity' : 'assets';\n      let amount = zero;\n      let touched = false;\n\n      for (const number of allNumbers) {\n        if (!leafMatches(leaf, number)) continue;\n        const debit = debits.get(number) ?? zero;\n        const credit = credits.get(number) ?? zero;\n        amount =\n          section === 'assets'\n            ? amount.add(debit).subtract(credit)\n            : amount.add(credit).subtract(debit);\n        touched = touched || touchedAccounts.has(number);\n      }\n\n      if (leaf.includesNetIncome) {\n        amount = amount.add(netIncome);\n        touched = touched || !netIncome.isZero();\n      }\n\n      if (amount.isZero() && !touched) continue;\n\n      sections[section].push({ key: leaf.key, label: leaf.label, amount: amount.amountAsString() });\n      totals[section] = totals[section].add(amount);\n    }\n\n    // The catch-all per section, appended last and only when it carries something. Amounts follow\n    // the same sign rule as the section they land in, so the identity holds again.\n    for (const section of ['assets', 'liabilitiesAndEquity'] as const) {\n      let amount = zero;\n      let touched = false;\n\n      for (const number of unmatched) {\n        if ((sectionOf.get(number) ?? 'assets') !== section) continue;\n        const debit = debits.get(number) ?? zero;\n        const credit = credits.get(number) ?? zero;\n        amount = section === 'assets' ? amount.add(debit).subtract(credit) : amount.add(credit).subtract(debit);\n        touched = touched || touchedAccounts.has(number);\n      }\n\n      if (!touched) continue;\n      sections[section].push({ key: UNASSIGNED, label: UNASSIGNED_LABEL, amount: amount.amountAsString() });\n      totals[section] = totals[section].add(amount);\n    }\n\n    const gapWarnings = unmatched\n      .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n      .map((account) => ({ account, assignedTo: UNASSIGNED }));\n\n    return {\n      assets: sections.assets,\n      assetsTotal: totals.assets.amountAsString(),\n      liabilitiesAndEquity: sections.liabilitiesAndEquity,\n      liabilitiesAndEquityTotal: totals.liabilitiesAndEquity.amountAsString(),\n      gapWarnings,\n    };\n  }\n\n  /**\n   * Which mappings this tenant could use — part of the refusal, because the refusal is the only\n   * place a caller learns it. A `default` tenant has none at all: the neutral pack ships no mapping\n   * module, since a jurisdiction-free chart has no lawful statement layout to ship (IMPL-032). That\n   * is a legitimate answer and used to arrive as \"requires the parameter mapping\", which reads as\n   * *you forgot something* rather than *this pack cannot do this*.\n   */\n  private mappingRefusal(projection: string, mappingId: string): DomainError {\n    const available = this.mappings.summaries().map((summary) => summary.id);\n    if (available.length === 0) {\n      return new DomainError(\n        'E_INPUT_INVALID',\n        `${projection} needs a mapping and this tenant has none: its pack ships no mapping module, so one has to be loaded with importMapping`,\n        { mapping: mappingId, available },\n      );\n    }\n    return new DomainError(\n      'E_INPUT_INVALID',\n      mappingId === ''\n        ? `${projection} requires the parameter \"mapping\"`\n        : `mapping \"${mappingId}\" is not loaded`,\n      { mapping: mappingId, available },\n    );\n  }\n}\n","import Big from 'big.js';\nimport { DomainError } from '../../domain-error.js';\nimport type { Mapping } from './mapping/mapping.js';\nimport type { MappingRegistry } from './mapping/mapping-registry.js';\nimport type {\n  AccountRepository,\n  FiscalYearRepository,\n  JournalRepository,\n  OpenItemRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport type { Account } from '../../substrate/account.js';\nimport type { EntryLine } from '../../substrate/entry-line.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport { isIntegerParam } from './parameters.js';\n\nconst NON_PROFIT_SUBTYPES = new Set(['bank', 'cash', 'transit', 'ar', 'ap']);\n\n/**\n * Cash-basis accounting as a projection over the double-entry journal — rules R1–R7\n * (euer-projektions-beweis.md). Cash effect via money accounts, OP link on\n * settlement (proportional), 10-day rule, VAT cash-effective, R7 includeNonCash.\n * Bound to the calendar year: a deviating FY → E_CASHBASIS_DEVIATING_FISCAL_YEAR.\n */\nexport class CashBasisProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly openItems: OpenItemRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly fiscalYears: FiscalYearRepository,\n    private readonly mappings: MappingRegistry,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    // `year` is required. Defaulting it to 0 built the date \"0000-01-01\": in Node that used to\n    // throw an uncaught InvalidValue, in PHP it returned an empty report (IMPL-006/IMPL-009). Both\n    // were wrong in the same place — a missing required parameter must say so.\n    if (!isIntegerParam(params.year)) {\n      throw new DomainError('E_INPUT_INVALID', 'cashBasisReport requires the parameter \"year\"', {\n        year: params.year === undefined ? null : String(params.year),\n      });\n    }\n    const year = params.year;\n    const asOf = typeof params.asOf === 'string' ? CalendarDate.of(params.asOf) : null;\n    // An unknown mapping used to be ignored here while incomeStatement/balanceSheet threw on\n    // the same value — same parameter, same registry, two behaviours.\n    let mapping = null;\n    if (params.mapping !== undefined && params.mapping !== null) {\n      mapping = typeof params.mapping === 'string' ? this.mappings.byId(params.mapping) : null;\n      if (mapping === null) {\n        throw new DomainError('E_INPUT_INVALID', `mapping \"${String(params.mapping)}\" is not loaded`, {\n          mapping: String(params.mapping),\n        });\n      }\n    }\n\n    this.assertCalendarYearFiscalYears(year);\n\n    const income = new Map<string, Money>();\n    const expenses = new Map<string, Money>();\n    // Accounts that fell back to their own name because the mapping assigns them no position.\n    const gapAccounts = new Map<string, string>();\n    const addTo = (bucket: Map<string, Money>, label: string, amount: Money): void => {\n      bucket.set(label, (bucket.get(label) ?? Money.zero(this.baseCurrency)).add(amount));\n    };\n\n    for (const entry of this.journal.all()) {\n      if (asOf !== null && entry.entryDate.isAfter(asOf)) continue;\n\n      const bankFlow = this.bankFlow(entry);\n\n      if (bankFlow.isZero()) {\n        // R7: non-cash mandatory categories (posting year).\n        if (mapping === null || entry.entryDate.year() !== year) continue;\n        for (const line of entry.lines()) {\n          const account = this.accounts.byId(line.accountId);\n          if (account === null) continue;\n          const leaf = mapping.leafFor(account.number.value);\n          if (leaf === null || !leaf.includeNonCash) continue;\n\n          if (account.type === 'revenue' || account.subtype === 'tax_out') {\n            const signed = line.side === 'credit' ? line.money : line.money.negate();\n            addTo(income, leaf.label, signed);\n          } else if (account.type === 'expense' || account.subtype === 'tax_in') {\n            const signed = line.side === 'debit' ? line.money : line.money.negate();\n            addTo(expenses, leaf.label, signed);\n          }\n        }\n        continue;\n      }\n\n      // R1: cash-effective — target year (R2), source possibly via OP link.\n      if (this.assignYear(entry) !== year) continue;\n      const inflow = bankFlow.isPositive();\n\n      for (const sourced of this.sourceLines(entry)) {\n        const account = this.accounts.byId(sourced.line.accountId);\n        if (account === null || (account.subtype !== null && NON_PROFIT_SUBTYPES.has(account.subtype))) {\n          continue;\n        }\n        const amount = this.proportional(sourced.line.money, sourced.ratio);\n\n        if (account.subtype === 'tax_out' || account.subtype === 'tax_in') {\n          // Tax flows through the cash-basis result only where the pack's category\n          // mapping maps the tax account (and provides its label). The German EÜR maps\n          // its VAT accounts → VAT becomes income/expense; an unmapped tax account is a\n          // neutral pass-through (e.g. US sales tax). No jurisdiction text in the core.\n          const taxLeaf = mapping !== null ? mapping.leafFor(account.number.value) : null;\n          if (taxLeaf === null) continue;\n          if (account.subtype === 'tax_out') {\n            addTo(inflow ? income : expenses, taxLeaf.label, amount);\n          } else {\n            addTo(expenses, taxLeaf.label, amount);\n          }\n        } else if (account.type === 'revenue') {\n          addTo(income, this.label(mapping, account, gapAccounts), amount);\n        } else if (account.type === 'expense') {\n          addTo(expenses, this.label(mapping, account, gapAccounts), amount);\n        }\n        // R4/R5: assets, loans, private, pass-through items — neutral.\n      }\n    }\n\n    // Sorted by account number (code points) for determinism; only accounts that actually\n    // contributed are named, which is what a reader of THIS report needs.\n    const gapWarnings = [...gapAccounts.keys()]\n      .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n      .map((account) => ({ account, assignedTo: gapAccounts.get(account)! }));\n\n    // The result the statement exists to produce (F-IO-003).\n    //\n    // It used to publish every figure it is built from and not the figure itself, and the caller\n    // could not fill the gap: subtracting one bucket from the other is arithmetic across a\n    // projection's own fields, which this library tells embeddings not to do. Meanwhile\n    // `incomeStatement` hands out `netIncome` and `balanceSheet` both totals — three statements of\n    // one family, and the third published neither. All of it is a sum over lines already held here.\n    const incomeRows = this.serializeBucket(income);\n    const expenseRows = this.serializeBucket(expenses);\n    const totalIncome = this.total(incomeRows);\n    const totalExpenses = this.total(expenseRows);\n\n    return {\n      income: incomeRows,\n      expenses: expenseRows,\n      totalIncome: totalIncome.amountAsString(),\n      totalExpenses: totalExpenses.amountAsString(),\n      surplus: totalIncome.subtract(totalExpenses).amountAsString(),\n      gapWarnings,\n    };\n  }\n\n  private assertCalendarYearFiscalYears(year: number): void {\n    const y = String(year).padStart(4, '0');\n    const start = CalendarDate.of(`${y}-01-01`);\n    const end = CalendarDate.of(`${y}-12-31`);\n\n    for (const fiscalYear of this.fiscalYears.all()) {\n      const overlaps = !fiscalYear.end.isBefore(start) && !fiscalYear.start.isAfter(end);\n      if (!overlaps) continue;\n      const isCalendarYear =\n        fiscalYear.start.iso.slice(5) === '01-01' && fiscalYear.end.iso.slice(5) === '12-31';\n      if (!isCalendarYear) {\n        throw new DomainError(\n          'E_CASHBASIS_DEVIATING_FISCAL_YEAR',\n          `Fiscal year ${fiscalYear.year} (${fiscalYear.start.iso} to ${fiscalYear.end.iso}) deviates from the calendar year — cash-basis accounting is bound to the calendar year`,\n          { fiscalYear: fiscalYear.year },\n        );\n      }\n    }\n  }\n\n  private bankFlow(entry: JournalEntry): Money {\n    let flow = Money.zero(this.baseCurrency);\n    for (const line of entry.lines()) {\n      const account = this.accounts.byId(line.accountId);\n      const subtype = account?.subtype ?? null;\n      if (subtype !== 'bank' && subtype !== 'cash') continue;\n      flow = line.side === 'debit' ? flow.add(line.money) : flow.subtract(line.money);\n    }\n    return flow;\n  }\n\n  private assignYear(entry: JournalEntry): number {\n    const voucher = this.vouchers.byId(entry.voucherId);\n    if (\n      voucher !== null &&\n      voucher.recurring &&\n      voucher.economicYear !== null &&\n      voucher.due !== null &&\n      this.inTenDayWindow(entry.entryDate) &&\n      this.inTenDayWindow(voucher.due)\n    ) {\n      return voucher.economicYear;\n    }\n    return entry.entryDate.year();\n  }\n\n  private inTenDayWindow(date: CalendarDate): boolean {\n    const month = date.month();\n    const day = Number(date.iso.slice(8, 10));\n    return (month === 12 && day >= 22) || (month === 1 && day <= 10);\n  }\n\n  private sourceLines(entry: JournalEntry): Array<{ line: EntryLine; ratio: Big }> {\n    const sourced: Array<{ line: EntryLine; ratio: Big }> = [];\n\n    for (const item of this.openItems.all()) {\n      for (const settlement of item.settlements()) {\n        if (!settlement.entryId.equals(entry.id)) continue;\n        const origin = this.journal.byId(item.originEntryId);\n        if (origin === null || item.money.isZero()) continue;\n        const ratio = new Big(settlement.money.amountAsString()).div(new Big(item.money.amountAsString()));\n        for (const line of origin.lines()) sourced.push({ line, ratio });\n      }\n    }\n\n    if (sourced.length > 0) return sourced;\n\n    const one = new Big(1);\n    for (const line of entry.lines()) sourced.push({ line, ratio: one });\n    return sourced;\n  }\n\n  private proportional(amount: Money, ratio: Big): Money {\n    if (ratio.eq(1)) return amount.abs();\n    return Money.fromCalculation(new Big(amount.abs().amountAsString()).times(ratio), this.baseCurrency);\n  }\n\n  /**\n   * R6: category = mapping label, otherwise the account's own name.\n   *\n   * The fallback keeps the money visible, and that is the important half — but on its own it is also\n   * silent, and this report is the one that gets copied onto an official form. An account that falls\n   * back appears under a name that matches no line of that form, and nothing said so. The income\n   * statement has warned about its gaps since it gained the catch-all; this one did not, which is the\n   * wrong way round: the statement WITHOUT diagnostics was the statement that goes to the tax office.\n   *\n   * Only when a mapping was requested at all — without one every account \"falls back\" by definition,\n   * and warning about all of them would be noise, not information.\n   */\n  private label(mapping: Mapping | null, account: Account, gapAccounts: Map<string, string>): string {\n    if (mapping !== null) {\n      const leaf = mapping.leafFor(account.number.value);\n      if (leaf !== null) return leaf.label;\n      gapAccounts.set(account.number.value, account.name);\n    }\n    return account.name;\n  }\n\n  /** Summed from the serialized rows, not from the map: what is reported and what is totalled agree. */\n  private total(rows: Array<{ category: string; amount: string }>): Money {\n    let sum = Money.zero(this.baseCurrency);\n    for (const row of rows) sum = sum.add(Money.of(row.amount, this.baseCurrency));\n    return sum;\n  }\n\n  private serializeBucket(bucket: Map<string, Money>): Array<{ category: string; amount: string }> {\n    const labels = [...bucket.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    const rows: Array<{ category: string; amount: string }> = [];\n    for (const label of labels) {\n      const amount = bucket.get(label)!;\n      if (amount.isZero()) continue;\n      rows.push({ category: label, amount: amount.amountAsString() });\n    }\n    return rows;\n  }\n}\n","import type { AssetRepository } from '../../port.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\n\n/**\n * Asset register (a jurisdiction may mandate it even under cash-basis accounting). Sorting:\n * acquisition date, then ID (deterministic).\n */\nexport class AssetRegisterProjection {\n  constructor(private readonly assets: AssetRepository) {}\n\n  compute(params: Record<string, unknown>): { assets: Array<Record<string, unknown>> } {\n    const asOf = typeof params.asOf === 'string' ? CalendarDate.of(params.asOf) : null;\n\n    const sorted = [...this.assets.all()].sort((a, b) => {\n      const byDate = a.acquiredOn.compareTo(b.acquiredOn);\n      return byDate !== 0 ? byDate : a.id.compareTo(b.id);\n    });\n\n    const rows: Array<Record<string, unknown>> = [];\n    for (const asset of sorted) {\n      if (asOf !== null && asset.acquiredOn.isAfter(asOf)) continue;\n      const row = asset.toJSON();\n      row.accumulatedDepreciation = asset.accumulatedDepreciationAt(asOf).toJSON();\n      row.bookValue = asset.bookValueAt(asOf).toJSON();\n      if (asset.route === 'capitalize') row.depreciationSchedule = asset.scheduleSummary();\n      // The additional allowance, from the register rather than only from a booking's answer\n      // (F-AST-005). `bookSpecialDepreciation` reports what is left AFTER it ran; before it ran,\n      // nothing said whether the asset had elected the allowance at all — so a screen had to offer\n      // the form on every capitalised row and let the engine refuse the ones that had not.\n      const remaining = asset.specialDepreciationRemaining();\n      row.specialDepreciation = {\n        elected: asset.specialDepreciationBudget !== null,\n        allowance: asset.specialDepreciationBudget?.toJSON() ?? null,\n        remaining: remaining?.toJSON() ?? null,\n      };\n      rows.push(row);\n    }\n    return { assets: rows };\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport { FORMAT_VERSION } from '../../substrate/format-version.js';\nimport { createHash } from 'node:crypto';\nimport { canonicalJson } from '../../substrate/canonical-json.js';\nimport type { Clock } from '../../substrate/clock.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport type { Uuid } from '../../substrate/uuid.js';\nimport type {\n  AccountRepository,\n  AuditTrail,\n  JournalRepository,\n  PartnerRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport { integerOrNull } from './parameters.js';\n\nconst LINE_FIELDS = ['accountId', 'side', 'money', 'dimensions', 'taxTag'] as const;\n\nfunction withoutNulls(row: Record<string, unknown>): Record<string, unknown> {\n  return Object.fromEntries(Object.entries(row).filter(([, value]) => value !== null));\n}\n\n/**\n * GoBD-Z3 export (SF-14): manifest with SHA-256 stream hashes over RFC-8785-\n * canonicalized rows, field catalog, journal complete in sequenceNumber\n * order. auditLog is always part of the export (v0.5/SPEC-005).\n */\n/**\n * The only journal format there is. Declared as a set rather than inlined so adding a second one\n * is a data change here, not a new branch: `format` exists to guard the caller's typo, and a\n * parameter that silently accepts anything guards nothing.\n */\nconst JOURNAL_FORMATS: ReadonlySet<string> = new Set(['gobd-z3']);\n\nexport class JournalExportProjection {\n  constructor(\n    private readonly tenantId: Uuid,\n    private readonly tenantName: string,\n    private readonly baseCurrency: Currency,\n    private readonly journal: JournalRepository,\n    private readonly accounts: AccountRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly partners: PartnerRepository,\n    private readonly audit: AuditTrail,\n    private readonly clock: Clock,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    // Absent still means gobd-z3; a value that is present and unknown used to be ignored, so the\n    // caller got the Z3 stream under whatever label they had typed.\n    const format = params.format;\n    if (format !== undefined && format !== null && (typeof format !== 'string' || !JOURNAL_FORMATS.has(format))) {\n      throw new DomainError('E_INPUT_INVALID', 'journalExport: \"format\" must be gobd-z3', {\n        format: rejectedValue(format),\n      });\n    }\n\n    const fiscalYear = integerOrNull(params.fiscalYear);\n    const entries = fiscalYear === null ? this.journal.all() : this.journal.forFiscalYear(fiscalYear);\n\n    const streams: Record<string, unknown[]> = {\n      journal: entries.map((entry) => JournalExportProjection.formatEntry(entry)),\n      accounts: this.accounts.all().map((account) => withoutNulls(account.toJSON())),\n      vouchers: this.vouchers.all().map((voucher) => withoutNulls(voucher.toJSON())),\n    };\n    if (this.partners.all().length > 0) {\n      // Nulls stripped like the accounts and vouchers above, and for a reason that was latent\n      // rather than cosmetic (IMPL-027): the format declares `vatId` as a string and `address` as\n      // an object, so a partner without either exported a `null` the schema refuses. Nothing\n      // noticed because no schema test had ever exported a partner. One now does.\n      streams.partners = this.partners.all().map((partner) => withoutNulls(partner.toJSON()));\n    }\n    streams.auditLog = this.audit.all().map((record) => record.toJSON());\n\n    const contentHashes: Record<string, string> = {};\n    for (const [name, rows] of Object.entries(streams)) {\n      const lines = rows.map((row) => canonicalJson(row));\n      contentHashes[name] = createHash('sha256').update(lines.join('\\n')).digest('hex');\n    }\n\n    const allFinalized = entries.every((entry) => entry.isFinalized());\n\n    return {\n      manifest: {\n        formatVersion: FORMAT_VERSION,\n        tenantId: this.tenantId.value,\n        tenantName: this.tenantName,\n        baseCurrency: this.baseCurrency.code,\n        exportedAt: this.clock.now().toISOString(),\n        hashAlgorithm: 'sha256',\n        streams: Object.keys(streams),\n        contentHashes,\n      },\n      fieldCatalogIncluded: true,\n      fieldCatalog: this.fieldCatalog(Object.keys(streams)),\n      journal: { entryCount: entries.length, ordering: 'sequenceNumber', allFinalized },\n      data: streams,\n    };\n  }\n\n  private static formatEntry(entry: JournalEntry): Record<string, unknown> {\n    const data = entry.toJSON();\n    const lines = Array.isArray(data.lines) ? data.lines : [];\n    data.lines = lines.map((line) => {\n      const source = line as Record<string, unknown>;\n      const stripped: Record<string, unknown> = {};\n      for (const field of LINE_FIELDS) stripped[field] = source[field];\n      return stripped;\n    });\n    return data;\n  }\n\n  /**\n   * Field catalog (GoBD Z3 description standard): name, type, meaning — **complete** for every\n   * stream the export carries.\n   *\n   * Complete is the whole point and it was not true until 2026-08-28 (IMPL-038). The catalogue\n   * named 4 of the account's 8 fields, 2 of the voucher's 12, 4 of the audit record's 9, missed\n   * `voucherDate` on the posting, and did not mention the `partners` stream at all — so an auditor\n   * reading the description and the data side by side found fields in the data the\n   * self-description does not admit to. A Z3 data set that under-describes itself is the one\n   * failure this field exists to prevent.\n   *\n   * Keyed by stream and filtered to the streams actually exported, because `partners` is\n   * conditional: describing a stream that is not on the carrier is the same defect mirrored.\n   */\n  private fieldCatalog(streams: string[]): Record<string, Array<{ name: string; type: string; meaning: string }>> {\n    const catalog: Record<string, Array<{ name: string; type: string; meaning: string }>> = {\n      journal: [\n        { name: 'id', type: 'uuid', meaning: 'Eindeutige Buchungs-ID (UUIDv7)' },\n        { name: 'sequenceNumber', type: 'integer', meaning: 'Lückenlose Journalnummer je Geschäftsjahr' },\n        { name: 'status', type: 'string', meaning: 'entered|finalized (Festschreibung)' },\n        { name: 'entryDate', type: 'date', meaning: 'Buchungsdatum (zonenlos)' },\n        { name: 'voucherDate', type: 'date|null', meaning: 'Belegdatum der Buchung, sofern abweichend erfasst' },\n        { name: 'recordedAt', type: 'timestamp', meaning: 'Erfassungszeitpunkt' },\n        { name: 'periodRef', type: 'object', meaning: 'Geschäftsjahr + Periode' },\n        { name: 'voucherId', type: 'uuid', meaning: 'Belegreferenz (Pflicht)' },\n        { name: 'text', type: 'string', meaning: 'Buchungstext' },\n        { name: 'lines', type: 'array', meaning: 'Positionen: accountId, side (debit|credit), money, dimensions, taxTag' },\n        { name: 'reverses', type: 'uuid|null', meaning: 'Rückverweis bei Storno (Generalumkehr)' },\n        { name: 'reversedBy', type: 'uuid|null', meaning: 'Verweis auf die Stornobuchung' },\n      ],\n      accounts: [\n        { name: 'id', type: 'uuid', meaning: 'Eindeutige Konto-ID (UUIDv7); die Buchungsposition verweist hierauf, nicht auf die Nummer' },\n        { name: 'number', type: 'string', meaning: 'Kontonummer (führende Nullen signifikant)' },\n        { name: 'name', type: 'string', meaning: 'Kontobezeichnung' },\n        { name: 'type', type: 'string', meaning: 'asset|liability|equity|expense|revenue' },\n        { name: 'subtype', type: 'string|null', meaning: 'Kanonischer Subtyp, geschlossenes Repertoire seit Format 0.9 (bank, cash, transit, ar, ap, tax_in, tax_out, result_allocation, fixed_asset, opening_balance, private)' },\n        { name: 'status', type: 'string', meaning: 'active|locked — ein gesperrtes Konto nimmt keine Buchung mehr an' },\n        { name: 'validFrom', type: 'date|null', meaning: 'Beginn des Gültigkeitsfensters; fehlend = unbegrenzt' },\n        { name: 'validTo', type: 'date|null', meaning: 'Ende des Gültigkeitsfensters; fehlend = unbegrenzt' },\n      ],\n      vouchers: [\n        { name: 'id', type: 'uuid', meaning: 'Eindeutige Beleg-ID (UUIDv7); die Buchung verweist hierauf' },\n        { name: 'voucherNumber', type: 'string', meaning: 'Belegnummer' },\n        { name: 'voucherDate', type: 'date', meaning: 'Belegdatum' },\n        { name: 'due', type: 'date|null', meaning: 'Fälligkeit' },\n        { name: 'recurring', type: 'boolean|null', meaning: 'Dauerbeleg — wiederholt seine Nummer bestimmungsgemäß' },\n        { name: 'economicYear', type: 'integer|null', meaning: 'Wirtschaftsjahr der Zuordnung, wenn vom Buchungsjahr abweichend' },\n        { name: 'supplierTaxationMethod', type: 'string|null', meaning: 'Versteuerungsart des Ausstellers (Soll-/Ist-Versteuerung)' },\n        { name: 'serviceDate', type: 'date|null', meaning: 'Leistungsdatum (steuerlich entscheidend)' },\n        { name: 'servicePeriod', type: 'object|null', meaning: 'Leistungszeitraum {from, to}' },\n        { name: 'kind', type: 'string|null', meaning: 'Belegart' },\n        { name: 'partnerId', type: 'uuid|null', meaning: 'Verweis auf den Geschäftspartner' },\n        { name: 'issuer', type: 'string|null', meaning: 'Aussteller als Freitext, wenn kein Partnersatz existiert' },\n      ],\n      partners: [\n        { name: 'id', type: 'uuid', meaning: 'Eindeutige Partner-ID (UUIDv7)' },\n        { name: 'name', type: 'string', meaning: 'Name des Geschäftspartners' },\n        { name: 'kind', type: 'string', meaning: 'customer|supplier|both' },\n        { name: 'vatId', type: 'string|null', meaning: 'USt-IdNr.' },\n        { name: 'paymentTermsDays', type: 'integer|null', meaning: 'Zahlungsziel in Tagen' },\n        { name: 'accountNumbers', type: 'array|null', meaning: 'Zugeordnete Personenkonten' },\n        { name: 'address', type: 'object|null', meaning: 'Anschrift, vom Kern unverändert gespeichert' },\n        { name: 'status', type: 'string', meaning: 'active|inactive (Format 0.7); fehlend gilt als active' },\n      ],\n      auditLog: [\n        { name: 'id', type: 'uuid', meaning: 'Eindeutige Satz-ID (UUIDv7)' },\n        { name: 'at', type: 'timestamp', meaning: 'Änderungszeitpunkt' },\n        { name: 'actor', type: 'string', meaning: 'Audit-Identität' },\n        { name: 'objectType', type: 'string', meaning: 'Art des geänderten Objekts (account, entry, period, …)' },\n        { name: 'objectId', type: 'uuid', meaning: 'Identität des geänderten Objekts' },\n        { name: 'action', type: 'string', meaning: 'created|corrected|finalized|locked|…' },\n        { name: 'changes', type: 'object', meaning: 'Vorher/Nachher-Diff der geänderten Felder' },\n        { name: 'previousRecordHash', type: 'string|null', meaning: 'SHA-256 des Vorgängersatzes (Format 0.8); null beim ersten Satz und bei vor 0.8 geschriebenen Sätzen' },\n        { name: 'recordHash', type: 'string|null', meaning: 'SHA-256 dieses Satzes ohne dieses Feld selbst (Format 0.8)' },\n      ],\n    };\n\n    return Object.fromEntries(streams.filter((name) => name in catalog).map((name) => [name, catalog[name]!]));\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type {\n  AccountRepository,\n  JournalRepository,\n  PartnerRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport type { EntryLine } from '../../substrate/entry-line.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport type { TaxCodeRegistry } from '../expansion/tax/tax-code-registry.js';\nimport { integerOr, integerOrNull } from './parameters.js';\n\nconst TAX_SUBTYPES = new Set(['tax_in', 'tax_out']);\nconst DATEV_KINDS: ReadonlySet<string> = new Set(['entries', 'accounts', 'partners']);\n\nfunction pad2(value: number): string {\n  return String(value).padStart(2, '0');\n}\nfunction tagCode(line: EntryLine): string | null {\n  const code = line.taxTag?.code;\n  return typeof code === 'string' ? code : null;\n}\n\n/**\n * DATEV export (F-IO-005): posting batch, account labels, partner\n * master data. Tax lines arise on the DATEV side from the BU key and are\n * therefore folded into the base line; composite postings into sub-lines.\n */\nexport class DatevExportProjection {\n  constructor(\n    private readonly journal: JournalRepository,\n    private readonly accounts: AccountRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly partners: PartnerRepository,\n    private readonly registry: TaxCodeRegistry,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    // Every unknown kind fell through to the postings export but was echoed back under the\n    // label the caller sent: asking for \"accounts\" and typing \"account\" produced a file that\n    // announced itself as accounts and contained postings. Absent still means \"entries\".\n    const rawKind = params.kind;\n    let kind = 'entries';\n    if (rawKind !== undefined && rawKind !== null) {\n      if (typeof rawKind !== 'string' || !DATEV_KINDS.has(rawKind)) {\n        throw new DomainError('E_INPUT_INVALID', 'datevExport: \"kind\" must be entries, accounts or partners', {\n          kind: rejectedValue(rawKind),\n        });\n      }\n      kind = rawKind;\n    }\n    const rows =\n      kind === 'accounts' ? this.accountRows() : kind === 'partners' ? this.partnerRows() : this.entryRows(params);\n    return { kind, rows, rowCount: rows.length };\n  }\n\n  private entryRows(params: Record<string, unknown>): Array<Record<string, unknown>> {\n    const fiscalYear = integerOrNull(params.fiscalYear);\n    const fromPeriod = integerOr(params.fromPeriod, 1);\n    const throughPeriod = integerOr(params.throughPeriod, Number.MAX_SAFE_INTEGER);\n\n    const entries = fiscalYear === null ? this.journal.all() : this.journal.forFiscalYear(fiscalYear);\n    const rows: Array<Record<string, unknown>> = [];\n    for (const entry of entries) {\n      const period = entry.periodRef.period;\n      if (period < fromPeriod || period > throughPeriod) continue;\n      rows.push(...this.splitEntry(entry));\n    }\n    return rows;\n  }\n\n  private splitEntry(entry: JournalEntry): Array<Record<string, unknown>> {\n    let lead: EntryLine | null = null;\n    const contraLines: EntryLine[] = [];\n    const taxLines: EntryLine[] = [];\n\n    for (const line of entry.lines()) {\n      const account = this.accounts.byId(line.accountId);\n      const isTaxLine =\n        account?.subtype != null && TAX_SUBTYPES.has(account.subtype) && line.taxTag !== null;\n      if (isTaxLine) {\n        taxLines.push(line);\n        continue;\n      }\n      if (lead === null && line.taxTag === null) {\n        lead = line;\n        continue;\n      }\n      contraLines.push(line);\n    }\n\n    if (lead === null || contraLines.length === 0) return [];\n\n    const voucher = this.vouchers.byId(entry.voucherId);\n    const rows: Array<Record<string, unknown>> = [];\n\n    for (const contra of contraLines) {\n      let gross = contra.money;\n      let buKey: string | null = null;\n      const contraCode = tagCode(contra);\n      if (contraCode !== null) {\n        buKey = this.registry.datevBuFor(contraCode);\n        for (const taxLine of taxLines) {\n          if (tagCode(taxLine) === contraCode) gross = gross.add(taxLine.money);\n        }\n      }\n\n      rows.push({\n        // The batch carries the amount without a sign (\"Umsatz ohne Soll/Haben-Kz\"): direction comes\n        // from the indicator, and a cancellation is marked as Generalumkehr rather than by flipping the\n        // side or sending a negative number. Since this core reverses by general reversal (negated\n        // amount, unchanged side), abs() alone made the reversal byte-identical to the posting it\n        // cancels — an import doubled the turnover instead of clearing it. The marker tells them apart.\n        generalReversal: entry.reverses !== null,\n        amount: gross.abs().amountAsString(),\n        debitCredit: lead.side === 'debit' ? 'S' : 'H',\n        account: lead.account.value,\n        contraAccount: contra.account.value,\n        buKey,\n        documentField1: voucher === null ? '' : voucher.voucherNumber,\n        date: `${pad2(entry.entryDate.month())}${pad2(Number(entry.entryDate.iso.slice(8, 10)))}`,\n        text: entry.text(),\n        finalized: entry.isFinalized(),\n      });\n    }\n    return rows;\n  }\n\n  private accountRows(): Array<Record<string, unknown>> {\n    return this.accounts.all().map((account) => ({\n      number: account.number.value,\n      name: account.name,\n      type: account.type,\n    }));\n  }\n\n  private partnerRows(): Array<Record<string, unknown>> {\n    return this.partners.all().map((partner) => partner.toJSON());\n  }\n}\n","import { Mapping } from './mapping.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Loaded mappings of a tenant (mutable via importMapping). */\nexport class MappingRegistry {\n  private readonly byIdMap = new Map<string, Mapping>();\n\n  static empty(): MappingRegistry {\n    return new MappingRegistry();\n  }\n\n  static fromRuleModules(raw: unknown[]): MappingRegistry {\n    const registry = new MappingRegistry();\n    for (const mappingData of raw) {\n      if (isRecord(mappingData)) registry.add(Mapping.fromData(mappingData));\n    }\n    return registry;\n  }\n\n  add(mapping: Mapping): void {\n    this.byIdMap.set(mapping.id, mapping);\n  }\n\n  byId(id: string): Mapping | null {\n    return this.byIdMap.get(id) ?? null;\n  }\n\n  /**\n   * Which mappings are in force, by name — what `tenantConfiguration` publishes.\n   *\n   * Identity only, never the positions. The definitions are the pack's, and the handbook rule that\n   * keeps them there is deliberate: the embedding pins and ships the pack, summae takes it on every\n   * open and stores no copy, because two answers to \"which rules is this tenant on\" is one answer\n   * too many. Publishing the leaves here would create exactly that second answer.\n   *\n   * What a caller cannot know without this is the part that is genuinely summae's: which `mapping`\n   * names `balanceSheet`, `incomeStatement` and `cashBasisReport` will accept — the pack's, plus\n   * whatever `importMapping` layered on top or replaced.\n   *\n   * Sorted by id, so the answer does not depend on the order the registry was filled in.\n   */\n  summaries(): Array<{ id: string; kind: string; version: string }> {\n    return [...this.byIdMap.values()]\n      .map((mapping) => ({ id: mapping.id, kind: mapping.kind, version: mapping.version }))\n      .sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport { UNASSIGNED } from './unassigned.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\nimport type { AccountRepository } from '../../../port.js';\nimport { isBalanceCarrying } from '../../../substrate/types.js';\nimport { leafMatches, Mapping } from './mapping.js';\nimport type { MappingRegistry } from './mapping-registry.js';\nimport type { TenantConfigStore } from '../../../composition/tenant-config-store.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Mapping import (api.md): overlap → E_MAPPING_OVERLAP; gaps are not an\n * error but gapWarnings[] with the catch-all position `_unassigned`. Checked against\n * the actually existing accounts per mapping kind.\n */\nexport class MappingImporter {\n  constructor(\n    private readonly accounts: AccountRepository,\n    private readonly registry: MappingRegistry,\n    // A mapping is tenant-level configuration; like the tax profile it has no identity of\n    // its own, so the audit record names the tenant and puts the kind into the diff.\n    private readonly tenantId: Uuid | null = null,\n    private readonly audit: AuditWriter | null = null,\n    /** Where the import is kept, so it survives the process that made it (SPEC-015). */\n    private readonly configStore: TenantConfigStore | null = null,\n  ) {}\n\n  import(input: Record<string, unknown>): Record<string, unknown> {\n    const data = isRecord(input.mapping) ? input.mapping : {};\n    const mapping = Mapping.fromData(data);\n    const gapWarnings: Array<{ account: string; assignedTo: string }> = [];\n\n    for (const account of this.relevantAccounts(mapping.kind)) {\n      const matches = mapping.leaves\n        .filter((leaf) => leafMatches(leaf, account.number.value))\n        .map((leaf) => leaf.key);\n\n      if (matches.length > 1) {\n        throw new DomainError(\n          'E_MAPPING_OVERLAP',\n          `Account ${account.number.value} falls into multiple positions: ${matches.join(', ')}`,\n          { account: account.number.value, positions: matches },\n        );\n      }\n      if (matches.length === 0) {\n        gapWarnings.push({ account: account.number.value, assignedTo: UNASSIGNED });\n      }\n\n      // The offsetting prohibition, at the one place a mapping enters a running tenant. The rule\n      // everybody knows and nothing checked: a position that draws a receivable range AND a payable\n      // range reports one netted figure, and every gate stays green because the statement still\n      // balances.\n      //\n      // Checked on the account TYPE, not on the balance. An overdrawn bank account is still an asset\n      // account and belongs on the assets side; a position holding it offsets nothing. What is\n      // forbidden is a position that SELECTS both kinds, because then no reader can tell what the\n      // figure is made of.\n      if (mapping.kind === 'balance-sheet' && matches.length === 1) {\n        const leaf = mapping.leaves.find((candidate) => candidate.key === matches[0]);\n        const side = leaf?.side ?? null;\n        if (side !== null) {\n          const belongs =\n            side === 'assets'\n              ? account.type === 'asset'\n              : account.type === 'liability' || account.type === 'equity';\n\n          if (!belongs) {\n            throw new DomainError(\n              'E_MAPPING_SIDE_MIXED',\n              `Position ${String(matches[0])} is on the ${side} side and takes account ` +\n                `${account.number.value}, which is of type \"${account.type}\"`,\n              { position: matches[0], side, account: account.number.value, type: account.type },\n            );\n          }\n        }\n      }\n    }\n\n    this.registry.add(mapping);\n    // After the registry, never before: a rejected mapping (overlap above) must store nothing.\n    this.configStore?.rememberMapping(data);\n\n    if (this.audit !== null && this.tenantId !== null) {\n      this.audit.record(this.audit.actorOf(input), 'mapping', this.tenantId, 'imported', {\n        kind: { from: null, to: mapping.kind },\n        mappingId: { from: null, to: mapping.id },\n      });\n    }\n\n    return { imported: true, id: mapping.id, kind: mapping.kind, gapWarnings };\n  }\n\n  private relevantAccounts(kind: string) {\n    return this.accounts.all().filter((account) => {\n      if (kind === 'balance-sheet') return isBalanceCarrying(account.type);\n      if (kind === 'income-statement') return !isBalanceCarrying(account.type);\n      return false; // e.g. cash-basis-categories: deliberately partial\n    });\n  }\n}\n","import { DomainError } from '../../../domain-error.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\n\ninterface Segment {\n  validFrom: CalendarDate;\n  value: boolean;\n}\n\n/**\n * Tenant tax profile (tax-modell.md aggregate 2): taxation method,\n * small-business status with validity period (mid-year change,\n * SF-11), VAT filing period.\n */\nexport class TaxProfile {\n  private constructor(\n    private readonly method: string,\n    private smallBusiness: Segment[],\n    private readonly period: string,\n  ) {}\n\n  /**\n   * The two documented sets, refused rather than approximated (F-TAX-003).\n   *\n   * `taxationMethod` used to be `=== 'cash' ? 'cash' : 'accrual'` and `vatPeriod`\n   * `=== 'monthly' ? 'monthly' : 'quarterly'`, so a typo, a `null` or an object all arrived as a\n   * valid-looking profile that books differently, and nothing said so. This is not a value object\n   * built from a trusted internal source: `fromData` is fed from an embedding's configuration file,\n   * which is exactly where a typo lives — and the value it decides is whether VAT falls due on\n   * invoice or on payment.\n   *\n   * **The two sets are not the same kind of thing, and only one of them is safely here.**\n   * `taxationMethod` is substrate mechanism: accrual and cash are the two ways this engine can time\n   * a tax liability, and it implements both. `vatPeriod` is a *label* — it records which window a\n   * tenant files in and selects nothing (`vatReturn` takes its own window). Which filing windows\n   * exist is a question jurisdictions answer differently, so a closed list of them in the substrate\n   * is a claim the substrate has no business making — **which is why the pack answers it now**\n   * (SPEC-016): `packPolicy.vatPeriods` declares the windows a jurisdiction files in, and a pack\n   * that declares them overrides the substrate's list entirely.\n   */\n  /**\n   * The two ways this engine can recognise revenue. Published because the pack resolver checks\n   * `appliesWhen.taxationMethod` against it (I10) — a private list could only be checked by\n   * copying it, and a copied repertoire is a repertoire that drifts.\n   */\n  static readonly METHODS = ['accrual', 'cash'];\n\n  /**\n   * The filing windows assumed when a pack declares none — a **default, not a definition**\n   * (SPEC-016). `packPolicy.vatPeriods` overrides it entirely, which is what lets a jurisdiction\n   * that files bi-monthly say so without the substrate learning the word.\n   */\n  private static readonly PERIODS = ['monthly', 'quarterly', 'yearly'];\n\n  /**\n   * @param vatPeriods what the pack recognises; absent = the substrate default (SPEC-016). Which\n   * filing windows exist is a question jurisdictions answer differently, so a closed list of them\n   * in the substrate is a claim the substrate has no business making — the pack answers it now, and\n   * a pack that declares nothing keeps exactly the behaviour it had.\n   */\n  static fromData(data: Record<string, unknown>, vatPeriods?: readonly string[] | null): TaxProfile {\n    const method = TaxProfile.oneOf(data.taxationMethod, TaxProfile.METHODS, 'taxationMethod', 'accrual');\n    const declared = vatPeriods === undefined || vatPeriods === null || vatPeriods.length === 0 ? null : vatPeriods;\n    const periods = declared ?? TaxProfile.PERIODS;\n    // The substrate default keeps its documented `quarterly`; a declaring pack gets its own first\n    // entry, because a pack that does not file quarterly should not have it as a fallback.\n    const fallback = declared === null ? 'quarterly' : (declared[0] as string);\n    const period = TaxProfile.oneOf(data.vatPeriod, periods, 'vatPeriod', fallback);\n\n    const segments: Segment[] = [];\n    const smallBusiness = data.smallBusiness ?? false;\n    if (typeof smallBusiness === 'boolean') {\n      if (smallBusiness) segments.push({ validFrom: CalendarDate.of('0001-01-01'), value: true });\n    } else if (Array.isArray(smallBusiness)) {\n      for (const segment of smallBusiness) {\n        if (segment === null || typeof segment !== 'object') continue;\n        const s = segment as Record<string, unknown>;\n        if (typeof s.validFrom !== 'string') continue;\n        segments.push({ validFrom: CalendarDate.of(s.validFrom), value: s.value === true });\n      }\n    }\n\n    return new TaxProfile(method, TaxProfile.sorted(segments), period);\n  }\n\n  /**\n   * A profile summae itself stored, rebuilt without re-validating it.\n   *\n   * Validation belongs at the boundary, and this is not one: these values were checked when they\n   * arrived. Re-checking them on the way *out* of our own store would mean a tenant whose pack\n   * later drops a filing window can no longer be opened — a rule change reaching backwards into\n   * books that were kept correctly under the old one.\n   */\n  static restore(data: Record<string, unknown>): TaxProfile {\n    const method = typeof data.taxationMethod === 'string' ? data.taxationMethod : 'accrual';\n    const period = typeof data.vatPeriod === 'string' ? data.vatPeriod : 'quarterly';\n\n    const segments: Segment[] = [];\n    for (const segment of Array.isArray(data.smallBusiness) ? data.smallBusiness : []) {\n      if (segment === null || typeof segment !== 'object') continue;\n      const s = segment as Record<string, unknown>;\n      if (typeof s.validFrom !== 'string') continue;\n      segments.push({ validFrom: CalendarDate.of(s.validFrom), value: s.value === true });\n    }\n\n    return new TaxProfile(method, TaxProfile.sorted(segments), period);\n  }\n\n  /** Absent keeps the documented default; anything else must be one of the documented values. */\n  private static oneOf(value: unknown, allowed: readonly string[], field: string, fallback: string): string {\n    if (value === undefined) return fallback;\n    if (typeof value === 'string' && allowed.includes(value)) return value;\n    throw new DomainError(\n      'E_INPUT_INVALID',\n      `taxProfile.${field} must be one of ${allowed.map((a) => `\"${a}\"`).join(', ')}`,\n      { [field]: value === null ? null : typeof value === 'string' ? value : typeof value },\n    );\n  }\n\n  static default(): TaxProfile {\n    return new TaxProfile('accrual', [], 'quarterly');\n  }\n\n  taxationMethod(): string {\n    return this.method;\n  }\n\n  isCashBasis(): boolean {\n    return this.method === 'cash';\n  }\n\n  vatPeriod(): string {\n    return this.period;\n  }\n\n  smallBusinessAt(date: CalendarDate): boolean {\n    let value = false;\n    for (const segment of this.smallBusiness) {\n      if (segment.validFrom.isAfter(date)) break;\n      value = segment.value;\n    }\n    return value;\n  }\n\n  setSmallBusiness(validFrom: CalendarDate, value: boolean): void {\n    const segments = this.smallBusiness.filter((segment) => !segment.validFrom.equals(validFrom));\n    segments.push({ validFrom, value });\n    this.smallBusiness = TaxProfile.sorted(segments);\n  }\n\n  private static sorted(segments: Segment[]): Segment[] {\n    return [...segments].sort((a, b) => a.validFrom.compareTo(b.validFrom));\n  }\n\n  toJSON(): Record<string, unknown> {\n    return {\n      taxationMethod: this.method,\n      vatPeriod: this.period,\n      smallBusiness: this.smallBusiness.map((segment) => ({\n        validFrom: segment.validFrom.iso,\n        value: segment.value,\n      })),\n    };\n  }\n}\n","import type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { TenantConfigStore } from '../../../composition/tenant-config-store.js';\nimport { DomainError } from '../../../domain-error.js';\nimport type { JournalRepository } from '../../../port.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport { Money } from '../../../substrate/money.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\nimport type { TaxCodeRegistry } from './tax-code-registry.js';\nimport type { TaxCodeVersion } from './tax-code-version.js';\nimport type { TaxProfile } from './tax-profile.js';\nimport { splitByBase } from './tax-bases.js';\nimport { mechanismFor } from './tax-mechanisms.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\ninterface NetLine {\n  account: string;\n  money: Money;\n  code: string;\n  /**\n   * Carried through untouched, never interpreted here (F-CORE-006).\n   *\n   * The expansion used to rebuild each input line as `{account, money, code}`, so everything else\n   * on it — `dimensions` above all — was gone before the line reached the ledger. The posting\n   * succeeded, the figures were right, and the cost centre had disappeared. Validating the values\n   * is the ledger's job (they are a constraint, not an expansion), so this is a passthrough: an\n   * unknown cost centre is still refused, now that the line arrives whole.\n   */\n  dimensions: unknown[];\n}\n\n/**\n * Tax expansion (tax-modell.md): side-effect-free. Determinism (§2):\n * VAT per voucher per tax rate — sum net per code, compute tax, round\n * half-up ONCE. Version selection by service/voucher date.\n * Small-business exemption: no tax lines, gross = net.\n */\n\n/**\n * A tax line of 0.00 is dropped rather than forced through.\n *\n * The substrate forbids zero amounts, and rightly so — but a 1-cent invoice at 19 % legitimately\n * rounds to no tax at all, and the caller was told `E_ENTRY_INVALID_AMOUNT` on a line they never\n * wrote. Below 0.03 net nothing could be booked, which is a boundary nobody would predict and\n * that does not exist in the subject matter. The base stays on the net line's taxTag, so the VAT\n * return still reports it; only the tax is zero, which it is.\n */\nfunction withoutZeroTaxLines(\n  lines: Array<Record<string, unknown>>,\n  currency: Currency,\n): Array<Record<string, unknown>> {\n  return lines.filter((line) => {\n    const money = line.money;\n    if (typeof money !== 'object' || money === null) return true;\n    const amount = (money as Record<string, unknown>).amount;\n    return typeof amount !== 'string' || !Money.of(amount, currency).isZero();\n  });\n}\n\nexport class TaxService {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly registry: TaxCodeRegistry,\n    private readonly profileValue: TaxProfile,\n    private readonly journal: JournalRepository,\n    // Pack parameter: 'perVoucher' (tax once per code) | 'perLine' (per line).\n    private readonly taxRoundingGranularity: string = 'perVoucher',\n    // The tax profile is a tenant-level singleton: it has no identity of its own, so the\n    // audit record names the tenant as the object it belongs to (F-CORE-014 \"Steuerschlüssel\").\n    private readonly tenantId: Uuid | null = null,\n    private readonly audit: AuditWriter | null = null,\n    /** Where a profile change is kept, so it outlives this object (SPEC-015). */\n    private readonly configStore: TenantConfigStore | null = null,\n  ) {}\n\n  profile(): TaxProfile {\n    return this.profileValue;\n  }\n\n  registryHandle(): TaxCodeRegistry {\n    return this.registry;\n  }\n\n  expand(input: Record<string, unknown>): Record<string, unknown> {\n    // v0.4: rule version follows the service date, fallback voucher date.\n    const date =\n      typeof input.serviceDate === 'string'\n        ? this.parseDate(input.serviceDate)\n        : this.parseDate(input.date);\n    // A silent default here booked an incoming invoice fully inverted: `\"Input\"` with a\n    // capital I (or any typo) fell through to \"output\", so the expense was credited and the\n    // payable debited — a valid-looking, mirror-image posting that nothing downstream flags.\n    // Absent stays \"output\" (the documented default); a WRONG value is a caller mistake.\n    const rawDirection = input.direction;\n    if (rawDirection !== undefined && rawDirection !== null && rawDirection !== 'input' && rawDirection !== 'output') {\n      throw new DomainError('E_INPUT_INVALID', `direction must be \"input\" or \"output\"`, {\n        direction: String(rawDirection),\n      });\n    }\n    const direction = rawDirection === 'input' ? 'input' : 'output';\n\n    /**\n     * A consideration reduction after the fact (F-TAX-014).\n     *\n     * `true` books the **mirror** of the posting `direction` describes and tags it so the reporting\n     * key goes *down*: the net line and the tax line swap sides, and the tag carries a negative\n     * base. Nothing else changes — same code, same version, same reporting key, because a reduction\n     * of a taxed supply belongs in the key the supply was reported under.\n     *\n     * Law-free, which is why it is a flag here and not a mechanism in the closed repertoire:\n     * *whether* a discount, a credit note or a price reduction changes the taxable base is\n     * jurisdiction law and the caller's decision — the DE pack answers it one way, another pack may\n     * answer it differently; *mirroring a taxed\n     * posting* is mechanism and identical everywhere.\n     *\n     * It was reachable before, and only this way: a plain `post` with a hand-written `taxTag`\n     * carrying a negative `baseMoney` — see the fixture `core/settlement-discount`, which has\n     * pinned exactly that since v0.4. That path asks the caller to know the tag shape, the applied\n     * rule version and the reporting key, which is library-internal knowledge and a German form\n     * number on an application's screen. An embedding reported the case as unbuildable for\n     * precisely that reason.\n     */\n    const reduction = input.reduction === true;\n    const defaultCode = asString(input.taxCode);\n\n    const rawLines = Array.isArray(input.netLines) ? input.netLines : [];\n    if (rawLines.length === 0) {\n      throw new DomainError('E_ENTRY_TOO_FEW_LINES', 'expandTax without net lines');\n    }\n\n    const netLines: NetLine[] = rawLines.map((rawLine) => {\n      if (!isRecord(rawLine)) {\n        throw new DomainError('E_ENTRY_INVALID_AMOUNT', 'net line is not a structure');\n      }\n      const code = asString(rawLine.taxCode) ?? defaultCode;\n      if (code === null) {\n        throw new DomainError('E_TAXCODE_UNKNOWN', 'line without tax code (no default set)');\n      }\n      return {\n        account: asString(rawLine.account) ?? '',\n        money: this.parseMoney(rawLine.money),\n        code,\n        dimensions: Array.isArray(rawLine.dimensions) ? rawLine.dimensions : [],\n      };\n    });\n\n    // Reference check fully before computation (order-independent).\n    for (const line of netLines) this.registry.get(line.code);\n\n    const versions = new Map<string, TaxCodeVersion>();\n    const bases = new Map<string, Money>();\n    for (const line of netLines) {\n      if (!versions.has(line.code)) versions.set(line.code, this.registry.versionFor(line.code, date));\n      bases.set(line.code, (bases.get(line.code) ?? Money.zero(this.baseCurrency)).add(line.money));\n    }\n\n    let netTotal = Money.zero(this.baseCurrency);\n    for (const line of netLines) netTotal = netTotal.add(line.money);\n\n    // The side every line of this expansion sits on. One place, because a reduction flips ALL of\n    // them together — a mirror with one line left standing is an unbalanced entry at best and a\n    // wrong VAT return at worst.\n    const plainSide = direction === 'output' ? 'credit' : 'debit';\n    const sideFor = reduction ? (plainSide === 'credit' ? 'debit' : 'credit') : plainSide;\n\n    // The tag's base is what `vatReturn` adds to the reporting key, and it is signed there by the\n    // tag rather than by the line's side. So a reduction carries a negative base — the same\n    // convention `core/settlement-discount` has pinned by hand since v0.4.\n    const tagBase = (base: Money): Money => (reduction ? base.negate() : base);\n\n    if (this.profileValue.smallBusinessAt(date)) {\n      return {\n        netLines: netLines.map((line) => ({\n          account: line.account,\n          side: sideFor,\n          money: line.money.toJSON(),\n          taxTag: null,\n          dimensions: line.dimensions,\n        })),\n        taxLines: [],\n        grossTotal: netTotal.toJSON(),\n      };\n    }\n\n    // perLine (pack parameter): round tax per line, one tax line per\n    // line. Standard mechanism only (perLine not combined with RC/IC).\n    if (this.taxRoundingGranularity === 'perLine') {\n      const taxLines: Array<Record<string, unknown>> = [];\n      let grossTotal = netTotal;\n      // With an inclusive base the amount handed in is the gross, so the NET LINE moves too — the\n      // split is what the caller could not do themselves, and returning their gross as a net line\n      // would post the tax twice. Collected per line and used for the output below.\n      const netAmounts: Money[] = [];\n      const lineTags = netLines.map((line) => {\n        const version = versions.get(line.code)!;\n        const split = splitByBase(version.taxBase, line.money, version.rate, this.baseCurrency);\n        netAmounts.push(split.base);\n        const tag = this.tag(line.code, version, version.reportingKey, tagBase(split.base));\n        taxLines.push({ account: version.taxAccount, side: sideFor, money: split.tax.toJSON(), taxTag: tag });\n        grossTotal = grossTotal.add(split.tax);\n        return tag;\n      });\n      // An inclusive base already contained its tax, so the gross must not gain it a second time.\n      for (const [index, line] of netLines.entries()) {\n        if (versions.get(line.code)!.taxBase === 'inclusive') {\n          grossTotal = grossTotal.subtract(line.money).add(netAmounts[index]!);\n        }\n      }\n      return {\n        netLines: netLines.map((line, index) => ({\n          account: line.account,\n          side: sideFor,\n          money: (netAmounts[index] ?? line.money).toJSON(),\n          taxTag: lineTags[index] ?? null,\n          dimensions: line.dimensions,\n        })),\n        taxLines: withoutZeroTaxLines(taxLines, this.baseCurrency),\n        grossTotal: grossTotal.toJSON(),\n      };\n    }\n\n    // Sort groups deterministically by tax account (codepoints).\n    const codes = [...bases.keys()].sort((a, b) => {\n      const aa = versions.get(a)!.taxAccount;\n      const bb = versions.get(b)!.taxAccount;\n      return aa < bb ? -1 : aa > bb ? 1 : 0;\n    });\n\n    const taxLines: Array<Record<string, unknown>> = [];\n    let grossTotal = netTotal;\n    const baseTags = new Map<string, Record<string, unknown>>();\n    const inclusiveNet = new Map<(typeof netLines)[number], Money>();\n\n    for (const code of codes) {\n      const version = versions.get(code)!;\n      const split = splitByBase(version.taxBase, bases.get(code)!, version.rate, this.baseCurrency);\n      const base = split.base;\n      const tax = split.tax;\n\n      const contribution = mechanismFor(version.mechanism).contribute({\n        version,\n        tax,\n        outputSide: sideFor,\n        tag: (reportingKey) => this.tag(code, version, reportingKey, tagBase(base)),\n        zero: Money.zero(this.baseCurrency),\n      });\n      for (const line of contribution.taxLines) taxLines.push(line);\n      baseTags.set(code, contribution.baseTag);\n      grossTotal = grossTotal.add(contribution.grossDelta);\n\n      // With an inclusive base the group's amount was the gross, so the NET LINES have to shrink to\n      // the base — and by the shared rule, not by a second rounding. `allocate` distributes the\n      // group base over its lines by largest remainder weighted with the amounts they came in with,\n      // which is the same mechanism `allocate` the operation offers and the only one that\n      // guarantees the parts add up to the whole. A per-line recomputation would not: two lines\n      // each rounding half a cent up produce a group that is a cent too large.\n      if (version.taxBase === 'inclusive') {\n        const members = netLines.filter((line) => line.code === code);\n        const parts = base.allocate(...members.map((line) => line.money.amountAsString()));\n        members.forEach((line, index) => inclusiveNet.set(line, parts[index]!));\n        grossTotal = grossTotal.subtract(bases.get(code)!).add(base);\n      }\n    }\n\n    return {\n      netLines: netLines.map((line) => ({\n        account: line.account,\n        side: sideFor,\n        money: (inclusiveNet.get(line) ?? line.money).toJSON(),\n        taxTag: baseTags.get(line.code) ?? null,\n        dimensions: line.dimensions,\n      })),\n      taxLines: withoutZeroTaxLines(taxLines, this.baseCurrency),\n      grossTotal: grossTotal.toJSON(),\n    };\n  }\n\n  setProfile(input: Record<string, unknown>): TaxProfile {\n    const smallBusiness = input.smallBusiness;\n    if (!isRecord(smallBusiness) || typeof smallBusiness.validFrom !== 'string') {\n      throw new DomainError('E_PROFILE_RETROACTIVE_CONFLICT', 'setTaxProfile requires smallBusiness.validFrom');\n    }\n    const validFrom = this.parseDate(smallBusiness.validFrom);\n\n    for (const entry of this.journal.all()) {\n      if (entry.isFinalized() && !entry.entryDate.isBefore(validFrom)) {\n        throw new DomainError(\n          'E_PROFILE_RETROACTIVE_CONFLICT',\n          `period from ${validFrom.iso} contains finalized entries (e.g. no. ${entry.sequenceNumber})`,\n          { validFrom: validFrom.iso, sequenceNumber: entry.sequenceNumber },\n        );\n      }\n    }\n\n    const before = this.profileValue.smallBusinessAt(validFrom);\n    this.profileValue.setSmallBusiness(validFrom, smallBusiness.value === true);\n    if (this.audit !== null && this.tenantId !== null) {\n      this.audit.record(this.audit.actorOf(input), 'taxProfile', this.tenantId, 'changed', {\n        smallBusiness: { from: before, to: smallBusiness.value === true },\n        validFrom: { from: null, to: validFrom.iso },\n      });\n    }\n    // Only here, after the retroactivity guard has let the change through.\n    this.configStore?.rememberTaxProfile(this.profileValue.toJSON());\n    return this.profileValue;\n  }\n\n  private tag(\n    code: string,\n    version: TaxCodeVersion,\n    reportingKey: string | null,\n    base: Money,\n  ): Record<string, unknown> {\n    return {\n      code,\n      appliedVersion: version.validFrom.iso,\n      reportingKey,\n      baseMoney: base.toJSON(),\n    };\n  }\n\n  private parseDate(date: unknown): CalendarDate {\n    try {\n      return CalendarDate.of(typeof date === 'string' ? date : '');\n    } catch (error) {\n      if (error instanceof InvalidValue) {\n        throw new DomainError('E_TAXCODE_NO_VALID_VERSION', 'voucher date missing or invalid');\n      }\n      throw error;\n    }\n  }\n\n  private parseMoney(raw: unknown): Money {\n    const amount = isRecord(raw) ? asString(raw.amount) : null;\n    if (amount === null) {\n      throw new DomainError('E_ENTRY_INVALID_AMOUNT', 'net line without amount');\n    }\n    try {\n      return Money.of(amount, this.baseCurrency);\n    } catch (error) {\n      if (error instanceof InvalidValue) {\n        throw new DomainError('E_ENTRY_INVALID_AMOUNT', `invalid amount \"${amount}\"`);\n      }\n      throw error;\n    }\n  }\n}\n","import type { AccountRepository, FiscalYearRepository, JournalRepository } from '../../port.js';\nimport type { LegalFormRegistry } from './legal-forms.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { isBalanceCarrying } from '../../substrate/types.js';\nimport { integerOrNull } from './parameters.js';\n\n/**\n * The result not yet appropriated (F-CORE-024/SF-25) — the read side of `appropriateResult`.\n *\n * Until this projection the figure existed but could not be *asked for*. It was computed on every\n * `appropriateResult` call and left the library only as the `available` detail of a refusal, so an\n * application that wanted to pre-fill a resolution dialog had two ways to learn it: provoke\n * `E_APPROPRIATION_EXCEEDS_RESULT` on purpose, or read the balance-sheet position carrying\n * `includesNetIncome` — which presupposes a mapping and knowledge of which position that is. A\n * number you can only obtain by doing it wrong is not published.\n *\n * **One pot, not one per year.** `result_allocation` accounts carry what has been appropriated, and\n * nothing in them says which year's profit they consumed. So the top-level figures describe the pot\n * as a whole and `byFiscalYear` describes where it came from. Only `available` is per year, and it\n * is exactly what `appropriateResult` would permit for a resolution naming that year — the same\n * function, not a second implementation of it, so the number a user reads and the number the\n * operation refuses against cannot drift apart.\n *\n * Sign convention follows the books, as everywhere else: positive is a profit, negative a loss.\n * Years come from the journal, in ascending order.\n *\n * The SAME shape lives in the PHP UnappropriatedResultProjection.\n */\nexport class UnappropriatedResult {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n  ) {}\n\n  /**\n   * The pot and its composition, in one pass: every year's own result in ascending order, the\n   * cumulative result through each, and what a resolution naming each year may still take.\n   */\n  figures(): {\n    cumulativeResult: Money;\n    allocated: Money;\n    byFiscalYear: Array<{ fiscalYear: number; result: Money; cumulativeResult: Money; available: Money }>;\n  } {\n    const scan = this.scan();\n    const years = [...scan.perYear.keys()].sort((a, b) => a - b);\n\n    let cumulative = Money.zero(this.baseCurrency);\n    const byFiscalYear = years.map((year) => {\n      const result = scan.perYear.get(year) ?? Money.zero(this.baseCurrency);\n      cumulative = cumulative.add(result);\n      return {\n        fiscalYear: year,\n        result,\n        cumulativeResult: cumulative,\n        available: this.availableFrom(cumulative, scan.result, scan.allocated),\n      };\n    });\n\n    return { cumulativeResult: scan.result, allocated: scan.allocated, byFiscalYear };\n  }\n\n  /**\n   * What `appropriateResult` may book for a resolution naming `fiscalYear`. Public because the\n   * expansion service asks it rather than computing its own.\n   */\n  available(fiscalYear: number): Money {\n    const scan = this.scan();\n    let cumulative = Money.zero(this.baseCurrency);\n    for (const [year, result] of scan.perYear) {\n      if (year <= fiscalYear) cumulative = cumulative.add(result);\n    }\n\n    return this.availableFrom(cumulative, scan.result, scan.allocated);\n  }\n\n  /**\n   * The pot decides the direction, the named year caps the size (IMPL-033).\n   *\n   * The figure itself is unchanged and stays the obvious one: what was earned through year Y, minus\n   * everything the allocation accounts already carry. Allocations are deliberately not cut at the\n   * year boundary — a resolution is dated *after* the year it appropriates, so cutting them would\n   * make every past appropriation invisible and let the same profit be appropriated twice.\n   *\n   * What that figure could not do alone is notice when it has gone past the end. Appropriate 1200 of\n   * a 1400 profit naming 2027, and 2026's figure comes out at 900 − 1200 = −300; the operation read\n   * that as an unappropriated *loss* of 300 and would book it, charging the books against a pot that\n   * held 200. So the pot — everything earned minus everything appropriated — decides the direction\n   * and the ceiling: a year figure pointing the other way is nothing to appropriate rather than a\n   * loss, and none of them may exceed what is actually left. Where the year figure was already\n   * right, which is every case that does not run past the pot, this changes nothing.\n   */\n  private availableFrom(cumulativeThroughYear: Money, totalResult: Money, allocated: Money): Money {\n    const pot = totalResult.subtract(allocated);\n    if (pot.isZero()) return pot;\n\n    const year = cumulativeThroughYear.subtract(allocated);\n    const towardsPot = pot.isNegative() ? year.negate() : year;\n    if (!towardsPot.isPositive()) return Money.zero(this.baseCurrency);\n\n    const capped = towardsPot.compareTo(pot.abs()) > 0 ? pot.abs() : towardsPot;\n\n    return pot.isNegative() ? capped.negate() : capped;\n  }\n\n  /**\n   * One pass over the journal: the result of each fiscal year, and what the `result_allocation`\n   * accounts carry over the whole journal (see `availableFrom` for why the whole journal).\n   */\n  private scan(): { perYear: Map<number, Money>; result: Money; allocated: Money } {\n    const perYear = new Map<number, Money>();\n    let result = Money.zero(this.baseCurrency);\n    let allocated = Money.zero(this.baseCurrency);\n\n    for (const entry of this.journal.all()) {\n      const year = entry.periodRef.fiscalYear;\n      if (!perYear.has(year)) perYear.set(year, Money.zero(this.baseCurrency));\n\n      for (const line of entry.lines()) {\n        const account = this.accounts.byId(line.accountId);\n        if (account === null) continue;\n\n        if (!isBalanceCarrying(account.type)) {\n          const signed = line.side === 'credit' ? line.money : line.money.negate();\n          perYear.set(year, (perYear.get(year) as Money).add(signed));\n          result = result.add(signed);\n          continue;\n        }\n        if (account.subtype === 'result_allocation') {\n          allocated = line.side === 'debit' ? allocated.add(line.money) : allocated.subtract(line.money);\n        }\n      }\n    }\n\n    return { perYear, result, allocated };\n  }\n}\n\n/**\n * The report itself: the pot, where it came from, and when a resolution about it falls due.\n *\n * The deadline is the part only the pack can answer — a German GmbH has eight months from the year\n * end, eleven if it is small; an AG eight; a sole proprietor passes no resolution at all — and only\n * the tenant can say which form it is (`setEntityProfile`). Where either is missing the fields are\n * `null` rather than a plausible default: an application must be able to tell \"no deadline in this\n * jurisdiction\" from \"nobody has said what this company is\".\n *\n * Monitoring the date stays outside. summae reports what the data say; who gets reminded, and what\n * happens when the date passes, is the embedding's workflow.\n *\n * The SAME shape lives in the PHP UnappropriatedResultProjection.\n */\nexport class UnappropriatedResultProjection {\n  constructor(\n    private readonly figures: UnappropriatedResult,\n    private readonly fiscalYears: FiscalYearRepository,\n    private readonly legalForms: LegalFormRegistry,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const wanted = integerOrNull(params.fiscalYear);\n    const figures = this.figures.figures();\n    const declared = this.legalForms.declared();\n    const resolution = this.legalForms.resolution();\n\n    const rows = figures.byFiscalYear\n      .filter((row) => wanted === null || row.fiscalYear === wanted)\n      .map((row) => ({\n        fiscalYear: row.fiscalYear,\n        result: row.result.amountAsString(),\n        cumulativeResult: row.cumulativeResult.amountAsString(),\n        available: row.available.amountAsString(),\n        resolutionDueBy: this.dueBy(row.fiscalYear),\n      }));\n\n    return {\n      cumulativeResult: figures.cumulativeResult.amountAsString(),\n      appropriated: figures.allocated.amountAsString(),\n      unappropriated: figures.cumulativeResult.subtract(figures.allocated).amountAsString(),\n      legalForm: declared === null ? null : declared.legalForm,\n      resolutionRequired: resolution === null ? null : resolution.required,\n      resolutionBasis: resolution === null ? null : resolution.basis,\n      byFiscalYear: rows,\n    };\n  }\n\n  /**\n   * The due date needs the year's END, which only the fiscal-year record knows: a year running July\n   * to June is not eight months from 31 December. A year the journal knows and the record does not\n   * cannot happen through the API, and reports `null` rather than inventing a December.\n   */\n  private dueBy(fiscalYear: number): string | null {\n    const year = this.fiscalYears.byYear(fiscalYear);\n    if (year === null) return null;\n    const due = this.legalForms.resolutionDueBy(year.end);\n    return due === null ? null : due.iso;\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type { AccountRepository, JournalRepository } from '../../port.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport type { Ledger } from '../../ledger/ledger.js';\nimport type { AuditWriter } from '../../ledger/audit-writer.js';\nimport { UnappropriatedResult } from '../projection/unappropriated-result.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * Appropriation of profit as a named operation (F-CORE-024/SF-25, expansion).\n *\n * **Why this is not something `closeFiscalYear` does.** Appropriating a result is a *resolution*\n * — § 29 GmbHG, § 174 AktG and their equivalents elsewhere — and which part is distributed, put\n * into reserves or carried forward is not something a library can derive from the books. It is\n * also dated when the resolution is passed, which normally falls in the *following* fiscal year;\n * a close that booked it would have to invent a date it does not have. So summae does not decide,\n * it expands: the caller states the decision, the pack supplies the accounts.\n *\n * Before this operation existed the caller had to know the account numbers — the one part of the\n * bookkeeping where an embedding still had to (`2300 an 2100`). That is exactly where an agent or\n * an application guesses, and a guessed account number is a wrong posting rather than an error\n * message. Here a wrong target is refused by name and a wrong amount by the books.\n *\n * **What may be appropriated** is the result *not yet appropriated*, and that figure is not computed\n * here: `unappropriatedResult` publishes it and this operation asks the same projection, so the\n * number a user reads and the number this refuses against cannot drift apart. It is also the figure\n * the balance sheet reports in its `includesNetIncome` position.\n *\n * A loss appropriates the other way round (allocation account in credit), and the amounts stay\n * positive in the input either way: the direction follows from the books, not from a sign the\n * caller has to get right.\n *\n * The SAME shape lives in the PHP ResultAppropriationService.\n */\nexport class ResultAppropriationService {\n  private ruleModule: Record<string, unknown> = {};\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly journal: JournalRepository,\n    private readonly ledger: Ledger,\n    private readonly audit: AuditWriter,\n  ) {}\n\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  appropriate(input: Record<string, unknown>): Record<string, unknown> {\n    const actor = this.audit.actorOf(input);\n    const plug = this.plug();\n\n    const fiscalYear = input.fiscalYear;\n    if (typeof fiscalYear !== 'number' || !Number.isInteger(fiscalYear)) {\n      throw new DomainError('E_INPUT_INVALID', 'appropriateResult requires the parameter \"fiscalYear\"', {\n        fiscalYear: rejectedValue(input.fiscalYear),\n      });\n    }\n\n    const requested = this.parseAppropriations(input.appropriations, plug);\n    const available = new UnappropriatedResult(this.baseCurrency, this.accounts, this.journal).available(\n      fiscalYear,\n    );\n\n    // Nothing to appropriate is refused rather than posted as zero: an entry that moves nothing\n    // would sit in the books claiming a resolution took effect.\n    if (available.isZero()) {\n      throw new DomainError(\n        'E_APPROPRIATION_EXCEEDS_RESULT',\n        `Fiscal year ${fiscalYear} has no unappropriated result`,\n        { fiscalYear, available: available.amountAsString() },\n      );\n    }\n\n    const isProfit = !available.isNegative();\n    const capacity = isProfit ? available : available.negate();\n    let total = Money.zero(this.baseCurrency);\n    for (const item of requested) total = total.add(item.money);\n\n    if (total.compareTo(capacity) > 0) {\n      throw new DomainError(\n        'E_APPROPRIATION_EXCEEDS_RESULT',\n        `Appropriation of ${total.amountAsString()} exceeds the unappropriated result of ${available.amountAsString()}`,\n        { requested: total.amountAsString(), available: available.amountAsString(), fiscalYear },\n      );\n    }\n\n    // A profit leaves the allocation account in debit and reaches its targets in credit; a loss\n    // does the same journey backwards. The caller states amounts, never sides.\n    const allocationSide = isProfit ? 'debit' : 'credit';\n    const targetSide = isProfit ? 'credit' : 'debit';\n\n    const lines: Array<Record<string, unknown>> = [\n      { account: plug.allocationAccount, side: allocationSide, money: total.toJSON() },\n    ];\n    for (const item of requested) {\n      lines.push({ account: item.account, side: targetSide, money: item.money.toJSON() });\n    }\n\n    const text = asString(input.text) ?? `Appropriation of the result ${fiscalYear}`;\n    const result = this.ledger.post({\n      entryDate: input.entryDate,\n      voucherId: input.voucherId,\n      text,\n      lines,\n      ...(actor === null ? {} : { actor }),\n    });\n\n    const remaining = isProfit ? available.subtract(total) : available.add(total);\n\n    return {\n      entry: result.entry.toJSON(),\n      fiscalYear,\n      appropriated: requested.map((item) => ({\n        target: item.target,\n        account: item.account,\n        money: item.money.toJSON(),\n      })),\n      remaining: remaining.amountAsString(),\n    };\n  }\n\n  /** What the pack offers, or the refusal that says it offers nothing. */\n  private plug(): { allocationAccount: string; targets: Record<string, string> } {\n    const data = isRecord(this.ruleModule.resultAppropriation) ? this.ruleModule.resultAppropriation : null;\n    const allocationAccount = data === null ? null : asString(data.allocationAccount);\n    if (data === null || allocationAccount === null) {\n      throw new DomainError(\n        'E_APPROPRIATION_UNSUPPORTED',\n        'The pack declares no result appropriation, so summae does not know which accounts a resolution books against',\n      );\n    }\n    const targets: Record<string, string> = {};\n    for (const [name, target] of Object.entries(isRecord(data.targets) ? data.targets : {})) {\n      const account = isRecord(target) ? asString(target.account) : null;\n      if (account !== null) targets[name] = account;\n    }\n    return { allocationAccount, targets };\n  }\n\n  private parseAppropriations(\n    value: unknown,\n    plug: { targets: Record<string, string> },\n  ): Array<{ target: string; account: string; money: Money }> {\n    const items = Array.isArray(value) ? value : [];\n    if (items.length === 0) {\n      throw new DomainError('E_INPUT_INVALID', 'appropriateResult without appropriations');\n    }\n\n    const parsed: Array<{ target: string; account: string; money: Money }> = [];\n    const seen = new Set<string>();\n    for (const item of items) {\n      const target = isRecord(item) ? asString(item.target) : null;\n      if (target === null) {\n        throw new DomainError('E_INPUT_INVALID', 'An appropriation without a target', {\n          target: rejectedValue(isRecord(item) ? item.target : item),\n        });\n      }\n      const account = plug.targets[target];\n      if (account === undefined) {\n        // Named rather than validated against a fixed list: which targets exist is the pack's\n        // answer, and a jurisdiction that knows no distribution simply does not offer one.\n        throw new DomainError(\n          'E_APPROPRIATION_UNSUPPORTED',\n          `The pack offers no appropriation target \"${target}\"`,\n          { target, offered: Object.keys(plug.targets).sort() },\n        );\n      }\n      // Twice the same target would post two lines on one account in one entry — legal, and a\n      // sign the caller lost track of its own decision.\n      if (seen.has(target)) {\n        throw new DomainError('E_INPUT_INVALID', `Appropriation target \"${target}\" given twice`, { target });\n      }\n      seen.add(target);\n\n      const money = this.parseMoney(isRecord(item) ? item.money : null, target);\n      parsed.push({ target, account, money });\n    }\n    return parsed;\n  }\n\n  /**\n   * Amounts arrive in the same shape every posting line uses, and are refused with the same\n   * strictness — including the currency, which v1 pins to the tenant's.\n   */\n  private parseMoney(value: unknown, target: string): Money {\n    const amount = isRecord(value) ? asString(value.amount) : null;\n    const currency = isRecord(value) ? asString(value.currency) : null;\n    if (amount === null || currency !== this.baseCurrency.code) {\n      throw new DomainError('E_INPUT_INVALID', `Appropriation \"${target}\": money missing or not in ${this.baseCurrency.code}`, {\n        target,\n        money: rejectedValue(value),\n      });\n    }\n    let money: Money;\n    try {\n      money = Money.of(amount, this.baseCurrency);\n    } catch {\n      throw new DomainError('E_INPUT_INVALID', `Appropriation \"${target}\": \"${amount}\" is not a valid amount`, {\n        target,\n        money: rejectedValue(value),\n      });\n    }\n    if (!money.isPositive()) {\n      throw new DomainError('E_INPUT_INVALID', `Appropriation \"${target}\": amount must be > 0`, {\n        target,\n        money: rejectedValue(value),\n      });\n    }\n    return money;\n  }\n\n  /** Which targets this tenant can appropriate to — for a caller that wants to offer a choice. */\n  offeredTargets(): string[] {\n    const data = isRecord(this.ruleModule.resultAppropriation) ? this.ruleModule.resultAppropriation : null;\n    if (data === null) return [];\n    return Object.keys(isRecord(data.targets) ? data.targets : {}).sort();\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { AuditWriter } from '../../ledger/audit-writer.js';\nimport type { TenantConfigStore } from '../../composition/tenant-config-store.js';\nimport type { Uuid } from '../../substrate/uuid.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** What a legal form obliges. `required: false` is an answer, not a gap. */\nexport interface ResolutionRule {\n  required: boolean;\n  deadlineMonths: number | null;\n  /** Which sentence of which statute the deadline comes from — the pack's words, never the core's. */\n  basis: string | null;\n  /** Deadlines that differ by size class, where the pack grades entities by size at all. */\n  bySizeClass: Record<string, number>;\n}\n\n/**\n * The legal forms a jurisdiction knows, and which one this tenant is (F-CORE-039).\n *\n * **Why a pack holds this at all.** `appropriateResult` books a resolution and could not say when\n * one is due, or whether one is due at all — and both answers differ by jurisdiction *and* by what\n * the entity is incorporated as. Some forms owe a resolution within a fixed number of months of the\n * year end, some owe one sooner when the entity is small, and some owe none at all because nobody\n * resolves anything. The mechanism here is only the arithmetic — a form, a number of months, a year\n * end, a date — and every number and every citation behind it is the pack's, carried through\n * untouched in `basis`. Nothing in this file knows a statute, and the guard that keeps it that way\n * is `no-jurisdiction-text`.\n *\n * **The split stays where it always is.** The pack declares the rule and this reports the date; who\n * gets reminded, and what happens when the date passes, is the embedding's workflow. summae states\n * what the data say, it does not chase anybody.\n *\n * **The tenant's own form is stored, not derived and not guessed.** There is no sensible default —\n * a pack cannot know what its user incorporated as — so a tenant that has not said reports `null`\n * everywhere rather than the most common form, and `setEntityProfile` is what says it. The size\n * class is optional for the same reason: where a jurisdiction grades entities by size it does so on\n * measures the books only partly hold (headcount, for one), so it is declared, not computed.\n *\n * The SAME shape lives in the PHP LegalFormRegistry.\n */\nexport class LegalFormRegistry {\n  static empty(): LegalFormRegistry {\n    return new LegalFormRegistry();\n  }\n\n  private declaredForm: string | null = null;\n  private declaredSizeClass: string | null = null;\n  private forms = new Map<string, { label: string; resolution: ResolutionRule }>();\n  private sizeClasses: readonly string[] = [];\n\n  /**\n   * Reads the `legalForms` plug out of the resolved bundle, the way every other plug arrives — the\n   * tenant is built first and the pack is handed to it afterwards. A pack without the module leaves\n   * the catalogue empty, which is a legitimate answer for a jurisdiction-free one and reported as\n   * such rather than as a defect.\n   */\n  setRuleModule(ruleModules: Record<string, unknown>): void {\n    const data = isRecord(ruleModules.legalForms) ? ruleModules.legalForms : null;\n    if (data === null) return;\n\n    const forms = new Map<string, { label: string; resolution: ResolutionRule }>();\n    for (const [name, form] of Object.entries(isRecord(data.forms) ? data.forms : {})) {\n      if (!isRecord(form)) continue;\n      const resolution = isRecord(form.resolution) ? form.resolution : {};\n      const bySizeClass: Record<string, number> = {};\n      for (const [size, months] of Object.entries(isRecord(resolution.bySizeClass) ? resolution.bySizeClass : {})) {\n        if (typeof months === 'number') bySizeClass[size] = months;\n      }\n      forms.set(name, {\n        label: typeof form.label === 'string' ? form.label : name,\n        resolution: {\n          required: resolution.required === true,\n          deadlineMonths: typeof resolution.deadlineMonths === 'number' ? resolution.deadlineMonths : null,\n          basis: typeof resolution.basis === 'string' ? resolution.basis : null,\n          bySizeClass,\n        },\n      });\n    }\n\n    this.forms = forms;\n    this.sizeClasses = Array.isArray(data.sizeClasses)\n      ? data.sizeClasses.filter((value): value is string => typeof value === 'string')\n      : [];\n  }\n\n  /** Which forms this tenant may declare, sorted — the pack's answer, and part of every refusal. */\n  offered(): string[] {\n    return [...this.forms.keys()].sort();\n  }\n\n  offeredSizeClasses(): string[] {\n    return [...this.sizeClasses].sort();\n  }\n\n  /**\n   * Sets what this tenant is. Refused by name against the pack's catalogue rather than accepted and\n   * ignored: a misspelt form would otherwise report \"no resolution required\" for a GmbH, which is\n   * the one wrong answer that looks like a right one.\n   */\n  set(legalForm: unknown, sizeClass: unknown): { legalForm: string; sizeClass: string | null } {\n    if (typeof legalForm !== 'string' || legalForm === '') {\n      throw new DomainError('E_INPUT_INVALID', 'setEntityProfile requires the parameter \"legalForm\"', {\n        legalForm: rejectedValue(legalForm),\n        offered: this.offered(),\n      });\n    }\n    if (!this.forms.has(legalForm)) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        this.forms.size === 0\n          ? `This tenant's pack declares no legal forms, so \"${legalForm}\" cannot be checked against anything`\n          : `The pack knows no legal form \"${legalForm}\"`,\n        { legalForm, offered: this.offered() },\n      );\n    }\n    if (sizeClass !== undefined && sizeClass !== null) {\n      if (typeof sizeClass !== 'string' || !this.sizeClasses.includes(sizeClass)) {\n        throw new DomainError('E_INPUT_INVALID', `The pack knows no size class \"${String(sizeClass)}\"`, {\n          sizeClass: rejectedValue(sizeClass),\n          offered: this.offeredSizeClasses(),\n        });\n      }\n    }\n\n    this.declaredForm = legalForm;\n    this.declaredSizeClass = typeof sizeClass === 'string' ? sizeClass : null;\n\n    return this.declared() as { legalForm: string; sizeClass: string | null };\n  }\n\n  /**\n   * Puts back what was stored, without checking it against the catalogue.\n   *\n   * Deliberately lenient where `set` is strict: the books outlive a pack version, and a pack that\n   * drops or renames a form must not make an existing tenant unopenable. The rule stops applying —\n   * `resolution()` finds nothing and the projection reports `null` — which is the honest answer and\n   * visible, rather than an open that fails with an error nobody can act on.\n   */\n  restore(data: Record<string, unknown> | null): void {\n    if (data === null) return;\n    this.declaredForm = typeof data.legalForm === 'string' ? data.legalForm : null;\n    this.declaredSizeClass = typeof data.sizeClass === 'string' ? data.sizeClass : null;\n  }\n\n  declared(): { legalForm: string; sizeClass: string | null } | null {\n    return this.declaredForm === null ? null : { legalForm: this.declaredForm, sizeClass: this.declaredSizeClass };\n  }\n\n  label(): string | null {\n    const form = this.declaredForm === null ? undefined : this.forms.get(this.declaredForm);\n    return form === undefined ? null : form.label;\n  }\n\n  /** What this tenant's form obliges, or `null` when nothing is declared or the pack lost the form. */\n  resolution(): ResolutionRule | null {\n    const form = this.declaredForm === null ? undefined : this.forms.get(this.declaredForm);\n    return form === undefined ? null : form.resolution;\n  }\n\n  /** The deadline in months for this tenant, size class taken into account. */\n  deadlineMonths(): number | null {\n    const rule = this.resolution();\n    if (rule === null || !rule.required) return null;\n    if (this.declaredSizeClass !== null && this.declaredSizeClass in rule.bySizeClass) {\n      return rule.bySizeClass[this.declaredSizeClass] as number;\n    }\n    return rule.deadlineMonths;\n  }\n\n  /**\n   * When a resolution about a year ending on `fiscalYearEnd` is due.\n   *\n   * The end of the nth month after the year end, not the same day n months later. Deadlines of this\n   * kind are written as \"within the first n months of the following financial year\", so a year\n   * ending 30 November with eight months has until 31 July — a day later than plain month\n   * arithmetic would say, and the wrong side of a deadline to be wrong on.\n   */\n  resolutionDueBy(fiscalYearEnd: CalendarDate): CalendarDate | null {\n    const months = this.deadlineMonths();\n    return months === null ? null : fiscalYearEnd.plusMonths(months).lastDayOfMonth();\n  }\n}\n\n/**\n * `setEntityProfile` — the write side of the registry (F-CORE-039).\n *\n * Three steps in a fixed order, the same order every configuration operation here uses: the\n * registry refuses first, the audit record is written second, the store third. A rejected call\n * therefore leaves no trail and no record — which is the discipline SPEC-015 had to invent after\n * five operations audited changes the books stopped carrying at the next restart.\n *\n * The SAME shape lives in the PHP EntityProfileService.\n */\nexport class EntityProfileService {\n  constructor(\n    private readonly registry: LegalFormRegistry,\n    private readonly audit: AuditWriter,\n    private readonly tenantId: Uuid,\n    private readonly configStore: TenantConfigStore | null,\n  ) {}\n\n  set(input: Record<string, unknown>): Record<string, unknown> {\n    const before = this.registry.declared();\n    const profile = this.registry.set(input.legalForm, input.sizeClass);\n\n    this.audit.record(this.audit.actorOf(input), 'entityProfile', this.tenantId, 'changed', {\n      legalForm: { from: before === null ? null : before.legalForm, to: profile.legalForm },\n      sizeClass: { from: before === null ? null : before.sizeClass, to: profile.sizeClass },\n    });\n    this.configStore?.rememberEntityProfile(profile);\n\n    return {\n      legalForm: profile.legalForm,\n      label: this.registry.label(),\n      sizeClass: profile.sizeClass,\n      resolutionRequired: this.registry.resolution()?.required ?? false,\n      resolutionDeadlineMonths: this.registry.deadlineMonths(),\n    };\n  }\n}\n","import Big from 'big.js';\nimport { DomainError } from '../../../domain-error.js';\nimport type { AuditWriter } from '../../../ledger/audit-writer.js';\nimport type { Ledger } from '../../../ledger/ledger.js';\nimport type { AccountRepository, VoucherRepository } from '../../../port.js';\nimport { Voucher } from '../../../records/voucher.js';\nimport { AccountNumber } from '../../../substrate/account-number.js';\nimport { CalendarDate } from '../../../substrate/calendar-date.js';\nimport type { Currency } from '../../../substrate/currency.js';\nimport { InvalidValue } from '../../../substrate/errors.js';\nimport type { IdGenerator } from '../../../substrate/id-generator.js';\nimport { Money } from '../../../substrate/money.js';\nimport type { Uuid } from '../../../substrate/uuid.js';\n\n/**\n * Percentage points at two decimals, in both languages.\n *\n * `BigDecimal` keeps the scale of its input and `Big` does not, so `100.00 − 60.00` prints `-40.00`\n * on one side and `-40` on the other. The computation uses the full precision that was supplied;\n * only the reported string is normalised.\n */\nfunction percentPoints(value: Big): string {\n  return value.toFixed(2);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Correcting a deducted input tax when the use of the thing it was deducted for has changed\n * (F-CORE-056).\n *\n * **Where the boundary actually runs, because this one was argued twice.** The *register* — which\n * assets are under observation, and until when — stays with the embedding application, and for a\n * reason that survives inspection: the trigger is a **change of use**, which is never posted. A\n * library that sees only postings cannot see the day a van starts being driven privately. What does\n * not stay outside is the arithmetic. The argument that put it there was *\"a figure produced wrongly\n * would look exactly as authoritative as one produced rightly\"* — which is a reason to compute it\n * where figures are fixture-pinned, deterministic and verified across two languages, not a reason to\n * compute it nowhere.\n *\n * **It is an expansion, not a projection, and that was the second correction.** A projection reads\n * the journal; this reads none of it — every input comes from outside. As an expansion it fits\n * exactly, and it is the better design for an unrelated reason: the correction gets **booked**\n * rather than computed and handed back for somebody else to book.\n *\n * **Socket and plug, with an unusually clean seam.** The mechanism is a pro-rata correction over an\n * observation period with de-minimis thresholds — the same shape wherever such a rule exists. Every\n * number is the pack's: how many years the period runs for which kind of thing, the two thresholds,\n * the accounts, and the key the correction is reported under. The `us` pack simply declares no such\n * module, and `adjustInputTax` then says so instead of inventing a period.\n */\nexport class InputTaxAdjustmentService {\n  private ruleModule: Record<string, unknown>;\n\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly accounts: AccountRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly ledger: Ledger,\n    private readonly ids: IdGenerator,\n    ruleModule: Record<string, unknown> = {},\n    private readonly audit: AuditWriter | null = null,\n  ) {\n    this.ruleModule = ruleModule;\n  }\n\n  setRuleModule(ruleModule: Record<string, unknown>): void {\n    this.ruleModule = ruleModule;\n  }\n\n  adjust(input: Record<string, unknown>): Record<string, unknown> {\n    const module = this.packModule();\n    const reason = this.requireString(input.reason, 'reason');\n    const date = this.requireDate(input.date, 'date');\n    const originalInputTax = this.requireMoney(input.originalInputTax, 'originalInputTax');\n    const originalShare = this.requirePercent(input.originalSharePercent, 'originalSharePercent');\n    const currentShare = this.requirePercent(input.currentSharePercent, 'currentSharePercent');\n    const assetKind = this.requireString(input.assetKind, 'assetKind');\n    const years = this.correctionYears(module, assetKind);\n\n    if (!originalInputTax.isPositive()) {\n      throw new DomainError(\n        'E_INPUT_INVALID',\n        'adjustInputTax: originalInputTax must be positive — there is nothing to correct',\n        { field: 'originalInputTax' },\n      );\n    }\n\n    const delta = currentShare.minus(originalShare);\n\n    // Both thresholds, in the order the pack states them. The first is about the thing (too small to\n    // observe at all), the second about the change (too small to be worth correcting). Reported as\n    // `notDue` with the threshold named, never as a silent zero: \"no correction is due\" and \"we did\n    // not compute one\" are different answers and only one of them is useful.\n    const deMinimis = isRecord(module.deMinimis) ? module.deMinimis : {};\n\n    const inputTaxAtMost = this.optionalMoney(deMinimis.inputTaxAtMost);\n    if (inputTaxAtMost !== null && originalInputTax.compareTo(inputTaxAtMost) <= 0) {\n      return this.notDue('inputTaxBelowThreshold', originalInputTax, delta, years, inputTaxAtMost.amountAsString());\n    }\n\n    const amount = this.yearlyCorrection(originalInputTax, delta, years);\n\n    const sharePointsAtLeast = this.optionalPercent(deMinimis.sharePointsAtLeast);\n    const amountAtMost = this.optionalMoney(deMinimis.amountAtMost);\n    if (\n      sharePointsAtLeast !== null &&\n      amountAtMost !== null &&\n      delta.abs().lt(sharePointsAtLeast) &&\n      amount.abs().compareTo(amountAtMost) <= 0\n    ) {\n      return this.notDue('changeBelowThreshold', originalInputTax, delta, years, `${sharePointsAtLeast.toString()}%`);\n    }\n\n    if (amount.isZero()) {\n      return this.notDue('noChange', originalInputTax, delta, years, null);\n    }\n\n    const accounts = this.accountsFrom(module);\n    const reportingKey = typeof module.reportingKey === 'string' ? module.reportingKey : null;\n\n    // A positive delta means more of the thing is now used in a way that allows the deduction, so\n    // more tax may be deducted; a negative one means part of what was deducted has to go back. The\n    // tax line carries the pack's reporting key so the correction reaches the return where the\n    // jurisdiction expects it — without a tag it would balance, sit correctly on the account, and\n    // contribute nothing to what is filed.\n    const magnitude = amount.abs();\n    const taxTag = reportingKey === null ? null : { reportingKey };\n    const lines = amount.isPositive()\n      ? [\n          { account: accounts.taxAccount, side: 'debit', money: magnitude.toJSON(), taxTag },\n          { account: accounts.incomeAccount, side: 'credit', money: magnitude.toJSON() },\n        ]\n      : [\n          { account: accounts.expenseAccount, side: 'debit', money: magnitude.toJSON() },\n          { account: accounts.taxAccount, side: 'credit', money: magnitude.toJSON(), taxTag },\n        ];\n\n    const entryId = this.post(date, `Input tax adjustment: ${reason}`, lines);\n\n    this.audit?.record(this.audit.actorOf(input), 'inputTaxAdjustment', entryId, 'adjusted', {\n      reason: { from: null, to: reason },\n      amount: { from: null, to: amount.amountAsString() },\n      sharePoints: { from: originalShare.toString(), to: currentShare.toString() },\n    });\n\n    return {\n      due: true,\n      amount: amount.toJSON(),\n      correctionYears: years,\n      sharePointsChanged: percentPoints(delta),\n      reportingKey,\n      entryId: entryId.value,\n    };\n  }\n\n  private notDue(\n    reason: string,\n    originalInputTax: Money,\n    delta: Big,\n    years: number,\n    threshold: string | null,\n  ): Record<string, unknown> {\n    return {\n      due: false,\n      notDueBecause: reason,\n      threshold,\n      amount: Money.zero(this.baseCurrency).toJSON(),\n      correctionYears: years,\n      sharePointsChanged: percentPoints(delta),\n      originalInputTax: originalInputTax.toJSON(),\n      entryId: null,\n    };\n  }\n\n  /**\n   * `originalInputTax × delta% ÷ years`, with one rounding at the end. `div` runs at big.js's\n   * default twenty decimal places, which is the scale the PHP side divides at for exactly this\n   * reason: rounding twice at the same two scales in both languages is what makes the last cent\n   * equal.\n   */\n  private yearlyCorrection(originalInputTax: Money, delta: Big, years: number): Money {\n    const divisor = new Big(100).times(years);\n    return Money.fromCalculation(\n      new Big(originalInputTax.amountAsString()).times(delta).div(divisor),\n      this.baseCurrency,\n    );\n  }\n\n  private accountsFrom(module: Record<string, unknown>): {\n    taxAccount: string;\n    expenseAccount: string;\n    incomeAccount: string;\n  } {\n    const declared = isRecord(module.accounts) ? module.accounts : {};\n    const out: Record<string, string> = {};\n\n    for (const key of ['taxAccount', 'expenseAccount', 'incomeAccount'] as const) {\n      const value = declared[key];\n      if (typeof value !== 'string' || value === '') {\n        throw new DomainError('E_PACK_INCOHERENT', `the pack declares no ${key} for the input-tax adjustment`, {\n          field: `inputTaxAdjustment.accounts.${key}`,\n        });\n      }\n      if (this.accounts.byNumber(AccountNumber.of(value)) === null) {\n        throw new DomainError(\n          'E_ACCOUNT_UNKNOWN',\n          `the input-tax adjustment names account ${value}, which does not exist`,\n          { account: value },\n        );\n      }\n      out[key] = value;\n    }\n\n    return out as { taxAccount: string; expenseAccount: string; incomeAccount: string };\n  }\n\n  private correctionYears(module: Record<string, unknown>, assetKind: string): number {\n    for (const period of Array.isArray(module.correctionPeriods) ? module.correctionPeriods : []) {\n      if (!isRecord(period) || period.assetKind !== assetKind) continue;\n      const years = period.years;\n      if (typeof years === 'number' && Number.isInteger(years) && years > 0) return years;\n    }\n\n    // Refused rather than defaulted. An observation period is the whole arithmetic: guessing five\n    // where the pack means ten halves every correction, and the figure would look exactly as\n    // authoritative as a right one.\n    throw new DomainError('E_PACK_INCOHERENT', `the pack declares no correction period for asset kind \"${assetKind}\"`, {\n      assetKind,\n    });\n  }\n\n  private packModule(): Record<string, unknown> {\n    const module = isRecord(this.ruleModule.inputTaxAdjustment) ? this.ruleModule.inputTaxAdjustment : null;\n    if (module === null) {\n      throw new DomainError(\n        'E_PACK_INCOHERENT',\n        'this pack has no input-tax adjustment — it declares no correction periods',\n        { field: 'inputTaxAdjustment' },\n      );\n    }\n    return module;\n  }\n\n  private post(date: CalendarDate, text: string, lines: Array<Record<string, unknown>>): Uuid {\n    const voucher = new Voucher({\n      id: this.ids.next(),\n      voucherNumber: `VST-KORR-${date.iso.replaceAll('-', '')}`,\n      voucherDate: date,\n      kind: 'internal',\n    });\n    this.vouchers.add(voucher);\n\n    const result = this.ledger.post({ entryDate: date.iso, voucherId: voucher.id.value, text, lines });\n    this.ledger.finalize({ entryId: result.entry.id.value });\n\n    return result.entry.id;\n  }\n\n  private requireString(raw: unknown, field: string): string {\n    if (typeof raw !== 'string' || raw.trim() === '') {\n      throw new DomainError('E_INPUT_INVALID', `${field} is required`, { field });\n    }\n    return raw;\n  }\n\n  private requireDate(raw: unknown, field: string): CalendarDate {\n    const value = this.requireString(raw, field);\n    try {\n      return CalendarDate.of(value);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a calendar date`, { field });\n    }\n  }\n\n  private requireMoney(raw: unknown, field: string): Money {\n    if (!isRecord(raw) || typeof raw.amount !== 'string') {\n      throw new DomainError('E_INPUT_INVALID', `${field} must be a money object`, { field });\n    }\n    const currency = typeof raw.currency === 'string' ? raw.currency : this.baseCurrency.code;\n    try {\n      return Money.of(raw.amount, currency);\n    } catch (error) {\n      if (!(error instanceof InvalidValue)) throw error;\n      throw new DomainError('E_INPUT_INVALID', `${field} is not a valid amount`, { field });\n    }\n  }\n\n  private optionalMoney(raw: unknown): Money | null {\n    if (typeof raw !== 'string' || raw === '') return null;\n    try {\n      return Money.of(raw, this.baseCurrency);\n    } catch {\n      return null;\n    }\n  }\n\n  private requirePercent(raw: unknown, field: string): Big {\n    const value = this.optionalPercent(raw);\n    if (value === null) {\n      throw new DomainError('E_INPUT_INVALID', `${field} must be a percentage as a decimal string`, { field });\n    }\n    return value;\n  }\n\n  private optionalPercent(raw: unknown): Big | null {\n    if (typeof raw !== 'string' || raw === '') return null;\n    try {\n      return new Big(raw);\n    } catch {\n      return null;\n    }\n  }\n}\n","import { AssetService } from '../policies/expansion/assets/asset-service.js';\nimport { ResultAppropriationService } from '../policies/expansion/result-appropriation-service.js';\nimport { EntityProfileService, LegalFormRegistry } from '../policies/projection/legal-forms.js';\nimport { CostingService } from '../policies/expansion/costing/costing-service.js';\nimport { InventoryService } from '../policies/expansion/inventory/inventory-service.js';\nimport { ProvisionService } from '../policies/expansion/provisions/provision-service.js';\nimport { DeferralService } from '../policies/expansion/deferrals/deferral-service.js';\nimport { InputTaxAdjustmentService } from '../policies/expansion/tax/input-tax-adjustment-service.js';\nimport {\n  InMemoryAccountRepository,\n  InMemoryAssetRepository,\n  InMemoryAuditTrail,\n  InMemoryFiscalYearRepository,\n  InMemoryJournalRepository,\n  InMemoryOpenItemRepository,\n  InMemoryCostingRunRepository,\n  InMemoryInventoryValuationRepository,\n  InMemoryProvisionRepository,\n  InMemoryDeferralRepository,\n  InMemoryPartnerRepository,\n  InMemoryTenantRecordRepository,\n  InMemoryVoucherRepository,\n} from '../in-memory.js';\nimport { PartnerService } from '../partner/partner-service.js';\nimport { AccountCombinationRegistry } from '../policies/constraint/account-combination-registry.js';\nimport { DimensionRegistry } from '../policies/constraint/dimension-registry.js';\nimport { AuditWriter } from '../ledger/audit-writer.js';\nimport {\n  emptyTenantConfig,\n  openTenantConfiguration,\n  type TenantConfigStore,\n} from './tenant-config-store.js';\nimport { Ledger } from '../ledger/ledger.js';\nimport { MappingRegistry } from '../policies/projection/mapping/mapping-registry.js';\nimport { TaxCodeRegistry } from '../policies/expansion/tax/tax-code-registry.js';\nimport { TaxProfile } from '../policies/expansion/tax/tax-profile.js';\nimport { TaxService } from '../policies/expansion/tax/tax-service.js';\nimport type {\n  AccountRepository,\n  AssetRepository,\n  AuditTrail,\n  CostingRunRepository,\n  InventoryValuationRepository,\n  DeferralRepository,\n  ProvisionRepository,\n  FiscalYearRepository,\n  JournalRepository,\n  OpenItemRepository,\n  PartnerRepository,\n  VoucherRepository,\n} from '../port.js';\nimport { type Clock, SystemClock } from '../substrate/clock.js';\nimport type { Currency } from '../substrate/currency.js';\nimport { type IdGenerator, UuidV7IdGenerator } from '../substrate/id-generator.js';\nimport type { Uuid } from '../substrate/uuid.js';\n\n/**\n * Tenant: bookkeeping unit, top-most data boundary (glossary `tenant`). Bundles\n * ports + services of one instance. Grows with the slices (Tax/Partner/Asset/\n * Costing follow); the adapter replaces only the ports.\n */\nexport class Tenant {\n  constructor(\n    readonly id: Uuid,\n    readonly name: string,\n    readonly baseCurrency: Currency,\n    readonly accounts: AccountRepository,\n    readonly fiscalYears: FiscalYearRepository,\n    readonly vouchers: VoucherRepository,\n    readonly journal: JournalRepository,\n    readonly openItems: OpenItemRepository,\n    readonly assets: AssetRepository,\n    readonly partners: PartnerRepository,\n    /** Reachable from the tenant like every other repository, so `costingRuns` can read it. */\n    readonly costingRuns: CostingRunRepository,\n    /** Same, for stock (F-CORE-050) — `inventoryValuation` reads it. */\n    readonly inventoryValuations: InventoryValuationRepository,\n    /** Same, for provisions (F-CORE-051) — `provisionRegister` reads it. */\n    readonly provisions: ProvisionRepository,\n    /** Same, for prepaid and deferred items (F-CORE-053) — `deferralRegister` reads it. */\n    readonly deferrals: DeferralRepository,\n    readonly audit: AuditTrail,\n    readonly ledger: Ledger,\n    readonly tax: TaxService,\n    readonly assetService: AssetService,\n    readonly resultAppropriation: ResultAppropriationService,\n    readonly costing: CostingService,\n    readonly inventory: InventoryService,\n    readonly provisionService: ProvisionService,\n    readonly deferralService: DeferralService,\n    /**\n     * The input-tax adjustment (F-CORE-056). No repository: the register of what is under\n     * observation is the embedding application's, because its trigger — a change of use — is never\n     * posted. Only the arithmetic and the posting live here.\n     */\n    readonly inputTaxAdjustment: InputTaxAdjustmentService,\n    readonly partnerService: PartnerService,\n    readonly mappings: MappingRegistry,\n    readonly clock: Clock,\n    readonly ids: IdGenerator,\n    /**\n     * Which pack this tenant was composed from — null for an inline rule bundle, where there\n     * is no manifest to name. Provenance, not rules: it exists so the system description can\n     * say what the books were kept under (F-IO-007).\n     */\n    readonly packIdentity: { id: string; version: string } | null = null,\n    /** Where configuration changes are kept; null when this tenant has no record (SPEC-015). */\n    readonly configStore: TenantConfigStore | null = null,\n    /**\n     * What the embedding declares about the identity behind `actor` (SPEC-020). Null = it has not\n     * said, which `systemDescription` reports as null rather than as \"no\". Not stored: it describes\n     * the running installation, not the books.\n     */\n    readonly actorAuthentication: { declared: boolean; method: string | null } | null = null,\n    /**\n     * Which legal forms the pack knows and which one this tenant is (F-CORE-039). Unlike\n     * `actorAuthentication` this one IS stored — it describes the entity whose books these are, not\n     * the installation running them, and changing it is an audited event with a date.\n     */\n    readonly legalForms: LegalFormRegistry = LegalFormRegistry.empty(),\n    readonly entityProfile: EntityProfileService | null = null,\n  ) {}\n\n  static inMemory(\n    name: string,\n    baseCurrency: Currency,\n    clock: Clock = new SystemClock(),\n    ids?: IdGenerator,\n    dimensions: DimensionRegistry = DimensionRegistry.empty(),\n    taxCodes: TaxCodeRegistry = TaxCodeRegistry.empty(),\n    taxProfile: TaxProfile = TaxProfile.default(),\n    mappings: MappingRegistry = MappingRegistry.empty(),\n    taxRoundingGranularity = 'perVoucher',\n    packIdentity: { id: string; version: string } | null = null,\n    actorAuthentication: { declared: boolean; method: string | null } | null = null,\n    /**\n     * The constraint socket's second plug (F-CORE-042). Appended rather than slotted next to\n     * `dimensions`, where it belongs by subject: thirteen call sites take the defaults, and moving\n     * a positional parameter to keep two related arguments adjacent would have edited all of them\n     * to say the same thing they already say.\n     */\n    combinations: AccountCombinationRegistry = AccountCombinationRegistry.empty(),\n  ): Tenant {\n    const idGen = ids ?? new UuidV7IdGenerator(clock);\n    const tenantId = idGen.next(); // tenant ID = first generated ID (determinism)\n    // An in-memory tenant gets a record too, so the four configuration operations behave the same\n    // way here as they do behind a database. It buys nothing within one process — which is exactly\n    // why the defect could hide from every fixture — but one code path is worth more than the\n    // saving, and a core test can now prove the round trip without an adapter.\n    const { store } = openTenantConfiguration(new InMemoryTenantRecordRepository(), {\n      id: tenantId.value,\n      name,\n      baseCurrency: baseCurrency.code,\n      packIdentity,\n      config: emptyTenantConfig(),\n    });\n    return Tenant.fromPorts(\n      tenantId,\n      name,\n      baseCurrency,\n      {\n        accounts: new InMemoryAccountRepository(),\n        fiscalYears: new InMemoryFiscalYearRepository(),\n        vouchers: new InMemoryVoucherRepository(),\n        journal: new InMemoryJournalRepository(),\n        openItems: new InMemoryOpenItemRepository(),\n        assets: new InMemoryAssetRepository(),\n        partners: new InMemoryPartnerRepository(),\n        costingRuns: new InMemoryCostingRunRepository(),\n        inventoryValuations: new InMemoryInventoryValuationRepository(),\n        provisions: new InMemoryProvisionRepository(),\n        deferrals: new InMemoryDeferralRepository(),\n        audit: new InMemoryAuditTrail(),\n      },\n      clock,\n      idGen,\n      dimensions,\n      taxCodes,\n      taxProfile,\n      mappings,\n      taxRoundingGranularity,\n      packIdentity,\n      store,\n      actorAuthentication,\n      combinations,\n    );\n  }\n\n  /**\n   * Build a tenant from arbitrary ports (service wiring stays here in the core).\n   * `inMemory` uses this with in-memory ports; the persistence adapter\n   * (`@superheld/summae-knex`) passes in DB-backed ports — the same\n   * `Tenant`, only different ports.\n   */\n  static fromPorts(\n    tenantId: Uuid,\n    name: string,\n    baseCurrency: Currency,\n    ports: {\n      accounts: AccountRepository;\n      fiscalYears: FiscalYearRepository;\n      vouchers: VoucherRepository;\n      journal: JournalRepository;\n      openItems: OpenItemRepository;\n      assets: AssetRepository;\n      partners: PartnerRepository;\n      costingRuns: CostingRunRepository;\n      inventoryValuations: InventoryValuationRepository;\n      provisions: ProvisionRepository;\n      deferrals: DeferralRepository;\n      audit: AuditTrail;\n    },\n    clock: Clock,\n    ids: IdGenerator,\n    dimensions: DimensionRegistry = DimensionRegistry.empty(),\n    taxCodes: TaxCodeRegistry = TaxCodeRegistry.empty(),\n    taxProfile: TaxProfile = TaxProfile.default(),\n    mappings: MappingRegistry = MappingRegistry.empty(),\n    taxRoundingGranularity = 'perVoucher',\n    packIdentity: { id: string; version: string } | null = null,\n    /**\n     * Where configuration changes are kept (SPEC-015). Null leaves the four configuration\n     * operations effective for this object only — which is what every tenant did before the\n     * record existed, and what an adapter without the table still does.\n     */\n    configStore: TenantConfigStore | null = null,\n    /** See the constructor: the embedding's declaration about `actor` (SPEC-020). */\n    actorAuthentication: { declared: boolean; method: string | null } | null = null,\n    /** The constraint socket's second plug (F-CORE-042) — see `inMemory` for why it is last. */\n    combinations: AccountCombinationRegistry = AccountCombinationRegistry.empty(),\n  ): Tenant {\n    const {\n      accounts,\n      fiscalYears,\n      vouchers,\n      journal,\n      openItems,\n      assets,\n      partners,\n      costingRuns,\n      inventoryValuations,\n      provisions,\n      deferrals,\n      audit,\n    } = ports;\n    // Built before the ledger, not with the other services below: the ledger reads the declared\n    // legal form on every posting to evaluate conditional constraint rules (F-CORE-047), and it\n    // must hold the same object `setEntityProfile` later writes to.\n    const legalForms = new LegalFormRegistry();\n    const ledger = new Ledger(\n      baseCurrency,\n      accounts,\n      fiscalYears,\n      vouchers,\n      journal,\n      openItems,\n      audit,\n      dimensions,\n      clock,\n      ids,\n      taxCodes,\n      tenantId,\n      configStore,\n      combinations,\n      legalForms,\n      taxProfile,\n    );\n    const auditWriter = new AuditWriter(audit, clock, ids);\n    const tax = new TaxService(\n      baseCurrency,\n      taxCodes,\n      taxProfile,\n      journal,\n      taxRoundingGranularity,\n      tenantId,\n      auditWriter,\n      configStore,\n    );\n    const assetService = new AssetService(baseCurrency, assets, fiscalYears, vouchers, ledger, ids, tenantId, auditWriter);\n    const resultAppropriation = new ResultAppropriationService(baseCurrency, accounts, journal, ledger, auditWriter);\n    const costing = new CostingService(\n      baseCurrency,\n      accounts,\n      journal,\n      costingRuns,\n      ids,\n      tenantId,\n      auditWriter,\n      configStore,\n    );\n    const inventory = new InventoryService(\n      baseCurrency,\n      accounts,\n      journal,\n      vouchers,\n      costingRuns,\n      inventoryValuations,\n      ledger,\n      ids,\n      {},\n      tenantId,\n      auditWriter,\n    );\n    const provisionService = new ProvisionService(\n      baseCurrency,\n      accounts,\n      vouchers,\n      provisions,\n      ledger,\n      ids,\n      {},\n      auditWriter,\n    );\n    const deferralService = new DeferralService(\n      baseCurrency,\n      accounts,\n      fiscalYears,\n      vouchers,\n      deferrals,\n      ledger,\n      ids,\n      {},\n      tenantId,\n      auditWriter,\n    );\n    const inputTaxAdjustment = new InputTaxAdjustmentService(\n      baseCurrency,\n      accounts,\n      vouchers,\n      ledger,\n      ids,\n      {},\n      auditWriter,\n    );\n    const partnerService = new PartnerService(partners, audit, clock, ids, accounts, vouchers, openItems);\n    const entityProfile = new EntityProfileService(legalForms, auditWriter, tenantId, configStore);\n\n    return new Tenant(\n      tenantId,\n      name,\n      baseCurrency,\n      accounts,\n      fiscalYears,\n      vouchers,\n      journal,\n      openItems,\n      assets,\n      partners,\n      costingRuns,\n      inventoryValuations,\n      provisions,\n      deferrals,\n      audit,\n      ledger,\n      tax,\n      assetService,\n      resultAppropriation,\n      costing,\n      inventory,\n      provisionService,\n      deferralService,\n      inputTaxAdjustment,\n      partnerService,\n      mappings,\n      clock,\n      ids,\n      packIdentity,\n      configStore,\n      actorAuthentication,\n      legalForms,\n      entityProfile,\n    );\n  }\n}\n","import type { AssetRepository } from '../../port.js';\nimport type { Asset } from '../expansion/assets/asset.js';\nimport { CalendarDate } from '../../substrate/calendar-date.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport { Money } from '../../substrate/money.js';\nimport { integerOr } from './parameters.js';\n\nconst FIGURES = [\n  'openingCost',\n  'additions',\n  'disposals',\n  'transfers',\n  'closingCost',\n  'openingDepreciation',\n  'depreciationOfYear',\n  'writeUpsOfYear',\n  'depreciationOnDisposals',\n  'closingDepreciation',\n  'openingBookValue',\n  'closingBookValue',\n] as const;\n\ntype Figure = (typeof FIGURES)[number];\n\n/**\n * The fixed-asset movement schedule (F-CORE-055).\n *\n * **The register answers a different question, and that is the whole reason this exists.**\n * `assetRegister` reports the *stock*: what an asset cost, what has been written off it, what it is\n * worth, at a cutoff date. A movement schedule reports the *year*: what was there at the start, what\n * came in, what went out, what was written off during it, and what is left. Every figure below is\n * already in the journal and in the asset records — the projection that shapes them was simply never\n * written, which is why the row sat in the census as \"a projection over data that is all present\".\n *\n * **Grouped by asset account, because that is what the statement wants.** A schedule is read\n * alongside the balance sheet, position by position, not asset by asset. Both are reported: the\n * per-asset rows because that is where a figure is checked, and the per-account totals because that\n * is where it is filed.\n *\n * **`transfers` is always `0.00`, and saying why is more useful than leaving the column out.** A\n * statutory schedule has a column for reclassifications between positions. summae has no operation\n * that moves an asset from one account to another, so the column is *structurally* zero rather than\n * unimplemented — a schedule missing the column would be incomplete for whoever files it, and one\n * that silently omitted it would be worse. If a transfer operation ever arrives, this column starts\n * carrying figures and nothing else about the shape changes.\n *\n * **What a disposal does to the year.** The whole accumulated depreciation of a disposed asset\n * leaves with it: it is reported under `onDisposals` and the closing accumulated depreciation is\n * zero. Netting it into the year's depreciation instead would show a year that wrote off less than\n * it did.\n */\nexport class AssetScheduleProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly assets: AssetRepository,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = integerOr(params.fiscalYear, 0);\n    const yearStart = CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-01-01`);\n    const yearEnd = CalendarDate.of(`${String(fiscalYear).padStart(4, '0')}-12-31`);\n\n    const assets = [...this.assets.all()].sort((a, b) => {\n      const byAccount = a.assetAccount.value.localeCompare(b.assetAccount.value);\n      if (byAccount !== 0) return byAccount;\n      const byDate = a.acquiredOn.compareTo(b.acquiredOn);\n      return byDate !== 0 ? byDate : a.id.compareTo(b.id);\n    });\n\n    const rows: Array<Record<string, unknown>> = [];\n    const byAccount = new Map<string, Record<Figure, Money>>();\n\n    for (const asset of assets) {\n      // An asset acquired after the year has no line in it at all. One disposed before it has none\n      // either — both would otherwise show a row of zeros that a reader has to discount.\n      if (asset.acquiredOn.isAfter(yearEnd)) continue;\n      const disposedOn = asset.disposedOnDate();\n      if (disposedOn !== null && disposedOn.isBefore(yearStart)) continue;\n\n      const figures = this.scheduleFor(asset, yearStart, yearEnd);\n      rows.push({\n        assetId: asset.id.value,\n        name: asset.name,\n        account: asset.assetAccount.value,\n        ...Object.fromEntries(FIGURES.map((key) => [key, figures[key].amountAsString()])),\n      });\n\n      const account = asset.assetAccount.value;\n      const group = byAccount.get(account) ?? this.zeroFigures();\n      for (const key of FIGURES) group[key] = group[key].add(figures[key]);\n      byAccount.set(account, group);\n    }\n\n    const totals = this.zeroFigures();\n    const groups = [...byAccount.keys()].sort().map((account) => {\n      const group = byAccount.get(account) as Record<Figure, Money>;\n      for (const key of FIGURES) totals[key] = totals[key].add(group[key]);\n      return {\n        account,\n        ...Object.fromEntries(FIGURES.map((key) => [key, group[key].amountAsString()])),\n      };\n    });\n\n    return {\n      fiscalYear,\n      assets: rows,\n      byAccount: groups,\n      totals: Object.fromEntries(FIGURES.map((key) => [key, totals[key].amountAsString()])),\n    };\n  }\n\n  private zeroFigures(): Record<Figure, Money> {\n    const zero = Money.zero(this.baseCurrency);\n    return Object.fromEntries(FIGURES.map((key) => [key, zero])) as Record<Figure, Money>;\n  }\n\n  private scheduleFor(asset: Asset, yearStart: CalendarDate, yearEnd: CalendarDate): Record<Figure, Money> {\n    const zero = Money.zero(this.baseCurrency);\n    const acquiredInYear = !asset.acquiredOn.isBefore(yearStart);\n    const disposedOn = asset.disposedOnDate();\n    const disposedInYear = disposedOn !== null && !disposedOn.isAfter(yearEnd);\n\n    const openingCost = acquiredInYear ? zero : asset.acquisitionCost;\n    const additions = acquiredInYear ? asset.acquisitionCost : zero;\n    const disposals = disposedInYear ? asset.acquisitionCost : zero;\n    const closingCost = openingCost.add(additions).subtract(disposals);\n\n    const openingDepreciation = acquiredInYear ? zero : asset.accumulatedDepreciationAt(dayBefore(yearStart));\n\n    let depreciationOfYear = zero;\n    let writeUpsOfYear = zero;\n    for (const booking of asset.depreciationsForPersistence()) {\n      const date = CalendarDate.of(booking.date);\n      if (date.isBefore(yearStart) || date.isAfter(yearEnd)) continue;\n\n      const amount = Money.of(booking.amount.amount, this.baseCurrency);\n      if (booking.kind === 'writeUp') {\n        // A write-up is stored as a negative depreciation so every existing reader picks it up; here\n        // it is reported positive under its own name, because a schedule that showed it as \"less\n        // depreciation\" would hide a legally distinct event.\n        writeUpsOfYear = writeUpsOfYear.add(amount.negate());\n        continue;\n      }\n      depreciationOfYear = depreciationOfYear.add(amount);\n    }\n\n    const depreciationOnDisposals = disposedInYear\n      ? openingDepreciation.add(depreciationOfYear).subtract(writeUpsOfYear)\n      : zero;\n\n    const closingDepreciation = openingDepreciation\n      .add(depreciationOfYear)\n      .subtract(writeUpsOfYear)\n      .subtract(depreciationOnDisposals);\n\n    return {\n      openingCost,\n      additions,\n      disposals,\n      // Structurally zero: see the class comment. The column is here so the schedule is complete in\n      // shape, not because a transfer could occur and did not.\n      transfers: zero,\n      closingCost,\n      openingDepreciation,\n      depreciationOfYear,\n      writeUpsOfYear,\n      depreciationOnDisposals,\n      closingDepreciation,\n      openingBookValue: openingCost.subtract(openingDepreciation),\n      closingBookValue: closingCost.subtract(closingDepreciation),\n    };\n  }\n}\n\n/**\n * The last day before a fiscal year starts — `accumulatedDepreciationAt` is inclusive, and a\n * schedule's opening figure is what stood there *before* the year, not on its first day.\n */\nfunction dayBefore(date: CalendarDate): CalendarDate {\n  const [year, month, day] = date.iso.split('-').map(Number) as [number, number, number];\n  const previous = new Date(Date.UTC(year, month - 1, day - 1));\n  return CalendarDate.of(previous.toISOString().slice(0, 10));\n}\n","import type { AccountRepository, JournalRepository, VoucherRepository } from '../../port.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport type { EntryLine } from '../../substrate/entry-line.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport { isBalanceCarrying } from '../../substrate/types.js';\nimport { Money } from '../../substrate/money.js';\nimport { integerOrNull } from './parameters.js';\n\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * AICPA Audit Data Standard (General Ledger) export — the US counterpart to `journalExport`\n * (GoBD-Z3, German) and `datevExport` (DATEV, German). The US has no statutory GL export format;\n * the AICPA ADS is the voluntary standard a US auditor expects. Emits the three GL streams with\n * the standard's field names (JSON form, per the AICPA-ADS/AuditData-API schema):\n *   - `journals`      (GLDetail)         — journal entries + line items\n *   - `trialBalance`  (GLAccountBalance) — beginning/ending account balances\n *   - `accounts`      (chart of accounts)\n * ADS line amounts are **signed** (debit positive, credit negative) — there is no debit/credit\n * indicator. Counterpart to the German exports; a different jurisdiction, a different \"Werk\".\n */\nexport class AuditDataExportProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly journal: JournalRepository,\n    private readonly accounts: AccountRepository,\n    private readonly vouchers: VoucherRepository,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const fiscalYear = integerOrNull(params.fiscalYear);\n    const inScope = fiscalYear === null ? this.journal.all() : this.journal.forFiscalYear(fiscalYear);\n    const prior =\n      fiscalYear === null ? [] : this.journal.all().filter((entry) => entry.periodRef.fiscalYear < fiscalYear);\n    const asOf = asString(params.asOf) ?? this.latestDate(inScope);\n\n    return {\n      standard: 'aicpa-ads-gl',\n      currency: this.baseCurrency.code,\n      journals: inScope.map((entry) => this.journalRow(entry)),\n      trialBalance: this.trialBalanceRows(prior, inScope, asOf, fiscalYear),\n      accounts: this.accountRows(),\n    };\n  }\n\n  private journalRow(entry: JournalEntry): Record<string, unknown> {\n    const voucher = this.vouchers.byId(entry.voucherId);\n    return {\n      journalId: entry.id.value,\n      effectiveDate: entry.entryDate.iso,\n      fiscalYear: entry.periodRef.fiscalYear,\n      period: entry.periodRef.period,\n      jeHeaderDescription: entry.text(),\n      source: voucher === null ? null : voucher.voucherNumber,\n      enteredDate: entry.recordedAt,\n      reversalIndicator: entry.reverses !== null,\n      reversalJournalId: entry.reverses?.value ?? null,\n      glLineItems: entry.lines().map((line, index) => ({\n        glAccountNumber: line.account.value,\n        journalIdLineNumber: `${entry.id.value}-${index + 1}`,\n        jeLineDescription: entry.text(),\n        transactionAmount: this.signed(line).amountAsString(),\n        transactionCurrency: this.baseCurrency.code,\n      })),\n    };\n  }\n\n  /** ADS convention: debit positive, credit negative. */\n  private signed(line: EntryLine): Money {\n    return line.side === 'debit' ? line.money : line.money.negate();\n  }\n\n  private trialBalanceRows(\n    prior: JournalEntry[],\n    current: JournalEntry[],\n    asOf: string | null,\n    fiscalYear: number | null,\n  ): Array<Record<string, unknown>> {\n    const beginning = this.signedSums(prior);\n    const ending = this.signedSums([...prior, ...current]);\n    // Income accounts start the fiscal year at zero (api.md: balance accounts cumulative, income\n    // accounts per fiscal year). Carrying their prior turnover into this stream made it disagree\n    // with trialBalance per account — two reports over the same books, side by side on an\n    // auditor's desk, with different numbers.\n    const currentOnly = this.signedSums(current);\n    const carrying = new Map<string, boolean>(\n      this.accounts.all().map((account) => [account.number.value, isBalanceCarrying(account.type)]),\n    );\n\n    const numbers = [...ending.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n    const zero = Money.zero(this.baseCurrency);\n    return numbers.map((number) => {\n      const isCarrying = carrying.get(number) ?? true;\n      return {\n        glAccountNumber: number,\n        balanceAsOfDate: asOf,\n        fiscalYear,\n        amountBeginning: (isCarrying ? (beginning.get(number) ?? zero) : zero).amountAsString(),\n        amountEnding: (isCarrying ? (ending.get(number) ?? zero) : (currentOnly.get(number) ?? zero)).amountAsString(),\n        amountCurrency: this.baseCurrency.code,\n      };\n    });\n  }\n\n  private signedSums(entries: JournalEntry[]): Map<string, Money> {\n    const sums = new Map<string, Money>();\n    for (const entry of entries) {\n      for (const line of entry.lines()) {\n        const key = line.account.value;\n        sums.set(key, (sums.get(key) ?? Money.zero(this.baseCurrency)).add(this.signed(line)));\n      }\n    }\n    return sums;\n  }\n\n  private accountRows(): Array<Record<string, unknown>> {\n    return this.accounts\n      .all()\n      .slice()\n      .sort((a, b) => (a.number.value < b.number.value ? -1 : a.number.value > b.number.value ? 1 : 0))\n      .map((account) => ({\n        glAccountNumber: account.number.value,\n        glAccountName: account.name,\n        accountType: account.type,\n        accountSubtype: account.subtype,\n        parentGLAccountNumber: null,\n      }));\n  }\n\n  private latestDate(entries: JournalEntry[]): string | null {\n    let latest: string | null = null;\n    for (const entry of entries) {\n      if (latest === null || entry.entryDate.iso > latest) latest = entry.entryDate.iso;\n    }\n    return latest;\n  }\n}\n","import { DomainError, rejectedValue } from '../../domain-error.js';\nimport type { Clock } from '../../substrate/clock.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport type { Uuid } from '../../substrate/uuid.js';\nimport type {\n  AccountRepository,\n  AuditTrail,\n  JournalRepository,\n  PartnerRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport { integerOrNull } from './parameters.js';\n\n/**\n * The Z3 data carrier: flat files plus the `index.xml` that describes them (F-IO-012).\n *\n * **What this closes.** `journalExport` has always produced the *self-describing data set* — streams\n * plus a field catalogue — and `datenformat.md` stated the intent that \"export in the\n * Beschreibungsstandard is a **mapping**, not an invention\". The mapping itself was not in the\n * package, so an audit asking for a Z3 data carrier needed tooling summae did not ship, and\n * `docs/gobd-conformance.md` §10 carried that as its last open row. It is a mapping and nothing more:\n * every value here already exists in the books.\n *\n * **Why this is a projection in the core and not pack data.** It looks jurisdiction-specific, and it\n * is — but so are `datevExport` (German) and `auditDataExport` (the US AICPA standard), and both live\n * here. The rule the three follow: a **published exchange format** is core code selected by the\n * caller; what varies *inside* it by jurisdiction is pack data. This one takes no pack data at all —\n * it describes summae's own streams — so there is nothing for a pack to supply.\n *\n * **Standard: version 1.6 of 1 March 2019**, DTD `gdpdu-01-03-2019.dtd`. The structure follows the\n * DTD exactly, and the element order is not decoration: `Table` fixes `URL, Name?, Description?,\n * Validity?, codepage?, (DecimalSymbol, DigitGroupingSymbol)?, …, (VariableLength | FixedLength)`,\n * and an importer rejects the file if they are shuffled.\n *\n * **Three decisions worth naming.**\n *\n * 1. **The journal is flattened to one row per line**, with the entry's header repeated. A CSV cannot\n *    nest, and an auditor's first act is to sum debit and credit per account — which needs the line,\n *    not the entry. `entryId` + `lineNumber` is the primary key, and both keys are declared, so the\n *    importer can join rather than being handed five unrelated files.\n * 2. **Nothing is written to disk**, because summae is a library and owns no file system. The tables\n *    come back as content, and the embedding writes them next to `index.xml`.\n * 3. **The DTD file itself is named, not shipped.** The standard requires it on the medium next to\n *    `index.xml`; it is Audicon's document, not ours, and a library that quietly redistributed a\n *    third party's normative file would be making a promise about its version that it cannot keep.\n *    `notProvided` says so rather than leaving it to be discovered at the audit desk.\n */\nconst GDPDU_STANDARD = 'Beschreibungsstandard für die Datenträgerüberlassung 1.6 (2019-03-01)';\nconst GDPDU_DTD = 'gdpdu-01-03-2019.dtd';\n\n/** `;` and `\"` are the standard's own defaults; declared explicitly rather than relied on. */\nconst COLUMN_DELIMITER = ';';\nconst TEXT_ENCAPSULATOR = '\"';\nconst RECORD_DELIMITER = '\\r\\n';\n\ntype ColumnType =\n  | { kind: 'alphanumeric' }\n  | { kind: 'date' }\n  | { kind: 'numeric'; accuracy: number };\n\ninterface Column {\n  readonly name: string;\n  readonly description: string;\n  readonly type: ColumnType;\n  readonly primaryKey?: boolean;\n}\n\ninterface TableSpec {\n  readonly url: string;\n  readonly name: string;\n  readonly description: string;\n  readonly columns: readonly Column[];\n  readonly rows: ReadonlyArray<ReadonlyArray<string>>;\n  readonly foreignKeys?: ReadonlyArray<{ columns: readonly string[]; references: string }>;\n}\n\nconst ALPHA: ColumnType = { kind: 'alphanumeric' };\nconst DATE: ColumnType = { kind: 'date' };\n\nfunction text(value: unknown): string {\n  if (value === null || value === undefined) return '';\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  return JSON.stringify(value);\n}\n\n/**\n * CSV with the standard's quoting: a value is wrapped when it carries the delimiter, a quote or a\n * line break, and an inner quote is doubled. Unconditional quoting would also be legal and is not\n * used, because a file an auditor may open by hand should be readable by hand.\n */\nfunction csvValue(value: string): string {\n  const needsQuoting =\n    value.includes(COLUMN_DELIMITER) || value.includes(TEXT_ENCAPSULATOR) || /[\\r\\n]/.test(value);\n  if (!needsQuoting) return value;\n  return TEXT_ENCAPSULATOR + value.split(TEXT_ENCAPSULATOR).join(TEXT_ENCAPSULATOR + TEXT_ENCAPSULATOR) + TEXT_ENCAPSULATOR;\n}\n\nfunction csv(columns: readonly Column[], rows: ReadonlyArray<ReadonlyArray<string>>): string {\n  const header = columns.map((column) => csvValue(column.name)).join(COLUMN_DELIMITER);\n  const body = rows.map((row) => row.map(csvValue).join(COLUMN_DELIMITER));\n  // A trailing record delimiter, so the last row ends like every other one. An importer that counts\n  // records by delimiter and one that counts by line then agree.\n  return [header, ...body].join(RECORD_DELIMITER) + RECORD_DELIMITER;\n}\n\nfunction xmlText(value: string): string {\n  return value\n    .split('&').join('&amp;')\n    .split('<').join('&lt;')\n    .split('>').join('&gt;');\n}\n\nexport class GdpduExportProjection {\n  constructor(\n    private readonly tenantId: Uuid,\n    private readonly tenantName: string,\n    private readonly baseCurrency: Currency,\n    private readonly journal: JournalRepository,\n    private readonly accounts: AccountRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly partners: PartnerRepository,\n    private readonly audit: AuditTrail,\n    private readonly clock: Clock,\n  ) {}\n\n  compute(params: Record<string, unknown>): Record<string, unknown> {\n    const mediaName = params.mediaName;\n    if (mediaName !== undefined && mediaName !== null && typeof mediaName !== 'string') {\n      throw new DomainError('E_INPUT_INVALID', 'gdpduExport: \"mediaName\" must be a string', {\n        mediaName: rejectedValue(mediaName),\n      });\n    }\n\n    const fiscalYear = integerOrNull(params.fiscalYear);\n    const tables = this.tables(fiscalYear);\n\n    return {\n      standard: GDPDU_STANDARD,\n      dtd: GDPDU_DTD,\n      indexXml: this.indexXml(String(mediaName ?? 'Disk1'), tables),\n      tables: tables.map((table) => ({\n        url: table.url,\n        name: table.name,\n        rowCount: table.rows.length,\n        content: csv(table.columns, table.rows),\n      })),\n      // The same shape `systemDescription` uses, and for the same reason: what a deliverable does\n      // NOT contain is part of the deliverable.\n      notProvided: [\n        `${GDPDU_DTD} itself — the standard requires it on the medium beside index.xml; obtain it from the`\n        + ' publisher of the Beschreibungsstandard and place it there. summae names the version it wrote'\n        + ' against rather than redistributing a normative document it does not own.',\n        'Writing the files. summae is a library and owns no file system: index.xml and every table come'\n        + ' back as content for the embedding to write.',\n        'Document images. The carrier holds the bookkeeping data and the voucher REFERENCE; the voucher'\n        + ' files themselves are the archive\\'s, as everywhere else in summae.',\n      ],\n    };\n  }\n\n  private tables(fiscalYear: number | null): TableSpec[] {\n    const entries = fiscalYear === null ? this.journal.all() : this.journal.forFiscalYear(fiscalYear);\n    const accountNames = new Map<string, string>();\n    for (const account of this.accounts.all()) {\n      const data = account.toJSON();\n      accountNames.set(text(data.number), text(data.name));\n    }\n    const voucherNumbers = new Map<string, string>();\n    for (const voucher of this.vouchers.all()) {\n      const data = voucher.toJSON();\n      voucherNumbers.set(text(data.id), text(data.voucherNumber));\n    }\n\n    const scale = this.baseCurrency.scale;\n    const journalRows: string[][] = [];\n    for (const entry of entries) {\n      const data = entry.toJSON();\n      const lines = Array.isArray(data.lines) ? data.lines : [];\n      lines.forEach((raw, index) => {\n        const line = raw as Record<string, unknown>;\n        const money = (line.money ?? {}) as Record<string, unknown>;\n        const tag = (line.taxTag ?? null) as Record<string, unknown> | null;\n        const account = text(line.account);\n        journalRows.push([\n          text(data.id),\n          String(index + 1),\n          text(data.sequenceNumber),\n          text(data.entryDate),\n          text(data.voucherId),\n          voucherNumbers.get(text(data.voucherId)) ?? '',\n          text(data.text),\n          account,\n          accountNames.get(account) ?? '',\n          text(line.side),\n          text(money.amount),\n          text(money.currency),\n          tag === null ? '' : text(tag.code),\n          tag === null ? '' : text(tag.reportingKey),\n          text(data.status),\n          text(data.reverses),\n          text(data.reversedBy),\n          text(data.recordedAt),\n        ]);\n      });\n    }\n\n    const tables: TableSpec[] = [\n      {\n        url: 'journal.csv',\n        name: 'Journal',\n        description: 'Buchungssätze, eine Zeile je Buchungsposition (Journalfunktion)',\n        columns: [\n          { name: 'entryId', description: 'Eindeutige Buchungs-ID (UUIDv7)', type: ALPHA, primaryKey: true },\n          { name: 'lineNumber', description: 'Position innerhalb der Buchung, ab 1', type: { kind: 'numeric', accuracy: 0 }, primaryKey: true },\n          { name: 'sequenceNumber', description: 'Lückenlose Journalnummer je Geschäftsjahr', type: { kind: 'numeric', accuracy: 0 } },\n          { name: 'entryDate', description: 'Buchungsdatum (zonenlos)', type: DATE },\n          { name: 'voucherId', description: 'Belegreferenz (Pflicht)', type: ALPHA },\n          { name: 'voucherNumber', description: 'Belegnummer des referenzierten Belegs', type: ALPHA },\n          { name: 'text', description: 'Buchungstext', type: ALPHA },\n          { name: 'accountNumber', description: 'Kontonummer (führende Nullen signifikant)', type: ALPHA },\n          { name: 'accountName', description: 'Kontobezeichnung zum Zeitpunkt des Exports', type: ALPHA },\n          { name: 'side', description: 'debit|credit (Soll/Haben)', type: ALPHA },\n          { name: 'amount', description: 'Betrag in Belegwährung, Vorzeichen positiv', type: { kind: 'numeric', accuracy: scale } },\n          { name: 'currency', description: 'ISO-4217-Code', type: ALPHA },\n          { name: 'taxCode', description: 'Steuerschlüssel des Packs, leer wenn ungetaggt', type: ALPHA },\n          { name: 'taxReportingKey', description: 'Meldeschlüssel (z. B. UStVA-Kennzahl)', type: ALPHA },\n          { name: 'status', description: 'entered|finalized (Festschreibung)', type: ALPHA },\n          { name: 'reverses', description: 'Bei Storno: ID der stornierten Buchung', type: ALPHA },\n          { name: 'reversedBy', description: 'Bei stornierter Buchung: ID der Stornobuchung', type: ALPHA },\n          { name: 'recordedAt', description: 'Erfassungszeitpunkt (kanonisch, UTC)', type: ALPHA },\n        ],\n        rows: journalRows,\n        foreignKeys: [\n          { columns: ['accountNumber'], references: 'accounts.csv' },\n          { columns: ['voucherId'], references: 'vouchers.csv' },\n        ],\n      },\n      {\n        url: 'accounts.csv',\n        name: 'Konten',\n        description: 'Kontenplan (Kontenfunktion)',\n        columns: [\n          { name: 'number', description: 'Kontonummer', type: ALPHA, primaryKey: true },\n          { name: 'name', description: 'Kontobezeichnung', type: ALPHA },\n          { name: 'type', description: 'asset|liability|equity|expense|revenue', type: ALPHA },\n          { name: 'subtype', description: 'Kanonischer Subtyp (bank, cash, ar, ap, tax_in, …)', type: ALPHA },\n          { name: 'status', description: 'active|locked', type: ALPHA },\n        ],\n        rows: this.accounts.all().map((account) => {\n          const data = account.toJSON();\n          return [text(data.number), text(data.name), text(data.type), text(data.subtype), text(data.status)];\n        }),\n      },\n      {\n        url: 'vouchers.csv',\n        name: 'Belege',\n        description: 'Belegstammdaten; die Belegbilder selbst gehören dem Archiv',\n        columns: [\n          { name: 'voucherId', description: 'Eindeutige Beleg-ID', type: ALPHA, primaryKey: true },\n          { name: 'voucherNumber', description: 'Belegnummer', type: ALPHA },\n          { name: 'voucherDate', description: 'Belegdatum', type: DATE },\n          { name: 'serviceDate', description: 'Leistungsdatum, falls erfasst — maßgeblich für die Steuerregelversion', type: DATE },\n          { name: 'kind', description: 'Belegart', type: ALPHA },\n          { name: 'partnerId', description: 'Geschäftspartner, falls zugeordnet', type: ALPHA },\n        ],\n        rows: this.vouchers.all().map((voucher) => {\n          const data = voucher.toJSON();\n          return [\n            text(data.id),\n            text(data.voucherNumber),\n            text(data.voucherDate),\n            text(data.serviceDate),\n            text(data.kind),\n            text(data.partnerId),\n          ];\n        }),\n      },\n    ];\n\n    const partners = this.partners.all();\n    if (partners.length > 0) {\n      tables.push({\n        url: 'partners.csv',\n        name: 'Geschaeftspartner',\n        description: 'Debitoren/Kreditoren-Stammdaten',\n        columns: [\n          { name: 'partnerId', description: 'Eindeutige Partner-ID', type: ALPHA, primaryKey: true },\n          { name: 'name', description: 'Name des Geschäftspartners', type: ALPHA },\n          { name: 'kind', description: 'customer|supplier|both', type: ALPHA },\n          { name: 'vatId', description: 'USt-IdNr., falls erfasst', type: ALPHA },\n        ],\n        rows: partners.map((partner) => {\n          const data = partner.toJSON();\n          return [text(data.id), text(data.name), text(data.kind), text(data.vatId)];\n        }),\n      });\n    }\n\n    tables.push({\n      url: 'auditLog.csv',\n      name: 'Aenderungsprotokoll',\n      description: 'Audit-Trail; seit Format 0.8 hash-verkettet (Unveränderbarkeit prüfbar)',\n      columns: [\n        { name: 'recordId', description: 'Eindeutige Satz-ID', type: ALPHA, primaryKey: true },\n        { name: 'at', description: 'Änderungszeitpunkt (kanonisch, UTC)', type: ALPHA },\n        { name: 'actor', description: 'Vom Aufrufer gemeldete Identität; nie verifiziert', type: ALPHA },\n        { name: 'objectType', description: 'Betroffener Objekttyp; \"redacted\" = nach Löschrecht geleerte Hülle', type: ALPHA },\n        { name: 'objectId', description: 'Betroffenes Objekt', type: ALPHA },\n        { name: 'action', description: 'created|corrected|finalized|locked|…', type: ALPHA },\n        { name: 'changes', description: 'Vorher/Nachher-Diff der geänderten Felder (JSON)', type: ALPHA },\n        { name: 'previousRecordHash', description: 'SHA-256 des Vorgängersatzes (Hash-Kette)', type: ALPHA },\n        { name: 'recordHash', description: 'SHA-256 dieses Satzes', type: ALPHA },\n      ],\n      rows: this.audit.all().map((record) => {\n        const data = record.toJSON();\n        return [\n          text(data.id),\n          text(data.at),\n          text(data.actor),\n          text(data.objectType),\n          text(data.objectId),\n          text(data.action),\n          JSON.stringify(data.changes ?? {}),\n          text(data.previousRecordHash),\n          text(data.recordHash),\n        ];\n      }),\n    });\n\n    return tables;\n  }\n\n  /**\n   * The `index.xml`, in the DTD's element order.\n   *\n   * Written by hand rather than through an XML library, deliberately and for the same reason the\n   * core carries no framework: the file is small, its shape is fixed by a DTD, and the two languages\n   * have to emit the **same bytes** — which a serialiser's own whitespace and attribute habits would\n   * quietly prevent.\n   */\n  private indexXml(mediaName: string, tables: readonly TableSpec[]): string {\n    const out: string[] = [];\n    out.push('<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>');\n    out.push(`<!DOCTYPE DataSet SYSTEM \"${GDPDU_DTD}\">`);\n    out.push('<DataSet>');\n    out.push('  <Version>1.0</Version>');\n    out.push('  <DataSupplier>');\n    out.push(`    <Name>${xmlText(this.tenantName)}</Name>`);\n    out.push(`    <Location>${xmlText(this.tenantId.value)}</Location>`);\n    out.push(`    <Comment>summae, exportiert ${xmlText(this.clock.now().toISOString())}</Comment>`);\n    out.push('  </DataSupplier>');\n    out.push('  <Media>');\n    out.push(`    <Name>${xmlText(mediaName)}</Name>`);\n    for (const table of tables) out.push(...this.tableXml(table));\n    out.push('  </Media>');\n    out.push('</DataSet>');\n    return out.join('\\n') + '\\n';\n  }\n\n  private tableXml(table: TableSpec): string[] {\n    const out: string[] = [];\n    out.push('    <Table>');\n    out.push(`      <URL>${xmlText(table.url)}</URL>`);\n    out.push(`      <Name>${xmlText(table.name)}</Name>`);\n    out.push(`      <Description>${xmlText(table.description)}</Description>`);\n    out.push('      <UTF8 />');\n    // Amounts are written the way summae stores them — a dot decimal and no grouping — so the\n    // symbols are declared rather than left to the standard's German defaults, which would read\n    // \"1234.56\" as one million.\n    out.push('      <DecimalSymbol>.</DecimalSymbol>');\n    out.push('      <DigitGroupingSymbol>,</DigitGroupingSymbol>');\n    out.push('      <VariableLength>');\n    out.push(`        <ColumnDelimiter>${xmlText(COLUMN_DELIMITER)}</ColumnDelimiter>`);\n    out.push('        <RecordDelimiter>&#13;&#10;</RecordDelimiter>');\n    out.push(`        <TextEncapsulator>${xmlText(TEXT_ENCAPSULATOR)}</TextEncapsulator>`);\n    // The DTD requires every primary key BEFORE the ordinary columns, whatever their order in the\n    // file: `((VariablePrimaryKey+, VariableColumn*) | (VariableColumn+))`.\n    for (const column of table.columns.filter((c) => c.primaryKey === true)) {\n      out.push(...this.columnXml('VariablePrimaryKey', column));\n    }\n    for (const column of table.columns.filter((c) => c.primaryKey !== true)) {\n      out.push(...this.columnXml('VariableColumn', column));\n    }\n    for (const key of table.foreignKeys ?? []) {\n      out.push('        <ForeignKey>');\n      for (const name of key.columns) out.push(`          <Name>${xmlText(name)}</Name>`);\n      out.push(`          <References>${xmlText(key.references)}</References>`);\n      out.push('        </ForeignKey>');\n    }\n    out.push('      </VariableLength>');\n    out.push('    </Table>');\n    return out;\n  }\n\n  private columnXml(element: string, column: Column): string[] {\n    const out: string[] = [];\n    out.push(`        <${element}>`);\n    out.push(`          <Name>${xmlText(column.name)}</Name>`);\n    out.push(`          <Description>${xmlText(column.description)}</Description>`);\n    if (column.type.kind === 'alphanumeric') {\n      out.push('          <AlphaNumeric />');\n    } else if (column.type.kind === 'date') {\n      out.push('          <Date>');\n      // Explicitly ISO, because the standard's default is DD.MM.YYYY and summae writes dates\n      // zoneless in ISO everywhere. YYYY-MM-DD is one of the formats the standard names.\n      out.push('            <Format>YYYY-MM-DD</Format>');\n      out.push('          </Date>');\n    } else {\n      out.push('          <Numeric>');\n      out.push(`            <Accuracy>${column.type.accuracy}</Accuracy>`);\n      out.push('          </Numeric>');\n    }\n    out.push(`        </${element}>`);\n    return out;\n  }\n}\n","import type { AuditTrail } from '../../port.js';\nimport { hashOf } from '../../records/audit-record.js';\n\n/**\n * Walks the audit trail's hash chain and says whether it still holds (format 0.8).\n *\n * **Why this projection is the feature, and the two hash fields are only its data.** Until now the\n * trail was append-only *because no code path updates or deletes it* — a property of the procedure,\n * not of the data. An auditor could check the code, or trust the deployment, and nothing else;\n * `docs/gobd-conformance.md` §13 says plainly that a direct `UPDATE` against a `summae_*` table\n * leaves no trace. It now leaves one, and this is where it becomes visible. Storing hashes and never\n * offering a way to check them would be decoration.\n *\n * **Four states per record, and keeping them apart is the whole difficulty:**\n *\n * - **chained** — carries both hashes, its own recomputes, and its link matches its predecessor.\n * - **unchained** — written before format 0.8, so it has no hash. Reported as its own number and\n *   never as a break: a library that cried tampering over its own upgrade would be useless. They\n *   can only sit at the *front*; an unchained record appearing after a chained one is an insertion\n *   and is reported as a break.\n * - **redacted** — erased under a privacy right (F-CORE-040). The shell keeps both hashes, so the\n *   link still resolves; its content cannot be recomputed, because there is none. Counted, not\n *   verified, and the count is published so nobody reads the difference as a silent pass.\n * - **broken** — everything else, with the reason named.\n *\n * **What it cannot do**, stated because a guarantee's edge is part of it:\n *\n * - Records removed from the **end** leave nothing behind to notice. Every chain has this hole. The\n *   answer is the published `head`: keep it somewhere summae cannot reach and compare.\n * - Two concurrent appends can read the same head and both link to it. That is a *fork*, and it is\n *   reported as a break — truthfully, because from the data alone a fork and a removal look the\n *   same. Serialising appends is the embedding's to arrange, like every other write.\n * - It proves the trail's own integrity, not the books'. A chain over the postings would need\n *   `previousEntryHash`, which the data format reserves and forbids writers to populate in v0.x\n *   (SPEC-022) — a chain every conforming reader is told to ignore would be evidence for nobody.\n */\nexport class AuditTrailIntegrityProjection {\n  constructor(private readonly audit: AuditTrail) {}\n\n  run(): Record<string, unknown> {\n    const records = this.audit.all();\n    const breaks: Array<Record<string, unknown>> = [];\n    let chained = 0;\n    let unchained = 0;\n    let redacted = 0;\n    let previousHash: string | null = null;\n    let seenChained = false;\n\n    for (const record of records) {\n      if (record.recordHash === null) {\n        unchained += 1;\n        if (seenChained) {\n          breaks.push({\n            recordId: record.id.value,\n            at: record.at,\n            reason: 'unchainedAfterChained',\n            detail: 'a record without a hash follows chained ones, which is where an insertion shows',\n          });\n        }\n        continue;\n      }\n\n      seenChained = true;\n      if (record.isRedacted()) {\n        redacted += 1;\n      } else {\n        chained += 1;\n        const recomputed = hashOf(record);\n        if (recomputed !== record.recordHash) {\n          breaks.push({\n            recordId: record.id.value,\n            at: record.at,\n            reason: 'contentMismatch',\n            detail: 'the record no longer hashes to the value it carries',\n          });\n        }\n      }\n\n      if (record.previousRecordHash !== previousHash) {\n        breaks.push({\n          recordId: record.id.value,\n          at: record.at,\n          reason: 'linkMismatch',\n          detail: 'the link does not name the preceding record — one was changed, removed or inserted',\n        });\n      }\n      previousHash = record.recordHash;\n    }\n\n    return {\n      records: records.length,\n      chained,\n      unchained,\n      redacted,\n      // The tip of the chain. Keep it outside summae and compare later: it is the only thing that\n      // notices records dropped from the end.\n      head: previousHash,\n      intact: breaks.length === 0,\n      breaks,\n    };\n  }\n}\n","import type { CostingRunRepository } from '../../port.js';\n\n/**\n * Which costing runs exist (F-KLR-001).\n *\n * `costAllocationSheet`, `overheadRates` and `productionCost` all require a `runId`, and until this\n * existed no projection answered where one comes from: the only way to hold a valid id was to have\n * kept the one `runCosting` returned. An embedding therefore had to keep its own table of run ids\n * beside the books — a second register of library state, which is the arrangement F-13 already\n * named as a bug waiting for the first change that does not pass through the screen that writes it.\n *\n * The repository has sorted `all()` since the runs were persisted, so this is a published-surface\n * gap and not a design boundary: the data was there and the way to it was not.\n *\n * Deliberately thin. It reports what a run *is* — id, period, version, status, method — and nothing\n * computed from one; the three projections above are where a run's figures live, and duplicating a\n * total here would create a second answer to a question that already has one.\n */\nexport class CostingRunsProjection {\n  constructor(private readonly runs: CostingRunRepository) {}\n\n  compute(params: Record<string, unknown>): { runs: Array<Record<string, unknown>> } {\n    const fiscalYear = typeof params.fiscalYear === 'number' ? params.fiscalYear : null;\n    const period = typeof params.period === 'number' ? params.period : null;\n\n    // `all()` is already sorted by period, then version — the order a reader of a period's history\n    // wants, and the order the next version number comes from. Filtering keeps it.\n    const rows = this.runs\n      .all()\n      .filter((run) => fiscalYear === null || run.period.fiscalYear === fiscalYear)\n      .filter((run) => period === null || run.period.period === period)\n      .map((run) => ({\n        runId: run.id.value,\n        fiscalYear: run.period.fiscalYear,\n        period: run.period.period,\n        version: run.version,\n        status: run.status(),\n        method: run.method,\n      }));\n\n    return { runs: rows };\n  }\n}\n","import type { CostingRunRepository } from '../../port.js';\n\n/**\n * Consistency of measurement across periods (F-CORE-049).\n *\n * **Half of this was already built, and saying which half is the point.** A released costing run has\n * always frozen the basis it was computed under: `productionCost.components` lists every configured\n * component with the pack's treatment and whether it went in, and the run *stores* that rather than\n * recomputing it, on the stated ground that \"a released run that answers differently tomorrow is not\n * released\". So the record existed. What did not exist was anybody comparing two records. The\n * election lives in the tenant configuration and can be changed between two runs, and until this\n * projection there was no question you could ask that would have told you.\n *\n * **It reports; it does not refuse — and that is a rule about rules, not a softness.** Frameworks\n * that require measurement to stay consistent also permit a departure that is justified and\n * disclosed. A mechanism that rejected a changed election would therefore be *wrong* rather than\n * merely strict: it would enforce half a rule. Whether a departure is justified is a judgement about\n * the business, which no library can make. What a library can do is make the departure impossible to\n * miss. Same line `vatReturn.gapWarnings` and `duplicateVouchers` already draw.\n *\n * **Released runs only, all of them, in the repository's order.** A draft is a working figure, and a\n * basis that never reached a released run never reached the books either. Every released run is\n * reported and not merely the newest per period: re-releasing a period under a different basis *is*\n * a change of measurement, and one that whoever read the earlier version has already relied on.\n * Collapsing to the newest would hide exactly that.\n *\n * **`withoutBasis` is not padding.** A tenant that valued under a basis and then ran without one has\n * not changed the basis, so it does not belong in `changes` — but a reader comparing two periods\n * needs to know the second measured nothing rather than measured the same. An omission that is not\n * stated reads as agreement.\n *\n * **Named more broadly than its current content, deliberately.** The production-cost election is the\n * only measurement option summae has today. When stock arrives with a consumption sequence, or\n * provisions with a discount rate, they belong in *this* answer and not in a second projection with\n * a third name — the question being asked is \"did the way you measure change\", and it is asked once.\n *\n * The projection carries **no threshold, no citation and no verdict**: which framework demands the\n * comparison, and what counts as a justified departure, is pack and census territory (the German\n * reading is in `docs/hgb-conformance.md`). The core only guarantees that the two bases end up on\n * the table next to each other.\n */\n\ninterface BasisRow {\n  runId: string;\n  fiscalYear: number;\n  period: number;\n  version: number;\n  included: string[];\n  elected: string[];\n}\n\nexport class MeasurementConsistencyProjection {\n  constructor(private readonly runs: CostingRunRepository) {}\n\n  compute(_params: Record<string, unknown>): Record<string, unknown> {\n    const rows: BasisRow[] = [];\n    const withoutBasis: Array<Record<string, unknown>> = [];\n\n    for (const run of this.runs.all()) {\n      if (run.status() !== 'released') continue;\n\n      const where = {\n        runId: run.id.value,\n        fiscalYear: run.period.fiscalYear,\n        period: run.period.period,\n        version: run.version,\n      };\n\n      if (run.productionCost === null) {\n        withoutBasis.push(where);\n        continue;\n      }\n\n      const included: string[] = [];\n      const elected: string[] = [];\n      for (const component of run.productionCost.components) {\n        if (!component.included) continue;\n        included.push(component.id);\n        // The election is the optional half. A mandatory component is in the basis because the pack\n        // says so, and reporting it as a choice would blame the preparer for the jurisdiction — the\n        // two must stay distinguishable, or a pack that promotes a component from optional to\n        // mandatory reads as the tenant having changed its mind.\n        if (component.treatment === 'optional') elected.push(component.id);\n      }\n\n      // Sorted by code point, like every other list this library emits: the basis is a SET, and\n      // comparing two of them must not depend on the order the components were configured in. Two\n      // runs with the same components in a different order are the same measurement.\n      included.sort();\n      elected.sort();\n\n      rows.push({ ...where, included, elected });\n    }\n\n    const changes: Array<Record<string, unknown>> = [];\n    for (let i = 1; i < rows.length; i += 1) {\n      const previous = rows[i - 1] as BasisRow;\n      const current = rows[i] as BasisRow;\n\n      const added = current.included.filter((id) => !previous.included.includes(id));\n      const removed = previous.included.filter((id) => !current.included.includes(id));\n      if (added.length === 0 && removed.length === 0) continue;\n\n      changes.push({\n        fromRunId: previous.runId,\n        toRunId: current.runId,\n        from: { fiscalYear: previous.fiscalYear, period: previous.period },\n        to: { fiscalYear: current.fiscalYear, period: current.period },\n        added,\n        removed,\n        // Reported, never judged. A change inside one fiscal year is still absorbed by that year's\n        // own result; a change that spans a year boundary is the one a reader has to account for,\n        // because the two years are then not comparable without an explanation. Which of the two a\n        // framework cares about is the pack's business — the flag exists so a caller does not have\n        // to derive it from two period numbers.\n        acrossFiscalYears: previous.fiscalYear !== current.fiscalYear,\n      });\n    }\n\n    return { runs: rows, withoutBasis, changes, consistent: changes.length === 0 };\n  }\n}\n","import type {\n  AssetRepository,\n  AuditTrail,\n  DeferralRepository,\n  PartnerRepository,\n  ProvisionRepository,\n  VoucherRepository,\n} from '../../port.js';\nimport { FORMAT_VERSION } from '../../substrate/format-version.js';\n\n/**\n * Where identifying data can sit in these books, and how much of it is actually there (F-CORE-041).\n *\n * The counterpart to `systemDescription`, which answers the same shape of question about auditing:\n * *what does this system record, and about what*. An operator preparing a record of processing\n * activities needs the same answer about people, and until now had to reconstruct it by reading\n * the schema by hand — which is a list that goes stale silently, because a field that has been\n * renamed still reads like a field.\n *\n * **Two halves, split along the project's own axis, and the split is the reason this belongs in\n * summae rather than in every application separately.**\n *\n * - **Where identifying data can sit is mechanism.** The partner aggregate has a name; the audit\n *   trail records an actor; a posting carries free text. That is true of the `us` pack exactly as\n *   of the `de` pack, it does not cite a statute, and it is what this projection reports.\n * - **Whether a given field *counts* as personal data is not mechanism.** The GDPR and the CCPA\n *   answer that differently, and a company identifier is personal data for a sole trader and not\n *   for a corporation. So this projection **never says \"this is personal data\"** — it says *this\n *   field holds free text an operator supplies*, and it counts what is present. The classification\n *   is the operator's, with their own legal advice, and `docs/gdpr-conformance.md` §1 is summae's\n *   own reading of it for the German/EU case.\n *\n * **It reports shape and counts, never content.** `filled` says how many partners carry an address,\n * not what any address says; `addressKeys` says which keys occur, not their values. A projection\n * built to help with a privacy obligation must not itself become the convenient place to read\n * everybody's data out of — and an operator asking \"what do we hold\" needs the inventory, not the\n * records, which `journalExport` already gives them.\n */\nexport class PersonalDataDescriptionProjection {\n  constructor(\n    private readonly partners: PartnerRepository,\n    private readonly vouchers: VoucherRepository,\n    private readonly audit: AuditTrail,\n    // The three stores that hold operator free text OUTSIDE the exchange format (IMPL-045).\n    // Optional because a hand-built tenant may not carry them; an absent store reports\n    // `present: null` — \"not counted\" — never 0, which would claim there is nothing there.\n    private readonly assets?: AssetRepository,\n    private readonly provisions?: ProvisionRepository,\n    private readonly deferrals?: DeferralRepository,\n  ) {}\n\n  compute(_params: Record<string, unknown>): Record<string, unknown> {\n    const partners = this.partners.all();\n    const vouchers = this.vouchers.all();\n\n    const addressKeys = new Set<string>();\n    let withAddress = 0;\n    let withVatId = 0;\n    for (const partner of partners) {\n      const address = partner.toJSON().address;\n      if (address !== null && typeof address === 'object' && !Array.isArray(address)) {\n        const keys = Object.keys(address as Record<string, unknown>);\n        if (keys.length > 0) {\n          withAddress += 1;\n          for (const key of keys) addressKeys.add(key);\n        }\n      }\n      if (typeof partner.toJSON().vatId === 'string') withVatId += 1;\n    }\n\n    const actors = new Set<string>();\n    for (const record of this.audit.all()) actors.add(record.actor);\n\n    let issuers = 0;\n    for (const voucher of vouchers) {\n      if (typeof voucher.toJSON().issuer === 'string') issuers += 1;\n    }\n\n    return {\n      formatVersion: FORMAT_VERSION,\n      // The declared shape: every place a value an operator typed can come to rest. `freeText`\n      // marks the ones whose content summae neither constrains nor interprets — the fields where\n      // anything at all can end up, which is what an inventory most needs flagged.\n      fields: [\n        { holder: 'partner', field: 'name', freeText: true, required: true, present: partners.length },\n        { holder: 'partner', field: 'vatId', freeText: true, required: false, present: withVatId },\n        { holder: 'partner', field: 'address', freeText: true, required: false, present: withAddress },\n        { holder: 'voucher', field: 'issuer', freeText: true, required: false, present: issuers },\n        { holder: 'journalEntry', field: 'text', freeText: true, required: false, present: null },\n        { holder: 'auditRecord', field: 'actor', freeText: true, required: true, present: actors.size },\n        {\n          // The one field that mirrors another: a diff of a partner change carries whatever the\n          // partner held. An inventory that lists `partner.name` and stops has missed the copy.\n          holder: 'auditRecord',\n          field: 'changes',\n          freeText: true,\n          required: true,\n          present: null,\n          mirrors: 'the fields of whatever record changed',\n        },\n        // Three fields that are NOT in the exchange format and were missing from this inventory\n        // until 2026-08-29 (IMPL-045). `journalExport` does not carry them, so an Art. 30 record\n        // assembled from the export alone misses them — and a provision is by its nature often\n        // about a named party: a dispute, a warranty claim, a severance.\n        { holder: 'asset', field: 'name', freeText: true, required: true, present: this.assets?.all().length ?? null },\n        { holder: 'provision', field: 'reason', freeText: true, required: true, present: this.provisions?.all().length ?? null },\n        { holder: 'deferral', field: 'reason', freeText: true, required: true, present: this.deferrals?.all().length ?? null },\n      ],\n      // Which address keys this tenant's data actually uses. The format declares a recommended\n      // shape and does not forbid others, so the only truthful answer to \"what is in there\" is to\n      // look — which is exactly the question a hand-written inventory cannot answer.\n      addressKeys: [...addressKeys].sort(),\n      counts: {\n        partners: partners.length,\n        vouchers: vouchers.length,\n        distinctActors: actors.size,\n      },\n      // Stated rather than implied: an operator reading this must not conclude that summae has\n      // classified anything for them.\n      classification: 'none — summae reports where operator-supplied text can sit, not which of it is personal data under any jurisdiction',\n    };\n  }\n}\n","import type { JournalRepository, PartnerRepository, VoucherRepository } from '../../port.js';\nimport type { Currency } from '../../substrate/currency.js';\nimport type { JournalEntry } from '../../substrate/journal-entry.js';\nimport { Money } from '../../substrate/money.js';\nimport type { Voucher } from '../../records/voucher.js';\n\n/**\n * Documents that look like they were entered twice (F-CORE-044).\n *\n * **The defect this exists for.** `voucherNumber` is a free string with no uniqueness of any kind,\n * and `postVoucher` even substitutes `''` when none is supplied. The same incoming invoice booked\n * twice therefore produces two vouchers, two balanced entries, two open items and two input-tax\n * deductions, and every invariant the library has is satisfied: the entries balance, they carry a\n * voucher, they sit in an open period, the trial balance adds up. Nothing in summae notices, and\n * nothing in the reports looks wrong — the second deduction is simply money claimed twice.\n *\n * **Why a projection and not a refusal.** Duplicate voucher numbers are legitimate across sources:\n * two suppliers may both send their invoice number 1, and a tenant that uses the supplier's number\n * as its own voucher number will meet that in its first year. So the grouping is by *document\n * identity* — the issuer plus the number — and even then the answer is a report, not an error. This\n * follows the line `vatReturn.gapWarnings` draws: name it at the figures, let the application\n * decide. A hard uniqueness rule would be wrong in a way that cannot be worked around, and the one\n * thing worse than a missing check is one that blocks correct bookkeeping.\n *\n * **Deliberately no parameters, and that is a decision rather than an omission.** A date window is\n * the obvious one to offer and the wrong one to have: an invoice entered in December and again in\n * January is exactly the case this projection exists for, and any window on the voucher date hides\n * it at the boundary. `accounts` takes no parameters for the same kind of reason.\n *\n * **Three exclusions, each because including it would produce noise rather than findings:**\n * a voucher with an empty `voucherNumber` (there is nothing to compare — and it is not this\n * projection's business to complain about that); a voucher flagged `recurring` (a Dauerbeleg\n * repeating its number is what the flag means); and, per voucher, entries that are a reversal or\n * have been reversed — `postedTotal` counts only what still moves the books, so a duplicate that\n * has already been corrected reads `0.00` instead of dropping out silently. `stillPosted` counts\n * the vouchers in a group that have a non-zero total, which is the number an application acts on.\n *\n * Substrate, not pack: entering one document twice is wrong in every jurisdiction, and the\n * projection cites no statute.\n */\nexport class DuplicateVouchersProjection {\n  constructor(\n    private readonly baseCurrency: Currency,\n    private readonly vouchers: VoucherRepository,\n    private readonly journal: JournalRepository,\n    /** Only for the name — a duplicate list that says `partnerId` and not \"Mueller GmbH\" is read by nobody. */\n    private readonly partners: PartnerRepository,\n  ) {}\n\n  compute(): Record<string, unknown> {\n    const entriesByVoucher = this.entriesByVoucher();\n\n    const groups = new Map<string, Voucher[]>();\n    for (const voucher of this.vouchers.all()) {\n      if (voucher.voucherNumber === '' || voucher.recurring) continue;\n      const key = DuplicateVouchersProjection.groupKey(voucher);\n      const bucket = groups.get(key);\n      if (bucket === undefined) groups.set(key, [voucher]);\n      else bucket.push(voucher);\n    }\n\n    const keys = [...groups.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n\n    const duplicates: Array<Record<string, unknown>> = [];\n    let voucherCount = 0;\n    for (const key of keys) {\n      const members = groups.get(key) ?? [];\n      if (members.length < 2) continue;\n\n      members.sort((a, b) => {\n        const byDate = a.voucherDate.iso < b.voucherDate.iso ? -1 : a.voucherDate.iso > b.voucherDate.iso ? 1 : 0;\n        if (byDate !== 0) return byDate;\n        return a.id.value < b.id.value ? -1 : a.id.value > b.id.value ? 1 : 0;\n      });\n\n      const rows: Array<Record<string, unknown>> = [];\n      let stillPosted = 0;\n      for (const voucher of members) {\n        const entries = entriesByVoucher.get(voucher.id.value) ?? [];\n        const total = this.postedTotal(entries);\n        if (!total.isZero()) stillPosted += 1;\n        rows.push(this.serialize(voucher, entries, total));\n      }\n\n      const first = members[0]!;\n      duplicates.push({\n        voucherNumber: first.voucherNumber,\n        partnerId: first.partnerId?.value ?? null,\n        partnerName: first.partnerId === null ? null : (this.partners.byId(first.partnerId)?.name() ?? null),\n        issuer: first.issuer,\n        count: members.length,\n        stillPosted,\n        vouchers: rows,\n      });\n      voucherCount += members.length;\n    }\n\n    return { count: duplicates.length, voucherCount, duplicates };\n  }\n\n  /**\n   * Issuer identity first, so two documents from the same source sort together, then the number,\n   * separated by a byte that cannot occur in either — without it, issuer \"AB\" + number \"C\" and\n   * issuer \"A\" + number \"BC\" would be one group. `partnerId` wins over `issuer` when both are\n   * present: the master record is the identity, the string is what somebody typed. Vouchers with\n   * neither group among themselves — two vouchers \"RE-4711\" from nowhere in particular are still\n   * worth a second look.\n   */\n  private static groupKey(voucher: Voucher): string {\n    const issuer = voucher.partnerId?.value ?? voucher.issuer ?? '';\n    return `${issuer}\\u001f${voucher.voucherNumber}`;\n  }\n\n  private entriesByVoucher(): Map<string, JournalEntry[]> {\n    const byVoucher = new Map<string, JournalEntry[]>();\n    for (const entry of this.journal.all()) {\n      const bucket = byVoucher.get(entry.voucherId.value);\n      if (bucket === undefined) byVoucher.set(entry.voucherId.value, [entry]);\n      else bucket.push(entry);\n    }\n    return byVoucher;\n  }\n\n  /**\n   * What the voucher still moves: the debit side of its entries, skipping any entry that is a\n   * reversal or has been reversed. A duplicate that was already corrected therefore reads `0.00`\n   * and stays visible with its history, instead of disappearing from a list somebody is using to\n   * decide whether it was corrected.\n   */\n  private postedTotal(entries: JournalEntry[]): Money {\n    let total = Money.zero(this.baseCurrency);\n    for (const entry of entries) {\n      if (entry.reverses !== null || entry.reversedBy() !== null) continue;\n      for (const line of entry.lines()) {\n        if (line.side === 'debit') total = total.add(line.money);\n      }\n    }\n    return total;\n  }\n\n  private serialize(voucher: Voucher, entries: JournalEntry[], total: Money): Record<string, unknown> {\n    const ordered = [...entries].sort((a, b) => {\n      const byYear = a.periodRef.fiscalYear - b.periodRef.fiscalYear;\n      return byYear !== 0 ? byYear : a.sequenceNumber - b.sequenceNumber;\n    });\n\n    return {\n      voucherId: voucher.id.value,\n      voucherDate: voucher.voucherDate.iso,\n      postedTotal: total.toJSON(),\n      entries: ordered.map((entry) => ({\n        entryId: entry.id.value,\n        sequenceNumber: entry.sequenceNumber,\n        fiscalYear: entry.periodRef.fiscalYear,\n        entryDate: entry.entryDate.iso,\n        status: entry.isFinalized() ? 'finalized' : 'entered',\n        reverses: entry.reverses?.value ?? null,\n        reversedBy: entry.reversedBy()?.value ?? null,\n      })),\n    };\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport { CalendarDate } from '../substrate/calendar-date.js';\nimport { InvalidValue } from '../substrate/errors.js';\nimport type { Uuid } from '../substrate/uuid.js';\nimport { AuditWriter } from '../ledger/audit-writer.js';\nimport { Voucher } from '../records/voucher.js';\nimport type { Tenant } from './tenant.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * F-TAX-007: the supplier's taxation method on the voucher. It decides whether input tax may be\n * deducted on invoice or only on payment — a distinction German law makes binding for the\n * deducting side in 2028, and one only the incoming document can answer. The field was in the\n * data format (`enum [\"accrual\",\"cash\"]`) and in both record classes from the start, but nothing\n * ever read it out of the input, so it could not be anything but null.\n *\n * An unknown value is rejected rather than dropped: silently storing null would look exactly like\n * \"the supplier taxes on accrual\", which is the answer that permits the earlier deduction.\n */\nfunction supplierTaxationMethod(voucherData: Record<string, unknown>): string | null {\n  const value = voucherData.supplierTaxationMethod;\n  if (value === undefined || value === null) return null;\n\n  if (value !== 'accrual' && value !== 'cash') {\n    throw new DomainError(\n      'E_INPUT_INVALID',\n      `voucher.supplierTaxationMethod must be \"accrual\" or \"cash\", got ${typeof value === 'string' ? `\"${value}\"` : typeof value}`,\n    );\n  }\n\n  return value;\n}\n\n/**\n * Application-layer composition `postVoucher` (api.md, part of the spec): SF-02/03\n * in one call — create voucher, expandTax, post, OP creation.\n */\nexport class PostVoucherService {\n  constructor(private readonly tenant: Tenant) {}\n\n  /** Build + store voucher from `input.voucher` — shared by postVoucher and createVoucher. */\n  private buildAndAddVoucher(input: Record<string, unknown>): Voucher {\n    const voucherData = isRecord(input.voucher) ? input.voucher : {};\n\n    let voucherDate: CalendarDate;\n    try {\n      voucherDate = CalendarDate.of(asString(voucherData.voucherDate) ?? '');\n    } catch (error) {\n      if (error instanceof InvalidValue) {\n        throw new DomainError('E_ENTRY_NO_VOUCHER', 'Voucher needs voucher.voucherDate');\n      }\n      throw error;\n    }\n\n    // v0.4: partner must exist before anything is created.\n    let partnerId: Uuid | null = null;\n    if (voucherData.partnerId !== undefined && voucherData.partnerId !== null) {\n      partnerId = this.tenant.partnerService.require(voucherData.partnerId).id;\n    }\n\n    const date = (value: unknown): CalendarDate | null =>\n      typeof value === 'string' ? CalendarDate.of(value) : null;\n    const servicePeriod = isRecord(voucherData.servicePeriod) ? voucherData.servicePeriod : {};\n\n    const voucher = new Voucher({\n      id: this.tenant.ids.next(),\n      voucherNumber: asString(voucherData.voucherNumber) ?? '',\n      voucherDate,\n      due: date(voucherData.due),\n      recurring: voucherData.recurring === true,\n      economicYear: typeof voucherData.economicYear === 'number' ? voucherData.economicYear : null,\n      serviceDate: date(voucherData.serviceDate),\n      servicePeriodFrom: date(servicePeriod.from),\n      servicePeriodTo: date(servicePeriod.to),\n      kind: asString(voucherData.kind),\n      partnerId,\n      issuer: asString(voucherData.issuer),\n      supplierTaxationMethod: supplierTaxationMethod(voucherData),\n    });\n    this.tenant.vouchers.add(voucher);\n    // Shared by createVoucher and postVoucher, so one record covers both. A voucher is the\n    // anchor of the Belegfunktion — that one appeared has to be traceable even when no\n    // posting follows it (createVoucher deliberately posts nothing).\n    new AuditWriter(this.tenant.audit, this.tenant.clock, this.tenant.ids).record(\n      typeof input.actor === 'string' && input.actor !== '' ? input.actor : 'system',\n      'voucher',\n      voucher.id,\n      'created',\n      {\n        voucherNumber: { from: null, to: voucher.voucherNumber },\n        voucherDate: { from: null, to: voucher.voucherDate.iso },\n      },\n    );\n\n    return voucher;\n  }\n\n  /** createVoucher: create a voucher without posting — makes pack-mode fixtures complete (post/acquireAsset). */\n  createVoucher(input: Record<string, unknown>): Record<string, unknown> {\n    const voucher = this.buildAndAddVoucher(input);\n    return { id: voucher.id.value, voucherNumber: voucher.voucherNumber };\n  }\n\n  post(input: Record<string, unknown>): Record<string, unknown> {\n    const voucher = this.buildAndAddVoucher(input);\n    const voucherDate = voucher.voucherDate;\n\n    // Direct gross mode: explicit `lines` are posted without tax expansion\n    // (e.g. payments). The voucher wraps an ordinary posting.\n    if (Array.isArray(input.lines)) {\n      const directResult = this.tenant.ledger.post({\n        actor: input.actor ?? null,\n        entryDate: input.entryDate ?? voucherDate.iso,\n        voucherId: voucher.id.value,\n        text: input.text ?? '',\n        lines: input.lines,\n      });\n      return {\n        entry: JSON.parse(JSON.stringify(directResult.entry)) as Record<string, unknown>,\n        openItemsCreated: directResult.openItemsCreated.map((item) => JSON.parse(JSON.stringify(item)) as unknown),\n        voucherId: voucher.id.value,\n      };\n    }\n\n    const expansion = this.tenant.tax.expand({\n      date: voucherDate.iso,\n      serviceDate: voucher.taxDate().iso,\n      taxCode: input.taxCode ?? null,\n      direction: input.direction ?? 'output',\n      reduction: input.reduction ?? false,\n      netLines: input.netLines ?? [],\n    });\n\n    const direction = input.direction === 'input' ? 'input' : 'output';\n    const reduction = input.reduction === true;\n    const counterAccount = asString(input.counterAccount) ?? '';\n    // The gross side mirrors with everything else: a reduction gives money back, so a receivable\n    // goes down where the original supply put it up (F-TAX-014).\n    const plainCounterSide = direction === 'output' ? 'debit' : 'credit';\n    const counterSide = reduction ? (plainCounterSide === 'debit' ? 'credit' : 'debit') : plainCounterSide;\n    const netLines = Array.isArray(expansion.netLines) ? expansion.netLines : [];\n    const taxLines = Array.isArray(expansion.taxLines) ? expansion.taxLines : [];\n\n    const lines: Array<Record<string, unknown>> = [\n      {\n        account: counterAccount,\n        side: counterSide,\n        money: expansion.grossTotal,\n      },\n      ...netLines,\n      ...taxLines,\n    ];\n\n    const result = this.tenant.ledger.post({\n      actor: input.actor ?? null,\n      entryDate: input.entryDate ?? voucherDate.iso,\n      voucherId: voucher.id.value,\n      text: input.text ?? '',\n      lines,\n    });\n\n    return {\n      entry: JSON.parse(JSON.stringify(result.entry)) as Record<string, unknown>,\n      openItemsCreated: result.openItemsCreated.map((item) => JSON.parse(JSON.stringify(item)) as unknown),\n      grossTotal: expansion.grossTotal,\n      taxLines: expansion.taxLines,\n      voucherId: voucher.id.value,\n    };\n  }\n}\n","import { DomainError, rejectedValue } from '../domain-error.js';\nimport { matchesParameterType, type ParameterType } from '../policies/projection/parameters.js';\n\n/** What the contract says about one parameter. */\nexport interface ParameterSpec {\n  readonly type: ParameterType;\n  /** Declared for completeness; enforcing it is a separate step (see validateProjectionParams). */\n  readonly required?: true;\n  /** Passed by existing fixtures, read by no implementation — declared so the gap is visible. */\n  readonly acceptedWithoutEffect?: true;\n  /**\n   * What is inside a structure (SPEC-017). `fields` for an object, `element` for an array — the\n   * declaration every element is checked against. Recursive, and it stops where the declaration\n   * stops: a shape that is not written out is not checked, which is a decision the contract's\n   * author makes visibly rather than one that happens.\n   */\n  readonly fields?: Readonly<Record<string, ParameterSpec>>;\n  readonly element?: ParameterSpec;\n  /** Another schema owns this structure. The value is the reason, and it is required. */\n  readonly opaque?: string;\n}\n\n/**\n * The parameter contract of the projections, as data.\n *\n * This table is a hand-kept copy of `testing/testsuite/schema/api-parameters.json`, the\n * normative source. The core reads no files by design (framework-free, no I/O), so the table\n * has to live in the code — and a copy that nothing compares drifts. `projection-parameters.test.ts`\n * (PHP: `ProjectionParametersTest`) asserts this constant equals that file, in both languages.\n * Change the schema in the knowledge base, mirror it, and the tests tell you what to change here.\n */\nexport const PROJECTION_PARAMETERS: Readonly<Record<string, Readonly<Record<string, ParameterSpec>>>> = {\n  trialBalance: {\n    fiscalYear: { type: 'integer', required: true },\n    throughPeriod: { type: 'integer' },\n    includeZeroBalances: { type: 'boolean' },\n  },\n  accountSheet: {\n    account: { type: 'string', required: true },\n    fiscalYear: { type: 'integer', required: true },\n    throughPeriod: { type: 'integer' },\n  },\n  balanceSheet: {\n    mapping: { type: 'string', required: true },\n    fiscalYear: { type: 'integer' },\n    asOf: { type: 'date' },\n    incomeMapping: { type: 'string', acceptedWithoutEffect: true },\n  },\n  incomeStatement: {\n    mapping: { type: 'string', required: true },\n    fiscalYear: { type: 'integer', required: true },\n    fromPeriod: { type: 'integer' },\n    throughPeriod: { type: 'integer' },\n  },\n  cashBasisReport: {\n    year: { type: 'integer', required: true },\n    mapping: { type: 'string' },\n    asOf: { type: 'date' },\n  },\n  vatReturn: {\n    year: { type: 'integer', required: true },\n    quarter: { type: 'integer' },\n    month: { type: 'integer' },\n    asOf: { type: 'date' },\n  },\n  ecSalesList: {\n    year: { type: 'integer', required: true },\n    quarter: { type: 'integer' },\n  },\n  openItems: {\n    kind: { type: 'string' },\n    partnerId: { type: 'string' },\n    asOf: { type: 'date' },\n  },\n  assetRegister: {\n    asOf: { type: 'date' },\n  },\n  // Filters combine with AND; an absent one filters nothing. The four object filters arrived with\n  // F-CORE-036: the auditor's question is about ONE thing, and `from`/`to` alone forced the caller\n  // to transport the whole trail in order to discard most of it.\n  auditLog: {\n    from: { type: 'date' },\n    to: { type: 'date' },\n    objectType: { type: 'string' },\n    objectId: { type: 'string' },\n    actor: { type: 'string' },\n    action: { type: 'string' },\n    offset: { type: 'integer' },\n    limit: { type: 'integer' },\n  },\n  unfinalizedEntries: {\n    asOf: { type: 'date' },\n    olderThanDays: { type: 'integer' },\n    fiscalYear: { type: 'integer' },\n  },\n  // Takes no parameters: the description is a property of the software, not of a query.\n  personalDataDescription: {},\n  systemDescription: {},\n  auditTrailIntegrity: {},\n  // No parameters, and a date window in particular is refused on purpose: an invoice entered\n  // in December and again in January is the case this exists for, and any window on the\n  // voucher date hides it exactly at the boundary.\n  duplicateVouchers: {},\n  // Takes no parameters either, and the reason is the same shape: the chart is what it is. A\n  // filter would only save the caller a `filter()` while making \"which accounts exist\" a question\n  // with more than one answer.\n  accounts: {},\n  journal: {\n    fiscalYear: { type: 'integer', required: true },\n    fromDate: { type: 'date' },\n    toDate: { type: 'date' },\n    offset: { type: 'integer' },\n    limit: { type: 'integer' },\n  },\n  fiscalYears: {\n    fiscalYear: { type: 'integer' },\n  },\n  unappropriatedResult: {\n    fiscalYear: { type: 'integer' },\n  },\n  cashJournal: {\n    fiscalYear: { type: 'integer', required: true },\n  },\n  journalExport: {\n    fiscalYear: { type: 'integer', required: true },\n    format: { type: 'string' },\n  },\n  gdpduExport: {\n    fiscalYear: { type: 'integer' },\n    mediaName: { type: 'string' },\n  },\n  datevExport: {\n    kind: { type: 'string' },\n    fiscalYear: { type: 'integer' },\n    fromPeriod: { type: 'integer' },\n    throughPeriod: { type: 'integer' },\n  },\n  auditDataExport: {\n    fiscalYear: { type: 'integer', required: true },\n    asOf: { type: 'date' },\n  },\n  costAllocationSheet: {\n    runId: { type: 'string', required: true },\n    fiscalYear: { type: 'integer' },\n    period: { type: 'integer' },\n  },\n  costingRuns: {\n    fiscalYear: { type: 'integer' },\n    period: { type: 'integer' },\n  },\n  overheadRates: {\n    runId: { type: 'string', required: true },\n  },\n  productionCost: {\n    runId: { type: 'string', required: true },\n  },\n  // No parameters, and a fiscalYear filter would be actively wrong rather than merely absent: the\n  // question is whether the measurement basis changed ACROSS periods, so filtering to one period\n  // would hide the only answer worth having. duplicateVouchers refuses a date window on the same\n  // grounds. Which framework demands the comparison, and what it permits by way of exception, is\n  // the pack's business and the census's — not this table's.\n  measurementConsistency: {},\n  assetSchedule: {\n    fiscalYear: { type: 'integer', required: true },\n  },\n  deferralRegister: {\n    kind: { type: 'string' },\n    status: { type: 'string' },\n  },\n  provisionRegister: {\n    status: { type: 'string' },\n    asOf: { type: 'date' },\n  },\n  inventoryValuation: {\n    fiscalYear: { type: 'integer' },\n    period: { type: 'integer' },\n  },\n  // No parameters, for the third time and the same reason as systemDescription and accounts: a\n  // tenant has exactly one configuration. There is nothing to select, and a filter would turn\n  // \"what is this tenant set up as\" into a question with more than one answer.\n  tenantConfiguration: {},\n};\n\n/**\n * Checks a projection's params against the contract — once, at the dispatcher, instead of\n * 25 times inside the projections.\n *\n * Two rules, both about telling \"absent\" from \"wrong\":\n *   - a parameter that is not declared is a caller mistake, not something to ignore. Ignoring\n *     it turned a misspelled `fiscalYear` on vatReturn into a plausible ANNUAL figure where a\n *     quarter was asked for, and `includeZeroBalance` into a flag that did nothing.\n *   - a declared parameter present with the wrong type is rejected, never coerced. `2026.4` is\n *     not a year; whoever meant \"year 2026, period 4\" has to say which.\n * Absent keeps the documented default — that is not this function's business, it is the\n * reader's (`parameters.ts`).\n *\n * `null` counts as absent: JSON callers and CLI wrappers write an omitted parameter both ways,\n * and every projection has treated it as absent since long before this contract existed.\n */\nexport function validateProjectionParams(name: string, params: Record<string, unknown>): void {\n  const declared = PROJECTION_PARAMETERS[name];\n  // An unknown projection name is the dispatcher's own error (E_NOT_IMPLEMENTED); it must not\n  // be reported as an input problem on the way there.\n  if (declared === undefined) {\n    return;\n  }\n\n  for (const [key, value] of Object.entries(params)) {\n    const spec = declared[key];\n    if (spec === undefined) {\n      throw new DomainError('E_INPUT_INVALID', `${name}: unknown parameter \"${key}\"`, { parameter: key });\n    }\n    if (value === undefined || value === null) {\n      continue;\n    }\n    if (!matchesParameterType(value, spec.type)) {\n      throw new DomainError('E_INPUT_INVALID', `${name}: parameter \"${key}\" must be of type ${spec.type}`, {\n        [key]: rejectedValue(value),\n      });\n    }\n  }\n}\n","import { DomainError, rejectedValue } from '../domain-error.js';\nimport { matchesParameterType } from '../policies/projection/parameters.js';\nimport type { ParameterSpec } from './projection-parameters.js';\n\n/**\n * The input contract of the operations, as data — the write-side twin of\n * `PROJECTION_PARAMETERS` (F-9).\n *\n * The asymmetry this closes was the wrong way round for a long time. Every projection parameter\n * was declared and an undeclared one was `E_INPUT_INVALID` naming the parameter; `execute()` read\n * what it recognised out of the input and ignored the rest. So a typo in a *read* failed loudly\n * and a typo in a *write* was silent — and a write is the one that ends up in the books.\n *\n * Three defects had already come out of that silence: `expandTax` takes `date` where its\n * neighbours take `voucherDate`/`entryDate`, so the wrong name yielded a tax-version error naming\n * a field that was supplied; a wrong `direction` fell through to a default and booked an incoming\n * invoice inverted (IMPL-013, hardened by hand afterwards); and every numeric input was read with\n * a `typeof value === 'number'` check, so a form's `\"30\"` was not rejected but *ignored*, and the\n * documented default stood in its place.\n *\n * Same table, same source, same drift test as the projections: this is a hand-kept copy of\n * `testing/testsuite/schema/api-parameters.json` (the core reads no files by design) and\n * `operation-parameters.test.ts` asserts the two are equal, in both languages.\n *\n * **What it does not do: enforce `required`.** The flag is declared, and the check stays where it\n * is. An operation missing its subject already fails, and it fails with a better code than this\n * layer could give — `E_VOUCHER_UNKNOWN`, `E_ASSET_UNKNOWN`, `E_ENTRY_NO_VOUCHER` say what is\n * missing; a central `E_INPUT_INVALID` would say less and would overwrite error codes the fixtures\n * pin. The finding is about inputs that are *present and wrong*, and that is what this catches.\n */\nexport const OPERATION_PARAMETERS: Readonly<Record<string, Readonly<Record<string, ParameterSpec>>>> = {\n  post: {\n    voucherId: { type: 'string', required: true },\n    entryDate: { type: 'date', required: true },\n    lines: {\n      type: 'array',\n      required: true,\n      element: {\n        type: 'object',\n        fields: {\n          account: { type: 'string' },\n          side: { type: 'string' },\n          money: { type: 'money' },\n          dimensions: {\n            type: 'array',\n            element: {\n              type: 'object',\n              fields: {\n                type: { type: 'string' },\n                code: { type: 'string' },\n              },\n            },\n          },\n          taxTag: {\n            type: 'object',\n            fields: {\n              code: { type: 'string' },\n              appliedVersion: { type: 'string' },\n              reportingKey: { type: 'string' },\n              baseMoney: { type: 'money' },\n            },\n          },\n          openItem: { type: 'object', acceptedWithoutEffect: true, opaque: 'read by no implementation' },\n        },\n      },\n    },\n    text: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  postVoucher: {\n    voucher: {\n      type: 'object',\n      required: true,\n      fields: {\n        voucherNumber: { type: 'string' },\n        voucherDate: { type: 'date' },\n        serviceDate: { type: 'date' },\n        servicePeriod: { type: 'object', opaque: 'a from/to window the record stores whole' },\n        economicYear: { type: 'integer' },\n        due: { type: 'date' },\n        recurring: { type: 'boolean' },\n        issuer: { type: 'string' },\n        kind: { type: 'string' },\n        partnerId: { type: 'string' },\n        supplierTaxationMethod: { type: 'string' },\n      },\n    },\n    taxCode: { type: 'string' },\n    direction: { type: 'string' },\n    reduction: { type: 'boolean' },\n    netLines: {\n      type: 'array',\n      element: {\n        type: 'object',\n        fields: {\n          account: { type: 'string' },\n          money: { type: 'money' },\n          taxCode: { type: 'string' },\n          dimensions: {\n            type: 'array',\n            element: {\n              type: 'object',\n              fields: {\n                type: { type: 'string' },\n                code: { type: 'string' },\n              },\n            },\n          },\n        },\n      },\n    },\n    lines: {\n      type: 'array',\n      element: {\n        type: 'object',\n        fields: {\n          account: { type: 'string' },\n          side: { type: 'string' },\n          money: { type: 'money' },\n          dimensions: {\n            type: 'array',\n            element: {\n              type: 'object',\n              fields: {\n                type: { type: 'string' },\n                code: { type: 'string' },\n              },\n            },\n          },\n          taxTag: {\n            type: 'object',\n            fields: {\n              code: { type: 'string' },\n              appliedVersion: { type: 'string' },\n              reportingKey: { type: 'string' },\n              baseMoney: { type: 'money' },\n            },\n          },\n          openItem: { type: 'object', acceptedWithoutEffect: true, opaque: 'read by no implementation' },\n        },\n      },\n    },\n    counterAccount: { type: 'string' },\n    entryDate: { type: 'date' },\n    text: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  createVoucher: {\n    voucher: {\n      type: 'object',\n      required: true,\n      fields: {\n        voucherNumber: { type: 'string' },\n        voucherDate: { type: 'date' },\n        serviceDate: { type: 'date' },\n        servicePeriod: { type: 'object', opaque: 'a from/to window the record stores whole' },\n        economicYear: { type: 'integer' },\n        due: { type: 'date' },\n        recurring: { type: 'boolean' },\n        issuer: { type: 'string' },\n        kind: { type: 'string' },\n        partnerId: { type: 'string' },\n        supplierTaxationMethod: { type: 'string' },\n      },\n    },\n    actor: { type: 'string' },\n  },\n  correct: {\n    entryId: { type: 'string', required: true },\n    text: { type: 'string' },\n    lines: {\n      type: 'array',\n      element: {\n        type: 'object',\n        fields: {\n          account: { type: 'string' },\n          side: { type: 'string' },\n          money: { type: 'money' },\n          dimensions: {\n            type: 'array',\n            element: {\n              type: 'object',\n              fields: {\n                type: { type: 'string' },\n                code: { type: 'string' },\n              },\n            },\n          },\n          taxTag: {\n            type: 'object',\n            fields: {\n              code: { type: 'string' },\n              appliedVersion: { type: 'string' },\n              reportingKey: { type: 'string' },\n              baseMoney: { type: 'money' },\n            },\n          },\n          openItem: { type: 'object', acceptedWithoutEffect: true, opaque: 'read by no implementation' },\n        },\n      },\n    },\n    actor: { type: 'string' },\n  },\n  finalize: {\n    entryId: { type: 'string' },\n    finalizeUntil: { type: 'date' },\n    actor: { type: 'string' },\n  },\n  reverse: {\n    entryId: { type: 'string', required: true },\n    entryDate: { type: 'date', required: true },\n    text: { type: 'string' },\n    voucherId: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  settle: {\n    entryId: { type: 'string', required: true },\n    allocations: {\n      type: 'array',\n      required: true,\n      element: {\n        type: 'object',\n        fields: {\n          openItemId: { type: 'string' },\n          money: { type: 'money' },\n          difference: {\n            type: 'object',\n            fields: {\n              money: { type: 'money' },\n              kind: { type: 'string' },\n            },\n          },\n        },\n      },\n    },\n    actor: { type: 'string' },\n  },\n  createAccount: {\n    number: { type: 'string', required: true },\n    name: { type: 'string', required: true },\n    type: { type: 'string', required: true },\n    subtype: { type: 'string' },\n    status: { type: 'string' },\n    validFrom: { type: 'date' },\n    validTo: { type: 'date' },\n    actor: { type: 'string' },\n  },\n  lockAccount: {\n    number: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  unlockAccount: {\n    number: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  importChartOfAccounts: {\n    rows: {\n      type: 'array',\n      required: true,\n      element: {\n        type: 'object',\n        fields: {\n          number: { type: 'string' },\n          name: { type: 'string' },\n          type: { type: 'string' },\n          subtype: { type: 'string' },\n          status: { type: 'string' },\n          validFrom: { type: 'date' },\n          validTo: { type: 'date' },\n        },\n      },\n    },\n    format: { type: 'string', acceptedWithoutEffect: true },\n    actor: { type: 'string' },\n  },\n  defineDimensionType: {\n    code: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  defineDimensionValue: {\n    type: { type: 'string', required: true },\n    code: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  createFiscalYear: {\n    year: { type: 'integer', required: true },\n    start: { type: 'date', required: true },\n    end: { type: 'date', required: true },\n    actor: { type: 'string' },\n  },\n  closePeriod: {\n    fiscalYear: { type: 'integer', required: true },\n    period: { type: 'integer', required: true },\n    actor: { type: 'string' },\n  },\n  reopenPeriod: {\n    fiscalYear: { type: 'integer', required: true },\n    period: { type: 'integer', required: true },\n    actor: { type: 'string' },\n  },\n  closeFiscalYear: {\n    fiscalYear: { type: 'integer', required: true },\n    actor: { type: 'string' },\n  },\n  appropriateResult: {\n    fiscalYear: { type: 'integer', required: true },\n    entryDate: { type: 'date', required: true },\n    voucherId: { type: 'string', required: true },\n    text: { type: 'string' },\n    appropriations: {\n      type: 'array',\n      required: true,\n      element: {\n        type: 'object',\n        fields: {\n          target: { type: 'string' },\n          money: { type: 'money' },\n        },\n      },\n    },\n    actor: { type: 'string' },\n  },\n  expandTax: {\n    date: { type: 'date', required: true },\n    serviceDate: { type: 'date' },\n    direction: { type: 'string' },\n    reduction: { type: 'boolean' },\n    taxCode: { type: 'string' },\n    netLines: {\n      type: 'array',\n      required: true,\n      element: {\n        type: 'object',\n        fields: {\n          account: { type: 'string' },\n          money: { type: 'money' },\n          taxCode: { type: 'string' },\n          dimensions: {\n            type: 'array',\n            required: true,\n            element: {\n              type: 'object',\n              fields: {\n                type: { type: 'string' },\n                code: { type: 'string' },\n              },\n            },\n          },\n        },\n      },\n    },\n  },\n  setEntityProfile: {\n    legalForm: { type: 'string', required: true },\n    sizeClass: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  setTaxProfile: {\n    smallBusiness: {\n      type: 'object',\n      required: true,\n      fields: {\n        validFrom: { type: 'date' },\n        value: { type: 'boolean' },\n      },\n    },\n    reason: { type: 'string', acceptedWithoutEffect: true },\n    actor: { type: 'string' },\n  },\n  importMapping: {\n    mapping: { type: 'object', required: true, opaque: 'a whole mapping document; its shape is owned by format.schema.json, and declaring it twice would be the drift this contract exists to prevent' },\n    actor: { type: 'string' },\n  },\n  createPartner: {\n    name: { type: 'string', required: true },\n    kind: { type: 'string' },\n    vatId: { type: 'string' },\n    paymentTermsDays: { type: 'integer' },\n    accountNumbers: {\n      type: 'array',\n      element: { type: 'string' },\n    },\n    address: { type: 'object', opaque: 'free-form master data; the engine stores it whole and interprets no key of it' },\n    actor: { type: 'string' },\n  },\n  deactivatePartner: {\n    partnerId: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  reactivatePartner: {\n    partnerId: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  updatePartner: {\n    partnerId: { type: 'string', required: true },\n    name: { type: 'string' },\n    kind: { type: 'string' },\n    vatId: { type: 'string' },\n    paymentTermsDays: { type: 'integer' },\n    accountNumbers: {\n      type: 'array',\n      element: { type: 'string' },\n    },\n    address: { type: 'object', opaque: 'free-form master data; the engine stores it whole and interprets no key of it' },\n    actor: { type: 'string' },\n  },\n  erasePartner: {\n    partnerId: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  acquireAsset: {\n    name: { type: 'string' },\n    assetClass: { type: 'string' },\n    assetAccount: { type: 'string', required: true },\n    acquisitionCost: { type: 'money', required: true },\n    acquiredOn: { type: 'date', required: true },\n    voucherId: { type: 'string', required: true },\n    gwgChoice: { type: 'string' },\n    usefulLifeMonths: { type: 'integer' },\n    depreciationMethod: { type: 'string' },\n    dimensions: {\n      type: 'array',\n      element: {\n        type: 'object',\n        fields: {\n          type: { type: 'string' },\n          code: { type: 'string' },\n        },\n      },\n    },\n    specialDepreciation: { type: 'boolean' },\n    totalUnits: { type: 'integer' },\n    actor: { type: 'string' },\n  },\n  disposeAsset: {\n    assetId: { type: 'string', required: true },\n    disposedOn: { type: 'date', required: true },\n    proceeds: { type: 'money' },\n    proceedsAccount: { type: 'string' },\n    bankAccount: { type: 'string' },\n    voucherId: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  runDepreciation: {\n    fiscalYear: { type: 'integer', required: true },\n    period: { type: 'integer' },\n    actor: { type: 'string' },\n  },\n  adjustInputTax: {\n    originalInputTax: { type: 'money', required: true },\n    originalSharePercent: { type: 'string', required: true },\n    currentSharePercent: { type: 'string', required: true },\n    assetKind: { type: 'string', required: true },\n    reason: { type: 'string', required: true },\n    date: { type: 'date', required: true },\n    actor: { type: 'string' },\n  },\n  recognizeDeferral: {\n    kind: { type: 'string', required: true },\n    reason: { type: 'string', required: true },\n    counterAccount: { type: 'string', required: true },\n    amount: { type: 'money', required: true },\n    recognizedOn: { type: 'date', required: true },\n    firstFiscalYear: { type: 'integer', required: true },\n    firstPeriod: { type: 'integer', required: true },\n    periods: { type: 'integer', required: true },\n    actor: { type: 'string' },\n  },\n  runDeferralRelease: {\n    fiscalYear: { type: 'integer', required: true },\n    period: { type: 'integer', required: true },\n    actor: { type: 'string' },\n  },\n  recognizeProvision: {\n    account: { type: 'string', required: true },\n    reason: { type: 'string', required: true },\n    amount: { type: 'money', required: true },\n    recognizedOn: { type: 'date', required: true },\n    dueDate: { type: 'date' },\n    discountRate: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  useProvision: {\n    provisionId: { type: 'string', required: true },\n    amount: { type: 'money', required: true },\n    settlementAccount: { type: 'string', required: true },\n    date: { type: 'date', required: true },\n    actor: { type: 'string' },\n  },\n  releaseProvision: {\n    provisionId: { type: 'string', required: true },\n    amount: { type: 'money' },\n    date: { type: 'date', required: true },\n    actor: { type: 'string' },\n  },\n  remeasureProvision: {\n    provisionId: { type: 'string', required: true },\n    amount: { type: 'money', required: true },\n    date: { type: 'date', required: true },\n    discountRate: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  valuateInventory: {\n    fiscalYear: { type: 'integer', required: true },\n    period: { type: 'integer', required: true },\n    valuationDate: { type: 'date', required: true },\n    runId: { type: 'string' },\n    producedQuantity: { type: 'string' },\n    categories: {\n      type: 'array',\n      required: true,\n      element: {\n        type: 'object',\n        fields: {\n          account: { type: 'string' },\n          quantity: { type: 'string' },\n          unitCost: { type: 'string' },\n          marketValue: { type: 'string' },\n        },\n      },\n    },\n    actor: { type: 'string' },\n  },\n  reportAssetUsage: {\n    assetId: { type: 'string', required: true },\n    fiscalYear: { type: 'integer', required: true },\n    units: { type: 'integer', required: true },\n    voucherId: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  bookSpecialDepreciation: {\n    assetId: { type: 'string', required: true },\n    fiscalYear: { type: 'integer', required: true },\n    amount: { type: 'money', required: true },\n    voucherId: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  writeDownAsset: {\n    assetId: { type: 'string', required: true },\n    amount: { type: 'money', required: true },\n    date: { type: 'date', required: true },\n    reason: { type: 'string', required: true },\n    voucherId: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  writeUpAsset: {\n    assetId: { type: 'string', required: true },\n    amount: { type: 'money', required: true },\n    date: { type: 'date', required: true },\n    reason: { type: 'string', required: true },\n    voucherId: { type: 'string' },\n    actor: { type: 'string' },\n  },\n  setAllocationScheme: {\n    method: { type: 'string' },\n    steps: {\n      type: 'array',\n      element: {\n        type: 'object',\n        fields: {\n          sender: { type: 'string' },\n          receivers: {\n            type: 'array',\n            element: {\n              type: 'object',\n              fields: {\n                code: { type: 'string' },\n                share: { type: 'string' },\n              },\n            },\n          },\n        },\n      },\n    },\n    rates: {\n      type: 'array',\n      element: {\n        type: 'object',\n        fields: {\n          costCenter: { type: 'string' },\n          label: { type: 'string' },\n          base: {\n            type: 'object',\n            fields: {\n              accounts: {\n                type: 'array',\n                element: { type: 'string' },\n              },\n              costCenters: {\n                type: 'array',\n                element: { type: 'string' },\n              },\n            },\n          },\n        },\n      },\n    },\n    productionCost: {\n      type: 'object',\n      fields: {\n        include: {\n          type: 'array',\n          element: { type: 'string' },\n        },\n        components: {\n          type: 'array',\n          element: {\n            type: 'object',\n            fields: {\n              id: { type: 'string' },\n              base: {\n                type: 'object',\n                fields: {\n                  accounts: {\n                    type: 'array',\n                    element: { type: 'string' },\n                  },\n                  costCenters: {\n                    type: 'array',\n                    element: { type: 'string' },\n                  },\n                },\n              },\n            },\n          },\n        },\n      },\n    },\n    actor: { type: 'string' },\n  },\n  runCosting: {\n    fiscalYear: { type: 'integer', required: true },\n    period: { type: 'integer', required: true },\n    actor: { type: 'string' },\n  },\n  releaseCosting: {\n    runId: { type: 'string', required: true },\n    actor: { type: 'string' },\n  },\n  allocate: {\n    total: { type: 'money', required: true },\n    weights: {\n      type: 'array',\n      required: true,\n      element: { type: 'string' },\n    },\n  },\n};\n\n/**\n * Checks an operation's input against the contract — once, at the dispatcher, instead of inside\n * 31 handlers.\n *\n * The rules are the projections' rules, deliberately: an undeclared key is a caller mistake\n * rather than something to ignore, and a declared key present with the wrong type is rejected\n * rather than coerced. `null` counts as absent, because JSON callers and CLI wrappers write an\n * omitted input both ways and every handler has read it that way since long before this existed.\n *\n * An operation the table does not know is left alone: an unknown name is the dispatcher's own\n * error (`E_NOT_IMPLEMENTED`) and must not be reported as an input problem on the way there.\n * `operation-parameters.test.ts` holds the table's key set against `API_OPERATIONS`, so \"not\n * known here\" cannot quietly mean \"not checked\".\n */\nexport function validateOperationInput(op: string, input: Record<string, unknown>): void {\n  const declared = OPERATION_PARAMETERS[op];\n  if (declared === undefined) {\n    return;\n  }\n\n  validateFields(op, input, declared, '');\n}\n\n/**\n * The two rules, applied to one level of a structure.\n *\n * They are the same two the outer level has always had — an undeclared key is a caller mistake, a\n * declared key of the wrong type is rejected rather than coerced — and applying them at every\n * declared depth is the whole of SPEC-017. Requiredness is deliberately NOT checked here: it stays\n * with the operation, whose own error says more than a generic one (`post` refuses a line without\n * an account with its own code, naming the line).\n */\nfunction validateFields(\n  op: string,\n  value: Record<string, unknown>,\n  fields: Readonly<Record<string, ParameterSpec>>,\n  path: string,\n): void {\n  for (const [key, item] of Object.entries(value)) {\n    const spec = fields[key];\n    const here = path === '' ? key : `${path}.${key}`;\n\n    if (spec === undefined) {\n      throw new DomainError('E_INPUT_INVALID', `${op}: unknown input \"${here}\"`, { input: here });\n    }\n    if (item === undefined || item === null) {\n      continue;\n    }\n\n    validateValue(op, item, spec, here);\n  }\n}\n\n/**\n * One declared value: its type, and — where the declaration goes deeper — what is inside it.\n *\n * The recursion stops where the declaration stops, which is what makes this durable rather than\n * \"one level deeper\". `opaque` is the same statement with a reason attached, for a structure\n * another schema owns.\n */\nfunction validateValue(op: string, value: unknown, spec: ParameterSpec, path: string): void {\n  if (!matchesParameterType(value, spec.type)) {\n    throw new DomainError('E_INPUT_INVALID', `${op}: input \"${path}\" must be of type ${spec.type}`, {\n      [path]: rejectedValue(value),\n    });\n  }\n\n  if (spec.opaque !== undefined) return;\n\n  if (spec.type === 'object' && spec.fields !== undefined && isRecord(value)) {\n    validateFields(op, value, spec.fields, path);\n    return;\n  }\n\n  if (spec.type === 'array' && spec.element !== undefined && Array.isArray(value)) {\n    const element = spec.element;\n    value.forEach((item, index) => {\n      if (item === undefined || item === null) return;\n      validateValue(op, item, element, `${path}[${index}]`);\n    });\n  }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n","import { DomainError } from '../domain-error.js';\nimport { Money } from '../substrate/money.js';\nimport { AssetRegisterProjection } from '../policies/projection/asset-register.js';\nimport { AssetScheduleProjection } from '../policies/projection/asset-schedule.js';\nimport { AuditWriter } from '../ledger/audit-writer.js';\nimport { AuditDataExportProjection } from '../policies/projection/audit-data-export.js';\nimport { MappingImporter } from '../policies/projection/mapping/mapping-importer.js';\nimport { AccountSheetProjection } from '../policies/projection/account-sheet.js';\nimport { GdpduExportProjection } from '../policies/projection/gdpdu-export.js';\nimport { AuditTrailIntegrityProjection } from '../policies/projection/audit-trail-integrity.js';\nimport { AuditLogProjection } from '../policies/projection/audit-log.js';\nimport { CashJournalProjection } from '../policies/projection/cash-journal.js';\nimport { CostingRunsProjection } from '../policies/projection/costing-runs.js';\nimport { MeasurementConsistencyProjection } from '../policies/projection/measurement-consistency.js';\nimport { PersonalDataDescriptionProjection } from '../policies/projection/personal-data-description.js';\nimport { SystemDescriptionProjection } from '../policies/projection/system-description.js';\nimport { TenantConfigurationProjection } from '../policies/projection/tenant-configuration.js';\nimport { UnfinalizedEntriesProjection } from '../policies/projection/unfinalized-entries.js';\nimport { BalanceSheetProjection } from '../policies/projection/balance-sheet.js';\nimport { CashBasisProjection } from '../policies/projection/cash-basis.js';\nimport { DatevExportProjection } from '../policies/projection/datev-export.js';\nimport { DuplicateVouchersProjection } from '../policies/projection/duplicate-vouchers.js';\nimport { JournalExportProjection } from '../policies/projection/journal-export.js';\nimport { IncomeStatementProjection } from '../policies/projection/income-statement.js';\nimport { EcSalesListProjection } from '../policies/projection/ec-sales-list.js';\nimport { OpenItemsProjection } from '../policies/projection/open-items.js';\nimport { AccountsProjection } from '../policies/projection/accounts.js';\nimport { FiscalYearsProjection } from '../policies/projection/fiscal-years.js';\nimport { UnappropriatedResult, UnappropriatedResultProjection } from '../policies/projection/unappropriated-result.js';\nimport { JournalProjection } from '../policies/projection/journal.js';\nimport { TrialBalanceProjection } from '../policies/projection/trial-balance.js';\nimport { VatReturnProjection } from '../policies/projection/vat-return.js';\nimport { PostVoucherService } from './post-voucher-service.js';\nimport { validateProjectionParams } from './projection-parameters.js';\nimport { validateOperationInput } from './operation-parameters.js';\nimport type { Tenant } from './tenant.js';\n\n/** Plain-JSON serialization via toJSON() (like PHP's json_encode/decode). */\nfunction serialize(value: unknown): Record<string, unknown> {\n  return JSON.parse(JSON.stringify(value)) as Record<string, unknown>;\n}\n\n/**\n * Generic entry into all operations and projections of a tenant —\n * the interface for CLI and conformance runner. Names exactly per api.md.\n * Grows with the slices; the unimplemented reports E_NOT_IMPLEMENTED.\n */\nexport class TenantOperations {\n  constructor(private readonly tenant: Tenant) {}\n\n  execute(op: string, input: Record<string, unknown>): Record<string, unknown> {\n    // The input contract is checked here, before routing: one place instead of one check per\n    // handler, and the same place in both languages — the mirror of what `project()` does below.\n    // An operation below therefore reads inputs that are either absent or of the declared type.\n    validateOperationInput(op, input);\n\n    const ledger = this.tenant.ledger;\n\n    switch (op) {\n      case 'expandTax':\n        return this.tenant.tax.expand(input);\n      case 'setTaxProfile':\n        return serialize(this.tenant.tax.setProfile(input));\n      case 'postVoucher':\n        return new PostVoucherService(this.tenant).post(input);\n      case 'createVoucher':\n        return new PostVoucherService(this.tenant).createVoucher(input);\n      case 'post': {\n        const result = ledger.post(input);\n        return {\n          ...serialize(result.entry),\n          openItemsCreated: result.openItemsCreated.map((item) => serialize(item)),\n        };\n      }\n      case 'correct':\n        return serialize(ledger.correct(input));\n      case 'settle':\n        return { openItems: ledger.settle(input).map((item) => serialize(item)) };\n      case 'finalize':\n        return { finalizedCount: ledger.finalize(input) };\n      case 'reverse':\n        return serialize(ledger.reverse(input));\n      case 'closePeriod':\n        return ledger.closePeriod(input);\n      case 'reopenPeriod':\n        return ledger.reopenPeriod(input);\n      case 'closeFiscalYear':\n        return { fiscalYear: ledger.closeFiscalYear(input).year, status: 'closed' };\n      case 'appropriateResult':\n        return this.tenant.resultAppropriation.appropriate(input);\n      case 'setEntityProfile': {\n        const service = this.tenant.entityProfile;\n        if (service === null) throw new DomainError('E_NOT_IMPLEMENTED', 'Operation \"setEntityProfile\" is not defined');\n        return service.set(input);\n      }\n      case 'createAccount':\n        return serialize(ledger.createAccount(input));\n      case 'defineDimensionType':\n        return ledger.defineDimensionType(input);\n      case 'defineDimensionValue':\n        return ledger.defineDimensionValue(input);\n      case 'createFiscalYear': {\n        const fiscalYear = ledger.createFiscalYear(input);\n        return { year: fiscalYear.year, periodCount: fiscalYear.periods().length };\n      }\n      case 'lockAccount':\n        return serialize(ledger.lockAccount(input));\n      case 'unlockAccount':\n        return serialize(ledger.unlockAccount(input));\n      case 'importChartOfAccounts':\n        return { importedCount: ledger.importChartOfAccounts(input) };\n      case 'importMapping':\n        return new MappingImporter(\n          this.tenant.accounts,\n          this.tenant.mappings,\n          this.tenant.id,\n          new AuditWriter(this.tenant.audit, this.tenant.clock, this.tenant.ids),\n          this.tenant.configStore,\n        ).import(input);\n      case 'createPartner':\n        return serialize(this.tenant.partnerService.create(input));\n      case 'deactivatePartner':\n        return serialize(this.tenant.partnerService.setStatus(input, 'inactive'));\n      case 'reactivatePartner':\n        return serialize(this.tenant.partnerService.setStatus(input, 'active'));\n      case 'updatePartner':\n        return serialize(this.tenant.partnerService.update(input));\n      case 'erasePartner':\n        return this.tenant.partnerService.erase(input);\n      case 'acquireAsset':\n        return this.tenant.assetService.acquire(input);\n      case 'disposeAsset':\n        return this.tenant.assetService.dispose(input);\n      case 'reportAssetUsage':\n        return this.tenant.assetService.reportAssetUsage(input);\n      case 'bookSpecialDepreciation':\n        return this.tenant.assetService.bookSpecialDepreciation(input);\n      case 'writeDownAsset':\n        return this.tenant.assetService.writeDownAsset(input);\n      case 'writeUpAsset':\n        return this.tenant.assetService.writeUpAsset(input);\n      case 'runDepreciation':\n        return this.tenant.assetService.runDepreciation(input);\n      case 'valuateInventory':\n        return this.tenant.inventory.valuate(input);\n      case 'recognizeProvision':\n        return this.tenant.provisionService.recognize(input);\n      case 'useProvision':\n        return this.tenant.provisionService.use(input);\n      case 'releaseProvision':\n        return this.tenant.provisionService.release(input);\n      case 'remeasureProvision':\n        return this.tenant.provisionService.remeasure(input);\n      case 'recognizeDeferral':\n        return this.tenant.deferralService.recognize(input);\n      case 'runDeferralRelease':\n        return this.tenant.deferralService.runRelease(input);\n      case 'adjustInputTax':\n        return this.tenant.inputTaxAdjustment.adjust(input);\n      case 'allocate': {\n        // Largest-remainder distribution (Money.allocate), scale from the tenant currency\n        // (pack parameter currencyScale). Pure computation, no journal effect.\n        const totalRaw = input.total;\n        const amount =\n          totalRaw !== null && typeof totalRaw === 'object' && !Array.isArray(totalRaw)\n            ? (totalRaw as Record<string, unknown>).amount\n            : null;\n        const total = Money.of(typeof amount === 'string' ? amount : '', this.tenant.baseCurrency);\n        const weights = Array.isArray(input.weights) ? (input.weights as Array<number | string>) : [];\n        const parts = total.allocate(...weights);\n        return { parts: parts.map((part) => part.toJSON()), total: total.toJSON() };\n      }\n      case 'setAllocationScheme':\n        return this.tenant.costing.setAllocationScheme(input);\n      case 'runCosting': {\n        const run = this.tenant.costing.run(input);\n        return { runId: run.id.value, status: run.status(), version: run.version };\n      }\n      case 'releaseCosting': {\n        const released = this.tenant.costing.release(input);\n        return { runId: released.id.value, status: released.status() };\n      }\n      default:\n        throw new DomainError('E_NOT_IMPLEMENTED', `Operation \"${op}\" is not defined`);\n    }\n  }\n\n  project(name: string, params: Record<string, unknown>): Record<string, unknown> {\n    const tenant = this.tenant;\n\n    // The parameter contract is checked here, before routing: one place instead of one check\n    // per projection, and the same place in both languages. Projections below therefore read\n    // parameters that are either absent or of the declared type.\n    validateProjectionParams(name, params);\n\n    switch (name) {\n      case 'trialBalance':\n        return new TrialBalanceProjection(tenant.baseCurrency, tenant.accounts, tenant.journal).compute(params);\n      case 'openItems':\n        return new OpenItemsProjection(\n          tenant.openItems,\n          tenant.vouchers,\n          tenant.journal,\n          tenant.partners,\n        ).compute(params);\n      case 'accounts':\n        return new AccountsProjection(tenant.accounts).compute(params);\n      case 'journal':\n        return new JournalProjection(tenant.accounts, tenant.journal, tenant.vouchers, tenant.audit).compute(params);\n      case 'fiscalYears':\n        return new FiscalYearsProjection(tenant.fiscalYears).compute(params);\n      case 'unappropriatedResult':\n        return new UnappropriatedResultProjection(\n          new UnappropriatedResult(tenant.baseCurrency, tenant.accounts, tenant.journal),\n          tenant.fiscalYears,\n          tenant.legalForms,\n        ).compute(params);\n      case 'accountSheet':\n        return new AccountSheetProjection(tenant.baseCurrency, tenant.accounts, tenant.journal).compute(params);\n      case 'auditLog':\n        return new AuditLogProjection(tenant.audit).compute(params);\n      case 'unfinalizedEntries':\n        return new UnfinalizedEntriesProjection(tenant.journal, tenant.clock, tenant.audit).compute(params);\n      case 'personalDataDescription':\n        return new PersonalDataDescriptionProjection(\n          tenant.partners,\n          tenant.vouchers,\n          tenant.audit,\n          tenant.assets,\n          tenant.provisions,\n          tenant.deferrals,\n        ).compute(params);\n      case 'auditTrailIntegrity':\n        return new AuditTrailIntegrityProjection(tenant.audit).run();\n      case 'duplicateVouchers':\n        return new DuplicateVouchersProjection(\n          tenant.baseCurrency,\n          tenant.vouchers,\n          tenant.journal,\n          tenant.partners,\n        ).compute();\n      case 'systemDescription':\n        return new SystemDescriptionProjection(\n          tenant.id,\n          tenant.name,\n          tenant.baseCurrency,\n          tenant.packIdentity,\n          tenant.tax.profile().toJSON(),\n          tenant.actorAuthentication,\n        ).compute(params);\n      case 'tenantConfiguration':\n        return new TenantConfigurationProjection(\n          tenant.tax.profile().toJSON(),\n          tenant.ledger.dimensionRegistry(),\n          tenant.costing.allocationScheme(),\n          tenant.mappings,\n          tenant.resultAppropriation.offeredTargets(),\n          tenant.legalForms.declared(),\n          tenant.legalForms.offered(),\n          tenant.legalForms.offeredSizeClasses(),\n          tenant.ledger.combinationRegistry(),\n        ).compute(params);\n      case 'costingRuns':\n        return new CostingRunsProjection(tenant.costingRuns).compute(params);\n      case 'cashJournal':\n        return new CashJournalProjection(tenant.baseCurrency, tenant.accounts, tenant.journal).compute(params);\n      case 'assetRegister':\n        return new AssetRegisterProjection(tenant.assets).compute(params);\n      case 'assetSchedule':\n        return new AssetScheduleProjection(tenant.baseCurrency, tenant.assets).compute(params);\n      case 'costAllocationSheet':\n        return tenant.costing.costAllocationSheet(params);\n      case 'overheadRates':\n        return tenant.costing.overheadRates(params);\n      case 'productionCost':\n        return tenant.costing.productionCost(params);\n      case 'measurementConsistency':\n        return new MeasurementConsistencyProjection(tenant.costingRuns).compute(params);\n      case 'inventoryValuation':\n        return tenant.inventory.valuationReport(params);\n      case 'provisionRegister':\n        return tenant.provisionService.register(params);\n      case 'deferralRegister':\n        return tenant.deferralService.register(params);\n      case 'ecSalesList':\n        return new EcSalesListProjection(\n          tenant.baseCurrency,\n          tenant.journal,\n          tenant.vouchers,\n          tenant.partners,\n          tenant.tax.registryHandle(),\n        ).compute(params);\n      case 'incomeStatement':\n        return new IncomeStatementProjection(\n          tenant.baseCurrency,\n          tenant.accounts,\n          tenant.journal,\n          tenant.mappings,\n        ).compute(params);\n      case 'balanceSheet':\n        return new BalanceSheetProjection(\n          tenant.baseCurrency,\n          tenant.accounts,\n          tenant.journal,\n          tenant.mappings,\n        ).compute(params);\n      case 'vatReturn':\n        return new VatReturnProjection(\n          tenant.baseCurrency,\n          tenant.journal,\n          tenant.openItems,\n          tenant.vouchers,\n          tenant.accounts,\n          tenant.tax.registryHandle(),\n          tenant.tax.profile(),\n        ).compute(params);\n      case 'cashBasisReport':\n        return new CashBasisProjection(\n          tenant.baseCurrency,\n          tenant.accounts,\n          tenant.journal,\n          tenant.openItems,\n          tenant.vouchers,\n          tenant.fiscalYears,\n          tenant.mappings,\n        ).compute(params);\n      case 'gdpduExport':\n        return new GdpduExportProjection(\n          tenant.id,\n          tenant.name,\n          tenant.baseCurrency,\n          tenant.journal,\n          tenant.accounts,\n          tenant.vouchers,\n          tenant.partners,\n          tenant.audit,\n          tenant.clock,\n        ).compute(params);\n      case 'journalExport':\n        return new JournalExportProjection(\n          tenant.id,\n          tenant.name,\n          tenant.baseCurrency,\n          tenant.journal,\n          tenant.accounts,\n          tenant.vouchers,\n          tenant.partners,\n          tenant.audit,\n          tenant.clock,\n        ).compute(params);\n      case 'datevExport':\n        return new DatevExportProjection(\n          tenant.journal,\n          tenant.accounts,\n          tenant.vouchers,\n          tenant.partners,\n          tenant.tax.registryHandle(),\n        ).compute(params);\n      case 'auditDataExport':\n        return new AuditDataExportProjection(\n          tenant.baseCurrency,\n          tenant.journal,\n          tenant.accounts,\n          tenant.vouchers,\n        ).compute(params);\n      default:\n        throw new DomainError('E_NOT_IMPLEMENTED', `Projection \"${name}\" is not defined`);\n    }\n  }\n}\n","import { DomainError } from '../domain-error.js';\nimport { Account } from '../substrate/account.js';\nimport { FiscalYear } from '../substrate/fiscal-year.js';\nimport { isAccountType } from '../substrate/types.js';\nimport { MappingRegistry } from '../policies/projection/mapping/mapping-registry.js';\nimport { AccountNumber } from '../substrate/account-number.js';\nimport { CalendarDate } from '../substrate/calendar-date.js';\nimport type { Clock } from '../substrate/clock.js';\nimport { Currency } from '../substrate/currency.js';\nimport type { IdGenerator } from '../substrate/id-generator.js';\nimport { TaxCodeRegistry } from '../policies/expansion/tax/tax-code-registry.js';\nimport { TaxProfile } from '../policies/expansion/tax/tax-profile.js';\nimport {\n  AccountCombinationRegistry,\n  type AccountCombinationRuleData,\n  type AccountUsageRuleData,\n} from '../policies/constraint/account-combination-registry.js';\nimport { DimensionRegistry, type DimensionRuleData } from '../policies/constraint/dimension-registry.js';\nimport { Tenant } from './tenant.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/**\n * `createTenant` (SF-01): create a tenant from a profile — immediately postable. Profiles\n * are versioned rule-module data; the tenant pins the version.\n */\nexport class TenantFactory {\n  constructor(\n    private readonly ruleModules: Record<string, unknown>,\n    private readonly clock: Clock,\n    private readonly ids: IdGenerator,\n  ) {}\n\n  create(input: Record<string, unknown>): { tenant: Tenant; result: Record<string, unknown> } {\n    const profileId = asString(input.profile) ?? '';\n    const profile = this.findById('profiles', profileId);\n    if (profile === null) {\n      throw new DomainError('E_PROFILE_UNKNOWN', `Profile \"${profileId}\" does not exist`);\n    }\n\n    const coaId = asString(profile.chartOfAccounts) ?? '';\n    const coa = this.findById('chartsOfAccounts', coaId);\n    if (coa === null) {\n      throw new DomainError('E_PROFILE_UNKNOWN', `Chart of accounts \"${coaId}\" of the profile is missing`);\n    }\n\n    const wantedCodes = Array.isArray(profile.taxCodes) ? profile.taxCodes : [];\n    const allTaxCodes = Array.isArray(this.ruleModules.taxCodes) ? this.ruleModules.taxCodes : [];\n    const taxCodeData = allTaxCodes.filter(\n      (code): code is Record<string, unknown> => isRecord(code) && wantedCodes.includes(code.code),\n    );\n\n    const defaults = isRecord(profile.defaults) ? profile.defaults : {};\n    // Which filing windows exist is the pack's answer, not the substrate's (SPEC-016). A pack that\n    // says nothing gets the substrate's default; one that says something replaces it.\n    const policy = isRecord(this.ruleModules.packPolicy) ? this.ruleModules.packPolicy : null;\n    const vatPeriods = Array.isArray(policy?.vatPeriods)\n      ? policy.vatPeriods.filter((value): value is string => typeof value === 'string')\n      : null;\n    const taxProfile = TaxProfile.fromData(defaults, vatPeriods);\n\n    // packPolicy.currencyScale is a pack parameter: it sets the tenant's money scale\n    // (jurisdiction-free), not the global ISO default scale.\n    const packPolicy = isRecord(this.ruleModules.packPolicy) ? this.ruleModules.packPolicy : null;\n    const currencyScale =\n      packPolicy !== null && typeof packPolicy.currencyScale === 'number' ? packPolicy.currencyScale : undefined;\n    const taxRoundingGranularity =\n      packPolicy !== null && typeof packPolicy.taxRoundingGranularity === 'string'\n        ? packPolicy.taxRoundingGranularity\n        : undefined;\n\n    // Mappings (balance sheet/P&L/cash-basis) from the resolved pack into the tenant's registry —\n    // otherwise balanceSheet/incomeStatement do not find the mappings (pack-path parity with the inline path).\n    const mappings = MappingRegistry.fromRuleModules(\n      Array.isArray(this.ruleModules.mappings) ? this.ruleModules.mappings : [],\n    );\n\n    // Constraint plugs from the pack. Types and values stay the tenant's own master data\n    // (defineDimensionType/Value) — a jurisdiction has no opinion about what a company calls its cost\n    // centres — but WHICH ACCOUNTS MAY NOT BE POSTED WITHOUT ONE is a rule a pack can hold, and until\n    // now no pack could: the registry was built with nothing at all.\n    const dimensionRules = (Array.isArray(this.ruleModules.dimensionRules) ? this.ruleModules.dimensionRules : [])\n      .filter((rule): rule is DimensionRuleData => isRecord(rule));\n    // The socket's second predicate (F-CORE-042) — which accounts may not, or must not, meet in one\n    // entry. Threaded exactly like the first: pack data in, registry out, nothing law-shaped here.\n    const accountCombinationRules = (Array.isArray(this.ruleModules.accountCombinationRules) ? this.ruleModules.accountCombinationRules : [])\n      .filter((rule): rule is AccountCombinationRuleData => isRecord(rule));\n    // The socket's third word (F-CORE-047) — accounts this tenant may not touch at all, optionally\n    // conditioned on a tenant fact. Threaded the same way; the condition is evaluated at posting.\n    const accountUsageRules = (Array.isArray(this.ruleModules.accountUsageRules) ? this.ruleModules.accountUsageRules : [])\n      .filter((rule): rule is AccountUsageRuleData => isRecord(rule));\n\n    const tenant = Tenant.inMemory(\n      asString(input.name) ?? 'Tenant',\n      Currency.of(asString(input.baseCurrency) ?? 'EUR', currencyScale),\n      this.clock,\n      this.ids,\n      DimensionRegistry.fromData([], [], dimensionRules),\n      TaxCodeRegistry.fromData(taxCodeData),\n      taxProfile,\n      mappings,\n      taxRoundingGranularity,\n      this.packIdentity(),\n      null,\n      AccountCombinationRegistry.fromData(accountCombinationRules, accountUsageRules),\n    );\n\n    let accountCount = 0;\n    for (const accountData of Array.isArray(coa.accounts) ? coa.accounts : []) {\n      if (!isRecord(accountData)) continue;\n      const type = accountData.type;\n      if (!isAccountType(type)) continue;\n      tenant.accounts.add(\n        new Account(\n          tenant.ids.next(),\n          AccountNumber.of(asString(accountData.number) ?? ''),\n          asString(accountData.name) ?? '',\n          type,\n          asString(accountData.subtype),\n          'active',\n        ),\n      );\n      accountCount++;\n    }\n\n    const year = typeof input.firstFiscalYear === 'number' ? input.firstFiscalYear : 0;\n    if (year > 0) {\n      const y = String(year).padStart(4, '0');\n      tenant.fiscalYears.add(\n        FiscalYear.create(tenant.ids.next(), year, CalendarDate.of(`${y}-01-01`), CalendarDate.of(`${y}-12-31`)),\n      );\n    }\n\n    // Asset/depreciation rules from the pack (assetAccounts, depreciation) — parity with the inline path.\n    tenant.assetService.setRuleModule(this.ruleModules);\n    // And the same for costing: the pack decides which components may enter production cost.\n    tenant.costing.setRuleModule(this.ruleModules);\n    // And the appropriation plug: which account a resolution books against, and which targets exist.\n    tenant.resultAppropriation.setRuleModule(this.ruleModules);\n    // And the legal-form catalogue: which forms this jurisdiction knows, and what each one obliges.\n    tenant.legalForms.setRuleModule(this.ruleModules);\n    tenant.inventory.setRuleModule(this.ruleModules);\n    tenant.provisionService.setRuleModule(this.ruleModules);\n    tenant.deferralService.setRuleModule(this.ruleModules);\n    tenant.inputTaxAdjustment.setRuleModule(this.ruleModules);\n\n    return {\n      tenant,\n      result: {\n        id: tenant.id.value,\n        name: tenant.name,\n        profile: { id: profileId, version: asString(profile.version) ?? '' },\n        accountCount,\n        taxationMethod: taxProfile.taxationMethod(),\n      },\n    };\n  }\n\n  /**\n   * The pack the resolved bundle came from, when it came from one. An inline bundle has no\n   * manifest, so there is nothing to name and the description says so rather than guessing.\n   */\n  private packIdentity(): { id: string; version: string } | null {\n    const pack = isRecord(this.ruleModules.pack) ? this.ruleModules.pack : null;\n    if (pack === null) return null;\n    const id = asString(pack.id);\n    const version = asString(pack.version);\n    return id !== null && version !== null ? { id, version } : null;\n  }\n\n  private findById(module: string, id: string): Record<string, unknown> | null {\n    const list = Array.isArray(this.ruleModules[module]) ? (this.ruleModules[module] as unknown[]) : [];\n    for (const candidate of list) {\n      if (isRecord(candidate) && candidate.id === id) return candidate;\n    }\n    return null;\n  }\n}\n","import { createHash } from 'node:crypto';\nimport { DomainError } from '../domain-error.js';\nimport { mechanismFor } from '../policies/expansion/tax/tax-mechanisms.js';\nimport { TaxProfile } from '../policies/expansion/tax/tax-profile.js';\nimport { canonicalJson } from '../substrate/canonical-json.js';\nimport { ACCOUNT_SUBTYPES, isAccountSubtype } from '../substrate/types.js';\n\n/**\n * Pack resolver (`resolvePack`) — pure, side-effect-free resolution of a\n * manifest against a module store into a `ResolvedPack`. Design:\n * `_bauflow-pack-gate01/design/module-manifest-resolver.md` (§ 3 resolver semantics,\n * § 4 ResolvedPack == TenantFactory's ruleModules bundle).\n *\n * Guiding principle: no new engine capability. The resolver invents nothing; it selects,\n * checks and folds existing module data into exactly the structure that `TenantFactory`\n * today consumes hand-fed. Fails **loudly** (exactly one `E_PACK_*`/`E_POLICY_*`)\n * instead of silently computing wrong.\n *\n * Error classes (§ 3.2): `E_PACK_UNRESOLVED_REF` = a reference points to nothing;\n * `E_PACK_INCOHERENT` = references exist, but the bundle is contradictory;\n * `E_POLICY_INVALID` = policy value/copy wrong. Reference existence (step 2/3) takes\n * precedence over coherence/integrity (4/5).\n */\n\nconst MODULE_KINDS = ['accounts', 'tax', 'mapping', 'depreciation', 'policy', 'assetAccounts', 'productionCost', 'constraint', 'resultAppropriation', 'legalForms', 'inventory', 'provisions', 'deferrals', 'inputTaxAdjustment'] as const;\nconst ASSET_ACCOUNT_KEYS = [\n  'acquisitionCounterAccount',\n  'depreciationExpenseAccount',\n  'gwgExpenseAccount',\n  'disposalProceedsAccount',\n  'disposalLossAccount',\n] as const;\nconst ROUNDING_MODES = ['halfUpAwayFromZero', 'halfEven'];\nconst TAX_GRANULARITIES = ['perVoucher', 'perLine'];\n\nexport interface ModuleRef {\n  kind: string;\n  id: string;\n  version?: string;\n}\n\nexport interface PackModule {\n  formatVersion?: string;\n  id: string;\n  kind: string;\n  version: string;\n  name?: string;\n  contributes?: string[];\n  dependsOn?: ModuleRef[];\n  data: Record<string, unknown>;\n}\n\nexport interface PackManifest {\n  formatVersion?: string;\n  id: string;\n  name?: string;\n  version: string;\n  modules: ModuleRef[];\n  overrides?: { op: string; ref: ModuleRef; with?: ModuleRef }[];\n  taxCodes?: string[];\n  defaults?: Record<string, unknown>;\n  packPolicy: Record<string, unknown>;\n}\n\nexport interface ResolvedPack {\n  id: string;\n  version: string;\n  chartOfAccounts: { accounts: Record<string, unknown>[] };\n  taxCodes: Record<string, unknown>[];\n  mappings: Record<string, unknown>[];\n  assetAccounts: Record<string, unknown> | null;\n  depreciation: Record<string, unknown> | null;\n  productionCost: Record<string, unknown> | null;\n  inventory: Record<string, unknown> | null;\n  provisions: Record<string, unknown> | null;\n  deferrals: Record<string, unknown> | null;\n  inputTaxAdjustment: Record<string, unknown> | null;\n  resultAppropriation: Record<string, unknown> | null;\n  legalForms: Record<string, unknown> | null;\n  dimensionRules: Record<string, unknown>[];\n  accountCombinationRules: Record<string, unknown>[];\n  accountUsageRules: Record<string, unknown>[];\n  packPolicy: Record<string, unknown>;\n  profile: Record<string, unknown>;\n  contentDigest: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction asString(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\nfunction recordList(value: unknown): Record<string, unknown>[] {\n  return Array.isArray(value) ? value.filter(isRecord) : [];\n}\nfunction refKey(kind: string, id: string): string {\n  return `${kind}|${id}`;\n}\n/** Stable comparison by Unicode codepoints (determinism sort rule). */\nfunction byCodepoint(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * Order two published versions, newest last.\n *\n * **Segment by segment, numerically where both segments are numbers**, and by code point\n * otherwise. This used to be a plain code-point compare over the whole string, and that was correct\n * for every version that has ever shipped and wrong for the next one: `2026.10` sorts BELOW\n * `2026.9` by code point, because `'1' < '9'`. A request without a version means *current*, so the\n * tenth release of a pack would silently have resolved the ninth — the pack would look published\n * and nobody would be running it. The German pack reached `2026.9` on 2026-08-28, which is how\n * close this was.\n *\n * Nothing that exists resolves differently: with single-digit segments the two orders agree, which\n * is why the change is safe to make in one step rather than behind a flag. A segment that is not a\n * number (`1.0-beta`) still compares by code point, so a pack that versions itself some other way\n * keeps the behaviour it had.\n */\nfunction byVersion(a: string, b: string): number {\n  const left = a.split('.');\n  const right = b.split('.');\n  const count = Math.max(left.length, right.length);\n\n  for (let i = 0; i < count; i++) {\n    const l = left[i] ?? '';\n    const r = right[i] ?? '';\n    if (l === r) continue;\n    // A missing segment is lower than a present one: 2026.1 precedes 2026.1.1.\n    if (l === '' || r === '') return l === '' ? -1 : 1;\n    if (/^[0-9]+$/.test(l) && /^[0-9]+$/.test(r)) {\n      const dl = Number(l);\n      const dr = Number(r);\n      return dl < dr ? -1 : dl > dr ? 1 : 0;\n    }\n    return byCodepoint(l, r);\n  }\n  return 0;\n}\n\n/**\n * Pick a manifest out of a store by id, optionally pinned to a version.\n *\n * A published `(id, version)` names one bundle for good, so a library may hold several versions\n * of the same pack side by side and an old pin keeps resolving what it always resolved. A request\n * without a version means \"current\", and current is the **highest** version, compared segment by\n * segment and numerically where both segments are numbers (`byVersion`) — the\n * same rule module references already follow. Picking the first match instead would make the\n * answer depend on directory iteration order, which is not the same on two machines.\n */\nexport function findManifest(manifests: PackManifest[], id: string | null, version?: string | null): PackManifest {\n  const candidates = manifests.filter((m) => m.id === id && (version === null || version === undefined || m.version === version));\n  if (candidates.length === 0) {\n    throw new DomainError('E_PACK_UNRESOLVED_REF', `Manifest not found: ${id ?? ''}${version === null || version === undefined ? '' : `@${version}`}`);\n  }\n  const sorted = [...candidates].sort((a, b) => byVersion(a.version, b.version));\n  return sorted[sorted.length - 1]!;\n}\n\n/**\n * Fingerprint of everything a resolution produced.\n *\n * `version` is written by hand and can therefore lag behind, or stay put while the modules\n * underneath it move — which is exactly how one version number came to name several different\n * bundles. This one is derived, so nobody can forget to change it: two resolutions carrying the\n * same digest are the same pack, and the same version with two digests is a broken promise\n * somebody can now see. The version is part of the input, so a pure relabel changes it too.\n */\nfunction contentDigest(resolvedPack: Omit<ResolvedPack, 'contentDigest'>): string {\n  return createHash('sha256').update(canonicalJson(resolvedPack)).digest('hex');\n}\n\n/**\n * Resolves a manifest against a module store. Throws `DomainError` with the\n * matching `E_PACK_*`/`E_POLICY_*` code; otherwise returns a fully sound\n * `ResolvedPack`.\n */\nexport function resolvePack(manifest: PackManifest, moduleSource: PackModule[]): ResolvedPack {\n  // 1. Effective module list: apply overrides (remove/replace) in array order.\n  const effective: ModuleRef[] = manifest.modules.map((m) => ({ ...m }));\n  for (const ov of manifest.overrides ?? []) {\n    const idx = effective.findIndex((m) => m.kind === ov.ref.kind && m.id === ov.ref.id);\n    if (idx < 0) {\n      // Override targets nothing (also: a second remove/replace on the same ref).\n      throw new DomainError('E_PACK_INCOHERENT', `Override does not match: ${refKey(ov.ref.kind, ov.ref.id)}`);\n    }\n    if (ov.op === 'remove') {\n      effective.splice(idx, 1);\n    } else if (ov.op === 'replace') {\n      if (!ov.with) throw new DomainError('E_PACK_INCOHERENT', 'replace override without \"with\"');\n      effective[idx] = { ...ov.with };\n    } else {\n      throw new DomainError('E_PACK_INCOHERENT', `Unknown override operation: ${ov.op}`);\n    }\n  }\n\n  // 2. Resolve module references against the store (version missing → highest, see byVersion).\n  const resolved: PackModule[] = [];\n  for (const ref of effective) {\n    const candidates = moduleSource.filter(\n      (m) => m.kind === ref.kind && m.id === ref.id && (ref.version === undefined || m.version === ref.version),\n    );\n    if (candidates.length === 0) {\n      throw new DomainError('E_PACK_UNRESOLVED_REF', `Module not found: ${refKey(ref.kind, ref.id)}`);\n    }\n    candidates.sort((a, b) => byVersion(a.version, b.version));\n    resolved.push(candidates[candidates.length - 1]!);\n  }\n\n  // unknown kind → INCOHERENT\n  for (const m of resolved) {\n    if (!MODULE_KINDS.includes(m.kind as (typeof MODULE_KINDS)[number])) {\n      throw new DomainError('E_PACK_INCOHERENT', `Unknown module kind: ${m.kind}`);\n    }\n  }\n\n  // 3. Dependency DAG: missing dependsOn reference → UNRESOLVED_REF (before cycle check).\n  const present = new Set(resolved.map((m) => refKey(m.kind, m.id)));\n  for (const m of resolved) {\n    for (const dep of m.dependsOn ?? []) {\n      if (!present.has(refKey(dep.kind, dep.id))) {\n        throw new DomainError(\n          'E_PACK_UNRESOLVED_REF',\n          `dependsOn points to an unlisted module: ${refKey(dep.kind, dep.id)}`,\n        );\n      }\n    }\n  }\n  const sorted = topoSort(resolved, present);\n\n  // 4. Fold (topological). Colliding contributions → INCOHERENT (no silent overwrite).\n  const accounts: Record<string, unknown>[] = [];\n  const accountNumbers = new Set<string>();\n  // number -> type, for the offsetting invariant (I11).\n  const accountTypes = new Map<string, string>();\n  const taxCodes: Record<string, unknown>[] = [];\n  const taxCodeCodes = new Set<string>();\n  const mappings: Record<string, unknown>[] = [];\n  const mappingIds = new Set<string>();\n  let assetAccounts: Record<string, unknown> | null = null;\n  let depreciation: Record<string, unknown> | null = null;\n  let productionCost: Record<string, unknown> | null = null;\n  let inventory: Record<string, unknown> | null = null;\n  let provisions: Record<string, unknown> | null = null;\n  let deferrals: Record<string, unknown> | null = null;\n  let inputTaxAdjustment: Record<string, unknown> | null = null;\n  let resultAppropriation: Record<string, unknown> | null = null;\n  let legalForms: Record<string, unknown> | null = null;\n  const dimensionRules: Record<string, unknown>[] = [];\n  const accountCombinationRules: Record<string, unknown>[] = [];\n  const accountUsageRules: Record<string, unknown>[] = [];\n  let packPolicyModule: Record<string, unknown> | null = null;\n\n  for (const m of sorted) {\n    switch (m.kind) {\n      case 'accounts':\n        for (const account of recordList(m.data.accounts)) {\n          const number = asString(account.number) ?? '';\n          if (accountNumbers.has(number)) {\n            throw new DomainError('E_PACK_INCOHERENT', `Duplicate account number: ${number}`);\n          }\n          accountNumbers.add(number);\n          accountTypes.set(number, asString(account.type) ?? '');\n          const subtype = asString(account.subtype);\n          if (subtype !== null && !isAccountSubtype(subtype)) {\n            // Closed repertoire (substrate/types.ts): a misspelled subtype used to resolve into a\n            // chart where the engine read nothing from it. E_PACK_INCOHERENT because that is what\n            // it is — the modules resolve, the bundle asks for something that does not exist — and\n            // here rather than at the first posting, like every other coherence check.\n            throw new DomainError(\n              'E_PACK_INCOHERENT',\n              `Unknown account subtype \"${subtype}\" on account ${number}`,\n              { account: number, subtype, known: [...ACCOUNT_SUBTYPES] },\n            );\n          }\n          accounts.push(account);\n        }\n        break;\n      case 'tax':\n        for (const taxCode of recordList(m.data.taxCodes)) {\n          const code = asString(taxCode.code) ?? '';\n          if (taxCodeCodes.has(code)) {\n            throw new DomainError('E_PACK_INCOHERENT', `Duplicate taxCode.code: ${code}`);\n          }\n          taxCodeCodes.add(code);\n          taxCodes.push(taxCode);\n        }\n        break;\n      case 'mapping': {\n        const mapping = isRecord(m.data.mapping) ? m.data.mapping : null;\n        if (mapping === null) break;\n        const id = asString(mapping.id) ?? '';\n        if (mappingIds.has(id)) {\n          throw new DomainError('E_PACK_INCOHERENT', `Duplicate mapping.id: ${id}`);\n        }\n        mappingIds.add(id);\n        mappings.push(mapping);\n        break;\n      }\n      case 'assetAccounts':\n        assetAccounts = m.data;\n        break;\n      case 'productionCost':\n        productionCost = m.data;\n        break;\n      case 'inventory':\n        inventory = m.data;\n        break;\n      case 'provisions':\n        provisions = m.data;\n        break;\n      case 'deferrals':\n        deferrals = m.data;\n        break;\n      case 'inputTaxAdjustment':\n        inputTaxAdjustment = m.data;\n        break;\n      case 'resultAppropriation':\n        resultAppropriation = m.data;\n        break;\n      case 'legalForms':\n        legalForms = m.data;\n        break;\n      case 'constraint':\n        // Constraints add up rather than replace: two modules may each contribute rules, and a later\n        // one silently winning would make the pack order significant.\n        for (const rule of Array.isArray(m.data.dimensionRules) ? m.data.dimensionRules : []) {\n          if (isRecord(rule)) dimensionRules.push(rule);\n        }\n        for (const rule of Array.isArray(m.data.accountCombinationRules) ? m.data.accountCombinationRules : []) {\n          if (isRecord(rule)) accountCombinationRules.push(rule);\n        }\n        for (const rule of Array.isArray(m.data.accountUsageRules) ? m.data.accountUsageRules : []) {\n          if (isRecord(rule)) accountUsageRules.push(rule);\n        }\n        break;\n      case 'depreciation':\n        depreciation = m.data;\n        break;\n      case 'policy':\n        if (packPolicyModule !== null) {\n          throw new DomainError('E_PACK_INCOHERENT', 'More than one policy module');\n        }\n        packPolicyModule = isRecord(m.data.packPolicy) ? m.data.packPolicy : {};\n        break;\n    }\n  }\n\n  // 5. Referential integrity.\n  // I1: taxAccount (+ inputTaxAccount on reverse_charge) exists in the chart of accounts.\n  for (const taxCode of taxCodes) {\n    for (const version of recordList(taxCode.versions)) {\n      const taxAccount = asString(version.taxAccount);\n      if (taxAccount !== null && !accountNumbers.has(taxAccount)) {\n        throw new DomainError('E_PACK_UNRESOLVED_REF', `taxAccount without account: ${taxAccount} (I1)`);\n      }\n      if (mechanismFor(asString(version.mechanism) ?? 'standard').requiresInputTaxAccount) {\n        const inputTaxAccount = asString(version.inputTaxAccount);\n        if (inputTaxAccount !== null && !accountNumbers.has(inputTaxAccount)) {\n          throw new DomainError('E_PACK_UNRESOLVED_REF', `inputTaxAccount without account: ${inputTaxAccount} (I1)`);\n        }\n      }\n    }\n  }\n  // I3: all five assetAccounts.*Account (+ perClass) exist.\n  if (assetAccounts !== null) {\n    const def = isRecord(assetAccounts.default) ? assetAccounts.default : {};\n    for (const key of ASSET_ACCOUNT_KEYS) {\n      const number = asString(def[key]);\n      if (number === null || !accountNumbers.has(number)) {\n        throw new DomainError('E_PACK_UNRESOLVED_REF', `assetAccounts.${key} without account (I3)`);\n      }\n    }\n    const perClass = isRecord(assetAccounts.perClass) ? assetAccounts.perClass : {};\n    for (const cls of Object.values(perClass)) {\n      if (!isRecord(cls)) continue;\n      for (const value of Object.values(cls)) {\n        const number = asString(value);\n        if (number !== null && !accountNumbers.has(number)) {\n          throw new DomainError('E_PACK_UNRESOLVED_REF', `assetAccounts.perClass without account: ${number} (I3)`);\n        }\n      }\n    }\n  }\n  // I8: the appropriation module names accounts that exist — the allocation account and every\n  // target it offers. A target pointing at nothing would fail at posting time, deep inside an\n  // operation, instead of when the pack is composed.\n  if (resultAppropriation !== null) {\n    const allocation = asString(resultAppropriation.allocationAccount);\n    if (allocation === null || !accountNumbers.has(allocation)) {\n      throw new DomainError('E_PACK_UNRESOLVED_REF', 'resultAppropriation.allocationAccount without account (I8)');\n    }\n    const targets = isRecord(resultAppropriation.targets) ? resultAppropriation.targets : {};\n    if (Object.keys(targets).length === 0) {\n      throw new DomainError('E_PACK_INCOHERENT', 'resultAppropriation without a single target (I8)');\n    }\n    for (const [name, target] of Object.entries(targets)) {\n      const number = isRecord(target) ? asString(target.account) : null;\n      if (number === null || !accountNumbers.has(number)) {\n        throw new DomainError('E_PACK_UNRESOLVED_REF', `resultAppropriation.targets.${name} without account (I8)`);\n      }\n    }\n  }\n  // I9: the legal-form catalogue is usable — at least one form, and every form that requires a\n  // resolution says by when. A form declared without its deadline would report \"a resolution is due\"\n  // and no date, which is worse than saying nothing: an application cannot tell a missing rule from\n  // a form that genuinely has none.\n  if (legalForms !== null) {\n    const forms = isRecord(legalForms.forms) ? legalForms.forms : {};\n    if (Object.keys(forms).length === 0) {\n      throw new DomainError('E_PACK_INCOHERENT', 'legalForms without a single form (I9)');\n    }\n    for (const [name, form] of Object.entries(forms)) {\n      const resolution = isRecord(form) && isRecord(form.resolution) ? form.resolution : null;\n      if (resolution === null || typeof resolution.required !== 'boolean') {\n        throw new DomainError('E_PACK_INCOHERENT', `legalForms.forms.${name} without resolution.required (I9)`);\n      }\n      if (resolution.required && typeof resolution.deadlineMonths !== 'number') {\n        throw new DomainError('E_PACK_INCOHERENT', `legalForms.forms.${name} requires a resolution but names no deadline (I9)`);\n      }\n    }\n  }\n  // I10: every tenant fact an `appliesWhen` names is one this bundle can actually produce.\n  // Without this a mistyped legal form leaves the rule permanently DORMANT — the pack looks like it\n  // forbids something and forbids nothing, which is the same silent failure the closed subtype\n  // repertoire and the closed mechanism repertoire were built against. The legal forms are the\n  // pack's own catalogue, so they can only be checked here, where the constraint modules and the\n  // legalForms module are in the same hand.\n  const declaredForms = legalForms !== null && isRecord(legalForms.forms) ? Object.keys(legalForms.forms) : [];\n  for (const rule of [...accountCombinationRules, ...accountUsageRules]) {\n    const conditions = isRecord(rule.appliesWhen) ? rule.appliesWhen : {};\n    for (const form of Array.isArray(conditions.legalForm) ? conditions.legalForm : []) {\n      if (!declaredForms.includes(form as string)) {\n        throw new DomainError(\n          'E_PACK_INCOHERENT',\n          `appliesWhen.legalForm names ${String(form)}, which this pack does not declare (I10)`,\n          { legalForm: form, declared: declaredForms },\n        );\n      }\n    }\n    for (const method of Array.isArray(conditions.taxationMethod) ? conditions.taxationMethod : []) {\n      if (!(TaxProfile.METHODS as readonly string[]).includes(method as string)) {\n        throw new DomainError(\n          'E_PACK_INCOHERENT',\n          `appliesWhen.taxationMethod names ${String(method)}, which is not a taxation method (I10)`,\n          { taxationMethod: method, known: [...TaxProfile.METHODS] },\n        );\n      }\n    }\n  }\n  // I2: every mapping selector hits >= 1 account; fires only on a fully empty selector.\n  for (const mapping of mappings) {\n    checkMappingSelectors(mapping, accountNumbers);\n    // I11: no balance-sheet position may draw from both sides (offsetting prohibition).\n    checkBalanceSheetSides(mapping, accountNumbers, accountTypes);\n  }\n  // I4: every taxCode referenced by the manifest is provided by a tax module.\n  for (const code of manifest.taxCodes ?? []) {\n    if (typeof code === 'string' && !taxCodeCodes.has(code)) {\n      throw new DomainError('E_PACK_UNRESOLVED_REF', `Manifest taxCode without tax module: ${code} (I4)`);\n    }\n  }\n\n  // 6. packPolicy: manifest copy == resolved policy module + value ranges.\n  const effectivePolicy = packPolicyModule ?? manifest.packPolicy;\n  validatePolicyValues(effectivePolicy);\n  if (packPolicyModule !== null && !samePolicy(manifest.packPolicy, packPolicyModule)) {\n    throw new DomainError('E_POLICY_INVALID', 'Manifest packPolicy deviates from the policy module');\n  }\n\n  const synthCoaId = `${manifest.id}-coa`;\n  const profile: Record<string, unknown> = {\n    id: manifest.id,\n    name: manifest.name ?? manifest.id,\n    version: manifest.version,\n    chartOfAccounts: synthCoaId,\n    taxCodes: manifest.taxCodes ?? taxCodes.map((t) => asString(t.code) ?? ''),\n    mappings: mappings.map((m) => asString(m.id) ?? ''),\n    defaults: manifest.defaults ?? {},\n  };\n\n  const resolvedPack = {\n    id: manifest.id,\n    version: manifest.version,\n    chartOfAccounts: { accounts },\n    taxCodes,\n    mappings,\n    assetAccounts,\n    depreciation,\n    productionCost,\n    inventory,\n    provisions,\n    deferrals,\n    inputTaxAdjustment,\n    resultAppropriation,\n    legalForms,\n    dimensionRules,\n    accountCombinationRules,\n    accountUsageRules,\n    packPolicy: effectivePolicy,\n    profile,\n  };\n\n  return { ...resolvedPack, contentDigest: contentDigest(resolvedPack) };\n}\n\n/** Converts a ResolvedPack into the `ruleModules` bundle that `TenantFactory` consumes. */\nexport function ruleModulesFromResolved(pack: ResolvedPack): Record<string, unknown> {\n  // assetAccounts: resolver I3 validates the `default` form ({default:{accounts}}); the AssetService\n  // reads the accounts flat → unpack to the flat form here (pack-path parity with the inline path).\n  const aa = isRecord(pack.assetAccounts) ? pack.assetAccounts : null;\n  const assetAccounts = aa !== null && isRecord(aa.default) ? aa.default : (aa ?? {});\n  // depreciation data (gwgThresholds, usefulLife) the AssetService reads top-level → spread.\n  const depreciation = isRecord(pack.depreciation) ? pack.depreciation : {};\n  return {\n    // The identity travels with the bundle so a tenant can say which pack it runs on\n    // (systemDescription / F-IO-007). Everything else here is rules; this is provenance.\n    pack: { id: pack.id, version: pack.version, contentDigest: pack.contentDigest },\n    profiles: [pack.profile],\n    chartsOfAccounts: [{ id: asString(pack.profile.chartOfAccounts) ?? '', accounts: pack.chartOfAccounts.accounts }],\n    taxCodes: pack.taxCodes,\n    mappings: pack.mappings,\n    assetAccounts,\n    ...depreciation,\n    // Not spread like depreciation: the CostingService reads it under its own key, because\n    // \"treatments\" is a word another module could plausibly want too.\n    productionCost: isRecord(pack.productionCost) ? pack.productionCost : null,\n    // Which accounts hold stock and where each one's change is booked. A pack that stays silent\n    // simply does not support `valuateInventory`, which is the right answer for a jurisdiction-free\n    // one and for a service business alike.\n    inventory: isRecord(pack.inventory) ? pack.inventory : null,\n    // Which accounts hold provisions, what each books its expense and its release to, and whether\n    // long-dated ones must be discounted. A pack that stays silent does not support\n    // `recognizeProvision` — which is the right answer for a jurisdiction-free one.\n    provisions: isRecord(pack.provisions) ? pack.provisions : null,\n    // Which account holds a prepaid expense and which a deferred income. A pack that stays silent\n    // does not support `recognizeDeferral`, which is the right answer for one that does not\n    // distinguish the two.\n    deferrals: isRecord(pack.deferrals) ? pack.deferrals : null,\n    // The correction periods, thresholds, accounts and reporting key for the input-tax adjustment. A\n    // pack that stays silent has no such rule, and `adjustInputTax` says so rather than inventing an\n    // observation period.\n    inputTaxAdjustment: isRecord(pack.inputTaxAdjustment) ? pack.inputTaxAdjustment : null,\n    // The appropriation plug: which account the resolution books against, and which targets the\n    // jurisdiction offers. A pack that stays silent simply does not support the operation.\n    resultAppropriation: isRecord(pack.resultAppropriation) ? pack.resultAppropriation : null,\n    // Which legal forms this jurisdiction knows, and what each obliges. A pack that stays silent\n    // has no catalogue, which is a legitimate answer for a jurisdiction-free one.\n    legalForms: isRecord(pack.legalForms) ? pack.legalForms : null,\n    // The first constraint plug: which accounts may not be posted without which dimension.\n    dimensionRules: Array.isArray(pack.dimensionRules) ? pack.dimensionRules : [],\n    accountCombinationRules: Array.isArray(pack.accountCombinationRules) ? pack.accountCombinationRules : [],\n    accountUsageRules: Array.isArray(pack.accountUsageRules) ? pack.accountUsageRules : [],\n    packPolicy: pack.packPolicy,\n  };\n}\n\n/** Kahn-style topological sort; stable tie-break per (kind|id) codepoint. Cycle → INCOHERENT. */\nfunction topoSort(modules: PackModule[], present: Set<string>): PackModule[] {\n  const out: PackModule[] = [];\n  const done = new Set<string>();\n  const remaining = [...modules];\n  while (remaining.length > 0) {\n    const ready = remaining.filter((m) =>\n      (m.dependsOn ?? [])\n        .filter((dep) => present.has(refKey(dep.kind, dep.id)))\n        .every((dep) => done.has(refKey(dep.kind, dep.id))),\n    );\n    if (ready.length === 0) {\n      throw new DomainError('E_PACK_INCOHERENT', 'Dependency cycle');\n    }\n    ready.sort((a, b) => byCodepoint(refKey(a.kind, a.id), refKey(b.kind, b.id)));\n    const next = ready[0]!;\n    out.push(next);\n    done.add(refKey(next.kind, next.id));\n    remaining.splice(remaining.indexOf(next), 1);\n  }\n  return out;\n}\n\nfunction selectorText(selector: Record<string, unknown>): string {\n  if (Array.isArray(selector.numbers)) {\n    return `numbers ${selector.numbers.filter((n) => typeof n === 'string').join(', ')}`;\n  }\n  return `range ${asString(selector.from) ?? '?'}–${asString(selector.to) ?? '?'}`;\n}\n\nfunction checkMappingSelectors(mapping: Record<string, unknown>, accountNumbers: Set<string>): void {\n  const numbers = [...accountNumbers];\n  const mappingId = asString(mapping.id) ?? '?';\n  const visit = (position: Record<string, unknown>): void => {\n    for (const selector of recordList(position.accounts)) {\n      let hits = 0;\n      if (Array.isArray(selector.numbers)) {\n        hits = selector.numbers.filter((n) => typeof n === 'string' && accountNumbers.has(n)).length;\n      } else {\n        const from = asString(selector.from);\n        const to = asString(selector.to);\n        if (from !== null && to !== null) {\n          hits = numbers.filter((n) => byCodepoint(n, from) >= 0 && byCodepoint(n, to) <= 0).length;\n        }\n      }\n      if (hits === 0) {\n        // Naming all three is the difference between a five-minute fix and bisecting the pack:\n        // the message used to say only that \"a\" selector somewhere hit nothing, in a bundle that\n        // can hold hundreds of them across several mappings.\n        const positionKey = asString(position.key) ?? '?';\n        throw new DomainError(\n          'E_PACK_UNRESOLVED_REF',\n          `Mapping \"${mappingId}\", position \"${positionKey}\": ${selectorText(selector)} hits no account (I2). ` +\n            'Every selector must match at least one account of the chart the pack ships.',\n          { mapping: mappingId, position: positionKey, selector: selectorText(selector) },\n        );\n      }\n    }\n    for (const child of recordList(position.children)) {\n      visit(child);\n    }\n  };\n  for (const position of recordList(mapping.positions)) {\n    visit(position);\n  }\n}\n\n/**\n * The account numbers a selector actually hits, in chart order.\n */\nfunction selectedNumbers(selector: Record<string, unknown>, numbers: string[]): string[] {\n  if (Array.isArray(selector.numbers)) {\n    return selector.numbers.filter((n): n is string => typeof n === 'string');\n  }\n  const from = asString(selector.from);\n  const to = asString(selector.to);\n  if (from === null || to === null) return [];\n  return numbers.filter((n) => byCodepoint(n, from) >= 0 && byCodepoint(n, to) <= 0);\n}\n\n/**\n * I11 — a balance-sheet position may not draw from both sides of the balance sheet.\n *\n * **The rule everybody knows and nothing checked.** Offsetting assets against liabilities is\n * forbidden, and until now the pack author was simply trusted: a position could pull a receivable\n * range and a payable range and produce one netted figure, and every gate stayed green because the\n * statement still balanced. That is the same shape as the defects the constraint policy kind was\n * built for, one layer out — a rule so obvious that nobody wrote it down.\n *\n * **It is checked on the ACCOUNT TYPE, not on the balance.** A bank account that is overdrawn is\n * still an asset account and belongs on the assets side; a position holding it is not offsetting\n * anything. What is forbidden is a position that *selects* accounts of both kinds, because then no\n * reader can tell what the figure is made of.\n *\n * Only `balance-sheet` mappings. An income statement has no sides, and a cash-basis mapping is a\n * list of categories rather than a two-sided statement.\n */\nfunction checkBalanceSheetSides(\n  mapping: Record<string, unknown>,\n  accountNumbers: Set<string>,\n  accountTypes: Map<string, string>,\n): void {\n  if (asString(mapping.kind) !== 'balance-sheet') return;\n\n  const numbers = [...accountNumbers];\n  const mappingId = asString(mapping.id) ?? '?';\n\n  const visit = (position: Record<string, unknown>, inherited: string | null): void => {\n    const side = asString(position.side) ?? inherited;\n\n    for (const selector of recordList(position.accounts)) {\n      if (side === null) continue;\n\n      for (const number of selectedNumbers(selector, numbers)) {\n        const type = accountTypes.get(number) ?? '';\n        const belongs = side === 'assets' ? type === 'asset' : type === 'liability' || type === 'equity';\n\n        if (!belongs) {\n          const positionKey = asString(position.key) ?? '?';\n          throw new DomainError(\n            'E_PACK_INCOHERENT',\n            `Mapping \"${mappingId}\", position \"${positionKey}\" is on the ${side} side and selects account ` +\n              `${number}, which is of type \"${type}\" (I11). A balance-sheet position that draws from both ` +\n              'sides reports one netted figure and offsets what may not be offset.',\n            { mapping: mappingId, position: positionKey, account: number, type, side },\n          );\n        }\n      }\n    }\n\n    for (const child of recordList(position.children)) {\n      visit(child, side);\n    }\n  };\n\n  for (const position of recordList(mapping.positions)) {\n    visit(position, null);\n  }\n}\n\nfunction validatePolicyValues(policy: Record<string, unknown>): void {\n  const roundingMode = asString(policy.roundingMode);\n  if (roundingMode === null || !ROUNDING_MODES.includes(roundingMode)) {\n    throw new DomainError('E_POLICY_INVALID', `Invalid roundingMode: ${String(policy.roundingMode)}`);\n  }\n  const granularity = asString(policy.taxRoundingGranularity);\n  if (granularity === null || !TAX_GRANULARITIES.includes(granularity)) {\n    throw new DomainError('E_POLICY_INVALID', `Invalid taxRoundingGranularity: ${String(policy.taxRoundingGranularity)}`);\n  }\n  const scale = policy.currencyScale;\n  if (typeof scale !== 'number' || !Number.isInteger(scale) || scale < 0 || scale > 4) {\n    throw new DomainError('E_POLICY_INVALID', `currencyScale outside 0–4: ${String(scale)}`);\n  }\n}\n\nfunction samePolicy(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n  return (\n    a.roundingMode === b.roundingMode &&\n    a.taxRoundingGranularity === b.taxRoundingGranularity &&\n    a.currencyScale === b.currencyScale\n  );\n}\n"]}