# P1-0 Contract and Schema Design Freeze — review summary

Status: accepted P1-0 field-level summary. P1-0d transcribed the pinned C9/C15 rows, authored the
C11/C12/D6 additions with per-field provenance, closed C3 by immutability, and measured A3.
All deliberate changes are documentation only.
Prototype behavior was inspected read-only at detached commit
`9359c67c4ef0101218d7e0ffff1986114ba5cc7a`; only the explicitly authorized controlled-vocabulary
and code-table rows were copied, with source/blob provenance.

## Draft set

- `docs/p1-0-claude-extraction-contract.md` — normative single-document proposal contract and
  atomic response validation before extraction-derived projection.
- `docs/p1-0-discard-purge-lifecycle.md` — soft Discard, authorized Purge, never-delete DOCLOG,
  tombstone, and exact-hash resubmission behavior usable by both Sibyla and FDR.
- `docs/p1-0-schema-mapping.md` — field-level PostgreSQL mapping for the corrected layer 1–5
  roster, DOCARC/export support, Layer 6 ground-truth slice, history import, grandfathering,
  RelatedParty, controlled company scope, lossless user-observation import, and parked
  integration-ledger preservation.
- `docs/p1-0-codes-taxonomy-archive.md` — permanent-code ledger/sequences, proven identity keys,
  DOCTYP seed rows, and collision-safe class-based Nextcloud layout.
- `docs/p1-0-user-ai-roles-responsibilities-policy.md` — Sibyla-scoped policy adapted from the FDR
  draft, including exception-and-learning queue semantics and the AI-proposal/deterministic-action
  boundary.
- `AGENTS.md` — v5.0 instructions inherited by future sessions.

## Decisions captured

1. Claude returns proposals only. Intake Document and ExtractionAttempt persistence may precede
   response validation; strict deterministic validation is atomic and precedes every
   extraction-derived business projection or side effect. The seeded type is exactly
   `Invoice-Receipt`, and the warning collection maximum is five because its vocabulary has five
   unique codes.
2. Discard is reviewer-driven soft exclusion with bytes/audit retained. Purge is explicit,
   authorized, never automatic, and structurally denied after any fiscal/archive/reference-only
   history. DOCLOG and a safe tombstone remain forever.
3. The target roster uses MNGACC and DOCTYP and includes COCACC, DOCFLG, persisted DOCRQE/RECREV,
   Layer 5 bank tables, and PAYCTR/PAYDTL/RCVCTR/RCVDTL ground truth. OFDGAP is not a table: its
   Monthly-only detector is a DOCEFL Decision rule and the sheet renders from persistent findings.
4. LGCode is the permanent DOCLOG row identity on `(Filename, EntryCode)`; no `DocLogId` is added.
   P1-1 validates the pair↔LGCode bijection, not one-code-per-EntryCode.
5. Bank-generated P/F/O identity is readable SourceKey indexed by stored SHA-256 SourceKeyHash.
   SourceFile is provenance. Ordered `FdcHdrBankMovement` rows are the referential truth for both
   single and aggregate documents; SourceBMCode is only a human-readable pointer. The recomputed
   occurrence tiebreaker is mandatory. P1-1 must preflight PostgreSQL `pgcrypto` and
   `digest(bytea, text)` and fail closed before migration if unavailable.
6. Permanent codes use non-cycling PostgreSQL sequences and an append-only key ledger. Allocation
   uses `INSERT ... ON CONFLICT DO NOTHING RETURNING` followed, on loss, by a new-statement winner
   read and full-key comparison. `nextval()` is intentionally non-transactional, so rollback,
   crash, and concurrency losers leave gaps that can never be reused. Preserved imports initialize
   unused sequences once under exclusive bootstrap locks; runtime setval/restart is forbidden.
7. Pinned DOCTYP DocClass is `Payables|Receivable`; target-only Bank / Legal / Procurement / Other
   values are explicit C1–C19 extensions. Pinned imports derive only from the generated annex;
   explicitly decided target-only extensions are versioned and fail-closed, and are never claimed
   as pinned values. The seed is the 19 pinned rows transcribed with source/blob provenance plus
   `Duplicate|External`. `Duplicate|External` is Include/ArchiveOnly and preserves the
   real EntryCode; it is not ReferenceOnly. `Invoice-Receipt` and `Payroll-Receipt` retain their exact
   literals. Conditional fiscal eligibility has a separate condition field. Each multi-valued
   Allowed OriginClass cell expands into one row per `(DocumentType, OriginClass)` pair.
   ReferenceOnly is first-class and has no EntryCode.
8. Legal business-copy layout is subtype-first, then counterparty; Payables and Receivables have
   separate literal directories, and bank paths use only the controlled BNKACC token. All Period components derive
   from the document date. Fiscal/legal/procurement/other two-digit suffixes are stable and
   non-reused with fail-closed overflow; bank statements/corrections use an idempotent non-reused
   per-account-period `vNNNN` ledger with concurrent no-overwrite allocation and fail-closed
   overflow.
