Skip to content

Commit 716d8fe

Browse files
V29 Gate 6: Close settlement reconciliation repair
Specify and implement settlement reconciliation repair as a first-class V29 Terminal workflow. BTD reports now classify projection drift, emit repair actions, surface proof roots, and block settlement conservation drift. The API, Sandbox harness, Terminal journal projection, and detail card now carry that evidence through to operator-visible repair actions and proof roots. Add focused API, BTD, harness, and Terminal tests plus the Gate 6 checker and gate-quality workflow wiring.
1 parent ff2a3b4 commit 716d8fe

21 files changed

Lines changed: 1292 additions & 32 deletions

.github/workflows/bitcode-gate-quality.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ jobs:
6767
node scripts/check-v29-gate3-wallet-signer-btc-operations.mjs --skip-branch-check
6868
node scripts/check-v29-gate4-reading-pipeline-observability.mjs --skip-branch-check
6969
node scripts/check-v29-gate5-assetpack-disclosure-rights.mjs --skip-branch-check
70+
node scripts/check-v29-gate6-settlement-reconciliation-repair.mjs --skip-branch-check
7071
7172
- name: Validate source casing and imports
7273
run: |
@@ -76,6 +77,7 @@ jobs:
7677
- name: Type-check gate packages
7778
run: |
7879
pnpm --filter @bitcode/btd typecheck
80+
pnpm --filter @bitcode/api build
7981
pnpm --filter @bitcode/pipeline-asset-pack typecheck
8082
pnpm --filter @bitcode/pipeline-hosts typecheck
8183
@@ -84,6 +86,8 @@ jobs:
8486
pnpm --filter @bitcode/btd test
8587
pnpm --filter @bitcode/btd test -- --runTestsByPath __tests__/btc-fee-operation.test.ts
8688
pnpm --filter @bitcode/btd test -- --runTestsByPath __tests__/btd.test.ts
89+
pnpm --filter @bitcode/api exec jest --config jest.config.cjs --runTestsByPath src/routes/__tests__/btd-crypto.test.ts --runInBand
90+
pnpm --filter @bitcode/pipeline-hosts exec jest --config jest.config.cjs --runTestsByPath src/__tests__/asset-pack-harness.test.ts --runInBand
8791
pnpm --filter @bitcode/pipeline-asset-pack exec jest --config jest.config.cjs --passWithNoTests --forceExit
8892
pnpm --filter @bitcode/pipeline-asset-pack exec jest --config jest.config.cjs --runTestsByPath src/__tests__/reading-pipeline-observability.test.ts src/__tests__/reading-pipeline-contract.test.ts --runInBand
8993
pnpm --filter @bitcode/pipeline-asset-pack exec jest --config jest.config.cjs --runTestsByPath src/__tests__/asset-pack-disclosure.test.ts src/__tests__/postprocess.test.ts src/__tests__/read-need.test.ts --runInBand
@@ -99,6 +103,8 @@ jobs:
99103
tests/terminalTransactionQuery.test.ts \
100104
tests/terminalTransactionReadModel.test.ts \
101105
tests/terminalWalletBtcOperation.test.ts \
106+
tests/terminalJournalReconciliation.test.ts \
107+
tests/terminalTransactionDetailCards.test.tsx \
102108
tests/pipelineExecutionLogHeader.test.tsx \
103109
--runInBand
104110

BITCODE_SPEC_V29.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,43 @@ The Terminal Wallet/BTC section is source-safe before settlement.
225225
It may reveal quote roots, state labels, txids, and readiness blockers.
226226
It may not expose protected AssetPack source, wallet secrets, provider tokens, or private signing material.
227227

