Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/bitcode-gate-quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ jobs:
node scripts/check-bitcode-canonical-inputs.mjs --current-target V28
node scripts/check-v29-gate1-objectives-and-gating.mjs --skip-branch-check
node scripts/check-v29-gate2-terminal-transaction-read-models.mjs --skip-branch-check
node scripts/check-v29-gate3-wallet-signer-btc-operations.mjs --skip-branch-check

- name: Validate source casing and imports
run: |
Expand All @@ -62,6 +63,7 @@ jobs:
- name: Test gate packages
run: |
pnpm --filter @bitcode/btd test
pnpm --filter @bitcode/btd test -- --runTestsByPath __tests__/btc-fee-operation.test.ts
pnpm --filter @bitcode/pipeline-asset-pack exec jest --config jest.config.cjs --passWithNoTests --forceExit
pnpm --filter @bitcode/pipeline-hosts exec jest --config jest.config.cjs --passWithNoTests --forceExit

Expand All @@ -74,6 +76,7 @@ jobs:
tests/terminalDepositReadWorkbench.test.ts \
tests/terminalTransactionQuery.test.ts \
tests/terminalTransactionReadModel.test.ts \
tests/terminalWalletBtcOperation.test.ts \
tests/pipelineExecutionLogHeader.test.tsx \
--runInBand

Expand Down
36 changes: 31 additions & 5 deletions BITCODE_SPEC_V29.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@ The V29 domain model extends V28 operationally:
- `FindingFitsResult`: all threshold-passing fit deposits, search roots, ranking roots, blockers, no-worthy-fit posture, and selected synthesis context.
- `AssetPackPreview`: source-safe measurements, quality score, disclosure policy, access policy, fee quote, range projection, and protected-source lock.
- `SettlementUnlock`: BTC fee proof, BTD range/read-license/right transfer, paid disclosure decision, delivery admission, and reconciliation state.
- `BtcFeeQuote`: deterministic BTC fee quote with quote root, measurement root, purpose, network, sats, pricing version, expiration, and lifecycle state.
- `WalletSignerSessionRecovery`: signer-session posture proving whether the Reader wallet can sign a PSBT without server custody.
- `BtcFeeOperationPosture`: operational state over quote, signer, PSBT, broadcast, finality, replacement, reorg, failure, and blocked readiness.
- `TerminalTransaction`: URL-addressable activity combining execution, pipeline, agent, tool, prompt, ledger, database, delivery, and proof state.
- `TerminalTransactionReadModel`: typed operator projection of a selected `TerminalTransaction`, including route state, active detail section, low-detail summary, section availability, expandable audit posture, and source-safe raw-payload boundary.

Expand Down Expand Up @@ -191,14 +194,37 @@ The Terminal transaction read model must contain:
- selected transaction identity, activity type, lens, status, participant, repository, branch, timing, and proof posture;
- route state with canonical hrefs for each section and with the former `runId` carrier removed on write;
- low-detail default summary, metrics, and posture chips sufficient for ordinary operation without opening raw JSON;
- section read models for Shippables, identity, closure, proofs, history, journal, activity stream, and console;
- section read models for Shippables, identity, Wallet/BTC, closure, proofs, history, journal, activity stream, and console;
- explicit section availability: available, empty, or blocked with an operator-readable reason;
- expandable detail metadata preserving row counts, metric counts, payload availability, and target DOM section ids;
- a source-safe disclosure boundary: protected AssetPack source is never displayed before settlement, and raw payloads remain audit detail rather than the default operator contract.

The model is deterministic from execution history, detail readback, route query state, and data mode.
It must tolerate partial live readback by preserving a fallback selected-run projection while naming empty or blocked sections.

## V29 Wallet/BTC operation canon

Wallet and BTC fee state is an ordinary Terminal transaction surface, not an opaque settlement footnote.
The canonical wallet/BTC operation model is owned by `packages/btd` and projected by Terminal.

The operation model must contain:

- quote lifecycle: quoted, accepted, expired, superseded, and failed;
- deterministic quote root over quote id, purpose, network, sats, measurement root, issue time, and expiration;
- signer recovery: missing, prepared authorization required, stored authorization requiring live reconnect, expired, revoked, failed, network mismatch, capability missing, server-custody rejected, or live authorized;
- PSBT handoff: accepted quote prepares a PSBT; the wallet signs; the signed PSBT broadcasts;
- finality states: prepared, signed, broadcast, confirmed, replaced, reorged, and failed;
- blocked-readiness receipts naming the blocker id, summary, required action, quote id, wallet session id, receipt id, and no-server-custody posture;
- Terminal read rows and metrics for state, network, sats, confirmations, quote root, wallet session, payer wallet, PSBT handoff, txid, server custody, and next action.

No server component may custody the Reader private key.
Server-side routes may prepare receipts, validate proofs, serialize quote/posture evidence, and persist registry rows only when explicitly requested.
They must not claim signature, broadcast, finality, settlement unlock, or rights transfer without matching receipt and readback evidence.

The Terminal Wallet/BTC section is source-safe before settlement.
It may reveal quote roots, state labels, txids, and readiness blockers.
It may not expose protected AssetPack source, wallet secrets, provider tokens, or private signing material.

## V29 canonical subsystem surfaces

### Depositing and asset supply
Expand Down Expand Up @@ -265,10 +291,10 @@ It must tolerate partial live readback by preserving a fallback selected-run pro

- Current canonical objects and emitted artifacts: BTC fee quote, PSBT, payment observation, settlement unlock, BTD range, source-to-shares, journal entry, ledger anchor, reconciliation report.
- Current algorithms and derivation rules: Share-to-Fee pricing is deterministic from measurement weights and measurement volume; BTC fee payment gates protected-source unlock and read-license/right transfer.
- Current invariants and fail-closed conditions: settlement conservation drift, missing payment proof, stale fee quote, reorg, replacement, broadcast failure, or custody ambiguity blocks finality.
- Current proof obligations: quote root, PSBT state, txid or blocked-readiness receipt, ledger anchor, source-to-shares report, and reconciliation result.
- Current source-bearing implementation basis: `packages/btd` fee/range/journal/reconciliation primitives, UAPI settlement routes, Terminal payment UI, and Supabase projections.
- Current validating commands and parity basis: BTD tests, settlement route tests, staging ledger/database readback, and V29 gate checks.
- Current invariants and fail-closed conditions: settlement conservation drift, missing payment proof, stale fee quote, unaccepted quote, missing signer capability, reorg, replacement, broadcast failure, or custody ambiguity blocks finality.
- Current proof obligations: quote root, signer recovery state, PSBT state, txid or blocked-readiness receipt, ledger anchor, source-to-shares report, and reconciliation result.
- Current source-bearing implementation basis: `packages/btd` fee/range/journal/reconciliation primitives, UAPI settlement routes, Terminal Wallet/BTC section, and Supabase projections.
- Current validating commands and parity basis: BTD tests, settlement route tests, Terminal wallet/BTC tests, staging ledger/database readback, and V29 gate checks.
- Current accepted boundaries: value-bearing mainnet stays outside V29 unless separately approved.

### Proof contract, witnesses, and replay
Expand Down
10 changes: 10 additions & 0 deletions BITCODE_SPEC_V29_DELTA.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ Closure acceptance:

Gate 3 owns wallet connection depth, signer-session recovery, BTC fee quote lifecycle, PSBT handoff, broadcast/finality/replacement/reorg/failure states, blocked-readiness receipts, and no server-custody posture.

Closure acceptance:

- `packages/btd` defines `BtcFeeQuote`, `WalletSignerSessionRecovery`, `BtcFeeBlockedReadinessReceipt`, and `BtcFeeOperationPosture`.
- BTC fee quotes have deterministic quote roots, accepted/expired/superseded/failed lifecycle transitions, BTC-only fee asset, and measurement-root pricing posture.
- Signer recovery distinguishes missing, prepared, stored reconnect, expired, revoked, failed, network mismatch, capability missing, server-custody rejected, and live authorized states.
- BTC fee operation posture maps accepted quote, PSBT-ready, signed, broadcast, confirmed, replaced, reorged, failed, and blocked states into next actions and settlement booleans.
- The BTC fee API serializes operation posture and accepts JSON-safe quote carriers without mutating registry rows unless explicitly requested.
- Terminal adds a Wallet/BTC transaction detail section with source-safe metrics, rows, blockers, quote root, signer session, PSBT handoff, txid, finality, and server-custody posture.
- Gate-quality CI runs the Gate 3 checker plus BTD operation and Terminal Wallet/BTC tests.