9. Grandfathering is persisted from each flag instance's source DetectedAt against the rule's
   Sibyla `EnforcementStartsAt`, distinct from FDR authoring-time `EffectiveFrom`; ImportBatch time
   is irrelevant. All 52 imported rules use Sibyla go-live, grandfathering all 2,787 imported
   instances and leaving zero actively blocking on day one. C3 is closed: the named reject trigger
   makes `EnforcementStartsAt` immutable after import or first use, verdicts are never recomputed,
   and a correction creates a new rule version.
10. ENTMST receives RelatedParty classification tied to `CL000005` (`Banks / Financing`) and
    `CL000025` (`Revenue / Intercompany`). An Information / Non-Blocking DOCEFL rule requires
    both the relationship and one of those movement classifications. RelatedParty never becomes an
    entity-wide ignore.
11. The existing integration ledger keeps its non-null restrictive Document/ExtractionRevision
    FKs. FDCHDR distinguishes four anchors without fabrication: native extracted
    Document+ExtractionRevision, authenticated ManualEntryEvidence, deterministic bank SourceKey,
    or imported ImportEvidenceRow. Historical integration records are not repointed.
12. The D4 import design scopes full 2026 opening history plus complete reference data,
    explicitly including pinned `user_observations.json`; 2025 remains out. Observation keys, exact text,
    ordered DOCRQE/RECREV ReviewID targets, pending targets, and import evidence are lossless,
    append-only, idempotent, and protected as human authority. D9 control headers remain one
    current-state row per document; ImportPeriod/ImportBatchId record provenance, re-import replaces
    only rows governed by that period. `UpsertControlSnapshot` and the
    `RejectControlGoverningPeriodRegression` trigger reject an entire older batch with SQLSTATE
    23514; a row's governing period may only advance.
13. Retained content hashes are canonical company/hash/length duplicate-detection index rows with
    many capture-event links; they are never storage pointers. Byte storage and storage identity
    are per capture and never shared, even for byte-identical captures; reference counting is not
    implemented. Purge is capture-scoped storage hygiene, not RGPD erasure; content-level erasure
    is a named future capability outside P1-1a. A suppressed resubmission records a capture event
    and Annotation against it but creates no extraction-derived DOCLOG row. The current global
    unique Document hash index is replaced in its own reviewed P1-1b migration, never in P1-1a's
    initial train.
14. Malformed/structurally invalid extraction payloads create no ExtractionRevision or DOCLOG;
    ExtractionAttempt plus attempt-keyed DOCFAI/Decision review survive with NULL LGCode. A
    schema-valid `NOT_A_DOCUMENT` is distinct and creates the normal ExtractionRevision,
    DOCLOG/LGCode, DOCFAI, and Decision review path.
15. FDCHDR uses mutually exclusive partial uniqueness for source-fiscal semantic identity and
    bank-generated SourceKeyHash identity. DOCFLG snapshots rule ItemClass and only Decision can be
    Open/InReview or enforce. FL is permanent and stable, not sequential, on the complete
    SourceTextHash/DetectedAt recurrence key. Supersession identifies a successor or records a
    controlled reason why none exists.
16. Pinned internal fields are preserved without mislabeling renderer columns: DOCFLG
    PriorRelatedRecordID, DOCRQE ResolutionEvidence, BNKMOV Classified/ItemDesc, and engine-only
    RECREV ItemKey. BNKMOV has no Source column. DOCARC.DocumentDate is nullable and missing dates
    route to review without becoming archive-eligible.
17. Company scope is relationally closed through controlled CompanyRegistry codes resolved from
    authenticated context. Pinned `Company`/`CompanyCode` spellings remain export fields, while
    composite financial FKs reject cross-company FDCHDR, bank, reconciliation, PAY/RCV, manual,
    Document, bank-input evidence, official-statement qualification, and import-evidence links.
    Official-statement evidence is anchored to matching DOCLOG/DOCARC classification, route, and
    retained disposition, never an arbitrary Document row.
18. ENTITM stores JSON `CodeName`. The rendered workbook's `EntityCode` is a derived EC export;
    workbook import resolves EC to CodeName and JSON import reads CodeName directly. Only an
    unresolvable or ambiguous value is rejected. This does not reopen the settled EI mapping.
19. In Sibyla, Claude/AI reads, transcribes, and proposes only. Authenticated deterministic code performs
    approved captures, decisions, state changes, code issuance, writes, archive operations, and
    external integrations. FDR retains its own role model. Threshold changes and duplicate
    settlement trigger the named Policy Change Validation/review controls.

The corrected bank-reconciliation acceptance metric is the schema view over distinct BNKMOV
movements with at least one non-Unmatched BNKREC match, divided by all BNKMOV movements; Internal
counts and ledger-reference/no-entry does not. Its pinned baseline is 55.9% ±0.1%. The prototype's
94.6% uses an unreconstructible different definition and is not a Sibyla regression comparator.

Cross-matcher rejection identity is Company + source record type + source record ID + candidate
fingerprint. MatcherKind remains audit metadata only: rejection by matcher A blocks the same
candidate from matcher B, proven by a required cross-matcher SQLSTATE `23514` acceptance case.

