diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b3f86f9..c74ee00e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,14 @@ use the date the change landed on `main`. ## Unreleased +### Fixed +- `scripts/ci-local.sh conformance` failed on any uncommitted mirror change, + so a correctly re-mirrored protocol edit could not pass the local gate + before it was committed. It now compares the mirror's file contents before + and after re-mirroring; new, edited and deleted protocol files that were + never re-mirrored still fail it. (`conformance.yml` keeps its + clean-checkout `git status` check.) + ## 2026-10-23 ### Fixed diff --git a/apps/backend/CHANGELOG.md b/apps/backend/CHANGELOG.md index 5e74c105..9c282465 100644 --- a/apps/backend/CHANGELOG.md +++ b/apps/backend/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- A `Settlement` or `TransactionStatus` posted to `POST /api/v1/transaction` + for an existing transaction always answered `409` and never changed its + status: every `@type` was INSERTed under the referenced id. For an unknown + id it created an orphan "completed" transaction instead. Both now update the + existing transaction under a row lock, recording a `transaction.settled` / + `transaction.status_updated` loop event and a `status-updated` evidence + entry: `404 NOT_FOUND` for an unknown transaction, and `409 CONFLICT` for + leaving a terminal state (`completed`, `cancelled`, `disputed`) for a + non-terminal one or settling a terminal transaction again (SPEC §3.6). + A terminal-to-terminal update (e.g. disputing a completed transaction) is + allowed. The stored payload stays the original `MaterialTransaction`. + ## [0.11.0] - 2026-10-23 ### Security diff --git a/apps/backend/docs/SPEC-COMPLIANCE.md b/apps/backend/docs/SPEC-COMPLIANCE.md index 2de1015a..672b7b22 100644 --- a/apps/backend/docs/SPEC-COMPLIANCE.md +++ b/apps/backend/docs/SPEC-COMPLIANCE.md @@ -25,7 +25,7 @@ Checked against loop-protocol **v0.5.1** (SPECIFICATION.md v0.2.0 baseline, `ope | `POST /api/v1/product/search` | Core-DP (openapi tag) | ✅ Implemented | Additive lab profile endpoint | | `GET /api/v1/node/info` | MUST (§8.1) | ✅ Implemented | Validates against canonical node-info schema (location, capability enum enforced via config warning) | | `GET /api/v1/signals` | MUST (§8.1) | ✅ Implemented (v0.4.0) | LoopSignalConfig from `loop_signal_config` table; seeded per §6.1 example | -| `POST /api/v1/transaction` | MUST (§8.1) | ✅ Implemented (v0.4.0) | Canonical transaction schema (oneOf MaterialTransaction / Settlement / TransactionStatus); responds TransactionStatus with resolvable `settlement_url`; §3.6 status values enforced by DB CHECK; Idempotency-Key conflicts answered with the Core-DP `conflict` body (fixed v0.4.3) | +| `POST /api/v1/transaction` | MUST (§8.1) | ✅ Implemented (v0.4.0) | Canonical transaction schema (oneOf MaterialTransaction / Settlement / TransactionStatus); responds TransactionStatus with resolvable `settlement_url`; §3.6 status values enforced by DB CHECK; Settlement / TransactionStatus update the existing transaction (404 if unknown, 409 when leaving a terminal state or settling a terminal one; fixed after v0.11.0); Idempotency-Key conflicts answered with the Core-DP `conflict` body (fixed v0.4.3) | | `POST /api/v1/federate/announce` | MUST (§8.2) | ✅ Implemented (v0.4.0) | §9.2 headers enforced (see below) | | `POST /api/v1/federate/offer` | MUST (§8.2) | ✅ Implemented (v0.4.0) | §9.2 headers enforced; material must be hosted locally; expired offers rejected | | `POST /api/v1/material-status` | Optional (lab ext) | ✅ Implemented | Lab-only extension, excluded from protocol openapi.json | @@ -82,7 +82,7 @@ LoopCoin wallet, currency engine, or settlement execution. | Surface | Behavior | Status | | --- | --- | --- | -| `POST /api/v1/transaction` | Persists MaterialTransaction / Settlement / TransactionStatus; returns TransactionStatus with resolvable `settlement_url` | ✅ Record-only | +| `POST /api/v1/transaction` | Persists a MaterialTransaction; a Settlement / TransactionStatus updates that transaction's status (event + evidence recorded); returns TransactionStatus with resolvable `settlement_url` | ✅ Record-only | | `GET /api/v1/transaction/:id` | Returns stored TransactionStatus; no wallet lookup or clearing | ✅ Record-only | | LoopCoin transfer / config HTTP routes | Not implemented (spec §5 schema types exist; no wallet engine) | ⚠️ Intentional lab boundary | | `GET /api/v1/node/info` `capabilities` | May include `loopcoin`; advertises intent only — no currency engine behind it | ⚠️ Intentional lab boundary | diff --git a/apps/backend/src/db/loop.ts b/apps/backend/src/db/loop.ts index dcd70e51..9fbd5739 100644 --- a/apps/backend/src/db/loop.ts +++ b/apps/backend/src/db/loop.ts @@ -806,9 +806,26 @@ export function transactionIdentity(payload: LoopTransactionPayload): { id: stri return { id: payload.transaction_id as string, status: payload.status as string }; } +/** SPEC §3.6: a transaction in one of these states never leaves it for a non-terminal one. */ +export const TRANSACTION_TERMINAL_STATUSES = ['completed', 'cancelled', 'disputed']; + +/** + * MaterialTransaction creates the transaction (a duplicate id is a 23505 the + * route maps to 409). Settlement and TransactionStatus are updates of an + * existing transaction: they used to be INSERTed under the referenced id too, + * so for a real transaction they always failed with 409, and for an unknown + * one they created an orphan row. They now lock the row, apply the §3.6 rule + * (no way back from a terminal state; a Settlement completes a transaction + * that is not already terminal) and update its status. The stored payload + * stays the original MaterialTransaction; the Settlement/TransactionStatus + * body is kept in the loop event and the evidence log. + */ export async function createLoopTransaction(payload: LoopTransactionPayload, db?: PoolClient): Promise { + const { id, status } = transactionIdentity(payload); + if (payload['@type'] !== 'MaterialTransaction') { + return updateLoopTransactionStatus(payload, id, status, db); + } return withTransaction(async (client) => { - const { id, status } = transactionIdentity(payload); const { rows } = await client.query( `INSERT INTO loop_transactions (id, status, payload) VALUES ($1, $2, $3) @@ -831,6 +848,52 @@ export async function createLoopTransaction(payload: LoopTransactionPayload, db? }, db); } +async function updateLoopTransactionStatus( + payload: LoopTransactionPayload, + id: string, + status: string, + db?: PoolClient, +): Promise { + const settlement = payload['@type'] === 'Settlement'; + return withTransaction(async (client) => { + const { rows: current } = await client.query( + 'SELECT status FROM loop_transactions WHERE id = $1 FOR UPDATE', + [id], + ); + const existing = current[0] as { status: string } | undefined; + if (!existing) { + throw new LoopStateError('not_found', `Transaction with ID ${id} not found`); + } + if (TRANSACTION_TERMINAL_STATUSES.includes(existing.status)) { + if (settlement) { + throw new LoopStateError('conflict', `Transaction ${id} is already ${existing.status} and cannot be settled again`); + } + if (!TRANSACTION_TERMINAL_STATUSES.includes(status)) { + throw new LoopStateError('conflict', `Transaction ${id} is ${existing.status} (terminal) and cannot return to ${status}`); + } + } + + const { rows } = await client.query( + `UPDATE loop_transactions SET status = $2, updated_at = NOW() + WHERE id = $1 + RETURNING id, updated_at`, + [id, status], + ); + const updated = rows[0] as { id: string; updated_at: string }; + const eventType = settlement ? 'transaction.settled' : 'transaction.status_updated'; + const event = buildLoopEvent(eventType, 'transaction', updated.id, payload, updated.updated_at); + await insertLoopEvent( + { event_type: eventType, entity_type: 'transaction', entity_id: updated.id, payload: event }, + client, + ); + await insertLoopEvidence( + { subject: { type: 'transaction', id: updated.id }, eventType: 'status-updated', data: payload }, + client, + ); + return { id: updated.id, created_at: updated.updated_at, event }; + }, db); +} + export async function getLoopTransactionById(id: string): Promise { const { rows } = await pool.query( 'SELECT id, status, payload, created_at, updated_at FROM loop_transactions WHERE id = $1', diff --git a/apps/backend/src/routes/transactions.ts b/apps/backend/src/routes/transactions.ts index a4f145c4..8523f8f5 100644 --- a/apps/backend/src/routes/transactions.ts +++ b/apps/backend/src/routes/transactions.ts @@ -7,6 +7,7 @@ import { config } from '../config'; import { createLoopTransaction, getLoopTransactionById, + LoopStateError, transactionIdentity, type LoopTransactionPayload, } from '../db/loop'; @@ -88,6 +89,7 @@ export async function registerTransactionRoutes(app: FastifyInstance, deps: Tran response: { 201: transactionStatusResponseSchema, 400: specErrorResponseSchema, + 404: specErrorResponseSchema, 409: mixedWriteErrorResponseSchema, }, }, @@ -117,6 +119,13 @@ export async function registerTransactionRoutes(app: FastifyInstance, deps: Tran sendCoreDpError(reply, error); return; } + // Settlement / TransactionStatus for an unknown transaction (404), or + // one that would leave a terminal state (409, SPEC §3.6). + if (error instanceof LoopStateError) { + sendSpecError(reply, error.kind === 'not_found' ? 'NOT_FOUND' : 'CONFLICT', error.message, + error.kind === 'not_found' ? { searched_id: transactionIdentity(payload).id } : undefined); + return; + } const pgError = error as DbLikeError; if (pgError?.code === '23505') { sendSpecError(reply, 'CONFLICT', 'Transaction with this id already exists'); diff --git a/apps/backend/tests/transactions.routes.test.ts b/apps/backend/tests/transactions.routes.test.ts index f421eeee..8fe2eb15 100644 --- a/apps/backend/tests/transactions.routes.test.ts +++ b/apps/backend/tests/transactions.routes.test.ts @@ -318,3 +318,98 @@ describe('GET /api/v1/transaction/:id', () => { expect(payload.error.details.searched_id).toBe('TXN-2026-01-01-999'); }); }); + +// Settlement and TransactionStatus update an existing transaction (SPEC §3.6). +// They used to be INSERTed under the referenced id, so settling a real +// transaction always failed with 409 and settling an unknown one created an +// orphan "completed" row. These run against the real database layer. +describe('POST /api/v1/transaction updates an existing transaction', () => { + const ids: string[] = []; + const newId = () => { + const id = `TXN-2026-10-23-${Math.floor(Math.random() * 1e9).toString().padStart(9, '0')}`; + ids.push(id); + return id; + }; + const statusOf = async (id: string) => + ((await pool.query('SELECT status FROM loop_transactions WHERE id = $1', [id])).rows[0] as { status: string } | undefined)?.status; + const post = async (payload: Record) => { + const app = Fastify({ logger: false }); + registerLoopProtocolParsers(app); + registerLoopSchemas(app); + await registerTransactionRoutes(app); + try { + return await app.inject({ method: 'POST', url: '/api/v1/transaction', payload }); + } finally { + await app.close(); + } + }; + const transactionStatus = (id: string, status: string) => ({ + '@context': 'https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.2.0.jsonld', + '@type': 'TransactionStatus', + transaction_id: id, + status, + updated_at: '2026-10-23T12:00:00Z', + }); + + afterAll(async () => { + if (dbReady) { + for (const id of ids) { + await pool.query('DELETE FROM loop_transactions WHERE id = $1', [id]); + } + } + }); + + it.skipIf(!dbReady)('settles a pending transaction: 201 completed, and the stored status follows', async () => { + const id = newId(); + expect((await post({ ...materialTransactionPayload, id })).statusCode).toBe(201); + + const settled = await post({ ...settlementPayload, transaction_id: id }); + expect(settled.statusCode).toBe(201); + expect(settled.json().status).toBe('completed'); + expect(await statusOf(id)).toBe('completed'); + + const events = await pool.query( + "SELECT count(*)::int AS n FROM loop_events WHERE entity_id = $1 AND event_type = 'transaction.settled'", + [id], + ); + expect(events.rows[0].n).toBe(1); + const evidence = await pool.query( + "SELECT count(*)::int AS n FROM loop_evidence WHERE subject_type = 'transaction' AND subject_id = $1 AND event_type = 'status-updated'", + [id], + ); + expect(evidence.rows[0].n).toBe(1); + }); + + it.skipIf(!dbReady)('answers 404 for a Settlement of an unknown transaction and creates nothing', async () => { + const id = newId(); + const response = await post({ ...settlementPayload, transaction_id: id }); + expect(response.statusCode).toBe(404); + expect(response.json().error.code).toBe('NOT_FOUND'); + expect(response.json().error.details.searched_id).toBe(id); + expect(await statusOf(id)).toBeUndefined(); + }); + + it.skipIf(!dbReady)('applies TransactionStatus updates and refuses to leave a terminal state', async () => { + const id = newId(); + expect((await post({ ...materialTransactionPayload, id })).statusCode).toBe(201); + + const confirmed = await post(transactionStatus(id, 'confirmed')); + expect(confirmed.statusCode).toBe(201); + expect(await statusOf(id)).toBe('confirmed'); + + expect((await post(transactionStatus(id, 'completed'))).statusCode).toBe(201); + + // terminal -> non-terminal: rejected (§3.6 MUST NOT, SHOULD answer 409) + const backwards = await post(transactionStatus(id, 'in_transit')); + expect(backwards.statusCode).toBe(409); + expect(backwards.json().error.code).toBe('CONFLICT'); + expect(await statusOf(id)).toBe('completed'); + + // a completed transaction cannot be settled a second time + expect((await post({ ...settlementPayload, transaction_id: id })).statusCode).toBe(409); + + // terminal -> terminal stays possible (e.g. disputing a completed transaction) + expect((await post(transactionStatus(id, 'disputed'))).statusCode).toBe(201); + expect(await statusOf(id)).toBe('disputed'); + }); +}); diff --git a/apps/site/public/projects/loop-protocol/CHANGELOG.md b/apps/site/public/projects/loop-protocol/CHANGELOG.md index 520b0fff..dc9e2807 100644 --- a/apps/site/public/projects/loop-protocol/CHANGELOG.md +++ b/apps/site/public/projects/loop-protocol/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- `openapi.json`: `POST /api/v1/transaction` documents that a `Settlement` or + `TransactionStatus` updates the existing transaction named by + `transaction_id` (SPECIFICATION.md §3.6), and lists the `400`, `404` + (unknown transaction) and `409` (duplicate id, or leaving a terminal state) + responses it can return; only `201` was listed. + ### Changed - The protocol is developed in the public monorepo https://github.com/MycelAI/LocalLOOP: `CONTRIBUTING.md` invites issues and diff --git a/apps/site/public/projects/loop-protocol/openapi.json b/apps/site/public/projects/loop-protocol/openapi.json index 9582c7b5..8c87eb20 100644 --- a/apps/site/public/projects/loop-protocol/openapi.json +++ b/apps/site/public/projects/loop-protocol/openapi.json @@ -461,7 +461,8 @@ "/api/v1/transaction": { "post": { "tags": ["Transactions"], - "summary": "Create transaction", + "summary": "Create a transaction, or record a Settlement / TransactionStatus for an existing one", + "description": "A MaterialTransaction creates the transaction. A Settlement (marks it completed) or a TransactionStatus updates the existing transaction named by transaction_id, subject to SPECIFICATION.md §3.6: a transaction in a terminal state (completed, cancelled, disputed) cannot return to a non-terminal one, and a terminal transaction cannot be settled again.", "requestBody": { "required": true, "content": { @@ -472,12 +473,36 @@ }, "responses": { "201": { - "description": "Created", + "description": "Created, or status recorded", "content": { "application/ld+json": { "schema": { "$ref": "#/components/schemas/TransactionStatus" } } } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/ErrorResponse" } + } + } + }, + "404": { + "description": "Settlement or TransactionStatus for a transaction that does not exist", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/ErrorResponse" } + } + } + }, + "409": { + "description": "Transaction id already exists, or the update would leave a terminal state (SPECIFICATION.md §3.6)", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/ErrorResponse" } + } + } } } } diff --git a/protocol/CHANGELOG.md b/protocol/CHANGELOG.md index 520b0fff..dc9e2807 100644 --- a/protocol/CHANGELOG.md +++ b/protocol/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- `openapi.json`: `POST /api/v1/transaction` documents that a `Settlement` or + `TransactionStatus` updates the existing transaction named by + `transaction_id` (SPECIFICATION.md §3.6), and lists the `400`, `404` + (unknown transaction) and `409` (duplicate id, or leaving a terminal state) + responses it can return; only `201` was listed. + ### Changed - The protocol is developed in the public monorepo https://github.com/MycelAI/LocalLOOP: `CONTRIBUTING.md` invites issues and diff --git a/protocol/openapi.json b/protocol/openapi.json index 9582c7b5..8c87eb20 100644 --- a/protocol/openapi.json +++ b/protocol/openapi.json @@ -461,7 +461,8 @@ "/api/v1/transaction": { "post": { "tags": ["Transactions"], - "summary": "Create transaction", + "summary": "Create a transaction, or record a Settlement / TransactionStatus for an existing one", + "description": "A MaterialTransaction creates the transaction. A Settlement (marks it completed) or a TransactionStatus updates the existing transaction named by transaction_id, subject to SPECIFICATION.md §3.6: a transaction in a terminal state (completed, cancelled, disputed) cannot return to a non-terminal one, and a terminal transaction cannot be settled again.", "requestBody": { "required": true, "content": { @@ -472,12 +473,36 @@ }, "responses": { "201": { - "description": "Created", + "description": "Created, or status recorded", "content": { "application/ld+json": { "schema": { "$ref": "#/components/schemas/TransactionStatus" } } } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/ErrorResponse" } + } + } + }, + "404": { + "description": "Settlement or TransactionStatus for a transaction that does not exist", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/ErrorResponse" } + } + } + }, + "409": { + "description": "Transaction id already exists, or the update would leave a terminal state (SPECIFICATION.md §3.6)", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/ErrorResponse" } + } + } } } } diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 385213c8..b143ae13 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -33,11 +33,16 @@ for t in "${targets[@]}"; do conformance) cd "$ROOT" step "conformance: site mirror in sync with protocol/" + # Fingerprint the mirror's files before and after re-mirroring: any + # change (an edit, a deletion, or a new file git diff would not see + # because it is untracked) means protocol/ was not re-mirrored. Comparing + # contents, not git status, lets an already re-mirrored but uncommitted + # change pass, so the check also works before committing. + mirror_state() { (cd apps/site/public/projects && find . -type f -print0 | sort -z | xargs -0 sha256sum); } + before="$(mirror_state)" bash apps/site/scripts/aggregate-docs.sh >/dev/null - # git status, not git diff: a protocol file added without re-mirroring - # shows up as an *untracked* mirror copy, which git diff ignores. - if [[ -n "$(git status --porcelain -- apps/site/public/projects)" ]]; then - git status --short -- apps/site/public/projects + if [[ "$before" != "$(mirror_state)" ]]; then + diff <(echo "$before") <(mirror_state) | head -20 || true echo "Site mirror out of sync: run bash apps/site/scripts/aggregate-docs.sh and add the result" >&2 exit 1 fi