### Gate 4: Reading Transaction Recovery And Pipeline Observability

Gate 4 owns deep Terminal visibility over `ReadNeedComprehensionSynthesis` and `ReadFitsFindingSynthesis`, including execution, phase, PTRR agent, PTRR step, ThricifiedGeneration, prompt, tool, output, and typed parse telemetry.
Expand Down
14 changes: 14 additions & 0 deletions BITCODE_SPEC_V29_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ For a simplified reading of V29:

3. **Gate 3: Wallet Signer Session And BTC Fee Operations**
- Deepen signer-session recovery, BTC fee quote, PSBT handoff, broadcast, replacement, reorg, failure, and blocked-readiness states.
- Acceptance detail: BTC quote lifecycle and signer recovery are package-owned primitives; API responses expose JSON-safe operation posture; Terminal exposes Wallet/BTC as a route-owned transaction detail section with blockers before raw payloads.

4. **Gate 4: Reading Transaction Recovery And Pipeline Observability**
- Make `ReadNeedComprehensionSynthesis` and `ReadFitsFindingSynthesis` execution telemetry fully readable in Terminal at execution, phase, PTRR agent, PTRR step, ThricifiedGeneration, prompt, tool, raw output, and parsed output levels.
Expand Down Expand Up @@ -106,6 +107,19 @@ The low-detail default should answer:

The detailed view may still carry raw payload accordions for audit, but the ordinary collapsed view must be typed and readable.

## Gate 3 working notes

Gate 3 makes wallet and BTC fee operation readable and typed before the later settlement-repair gate.

Accepted Gate 3 posture:

- BTC fee quote lifecycle and quote-root derivation live in `packages/btd`.
- Signer-session recovery is explicit and never implies server custody.
- PSBT, signed, broadcast, confirmed, replaced, reorged, failed, and blocked readiness are represented as operation posture, not prose-only route errors.
- The BTC fee API can serialize the operation posture and normalize JSON-safe quote carriers.
- Terminal has a Wallet/BTC detail section so fee readiness is visible before raw ledger payload inspection.
- Gate 3 does not implement settlement reconciliation repair; Gate 6 owns drift repair and ledger/database reconciliation action depth.

## Later-version boundaries