The v5.0 closed decisions D1–D9 are not reopened: persisted queues; proven identity; Layer 5 in
Phase 1; full 2026 import; ReferenceOnly; separate ledger-reference/no-entry match status;
DetectedAt grandfathering; closed ItemClass; additive period-keyed controls.

## Current flow diagram

The earlier self-review over-claimed a cross-check of superseded v13 as completion of the required
flow deliverable. The current diagram is
`docs/2026-08-04 Sibyla_Organigrama_Fluxo_v14.svg`; it is the review reference, while the
substantive drafts remain authoritative. This correction pass did not redraw a v15.

The following historical diagram labels or edges are superseded by v5.0 and
D1–D9:

- “strict validation before persisting”: intake Document and ExtractionAttempt may persist first;
  no extraction-derived projection may persist before strict deterministic validation;
- ledger-reference/no-entry counted as reconciled: it is a distinct match status excluded from the
  reconciliation percentage;
- `NOT_A_DOCUMENT`/channel junk flowing automatically to `Discard / Purge`: a valid
  `NOT_A_DOCUMENT` follows the normal ExtractionRevision, DOCLOG/LGCode, DOCFAI, and Decision
  route; Purge is an explicit authorized action only after Discard;
- human validation before queue persistence: DOCRQE/RECREV persist findings first, then humans
  decide them;
- visual posting before the DOCFLG gate: non-grandfathered open blocking DOCFLG instances gate
  affected posting, classification, reconciliation, archive, or other actions before execution;
- “LGCode unique per EntryCode”: the actual DOCLOG/LGCode key is `(Filename, EntryCode)`;
- the warning that EntryCode P/F/O, LGCode, and PAYCODE/RCVCODE identities are unstable: D2 closed
  those identity defects;
- the generic Nextcloud `{Empresa}/{DocClass}/{Período}` business-copy layout shown by the SVG:
  the frozen business-copy layouts are class-specific; and
- “dedup by hash” as capture suppression: capture events remain distinct and link to a canonical
  company/hash/length record.

The diagram intentionally omits the ReferenceOnly branch; detailed malformed-response and valid
`NOT_A_DOCUMENT` failure routes; explicit PAY/RCV ground-truth and official-bank-input edges; the
exact DetectedAt-based blocking predicate (`ItemClass='Decision' AND Status IN
('Open','InReview') AND BlockingLevel<>'Non-Blocking' AND NOT IsGrandfathered`, with
`IsGrandfathered` derived from the instance's `DetectedAt` against `EnforcementStartsAt`); the
ExportRun ledger details; and deep DOCARC eligibility, including the nullable document-date review
gate. Those details remain covered by the authoritative drafts.

## P1-0 checklist self-review

| Prompt item | Draft/evidence | Result |
|---|---|---|
| Extraction contract | Exact type and identifier vocabularies; strict proposal validation; distinct malformed and valid NOT_A_DOCUMENT paths | Complete |
| Discard/Purge | Explicit entry states, counter-signed Posted/ReferenceOnly discard, exact restore target, per-capture byte storage, purge controls, tombstone/hash behavior, and bypass-harness isolation case | Complete for P1-0; B1 and O3 closed |
| Full schema | Corrected roster and fields; exhaustive A2 register; A1/A4/A5/A6/A7; controlled company scope; evidence modes; Layer 6 slice | Complete for P1-0 |
| Codes and identity | Concurrent allocation; source-verified keys; A3 measured BR key; run-scoped MatchGroupID; P1-1b issuance/swap boundaries | Complete for P1-0 |
| DOCTYP and DOCEFL | 19 extracted DOCTYP rows; 45 extracted DOCEFL rows; C11/C12/D6 authored rows with per-field provenance | Complete |
| Nextcloud | Canonical CounterpartyCodeName mapping and exact Legal subtype-first path | Complete |
| Roles policy | AI/proposal boundary, deterministic execution, counter-signature and restore authority | Complete |
| Grandfathering | DetectedAt comparison, immutable EnforcementStartsAt trigger, no verdict recompute | Complete |
| RelatedParty | Extracted CL000005/CL000025 and governed dual-condition rule | Complete |
| Review/sign-off gate | P1-0 accepted 2026-08-05; P1-0d closes its named row carve-out | Complete |
| Repository constraints | Documentation only; no source, tests, migration, database, merge, push, or deployment action | Satisfied |

## Recorded follow-up actions outside the P1-0 gate

Luís may later object to reversible decisions or perform source-repository cleanup, but none of
that blocks .NET work. The source-side ENTBNK duplicate merge, three residual FL classifications,
and reconciliation-metric explanation remain recorded follow-ups, not P1-0 decisions.

B1 supersedes and rejects the earlier reference-counted default: per-capture byte storage makes
the tombstone path safe independently of the unchanged eligibility predicate. B1 and O3 are
closed. Per `docs/PROJECT-STATE.md`, O5 is the only open project item.

## Gate to P1-1

P1-0 was accepted on 2026-08-05 and P1-0d closes its four-row carve-out. P1-1a may continue only
within its already-authorized disposable-database migration-train scope. These drafts do not
authorize a shared or persistent migration, live reference-data import, 2026 history import, or a
merge to `main`.