228+
## V29 settlement reconciliation repair canon
229+
230+
Settlement reconciliation is an ordinary Terminal workflow, not an after-action database debug task.
231+
The canonical report is produced from:
232+
233+
- ledger observed facts: fee receipts, ledger anchors, journal entries, BTD ranges, ownership events, read licenses, and finality state;
234+
- database projected facts: the Supabase readback rows that claim those ledger facts are durable in the application projection;
235+
- private metaphysical canonical facts: protected source metadata, need/fit context, access policy documents, encrypted storage pointers, disputes, and telemetry context represented only by roots;
236+
- settlement conservation checks: BTC debit/credit and fee/payment roots that must conserve before unlock;
237+
- delivery evidence: post-settlement pull-request visibility and recovery posture.
238+
239+
Drift is classified before repair:
240+
241+
- `missing_database_projection`: the ledger has a fact that the database projection has not read back;
242+
- `ledger_root_mismatch`: the database projection points at a different root than the ledger observation;
243+
- `ledger_finality_mismatch`: the projected finality differs from the observed finality;
244+
- `database_orphan_projection`: the database projects a fact that has no matching ledger observation;
245+
- `settlement_conservation_drift`: BTC debit/credit or fee/payment accounting does not conserve.
246+
247+
Repair actions are canonical and auditable:
248+
249+
- `retry_database_readback`;
250+
- `project_ledger_fact`;
251+
- `update_finality_state`;
252+
- `quarantine_database_projection`;
253+
- `pause_settlement_unlock`;
254+
- `recover_delivery`.
255+
256+
The reconciliation state is one of aligned, retryable, repairable, approval required, or blocked.
257+
Confirmed ledger facts that are missing from the database require operator-approved projection repair.
258+
Reorged or failed finality, database-only orphan projection, or settlement conservation drift blocks unlock and delivery.
259+
Delivery recovery is allowed only when settlement is otherwise aligned and the full AssetPack delivery target is not visible.
260+
261+
Terminal must show drift classes, blockers, repair actions, proof roots, observed facts, projected facts, canonical facts, journal entries, and repair receipts before raw payloads.
262+
The Vercel Sandbox harness must store the reconciliation report as settlement evidence when it claims ledger readback.
263+
The API may persist schema-compatible repair receipts while richer repair actions and proof roots remain report evidence until the registry schema is formally expanded.
264+
228265
## V29 canonical subsystem surfaces
229266

230267
### Depositing and asset supply

BITCODE_SPEC_V29_DELTA.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,16 @@ Closure acceptance:
140140

141141
Gate 6 owns ledger/database/metaphysical separation, journal diffing, reconciliation repair actions, proof-root surfacing, settlement conservation drift handling, and delivery recovery.
142142

143+
Closure acceptance:
144+
145+
- `@bitcode/btd` reconciliation reports carry `state`, `driftKindCounts`, `repairActions`, deterministic proof roots, and settlement conservation status while preserving private metaphysical canonical facts.
146+
- Projection repair receipts classify missing database projections, ledger-root mismatches, ledger-finality mismatches, database-only orphan projections, and settlement conservation drift.
147+
- Repair actions use canonical action kinds: retry database readback, project ledger fact, update finality state, quarantine database projection, pause settlement unlock, and recover delivery.
148+
- The Vercel Sandbox pipeline harness records `ledgerDatabaseReconciliation` evidence after settlement/readback and emits reconciliation state plus repair-action counts in telemetry.
149+
- Terminal journal detail renders drift classes, blocking reasons, ledger observed facts, database projected facts, metaphysical canonical facts, Terminal journal entries, repair actions, proof roots, and repair receipts without requiring browser-network inspection.
150+
- Focused BTD, API, pipeline-harness, and Terminal tests prove repair classification, conservation drift blocking, delivery recovery visibility, and proof-root projection.
151+
- `check:v29-gate6` and the gate-quality workflow fail closed when Gate 6 specification, implementation, tests, or workflow wiring is missing.
152+
143153
### Gate 7: Organization Permissions And Interface Authority
144154

145155
Gate 7 owns organization holdings, roles, read-license usage, registry-derived permission decisions, MCP/ChatGPT action authority alignment, and Terminal permission explainers.