- V30 remains reserved for Protocol/BTD hardening that is not necessary to close Terminal transaction depth.
Expand Down
26 changes: 25 additions & 1 deletion BITCODE_SPEC_V29_PARITY_MATRIX.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ No `_legacy/` source is active source truth.
| Draft family and branch posture | Gate 1 | `BITCODE_SPEC_V29.md`, DELTA, NOTES, PARITY, `BITCODE_SPEC.txt`, branch `v29/gate-1-objectives-and-gating` | drafted | V29 family validates in draft mode over active V28 and `check:v29-gate1` passes. |
| Workflow retargeting | Gate 1 | `.github/workflows/bitcode-gate-quality.yml`, `.github/workflows/bitcode-canon-quality.yml` | drafted | CI checks V28 active / V29 draft posture instead of stale V27/V28 posture. |
| Terminal transaction read models | Gate 2 | `uapi/app/terminal/terminal-transaction-read-model.ts`, `uapi/app/terminal/terminal-transaction-query.ts`, `TerminalTransactionWorkspace.tsx`, `TerminalTransactionDetailSurface.tsx`, UAPI tests, Gate 2 checker | drafted | Terminal transaction state is URL-addressable, recoverable, typed, low-detail by default, and expandable without raw JSON as the ordinary operator contract. |
| Wallet signer/BTC operations | Gate 3 | `packages/btd`, wallet API, BTC fee route, Terminal wallet UI | pending | Signer session, PSBT, broadcast/finality/reorg/replacement/failure states are ordinary Terminal states. |
| 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. |
| Reading pipeline observability | Gate 4 | `packages/pipelines/asset-pack`, `packages/pipeline-hosts`, Terminal stream components | pending | Pipeline/phase/PTRR/ThricifiedGeneration/tool/prompt telemetry is complete and readable. |
| AssetPack disclosure rights | Gate 5 | BTD access primitives, AssetPack preview UI, disclosure policy tests | pending | Source-safe preview and paid unlock are proven without source leakage. |
| Settlement reconciliation repair | Gate 6 | BTD journal/reconciliation, Supabase readback, Terminal repair UI | pending | Ledger, database, and metaphysical state drift is visible and repairable. |
Expand All @@ -68,6 +68,7 @@ No `_legacy/` source is active source truth.
| Spec-family shape | V29 SPEC, DELTA, NOTES, and PARITY satisfy the full spec-family checker | drafted |
| Gate 1 script | `pnpm run check:v29-gate1` fails closed on stale posture or missing gates | drafted |
| Gate 2 read model | `pnpm run check:v29-gate2` proves typed route-owned Terminal transaction reading | drafted |
| Gate 3 wallet/BTC operation | `pnpm run check:v29-gate3` proves quote lifecycle, signer recovery, blocked readiness, API posture, and Terminal Wallet/BTC detail | drafted |
| Product implementation gates | Gates 3-9 close remaining Terminal transaction depth with tests and docs | pending |
| Promotion gate | Gate 10 closes generated proof and promotion automation | pending |

Expand Down Expand Up @@ -115,3 +116,26 @@ Gate 1 is complete when the V29 draft family validates, `check:v29-gate1` passes
## Gate 2 completion condition

Gate 2 is complete when Terminal selected transaction state rewrites recoverable URLs, a typed read model drives detail navigation and low-detail summaries, focused tests pass, `check:v29-gate2` passes, CI invokes the checker, docs name the implemented source surfaces, and the gate branch is committed and pushed for review into `version/v29`.

## Gate 3 Parity

| Requirement | Source evidence | Current V29 judgment |
| --- | --- | --- |
| BTC fee quote lifecycle is package-owned | `packages/btd/src/btc-fee-operation.ts`, `packages/btd/__tests__/btc-fee-operation.test.ts` | drafted |
| Signer-session recovery is explicit and no-custody | `buildWalletSignerSessionRecovery`, BTD operation tests | drafted |
| Blocked-readiness receipts name blocker and repair path | `buildBtcFeeBlockedReadinessReceipt`, BTD operation tests | drafted |
| Operation posture covers PSBT, broadcast, finality, replacement, reorg, failure | `buildBtcFeeOperationPosture`, BTD operation tests | drafted |
| BTC fee route serializes JSON-safe operation posture | `packages/api/src/routes/btd-crypto.ts`, route typecheck, route tests | drafted |
| Terminal exposes Wallet/BTC detail section | `terminal-transaction-query.ts`, `terminal-transaction-read-model.ts`, `TerminalTransactionWalletBtcCard.tsx`, `terminal-wallet-btc-operation.ts`, UAPI tests | drafted |
| Gate 3 checker is wired to package scripts and CI | `scripts/check-v29-gate3-wallet-signer-btc-operations.mjs`, `package.json`, gate workflow | drafted |

## Gate 3 accepted boundaries

- Gate 3 does not implement full settlement reconciliation repair; Gate 6 owns drift repair and readback repair actions.
- Gate 3 does not expose protected AssetPack source before settlement.
- Gate 3 does not broadcast value-bearing mainnet transactions.
- Gate 3 does not add versioned API routes or source identifiers.

## Gate 3 completion condition

