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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions apps/backend/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions apps/backend/docs/SPEC-COMPLIANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |
Expand Down
65 changes: 64 additions & 1 deletion apps/backend/src/db/loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<LoopCreateResult> {
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)
Expand All @@ -831,6 +848,52 @@ export async function createLoopTransaction(payload: LoopTransactionPayload, db?
}, db);
}

async function updateLoopTransactionStatus(
payload: LoopTransactionPayload,
id: string,
status: string,
db?: PoolClient,
): Promise<LoopCreateResult> {
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<LoopTransactionRow | undefined> {
const { rows } = await pool.query(
'SELECT id, status, payload, created_at, updated_at FROM loop_transactions WHERE id = $1',
Expand Down
9 changes: 9 additions & 0 deletions apps/backend/src/routes/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { config } from '../config';
import {
createLoopTransaction,
getLoopTransactionById,
LoopStateError,
transactionIdentity,
type LoopTransactionPayload,
} from '../db/loop';
Expand Down Expand Up @@ -88,6 +89,7 @@ export async function registerTransactionRoutes(app: FastifyInstance, deps: Tran
response: {
201: transactionStatusResponseSchema,
400: specErrorResponseSchema,
404: specErrorResponseSchema,
409: mixedWriteErrorResponseSchema,
},
},
Expand Down Expand Up @@ -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');
Expand Down
95 changes: 95 additions & 0 deletions apps/backend/tests/transactions.routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => {
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');
});
});
7 changes: 7 additions & 0 deletions apps/site/public/projects/loop-protocol/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 27 additions & 2 deletions apps/site/public/projects/loop-protocol/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -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" }
}
}
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions protocol/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 27 additions & 2 deletions protocol/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -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" }
}
}
}
}
}
Expand Down
Loading
Loading