BITCODE_SPEC_V29_NOTES.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,23 @@ Accepted Gate 5 posture:
151151
- Gate pull request titles must carry the uppercase version and gate prefix so gate closure can be audited from GitHub history.
152152
- Gate 5 does not implement reconciliation repair, organization authority, full settlement UI depth, or browser proof; later V29 gates own those slices.
153153

154+
## Gate 6 working notes
155+
156+
Gate 6 hardens the settlement truth boundary after source-safe preview and before paid unlock/delivery are treated as admissible.
157+
158+
Implementation notes:
159+
160+
- Reconciliation must always separate ledger-observed facts from database-projected facts and private metaphysical canonical facts.
161+
- Metaphysical facts remain private root commitments; they are not rendered as protected source.
162+
- Repair receipts classify drift, while repair actions describe the operational next step.
163+
- Settlement conservation drift is not a warning; it blocks unlock because BTC debit/credit truth must conserve before BTD rights are transferred or source is delivered.
164+
- Delivery recovery is surfaced only after settlement is aligned and delivery evidence exists but the pull-request shippable is not visible in the transaction read model.
165+
166+
Operator notes:
167+
168+
- Terminal journal detail is the ordinary repair cockpit for this gate: drift classes, blockers, repair actions, proof roots, journal entries, and repair receipts must be visible without opening network logs.
169+
- Raw payload remains audit material, not the primary operator interface.
170+
154171
## Later-version boundaries
155172

156173
- V30 remains reserved for Protocol/BTD hardening that is not necessary to close Terminal transaction depth.

BITCODE_SPEC_V29_PARITY_MATRIX.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ No `_legacy/` source is active source truth.
5353
| Wallet signer/BTC operations | Gate 3 | `packages/btd/src/btc-fee-operation.ts`, BTC fee route, Terminal Wallet/BTC detail section, BTD and UAPI tests, Gate 3 checker | drafted | Signer session, PSBT, broadcast/finality/reorg/replacement/failure states are ordinary Terminal states. |
5454
| Reading pipeline observability | Gate 4 | `packages/pipelines/asset-pack/src/reading-pipeline-observability.ts`, `packages/pipeline-hosts/src/asset-pack-harness.ts`, Terminal stream components, Gate 4 checker | drafted | Pipeline/phase/PTRR/ThricifiedGeneration/tool/prompt/raw-output/parsed-output telemetry is contract-projected, complete, and readable. |
5555
| AssetPack disclosure rights | Gate 5 | `asset-pack-disclosure.ts`, AssetPack postprocess, sandbox harness, BTD access tests, Terminal disclosure review UI, Gate 5 checker | drafted | Source-safe preview and paid unlock are proven without protected-source leakage. |
56-
| Settlement reconciliation repair | Gate 6 | BTD journal/reconciliation, Supabase readback, Terminal repair UI | pending | Ledger, database, and metaphysical state drift is visible and repairable. |
56+
| Settlement reconciliation repair | Gate 6 | BTD journal/reconciliation, Supabase readback, sandbox harness settlement evidence, Terminal repair UI, Gate 6 checker | drafted | Ledger, database, and metaphysical state drift is classified, proof-rooted, repair-actioned, and visible. |
5757
| Organization permission authority | Gate 7 | access policy, org holdings, MCP/ChatGPT gates, Terminal permission UI | pending | Registry-derived roles, holdings, and read-license authority govern actions. |
5858
| Commercial formalization | Gate 8 | packages/protocol, package tests, import scans, docs | pending | Demonstration-origin commercial internals are package-native and no runtime demo imports remain. |
5959
| Terminal UX quality | Gate 9 | Playwright/Jest/a11y/responsive/browser QA | pending | Complete transaction cockpit is usable by default and inspectable in detail. |
@@ -182,6 +182,31 @@ Gate 4 is complete when Reading pipeline observability is package-owned, stream
182182

