docs: mark phases A and B done, add correction phase before the packaging

This commit is contained in:
ai-bot committed 2026-11-14 17:46:33 +00:00
1 parent fb1a219984
commit d972896e1a
1 file changed
+199 -258
+199 -258
View File
@@ -11,43 +11,6 @@ standard library, SQLite on the `main` volume, admin-password protected, UI in N
Nynorsk. After the last step the package builds, installs on StartOS, and produces the same Nynorsk. After the last step the package builds, installs on StartOS, and produces the same
figures as the owner's spreadsheet. figures as the owner's spreadsheet.
## Progress
Steps finished, in the order of this plan. The coding agent appends one line per
finished step, with the commit message it used where the spec left a choice.
- 1 `LICENSE` — GPL-3.0 verbatim, copyright line `Copyright (C) 2026 sondreolav` (no personal name in the spec).
- 2 `.gitignore`
- 3 `schema.sql` — the DDL of `docs/spec.md` §4 verbatim, 10 tables, 5 indexes.
- 4 `database.py`
- 5 `rates.py`
- 6 `auth.py` — the CSRF secret is derived from the session token, because `sessions` has no CSRF column; session lifetime 30 days (not specified).
- 7 `validation.py`
- 8 `ledger.py` — a sats fee raises the consumed sats for a sale and a spend only (spec §3.2); for a transfer it lowers what arrives, and elsewhere it is only recorded. `rebuild()` clears every consumption, because `lot_consumptions` is derived and `lot_picks` is the durable input; a stale pick is skipped rather than fatal.
- 9 `tax.py` — holdings come from the ledger at 31.12, so a sale in a later year cannot change an earlier year's formue.
- 10 `export.py` — `report_csv()` carries the UTF-8 BOM and is followed by `transactions_csv()`.
- 11 `maintenance.py` — `auth.reset_password()` added, because the action cannot know the old password.
- 12 `app.py` — server core, static pages, the session cookie, the CSRF check and `/api/auth/*`.
- 13 `app.py` — `/api/markets`, `/api/transactions`, `/api/lots`, `/api/prices`, `/api/settings`; every write that can move the ledger ends with `ledger.rebuild()`.
- 14 `app.py` — `/api/report` and `/api/report/export.csv`.
- 15 `tests/test_ledger.py` — the 8 cases of spec §5, plus `tests/__init__.py` so `unittest discover` finds the package.
- 16 `tests/test_tax.py` — the 8 cases of spec §6.
- decision: a leg carries one currency only (the CHECK of §4), so a buy keeps the NOK paid on `leg_out_ore`. §5.1 says `leg_in_ore`, which that CHECK forbids; `ledger.create_lots_for()` accepts either, and the form maps the given side to `leg_out_ore`.
- fix: `ledger._sats_to_consume()` returns 0 when `leg_out_sats` is NULL, so a buy with a sats fee consumes nothing — the fee lowers the sats that arrive instead (§3.2). Found by the fee case of `tests/test_tax.py`.
- next: run `python3 -m unittest discover -s tests -v`, then Phase B (`static/`).
- 17 `static/style.css` — one stylesheet, no external fonts; the class contract for the pages is in the header comment.
- 18 `static/session.js` — adds `X-CSRF-Token` from the `skuld_csrf` cookie and redirects to `/login` on 401.
- 19 `static/app.js` — `api()`, Norwegian formatting, the sheet row renderers, the type labels, the form helpers and the `document.body.dataset.page` dispatcher.
- 20 `static/login.html`, `static/login.js` — sign in and the create-admin form; on success `/` when accounts exist, else `/marknader`.
- 21 `static/index.html`, `static/index.js` — the main sheet of §7.2 with the year selector and the empty state.
- 22 `static/transactions.html`, `static/transactions.js` — the filterable list; generated `transfer_in` rows are marked and read-only.
- 23 `static/transaction.html`, `static/transaction.js` — the form of §7.3 with the Parti section and "Bruk automatisk".
- 24 `static/markets.html`, `static/markets.js` — the account admin.
- 25 `static/report.html`, `static/report.js` — the year report, the tax return block and the CSV button.
- 26 `static/settings.html`, `static/settings.js` — settings, the rate table and the password form.
- fix: `app.py` `ASSETS` now names every page script, and `validation.validate_settings()` accepts a wealth tax threshold of `0`.
- next: Phase C (`startos/`, `Dockerfile`, `Makefile`, `package.json`).
## Not in this plan ## Not in this plan
Everything in `docs/spec.md` §11. Specifically: no other assets than BTC, no price feeds or Everything in `docs/spec.md` §11. Specifically: no other assets than BTC, no price feeds or
@@ -62,7 +25,7 @@ a later project; the only concession to it is that the DDL lives in `schema.sql`
half-written. Never leave a page without its script or a module without its caller. half-written. Never leave a page without its script or a module without its caller.
- Commit at the end of each step, message in English, one line about what changed. - Commit at the end of each step, message in English, one line about what changed.
- Run the step's verification before moving on. If it fails, fix it in the same step. - Run the step's verification before moving on. If it fails, fix it in the same step.
- Do not reorder. Phase A is testable without any UI or packaging; Phase C is the packaging. - Do not reorder. Phase B2 must be finished before Phase C starts.
- When the spec is silent, choose the smaller option and record the choice in the commit - When the spec is silent, choose the smaller option and record the choice in the commit
message. Ask the owner only for the four open questions in the spec (§13). message. Ask the owner only for the four open questions in the spec (§13).
@@ -84,212 +47,185 @@ a later project; the only concession to it is that the DDL lives in `schema.sql`
| D12 | Non-taxable accounts are real accounts with `taxable = 0`, plus `custody_market_id` for the `TOT` rows | Reproduces the spreadsheet's main sheet, including the reconciliation rows | | D12 | Non-taxable accounts are real accounts with `taxable = 0`, plus `custody_market_id` for the `TOT` rows | Reproduces the spreadsheet's main sheet, including the reconciliation rows |
| D13 | No secret-scanning module, unlike VardKey | Skuld has no field where a seed phrase or a key would belong; a guard would be decoration | | D13 | No secret-scanning module, unlike VardKey | Skuld has no field where a seed phrase or a key would belong; a guard would be decoration |
| D14 | The 22 % rate is a setting, not a constant | Rates change; the report shows which rate produced the figures | | D14 | The 22 % rate is a setting, not a constant | Rates change; the report shows which rate produced the figures |
| D15 | BTC is shown in sats everywhere, in the UI and in the CSV; the only `10^8` conversion is inside the price and formue arithmetic | The owner reads sats; a BTC amount with eight decimals is unreadable in a sheet |
| D16 | NOK is displayed in whole kroner, stored and computed in øre; decimals are accepted only in input fields | The owner does not want to see decimals, but rounding in the ledger would lose øre and let sums drift |
| D17 | `admin_cost` has no account (`market_id` null), takes no fee, and consumes no lots | The owner wants it to stand on its own; it changes no holdings, so nothing else can be derived from it |
| D18 | The transaction price is derived on the fly and never stored, and is called `btc_price_ore` in the API on both transactions and lots | It is a function of legs the owner already entered, so storing it would let it drift; the owner's word for it is "bitcoin pris", so the API uses one name for one unit |
| D19 | The stored rate column keeps its name `prices.nok_per_btc_ore`, and the settings table keeps the heading `NOK per BTC` | It is Skatteetaten's year-end rate, not a transaction price; renaming a stored column buys a migration and nothing else |
| D20 | The Avgift section is hidden for `gift_received` and `admin_cost` | The owner's field list gives those two no fee, and the schema now refuses one |
## Phase A — application core (Python, testable from a terminal) ## Phase A — application core (steps 1-16) — DONE
### 1. `LICENSE` Implemented and committed: `LICENSE`, `.gitignore`, `schema.sql`, `database.py`, `rates.py`,
Add GPL-3.0, verbatim, with the owner's copyright line. `auth.py`, `validation.py`, `ledger.py`, `tax.py`, `export.py`, `maintenance.py`, `app.py` (in
**Verify:** file exists and starts with `GNU GENERAL PUBLIC LICENSE`. three steps) and `tests/test_ledger.py`, `tests/test_tax.py`.
`python3 -m unittest discover -s tests -v` is green.
### 2. `.gitignore` ## Phase B — user interface (steps 17-26) — DONE
Ignore `__pycache__/`, `*.pyc`, `*.sqlite3`, `*.sqlite3-journal`, `data/`, `node_modules/`,
`dist/`, `*.s9pk`, `.env`.
**Verify:** `git status` shows no database file or `__pycache__`.
### 3. `schema.sql` Implemented and committed: `static/style.css`, `static/session.js`, `static/app.js`, and the
The DDL from `docs/spec.md` §4, verbatim, in the same order, with `CREATE TABLE IF NOT EXISTS` page pairs `login.*`, `index.*`, `transactions.*`, `transaction.*`, `markets.*`, `report.*` and
and the indexes. No seed data. `settings.*`.
**Verify:** `sqlite3 /tmp/skuld.sqlite3 < schema.sql` succeeds; `.schema` lists every table.
### 4. `database.py` ## Phase B2 — corrections the owner asked for (steps 27-44)
`connect()` returning a connection with `PRAGMA foreign_keys = ON` and
`PRAGMA journal_mode = WAL`; `apply_schema()` reading `schema.sql` from the directory of this
file; `schema_version` written as `1`; `seed_defaults()` inserting the settings keys of
`docs/spec.md` §4.1 with their defaults and the six published BTC rates of §5.3 using
`INSERT OR IGNORE`; `get_setting(key)` / `set_setting(key, value)`; row factory so rows behave
like dicts. The database path comes from the `DATABASE_PATH` environment variable, defaulting
to `data/skuld.sqlite3` for local development, and the parent directory is created if missing.
**Verify:** `python3 -c "import database; database.connect(); print('ok')"` creates the file and
`sqlite3 data/skuld.sqlite3 "select count(*) from prices"` returns `6`.
### 5. `rates.py` Do these before Phase C. They change the ledger schema, the field set of one transaction type,
`year_end_date(tax_year)` returning `'<year+1>-01-01'`; `get_rate(tax_year)` reading `prices` the way amounts are shown, and add one derived figure. Nothing here is optional, and nothing
and returning øre per BTC or `None`; `set_rate(date, nok_per_btc_ore, source)`; `list_rates()`. here may spill into Phase C.
Money conversion helpers: `nok_to_ore(text)`, `ore_to_nok(ore)` and `parse_btc_to_sats(text)`
accepting both `,` and `.` as the decimal separator, rejecting more than 8 decimals.
**Verify:** a unit test asserting `year_end_date(2025) == '2026-01-01'`, `get_rate(2025)` equals
`88120606` øre, and `nok_to_ore("1 234,50") == 123450`.
### 6. `auth.py` ### 27. `schema.sql`
The admin account and the sessions, following the VardKey pattern described in `docs/spec.md` Change `transactions.market_id` from `INTEGER NOT NULL REFERENCES markets(id)` to
§9: `admin_exists()`, `create_admin(username, password)`, `verify_login(username, password)`, `INTEGER REFERENCES markets(id)`, with a comment that it is null only for `admin_cost`. Add the
`create_session()` returning the raw token, `session_valid(token)`, `delete_session(token)`, two CHECK constraints of `docs/spec.md` §4: `(type = 'admin_cost' OR market_id IS NOT NULL)` and
`change_password(current, new)`; PBKDF2-HMAC-SHA256 with a random 16-byte salt and an iteration `(type NOT IN ('gift_received', 'admin_cost') OR (fee_sats = 0 AND fee_ore = 0))`. `lots` keeps
count stored in the row; `hmac.compare_digest` for both the password and the session hash; its `NOT NULL`.
sessions store only the SHA-256 hash of the token with an expiry, and expired rows are deleted **Verify:** on a fresh database, an `INSERT` of an `admin_cost` row without a market succeeds,
on use. Minimum password length 12, enforced here and in `validation.py`. the same insert for a `trade` fails, and an `admin_cost` with a fee fails.
**Verify:** a unit test creating an admin, asserting the wrong password fails, the right one
passes, a session is valid once and that a second `session_valid` after expiry returns False.
### 7. `validation.py` ### 28. `rates.py`
Field validation returning `(value, error_message)` pairs with Nynorsk messages: dates, Replace `parse_btc_to_sats(text)` with `parse_sats(text)`: whole sats only, space, narrow space
amounts in sats and øre, the type list, the per-type required-field rules of `docs/spec.md` and non-breaking space allowed as thousands separators, a decimal separator rejected with
§7.3, the rule that exactly one leg of a `trade` is sats and the other NOK, that `ValueError`. Replace `ore_to_nok(ore)` with `kroner_whole(ore)`: whole kroner, halves rounded
`transfer_in` may not be chosen as a type, and that a `transfer_out` needs a different up, grouped with spaces, no unit and no decimals. Delete `sats_to_btc()`. Keep `nok_to_ore`,
destination account. `group_int`, `SATS_PER_BTC`, `ORE_PER_NOK` and the rate functions untouched.
**Verify:** a unit test covering one rejection per rule, asserting the message is Nynorsk and **Verify:** `parse_sats("1 500 000") == 1500000`, `parse_sats("1500000") == 1500000`,
the `field` name is the offending one. `parse_sats("0,5")` raises, `kroner_whole(106037489) == "1 060 375"`.
### 8. `ledger.py` ### 29. `validation.py`
The lot ledger of `docs/spec.md` §5: `create_lots_for(tx)`, `consume(tx, picks)`, `validate_sats` uses `rates.parse_sats` and its messages talk about sats: "Antal må fyllast ut.",
`candidate_lots(market_id, date)`, `pick_for_method(lots, sats, method)`, `holdings_at(date)`, "Antal må vere eit heiltal i sats.", "Antal må vere større enn null." `_ALLOWED_LEGS` for
`sats_in_market(market_id, date)` and `rebuild()`. Rounding exactly as §5.3. A shortfall raises `admin_cost` becomes `("leg_out_sats",)` and `_REQUIRED["admin_cost"]` becomes
`LedgerError` with the shortfall in sats. `rebuild()` deletes and replays as §5.4 describes and `(("leg_out_sats", "Fyll ut kostnaden i sats."),)`. `_check_admin_cost` requires exactly one
is idempotent. `leg_out_sats` and rejects `leg_out_ore`. `validate_transaction` must not require an account for
**Verify:** `tests/test_ledger.py` (step 15) plus, in this step, a manual check: `admin_cost` (store `market_id` as `None`), must still require one for every other type, must
`python3 -c "import ledger"` and a rebuild over an empty database does nothing and raises reject a fee for `admin_cost` and `gift_received`, and must default the taxable flag to 1 for
nothing. `admin_cost` since there is no account to take it from.
**Verify:** a manual check that an `admin_cost` payload without `market_id` validates clean, and
that the same payload with `leg_out_ore` gives a Nynorsk error on `leg_out_sats`.
### 9. `tax.py` ### 30. `ledger.py`
The year report of `docs/spec.md` §6: `report(year)` returning the per-account rows, the totals, Remove `admin_cost` from `CONSUMING_TYPES`. Rename the derived field of `_lot_view` from
the tax figures, the `skattemelding` block, the non-taxable rows and the `custody_totals` rows, `nok_per_btc_ore` to `btc_price_ore` (`docs/spec.md` §8), keeping the arithmetic identical.
using only the ledger state at 31.12 and the transactions of the year. No presentation logic and **Verify:** `python3 -m unittest discover -s tests -v`; an `admin_cost` row leaves every lot
no currency formatting here. untouched after `ledger.rebuild()`.
**Verify:** `tests/test_tax.py` (step 16) plus the golden example of §6.4 by hand for FIFO.
### 10. `export.py` ### 31. `tax.py`
`report_csv(year)` and `transactions_csv(year)`: semicolon-separated, UTF-8 BOM, Norwegian Add `btc_price_ore(tx)`: the bitcoin price of `docs/spec.md` §7.3 as øre per whole BTC, or
decimal comma, one block of report rows then one block of transactions with the consumed cost `None`. The kroner amount is `leg_out_ore` or `leg_in_ore`; the sats amount is the sats leg; for
per transaction. `income` and `gift_received` the kroner amount is `value_ore` with the incoming sats; for
**Verify:** `python3 -c "import export; print(export.report_csv(2024)[:80])"` and confirm the `spend` and `loss` it is `value_ore` with the outgoing sats; `transfer_out`, `transfer_in`,
BOM is present and the separator is `;`. `gift_given` and `admin_cost` give `None`. Round halves up.
### 11. `maintenance.py` Handle `admin_cost` with no account: it is no longer looked up among the accounts, it is counted
A command-line script the StartOS actions run inside the container: `set-admin-password` when its own `taxable` flag is set, its sats are summed into a new totals field
generating a random password inside the container, storing it, and printing one JSON object `admin_cost_sats`, and `admin_cost_ore` becomes `admin_cost_sats × the year-end rate ÷ 10^8`
`{"username": ..., "password": ...}` on stdout; `delete-all-data` wiping every table except when `deduct_admin_costs` is on and `0` otherwise. Keep every other figure as it is.
`admin` and `settings` and requiring `--confirm`. Both open the database at `DATABASE_PATH`. **Verify:** the golden price case — a buy of 1 000 sats for 10 kr gives
**Verify:** `DATABASE_PATH=/tmp/m.sqlite3 python3 maintenance.py set-admin-password` prints one `btc_price_ore == 100000000` (1 000 000 kr) — and `report(2024)` still returns every field of §6.
JSON object, and the password it prints logs in through `auth.verify_login`.
### 12. `app.py` — server core ### 32. `export.py`
`ThreadingHTTPServer` and a `BaseHTTPRequestHandler` subclass; the route table as a list of `JOIN markets m ON m.id = t.market_id` becomes `LEFT JOIN` in `transactions_csv`. Rename `_btc()`
`(method, pattern, handler)`; `/health` answering `{"status":"ok"}` without a session; static to `_sats()` and use `rates.group_int`; make `_amount()` use `rates.kroner_whole`. Headings
file serving from `static/` with correct content types and `Cache-Control: no-store`; the become `Antall inn (sats)`, `Antall ut (sats)`, `Avgift (sats)`, `Antall (sats)` and
session cookie; the CSRF check on every mutating `/api/*` call; the 401/redirect gate; and the `Antall (sats)` for the TOT block. Add a `Pris (kr)` column to the transaction block, after
`/api/auth/*` routes of `docs/spec.md` §8. Port from `PORT`, default 8080; binds `0.0.0.0`. `Til konto`, carrying `tax.btc_price_ore(row)`. Change the report line
**Verify:** `python3 app.py` then `curl -s localhost:8080/health` returns `{"status":"ok"}`, `Forvaltningskostnad (kr)` into `Forvaltningskostnad (sats)` from `admin_cost_sats`, and keep a
`curl -s -o /dev/null -w '%{http_code}' localhost:8080/api/markets` returns 401, and `Forvaltningskostnad (kr)` line from `admin_cost_ore`.
`curl -s localhost:8080/api/auth/state` returns `admin_exists: false`. **Verify:** download the CSV for a year with an `admin_cost` row and open it; the row is present,
the price column is filled for the trades, and no cell carries a decimal.
### 13. `app.py` — data routes ### 33. `app.py`
Add `/api/markets`, `/api/transactions`, `/api/lots`, `/api/prices` and `/api/settings` with the Make the account join a `LEFT JOIN markets m ON m.id = t.market_id` in `_load_transaction` and
methods of §8, calling `ledger.rebuild()` after every write that can change the ledger, and in `transactions_list`, so a row with no account is not dropped. Add `btc_price_ore` to both
returning validation errors as `{"error", "field"}` with status 400. payloads by calling `tax.btc_price_ore`. Confirm that `transactions_get` builds no candidate
**Verify:** create an account and a buy with `curl`, then `GET /api/lots` shows one lot with the lots for `admin_cost`, which step 30 should already have settled.
right sats and cost; delete the transaction and the lot is gone. **Verify:** `GET /api/transactions` returns the `admin_cost` row with `market_id: null`,
`market_name: null` and `btc_price_ore: null`, and a buy returns the golden price.
### 14. `app.py` — report routes ### 34. `tests/test_ledger.py`
Add `/api/report` and `/api/report/export.csv`, the latter with Update the fixtures to whole sats and the renamed lot field. Add: an `admin_cost` transaction
`Content-Disposition: attachment`. consumes nothing and leaves `holdings_at` unchanged; a rebuild after it still produces the same
**Verify:** `curl -s 'localhost:8080/api/report?year=2024'` returns the report JSON for a lots.
seeded year, and the CSV download opens in a spreadsheet with Norwegian number formatting. **Verify:** `python3 -m unittest discover -s tests -v` — green.
### 15. `tests/test_ledger.py` ### 35. `tests/test_tax.py`
`unittest`, run with the standard library only. Cases: FIFO/LIFO/HIFO ordering on the golden Update the fixtures and add: an `admin_cost` with `market_id` null and `taxable = 1` lands in
example of `docs/spec.md` §6.4; a partial consumption and its rounding; consuming across three `admin_cost_sats` and leaves every account row untouched; `admin_cost_ore` is 0 with the setting
lots; explicit picks overriding the method; a shortfall raising `LedgerError`; a transfer off, and the sats converted at the year-end rate with it on; `btc_price_ore` for the golden case
consuming at the source and mirroring the acquisition date and cost at the destination; a (1 000 sats for 10 kr → 1 000 000 kr) and for a sale (sats out, kroner in); `btc_price_ore` is
rebuild run twice producing identical rows; `holdings_at` before and after a sale. None for `transfer_out` and `admin_cost`.
**Verify:** `python3 -m unittest discover -s tests -v` — all green. **Verify:** `python3 -m unittest discover -s tests -v` — green.
### 16. `tests/test_tax.py` ### 36. `static/app.js`
`unittest`. Cases: the four gains of the golden example per method; formue from the year-end `formatSats(sats)` returns the grouped whole number of sats and nothing else, and its doc comment
rate; income as income and not as gain; a non-taxable account excluded from every total but says so. `formatKroner(ore)` returns whole kroner with spaces and the unit, rounding halves up,
present in the holdings; the `TOT` row summing the custodian's own sats and its dependants'; with no decimals. `formatOre(ore)` stays exactly as it is and stays exported: it is what fills a
fees applied per `docs/spec.md` §3.2 for a buy and a sell; a gift received setting the cost form from a stored value. `parseSats(text)` parses whole sats with spaces allowed and returns
basis; `netto`, `skatt_ore` and the `skattemelding` block. null for anything carrying a decimal separator.
**Verify:** `python3 -m unittest discover -s tests -v` — all green. **Verify:** in the browser console, `Skuld.formatSats(1500000)` is `"1 500 000"`,
`Skuld.formatKroner(106037489)` is `"1 060 375 kr"`, `Skuld.formatOre(123450)` is
`"1 234,50"`, and `Skuld.parseSats("1 500 000")` is `1500000`.
## Phase B — user interface (Nynorsk) ### 37. `static/transactions.html`
Add `<th class="numeric">Pris</th>` between the `Til konto` and `Inn` headings.
**Verify:** the list renders with the new column in the right place.
### 17. `static/style.css` ### 38. `static/transactions.js`
One stylesheet: layout, the main-sheet table with right-aligned numbers, the form, inline error `amount()` returns `Skuld.formatSats(sats) + " sats"` instead of `" BTC"`. Add the `Pris` cell
text, the navigation, and print styles for the report. No external fonts or CDNs. between the `Til konto` and `Inn` cells, showing `Skuld.formatKroner(transaction.btc_price_ore)`
**Verify:** open `/login` with the server running and confirm the page is readable and needs no or an empty string.
network access. **Verify:** a buy shows its price, a transfer shows an empty cell, and every sats cell ends in
`sats`.
### 18. `static/session.js` ### 39. `static/transaction.html`
Patches `window.fetch` to add the `X-CSRF-Token` header on same-origin calls when it is not Rename the lot table heading `Kostnad per BTC` to `Bitcoin pris`. Give the Marknad field a
already set, and to redirect to `/login` on a 401. `data-group="market"` wrapper so it can be hidden, and do the same for the whole Avgift
**Verify:** `curl -s localhost:8080/login` loads and the browser console shows no error; a `fieldset` with `data-group="fee"`.
mutation from the console carries the header. **Verify:** the form still renders, and nothing else moved.
### 19. `static/app.js` ### 40. `static/transaction.js`
Shared helpers used by every page: `api(method, path, body)` returning parsed JSON and throwing In `TYPE_FIELDS`: `admin_cost` becomes `out: {label: "Kostnad", currencies: ["sats"]}` with
an error object with `field`, number and date formatting for Norwegian, the main-sheet row `consumes: false`, `market: false` and `fee: false`; `gift_received` gets `fee: false`. Every
renderer, and the page dispatcher on `document.body.dataset.page`. other type gets `market: true, fee: true`. `applyType()` hides the market group and the fee
**Verify:** no page breaks; the console has no syntax errors. group when the type says so, sets the `market_id` select's `required` flag to match (a hidden
required field blocks the submit), and clears the value it hides. `payload()` sends
`market_id: null` for `admin_cost`. Keep `Skuld.formatOre` for the NOK inputs and use
`Skuld.parseSats` for the sats inputs and the lot amounts, which are now whole sats. Rename the
`nok_per_btc_ore` reads in `autoPick` and `buildLotRow` to `btc_price_ore`.
**Verify:** choose Forvaltningskostnad: the Marknad and Avgift sections disappear, the Valuta
selector is gone and fixed to sats, and saving writes a row with no account. Choose Gåve
(motteke): the Avgift section is gone.
### 20. `static/login.html`, `static/login.js` ### 41. `static/index.html`
Sign in, and the create-admin form when `admin_exists` is false, both in Nynorsk, with the Change the `Antall` heading to `Antall (sats)`.
password rule and the inline errors from the API. On success, go to `/` if accounts exist, **Verify:** the main sheet heading matches the values.
otherwise to `/marknader`.
**Verify:** a fresh database shows the create-admin form; after creating the admin, a reload
shows the sign-in form, and a wrong password shows a Nynorsk error.
### 21. `static/index.html`, `static/index.js` ### 42. `static/report.html`
The main sheet of `docs/spec.md` §7.2: totals row first, then taxable accounts, then the Change all three `Antall` headings to `Antall (sats)`.
non-taxable accounts, then the `TOT` rows, with the columns and headings of §7.2, a year **Verify:** the report headings match the values.
selector, a "Ny transaksjon" button, and the legend. Empty state per §7.5.
**Verify:** with the golden example loaded, the row for the account matches the numbers from
`/api/report`, and `TOT` rows appear only where an account has custody of another's coins.
### 22. `static/transactions.html`, `static/transactions.js` ### 43. `static/report.js`
The filterable list: year, account and type filters; newest first; each row links to the form; The `Forvaltningskostnad` figure shows sats:
generated `transfer_in` rows are marked as generated and cannot be edited. Delete asks for `Skuld.formatSats(totals.admin_cost_sats) + " sats"`, and when `totals.admin_cost_ore` is not
confirmation and deletes the pair for a `transfer_out`. zero a second figure shows the kroner that were deducted. The year-end rate line keeps
**Verify:** filtering by year and account changes the list; deleting a `transfer_out` removes `formatKroner`, which now prints whole kroner.
both rows. **Verify:** a year with an `admin_cost` shows it in sats; with the setting on, the kroner line
appears too.
### 23. `static/transaction.html`, `static/transaction.js` ### 44. `static/markets.html`
The form of `docs/spec.md` §7.3: the field order Generelt, the type-specific fields, Avgift, Change the `Antall` heading to `Antall (sats)`. `static/markets.js` needs no change: it already
Anna; the taxable checkbox ticked by default; the currency selectors; the `Parti` section with calls `Skuld.formatSats`, which now prints sats.
the candidate lots, the method's automatic pick pre-selected, the ability to tick other lots or **Verify:** the account table shows whole sats with spaces.
change the amounts, and a "Bruk automatisk" button. Inline Nynorsk errors, and the shortfall
message from `LedgerError` shown next to the amount.
**Verify:** save one transaction of each type; each appears in the list with the expected
figures; a shortfall produces the Nynorsk message and no row is written.
### 24. `static/markets.html`, `static/markets.js` ## Phase C — StartOS package (steps 45-60)
Account admin: name, kind (Børs/Lommebok/Anna), taxable flag, custody account, note, sort order,
archive. Refuse deletion of an account that has transactions, with the reason shown.
**Verify:** create one exchange, one wallet, one child account with the exchange as custodian,
and confirm the main sheet shows the `TOT` row.
### 25. `static/report.html`, `static/report.js` ### 45. `package.json`, `tsconfig.json`, `.prettierrc`
The year report of §6: the per-account table, the totals, the tax figures, the `skattemelding`
block with the four figures, the non-taxable section, the method and rate used, and the CSV
download button.
**Verify:** the figures equal the API response, and the download saves a file that opens in a
spreadsheet.
### 26. `static/settings.html`, `static/settings.js`
Settings: method (FIFO/LIFO/HIFO), tax rate, wealth tax switch, threshold and rate,
`deduct_admin_costs`, the rate table with editing, the price source text, and change password.
Changing the method warns that the figures will change and rebuilds the ledger.
**Verify:** switching FIFO → HIFO changes the report figures to the golden example's HIFO
values, and switching back restores them.
## Phase C — StartOS package
### 27. `package.json`, `tsconfig.json`, `.prettierrc`
The build tooling for the packaging TypeScript, copied in shape from the owner's VardKey The build tooling for the packaging TypeScript, copied in shape from the owner's VardKey
repository and the StartOS packaging guide. Start from the packaging workspace created by repository and the StartOS packaging guide. Start from the packaging workspace created by
`start-cli s9pk init-workspace` and read the recipe index before copying anything. `start-cli s9pk init-workspace` and read the recipe index before copying anything.
**Verify:** `npm install` succeeds and `npx tsc --noEmit` reports no errors. **Verify:** `npm install` succeeds and `npx tsc --noEmit` reports no errors.
### 28. `Dockerfile`, `.dockerignore` ### 46. `Dockerfile`, `.dockerignore`
Slim Python base; copy `app.py`, `auth.py`, `database.py`, `ledger.py`, `tax.py`, `rates.py`, Slim Python base; copy `app.py`, `auth.py`, `database.py`, `ledger.py`, `tax.py`, `rates.py`,
`export.py`, `validation.py`, `maintenance.py` and `schema.sql` into `/app`; copy `static/` into `export.py`, `validation.py`, `maintenance.py` and `schema.sql` into `/app`; copy `static/` into
`/app/static`. No `USER` line, because the `main` volume must be writable without a `chown`. `/app/static`. No `USER` line, because the `main` volume must be writable without a `chown`.
@@ -298,102 +234,107 @@ No packages installed: the app is standard library only.
`docker run --rm -e PORT=8080 -e DATABASE_PATH=/tmp/s.sqlite3 skuld-test python3 -c "import app"` `docker run --rm -e PORT=8080 -e DATABASE_PATH=/tmp/s.sqlite3 skuld-test python3 -c "import app"`
exits 0. exits 0.
### 29. `Makefile` ### 47. `Makefile`
The packaging targets of the StartOS template, pointing at `startos/index.ts`. The packaging targets of the StartOS template, pointing at `startos/index.ts`.
**Verify:** `make` produces `skuld.s9pk`. **Verify:** `make` produces `skuld.s9pk`.
### 30. `icon.svg` ### 48. `icon.svg`
The app icon, under 40 KiB, same artwork as any icon the app serves. A simple mark is enough; The app icon, under 40 KiB, same artwork as any icon the app serves. A simple mark is enough; do
do not add a second icon file. not add a second icon file.
**Verify:** the file is valid SVG and under the size limit. **Verify:** the file is valid SVG and under the size limit.
### 31. `startos/sdk.ts`, `startos/utils.ts` ### 49. `startos/sdk.ts`, `startos/utils.ts`
`sdk` built with the package id `skuld`; the constants `uiPort = 8080`, `volumeId = 'main'`, `sdk` built with the package id `skuld`; the constants `uiPort = 8080`, `volumeId = 'main'`,
`dataMountpoint = '/data'`, `databasePath = '/data/skuld.sqlite3'`, `imageId`, `subcontainerName`. `dataMountpoint = '/data'`, `databasePath = '/data/skuld.sqlite3'`, `imageId`, `subcontainerName`.
**Verify:** `npx tsc --noEmit` passes. **Verify:** `npx tsc --noEmit` passes.
### 32. `startos/manifest/index.ts`, `startos/manifest/i18n.ts` ### 50. `startos/manifest/index.ts`, `startos/manifest/i18n.ts`
The manifest: id `skuld`, Nynorsk title and description, `dockerBuild: {}`, architectures The manifest: id `skuld`, Nynorsk title and description, `dockerBuild: {}`, architectures
`x86_64` and `aarch64`, the `main` volume, the `ui` interface, no dependencies, the donation `x86_64` and `aarch64`, the `main` volume, the `ui` interface, no dependencies, the donation link
link if the owner wants one. if the owner wants one.
**Verify:** `make` still builds and the manifest text is Nynorsk. **Verify:** `make` still builds and the manifest text is Nynorsk.
### 33. `startos/versions/index.ts` ### 51. `startos/versions/index.ts`
The version graph with the first version and its `main` entry. The version graph with the first version and its `main` entry.
**Verify:** `npx tsc --noEmit` passes and `make` produces a package whose version matches. **Verify:** `npx tsc --noEmit` passes and `make` produces a package whose version matches.
### 34. `startos/interfaces.ts`, `startos/backups.ts`, `startos/dependencies.ts` ### 52. `startos/interfaces.ts`, `startos/backups.ts`, `startos/dependencies.ts`
The `ui` interface on port 8080 with `preferredExternalPort: 80`; The `ui` interface on port 8080 with `preferredExternalPort: 80`;
`sdk.Backups.ofVolumes('main')`; no dependencies. `sdk.Backups.ofVolumes('main')`; no dependencies.
**Verify:** `make` builds; the built package lists one interface and one volume. **Verify:** `make` builds; the built package lists one interface and one volume.
### 35. `startos/i18n/index.ts`, `startos/i18n/dictionaries/nb_NO.ts` ### 53. `startos/i18n/index.ts`, `startos/i18n/dictionaries/nb_NO.ts`
The i18n wrapper and the Nynorsk dictionary for everything StartOS displays: the readiness The i18n wrapper and the Nynorsk dictionary for everything StartOS displays: the readiness
messages, the action names and descriptions, the task text. messages, the action names and descriptions, the task text.
**Verify:** `make` builds and no user-facing string in `startos/` is English. **Verify:** `make` builds and no user-facing string in `startos/` is English.
### 36. `startos/actions/index.ts`, `startos/actions/setAdminPassword.ts`, `startos/actions/deleteAllData.ts` ### 54. `startos/actions/index.ts`, `startos/actions/setAdminPassword.ts`, `startos/actions/deleteAllData.ts`
The two actions of `docs/spec.md` §9, each running `maintenance.py` in a `withTemp` The two actions of `docs/spec.md` §9, each running `maintenance.py` in a `withTemp` subcontainer
subcontainer mounted on the main volume. `set-admin-password` shows the generated credentials mounted on the main volume. `set-admin-password` shows the generated credentials once;
once; `delete-all-data` refuses to run unless its confirmation box is ticked. `delete-all-data` refuses to run unless its confirmation box is ticked.
**Verify:** both actions appear under Actions & Config on a test box; the generated password **Verify:** both actions appear under Actions & Config on a test box; the generated password
signs in; the wipe returns the app to the empty state while the admin still works. signs in; the wipe returns the app to the empty state while the admin still works.
### 37. `startos/init/index.ts`, `startos/init/requireAdmin.ts` ### 55. `startos/init/index.ts`, `startos/init/requireAdmin.ts`
The init script registered in `sdk.setupInit()` after the actions, raising the recommended task The init script registered in `sdk.setupInit()` after the actions, raising the recommended task
"Set the admin password before Skuld can be used." while no admin exists and clearing it "Set the admin password before Skuld can be used." while no admin exists and clearing it
afterwards, with a stored replay id. The probe reads the SQLite database readonly in a afterwards, with a stored replay id. The probe reads the SQLite database readonly in a `withTemp`
`withTemp` subcontainer and fails open. subcontainer and fails open.
**Verify:** on a fresh install the task shows as recommended and the service still starts; after **Verify:** on a fresh install the task shows as recommended and the service still starts; after
setting the password the task disappears. setting the password the task disappears.
### 38. `startos/main.ts` ### 56. `startos/main.ts`
The single daemon `primary` in `skuld-sub`: image, the `main` volume mounted writable at The single daemon `primary` in `skuld-sub`: image, the `main` volume mounted writable at `/data`,
`/data`, `python3 app.py` with `PORT` and `DATABASE_PATH`, and the readiness check against `python3 app.py` with `PORT` and `DATABASE_PATH`, and the readiness check against
`http://127.0.0.1:8080/health` displayed as "Web Interface". The port must be the same number `http://127.0.0.1:8080/health` displayed as "Web Interface". The port must be the same number in
in `utils.ts`, `main.ts` and `interfaces.ts`. `utils.ts`, `main.ts` and `interfaces.ts`.
**Verify:** `make` builds and installing the package on a test box turns the health check green. **Verify:** `make` builds and installing the package on a test box turns the health check green.
### 39. `.github/workflows/build.yml` ### 57. `.github/workflows/build.yml`
The build workflow of the StartOS template: build and release the `.s9pk` on a tag. The build workflow of the StartOS template: build and release the `.s9pk` on a tag.
**Verify:** the workflow file is valid YAML and the lint job (if the template has one) passes. **Verify:** the workflow file is valid YAML and the lint job (if the template has one) passes.
### 40. `README.md` ### 58. `README.md`
The technical reference for an AI support agent or an administering agent, in the section order The technical reference for an AI support agent or an administering agent, in the section order of
of the owner's VardKey README: image and container runtime, volume and data layout, file models, the owner's VardKey README: image and container runtime, volume and data layout, file models,
dependencies, network access and interfaces, installation and first-run flow, actions, tasks, dependencies, network access and interfaces, installation and first-run flow, actions, tasks,
health checks, backups and restore, limitations and differences, and a quick reference block health checks, backups and restore, limitations and differences, and a quick reference block for
for AI consumers. AI consumers.
**Verify:** every claim in it matches `startos/` and the Dockerfile. **Verify:** every claim in it matches `startos/` and the Dockerfile.
### 41. `instructions.md` ### 59. `instructions.md`
The end-user documentation, in Nynorsk: what Skuld does, how to set the admin password, how to The end-user documentation, in Nynorsk: what Skuld does, how to set the admin password, how to
create accounts, how to enter each transaction type, how to read the main sheet, how to get the create accounts, how to enter each transaction type, how to read the main sheet, how to get the
tax figures, and the limitations — including that the database is not encrypted and that Skuld tax figures, and the limitations — including that the database is not encrypted, that amounts are
gives figures, not tax advice. shown in sats and whole kroner, and that Skuld gives figures, not tax advice.
**Verify:** a reader who has never seen the app can go from install to a tax figure. **Verify:** a reader who has never seen the app can go from install to a tax figure.
### 42. `AGENTS.md` ### 60. `AGENTS.md`
The repository mechanics: that the code is English and the UI Nynorsk, that `schema.sql` is the The repository mechanics: that the code is English and the UI Nynorsk, that `schema.sql` is the
only DDL source, that the ledger is rebuilt rather than patched, that `docs/spec.md` outranks only DDL source, that the ledger is rebuilt rather than patched, that amounts are sats and whole
this plan, and the build and test invocations. kroner, that `docs/spec.md` outranks this plan, and the build and test invocations.
**Verify:** it contradicts nothing in `docs/spec.md`. **Verify:** it contradicts nothing in `docs/spec.md`.
## Phase D — verification ## Phase D — verification
### 43. Build, install and run through ### 61. Build, install and run through
1. `python3 -m unittest discover -s tests -v` — all green. 1. `python3 -m unittest discover -s tests -v` — all green.
2. `make` — builds `skuld.s9pk` without warnings. 2. `make` — builds `skuld.s9pk` without warnings.
3. Install on a StartOS box: the service starts, the health check goes green, the interface 3. Install on a StartOS box: the service starts, the health check goes green, the interface opens,
opens, the first-run flow creates the admin. the first-run flow creates the admin.
4. Enter the golden example of `docs/spec.md` §6.4 through the UI and compare every figure with 4. Enter the golden example of `docs/spec.md` §6.4 through the UI and compare every figure with
the spec, for all three methods. the spec, for all three methods. Every BTC quantity must read as whole sats with spaces, and
5. Create a child account with the exchange as custodian and confirm the `TOT` row and the every kroner figure as whole kroner.
5. Enter a buy of 1 000 sats for 10 kr and confirm `Pris` reads `1 000 000 kr` on
`/transaksjonar`.
6. Enter a Forvaltningskostnad and confirm it has no account, no fee section, and its own line in
the report and the CSV.
7. Create a child account with the exchange as custodian and confirm the `TOT` row and the
exclusion from the totals. exclusion from the totals.
6. Do a transfer between two accounts, edit it, and delete it: the lots and the report must 8. Do a transfer between two accounts, edit it, and delete it: the lots and the report must return
return to their earlier state. to their earlier state.
7. Back up, restore, and confirm the figures are identical. 9. Back up, restore, and confirm the figures are identical.
8. Download the CSV and open it in a spreadsheet. 10. Download the CSV and open it in a spreadsheet.
## Verification commands ## Verification commands
@@ -408,5 +349,5 @@ this plan, and the build and test invocations.
| install on a StartOS box | the package really runs | | install on a StartOS box | the package really runs |
`make` and `npx tsc` need the StartOS packaging workspace (`start-cli s9pk init-workspace`) and `make` and `npx tsc` need the StartOS packaging workspace (`start-cli s9pk init-workspace`) and
Docker. If the toolchain is not available, say so in the step's commit message instead of Docker. If the toolchain is not available, say so in the step's commit message instead of skipping
skipping the step silently. the step silently.