Gate 3 is complete when package primitives model BTC quotes, signer recovery, operation posture, and blocked readiness; API responses serialize operation posture; Terminal has a Wallet/BTC route-owned detail section; focused package and UAPI tests pass; `check:v29-gate3` passes; CI invokes the checker and tests; docs name the implemented source surfaces; and the gate branch is committed and pushed for review into `version/v29`.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"check:v28-gate13": "node scripts/check-v28-gate13-product-closure-promotion-readiness.mjs",
"check:v29-gate1": "node scripts/check-v29-gate1-objectives-and-gating.mjs",
"check:v29-gate2": "node scripts/check-v29-gate2-terminal-transaction-read-models.mjs",
"check:v29-gate3": "node scripts/check-v29-gate3-wallet-signer-btc-operations.mjs",
"check:spec-quality": "node scripts/run-bitcode-spec-quality.mjs --mode basic",
"check:spec-quality:title": "node scripts/run-bitcode-spec-quality.mjs --mode strict-from-title",
"check:spec-quality:v24": "node scripts/run-bitcode-spec-quality.mjs --mode strict-version --version V24",
Expand Down
42 changes: 41 additions & 1 deletion packages/api/src/routes/__tests__/btd-crypto.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ import {
buildPostBtdReadAccessRoute,
buildPostBtdTerminalJournalRoute,
} from '../btd-crypto';
import { createBtdMeasureMintState } from '@bitcode/btd';
import {
advanceBtcFeeQuote,
buildBtcFeeQuote,
createBtdMeasureMintState,
} from '@bitcode/btd';

const issuedAt = '2026-05-06T00:00:00.000Z';

Expand All @@ -59,6 +63,23 @@ function walletSessionInput() {
};
}

function acceptedFeeQuote() {
return advanceBtcFeeQuote(
buildBtcFeeQuote({
quoteId: 'quote-api-1',
feePurpose: 'asset_pack_anchor',
network: 'signet',
sats: 1200n,
satsPerVbyte: 4,
measurementRoot: 'measurement-root-api-1',
relatedAssetPackId: 'asset-pack-api-1',
issuedAt,
expiresAt: '2026-05-06T01:00:00.000Z',
}),
{ state: 'accepted' },
);
}

function mintDraftInput() {
return {
assetPackId: 'asset-pack-api-1',
Expand Down Expand Up @@ -511,6 +532,7 @@ describe('BTD crypto API builders', () => {
receiptId: 'btc-fee-api-1',
feePurpose: 'asset_pack_anchor',
payerSession: walletSessionInput(),
feeQuote: acceptedFeeQuote(),
psbt: 'cHNidP8BAHECAAAAA',
satsPaid: 1200n,
satsPerVbyte: 4,
Expand Down Expand Up @@ -546,6 +568,12 @@ describe('BTD crypto API builders', () => {
expect(prepared.receipt.feeAsset).toBe('BTC');
expect(prepared.receipt.walletAuthorizationProof.proofKind).toBe('message_signature');
expect(prepared.receipt.exchangeSequence).toBe(11n);
expect(prepared.operationPosture).toMatchObject({
phase: 'psbt_ready',
canSignPsbt: true,
noServerCustody: true,
quote: { quoteId: 'quote-api-1' },
});
expect(prepared.terminalJournalEntry.transactionKind).toBe('btc_fee_payment');
expect(confirmed.receipt.txid).toBe('btc-txid-api-1');
expect(confirmed.receipt.confirmations).toBe(2);
Expand Down Expand Up @@ -915,6 +943,10 @@ describe('BTD crypto API builders', () => {
receiptId: 'btc-fee-api-1',
feePurpose: 'asset_pack_anchor',
payerSession: walletSessionInput(),
feeQuote: {
...acceptedFeeQuote(),
sats: '1200',
},
psbt: 'cHNidP8BAHECAAAAA',
satsPaid: '1200',
satsPerVbyte: 4,
Expand All @@ -933,6 +965,14 @@ describe('BTD crypto API builders', () => {
expect(body.receipt.feeAsset).toBe('BTC');
expect(body.receipt.serverCustody).toBe(false);
expect(body.receipt.exchangeSequence).toBe('11');
expect(body.operationPosture).toMatchObject({
phase: 'psbt_ready',
canSignPsbt: true,
quote: {
quoteId: 'quote-api-1',
sats: '1200',
},
});
expect(body.committed).toBe(true);
expect(insertBtcFeeTransaction).toHaveBeenCalledWith(
expect.objectContaining({
Expand Down
Loading
Loading