183183
- Gate 5 does not reveal protected AssetPack source before settlement.
184184
- Gate 5 does not perform settlement reconciliation repair; Gate 6 owns ledger/database drift and repair.
185+
186+
## Gate 6 Parity
187+
188+
Gate 6 closes the settlement reconciliation slice by making drift ordinary data instead of hidden operator guesswork.
189+
190+
Accepted surfaces:
191+
192+
- `packages/btd/src/reconciliation.ts` is the canonical reconciliation primitive for ledger observed facts, database projected facts, private metaphysical canonical facts, settlement conservation checks, projection repair receipts, repair actions, drift-kind counts, report state, and proof roots.
193+
- `packages/api/src/routes/btd-crypto.ts` accepts settlement conservation checks and binds reconciliation proof roots into the Terminal journal entry for reconciliation settlements.
194+
- `packages/pipeline-hosts/src/asset-pack-harness.ts` stores `asset-pack/settlement.ledgerDatabaseReconciliation`, includes it in evidence, and streams reconciliation state/repair-action count after ledger readback.
195+
- `uapi/app/terminal/terminal-journal-reconciliation.ts` projects the selected transaction into observed facts, projected facts, canonical facts, drift classes, blocking reasons, repair actions, proof roots, and repair receipts.
196+
- `uapi/app/terminal/TerminalTransactionJournalReconciliationCard.tsx` renders the above as a low-detail operator surface with raw payload still available behind expansion.
197+
198+
Accepted failure states:
199+
200+
- Confirmed ledger facts missing from database projection require operator-approved projection repair.
201+
- Reorged or failed fee/anchor finality blocks settlement unlock.
202+
- Database-only orphan projection blocks until quarantined or matched to a ledger observation.
203+
- BTC fee settlement conservation drift blocks unlock and delivery.
204+
- Post-settlement missing pull-request delivery produces a delivery recovery action without exposing protected source.
205+
206+
Gate 6 completion condition:
207+
208+
- `pnpm run check:v29-gate6` passes.
209+
- Focused BTD, API, pipeline-hosts, and UAPI tests prove repair classification, conservation drift, proof roots, and Terminal repair visibility.
185210
- Gate 5 does not implement organization authority beyond read-right state distinctions; Gate 7 owns registry-derived roles and holdings.
186211
- Gate 5 does not add browser proof or full UX polish; Gate 9 owns that surface.
187212
- Gate 5 does not add versioned API routes or source identifiers.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
"check:v29-gate3": "node scripts/check-v29-gate3-wallet-signer-btc-operations.mjs",
5050
"check:v29-gate4": "node scripts/check-v29-gate4-reading-pipeline-observability.mjs",
5151
"check:v29-gate5": "node scripts/check-v29-gate5-assetpack-disclosure-rights.mjs",
52+
"check:v29-gate6": "node scripts/check-v29-gate6-settlement-reconciliation-repair.mjs",
5253
"check:spec-quality": "node scripts/run-bitcode-spec-quality.mjs --mode basic",
5354
"check:spec-quality:title": "node scripts/run-bitcode-spec-quality.mjs --mode strict-from-title",
5455
"check:spec-quality:v24": "node scripts/run-bitcode-spec-quality.mjs --mode strict-version --version V24",

packages/api/jest.config.cjs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
rootDir: '.',
5+
roots: ['<rootDir>/src'],
6+
testMatch: ['<rootDir>/src/**/*.test.ts'],
7+
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
8+
transform: {
9+
'^.+\\.tsx?$': [
10+
'ts-jest',
11+
{
12+
tsconfig: '<rootDir>/tsconfig.json',
13+
diagnostics: false,
14+
},
15+
],
16+
},
17+
};

packages/api/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"types": "src/index.ts",
77
"scripts": {
88
"build": "tsc --noEmit",
9-
"test": "jest",
9+
"test": "jest --config jest.config.cjs",
1010
"dev": "tsc --watch"
1111
},
1212
"dependencies": {

packages/api/src/routes/__tests__/btd-crypto.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,9 +762,15 @@ describe('BTD crypto API builders', () => {
762762
});
763763

764764
expect(settlement.report.blocking).toBe(true);
765+
expect(settlement.report.state).toBe('approval_required');
765766
expect(settlement.report.repairs[0].repairKind).toBe('ledger_finality_state');
767+
expect(settlement.report.repairs[0].repairActionKind).toBe('update_finality_state');
768+
expect(settlement.report.proofRoots.repairPlanRoot).toMatch(/^btd-proof-root:repair-plan:/);
766769
expect(settlement.report.metaphysicalFacts[0].canonicalRoot).toBe('private-source-root');
767770
expect(settlement.terminalJournalEntry.transactionKind).toBe('ledger_database_reconciliation');
771+
expect(settlement.terminalJournalEntry.receiptRoots).toContain(
772+
settlement.report.proofRoots.repairPlanRoot,
773+
);
768774
});
769775

770776
it('builds deployment readiness, telemetry, and upgrade settlements', () => {
@@ -1230,6 +1236,15 @@ describe('BTD crypto API builders', () => {
12301236
private: true,
12311237
},
12321238
],
1239+
settlementConservationChecks: [
1240+
{
1241+
checkId: 'settlement-conservation-api-1',
1242+
expectedDebitSats: 1000,
1243+
observedDebitSats: 1000,
1244+
expectedCreditSats: 1000,
1245+
observedCreditSats: 900,
1246+
},
1247+
],
12331248
commitToRegistry: true,
12341249
issuedAt,
12351250
}),
@@ -1240,6 +1255,8 @@ describe('BTD crypto API builders', () => {
12401255
expect(response.status).toBe(200);
12411256
expect(body.kind).toBe('btd_ledger_database_reconciliation_settlement');
12421257
expect(body.report.blocking).toBe(true);
1258+
expect(body.report.state).toBe('blocked');
1259+
expect(body.report.driftKindCounts.settlement_conservation_drift).toBe(1);
12431260
expect(body.report.metaphysicalFacts[0].canonicalRoot).toBe('private-source-root');
12441261
expect(body.committed).toBe(true);
12451262
expect(insertReconciliationRepair).toHaveBeenCalledWith(

packages/api/src/routes/btd-crypto.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ export interface BtdLedgerDatabaseReconciliationInput {
302302
ledgerFacts: LedgerObservedFact[];
303303
databaseFacts: DatabaseProjectedFact[];
304304
metaphysicalFacts?: MetaphysicalCanonicalFact[];
305+
settlementConservationChecks?: Parameters<typeof reconcileLedgerDatabaseProjection>[0]['settlementConservationChecks'];
305306
commitToRegistry?: boolean;
306307
actorId?: string;
307308
issuedAt?: string;
@@ -926,6 +927,7 @@ export function buildBtdLedgerDatabaseReconciliationSettlement(
926927
ledgerFacts: input.ledgerFacts,
927928
databaseFacts: input.databaseFacts,
928929
metaphysicalFacts: input.metaphysicalFacts,
930+
settlementConservationChecks: input.settlementConservationChecks,
929931
issuedAt: input.issuedAt,
930932
});
931933
const terminalJournalEntry = buildTerminalJournalEntry({
@@ -950,6 +952,10 @@ export function buildBtdLedgerDatabaseReconciliationSettlement(
950952
report.reconciliationId,
951953
...report.repairs.map((repair) => repair.repairId),
952954
...report.metaphysicalFacts.map((fact) => fact.receiptRoot ?? fact.canonicalRoot),
955+
report.proofRoots.ledgerObservedRoot,
956+
report.proofRoots.databaseProjectionRoot,
957+
report.proofRoots.repairPlanRoot,
958+
report.proofRoots.settlementConservationRoot,
953959
],
954960
ledgerAnchorIds: input.ledgerFacts.map((fact) => fact.factId),
955961
exchangeSequence: BigInt(Math.max(1, input.ledgerFacts.length + input.databaseFacts.length)),

0 commit comments

Comments
 (0)