Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5ee5a50
WIP: notes are about a record, not only an attendee — NOT VERIFIED, f…
claude Jul 28, 2026
8d97fc2
Retire the attendee-only index from the note table's first migration
claude Jul 28, 2026
2eec413
Answer the schema, registry and code-quality checks the change moves
claude Jul 28, 2026
873189f
Open one note through the same opener as a batch
claude Jul 28, 2026
506d29a
Put the note routes' tests where the source can find them, and let a …
claude Jul 28, 2026
fc912b9
Give the new files direct tests, and record the four modules that hav…
claude Jul 28, 2026
8063d91
Answer the review: read the primary, refuse an empty ask, fix the plans
claude Jul 28, 2026
eec0f5b
Answer the second review: cover the walk fix, read one the same way a…
claude Jul 28, 2026
cb1c0dd
Ask whether it is a directory before reading it
claude Jul 28, 2026
bb7beb2
Read a folder's contents one way across the scripts
claude Jul 28, 2026
4f459d6
Answer the third review: strict walker, resumable index, batched note…
claude Jul 28, 2026
7ba7447
Say what happens when adding a column fails for another reason
claude Jul 28, 2026
d2b4a29
Take the database's word on every step, not just adding a column
claude Jul 28, 2026
b72a98e
Pin each step's tolerance to its own answer, and drop a call that did…
claude Jul 28, 2026
6a0fec5
Merge remote-tracking branch 'origin/main' into claude/site-tidyup-mi…
claude Jul 28, 2026
25e7844
Re-anchor equivalent mutants after merging main
claude Jul 28, 2026
2c5ffa7
Point the importer plan at where the notes store now lives
claude Jul 28, 2026
21e7fd2
Assert the empty note delete really asks the database nothing
claude Jul 28, 2026
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
28 changes: 28 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -1761,3 +1761,31 @@ as the supervisor is up, closing the gap. That means changing what
and thinking again about the startup grace, which exists because a process id
can be given to somebody else after the original has gone. Start at
`RUN_STARTUP_GRACE_MS` in `isolation-state.ts` and the comment above it.

## Four feature modules have no test at their mirrored path

*Origin: `deno task precommit:mutation` on the notes-migration branch, which
could not start.*

The mutation gate refuses to run a source that has mutants but no test at its
mirrored path under `test/`. Four modules are in that state:

- `src/features/admin/attendee-page.ts` (55 mutants)
- `src/features/admin/attendees-list.ts` (37)
- `src/features/admin/listing-page-data.ts` (45)
- `src/features/api/payment-processing/store-refund.ts` (29)

Nothing needs moving: no test imports any of them. They are reached only
through the app, by integration and Cucumber journeys, so each needs a direct
test written at `test/features/…` to match its path.

This blocks the gate for *any* branch that touches one of them, however small
the change — the notes migration only swapped an import in each. Until they
have direct tests, a branch touching them can prove its own work with a
targeted `deno task mutation <source> <tests>` run instead.

`src/features/admin/attendee-notes.ts` was in the same state and is now fixed:
its route suite drives real pages through the session helpers, so it moved from
`test/integration/admin/` to `test/features/admin/`, which is where that kind
of suite belongs (see "Let the misplaced-test list see past request helpers"
above). The other four have no such suite to move.
28 changes: 21 additions & 7 deletions scripts/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,29 @@ Examples:
/** Glob metacharacters; a path segment with none is a fixed directory name. */
const GLOB_CHARS = /[*?{}[\]]/;

/** Every file under `dir`, recursively; a missing directory yields nothing. */
async function* walkFiles(dir: string): AsyncGenerator<string> {
let entries: AsyncIterable<Deno.DirEntry>;
/**
* What `dir` holds, or nothing when there is no such directory — a path that
* has since moved or gone is asked for and simply answers with nothing. Reading
* the entries is what reaches the disk, so a missing directory shows up here
* rather than where the reader was created.
*/
const dirEntriesOrNone = async (dir: string): Promise<Deno.DirEntry[]> => {
const entries: Deno.DirEntry[] = [];
try {
entries = Deno.readDir(dir);
} catch {
return;
for await (const entry of Deno.readDir(dir)) entries.push(entry);
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
} catch (error) {
const gone =
error instanceof Deno.errors.NotFound ||
error instanceof Deno.errors.NotADirectory;
if (!gone) throw error;
return [];
}
for await (const entry of entries) {
return entries;
};

/** Every file under `dir`, recursively; a missing directory yields nothing. */
async function* walkFiles(dir: string): AsyncGenerator<string> {
for (const entry of await dirEntriesOrNone(dir)) {
const path = join(dir, entry.name);
if (entry.isDirectory) yield* walkFiles(path);
else if (entry.isFile) yield path;
Expand Down
15 changes: 8 additions & 7 deletions src/features/admin/attendee-notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ import { getSearchParam } from "#routes/url.ts";
import { getAttendeeOrNull } from "#shared/db/attendees/queries.ts";
import {
createOwnerNote,
deleteAttendeeNote,
getAttendeeNote,
type SystemNote,
} from "#shared/db/system-notes.ts";
deleteNote,
getNote,
} from "#shared/db/notes/queries.ts";
import { attendeeNotes } from "#shared/db/notes/target.ts";
import type { SystemNote } from "#shared/db/notes/types.ts";
import type { ResponseHandler } from "#shared/response-steps.ts";
import { requireRequestPrivateKey } from "#shared/session-private-key.ts";
import type { AdminSession, Attendee } from "#shared/types.ts";
Expand Down Expand Up @@ -73,7 +74,7 @@ const loadNote = async ({
attendeeId,
noteId,
}: NoteRouteParams): Promise<SystemNote | null> =>
getAttendeeNote(attendeeId, noteId, await requireRequestPrivateKey());
getNote(attendeeNotes(attendeeId), noteId, await requireRequestPrivateKey());
const noteEntityHandler = createEntityHandler<NoteRouteParams, SystemNote>(
loadNote,
);
Expand Down Expand Up @@ -134,7 +135,7 @@ const handleAddNotePost: TypedRouteHandler<"POST /admin/attendee/:attendeeId/not
400,
);
}
await createOwnerNote(attendeeId, note);
await createOwnerNote(attendeeNotes(attendeeId), note);
return redirect(
returnTarget(attendeeId, returnUrl),
t("notes.added"),
Expand Down Expand Up @@ -162,7 +163,7 @@ const handleDeleteNoteGet: TypedRouteHandler<"GET /admin/attendee/:attendeeId/no
/** POST /admin/attendee/:attendeeId/note/:noteId/delete — delete the note. */
const handleDeleteNotePost: TypedRouteHandler<"POST /admin/attendee/:attendeeId/note/:noteId/delete"> =
noteHandlers.post(async (note, _session, form, _request, { attendeeId }) => {
await deleteAttendeeNote(attendeeId, note.id);
await deleteNote(attendeeNotes(attendeeId), note.id);
return redirect(
returnTarget(attendeeId, form.getString("return_url")),
t("notes.deleted"),
Expand Down
7 changes: 4 additions & 3 deletions src/features/admin/attendee-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ import { loadPreviousBookings } from "#routes/admin/previous-bookings.ts";
import { requireSessionOr } from "#routes/auth.ts";
import { getEffectiveDomain } from "#shared/config.ts";
import { attendeeStatuses } from "#shared/db/attendee-statuses.ts";
import { getNotesFor } from "#shared/db/notes/queries.ts";
import { attendeeNotes } from "#shared/db/notes/target.ts";
import { settings } from "#shared/db/settings.ts";
import { getNotesForAttendee } from "#shared/db/system-notes.ts";
import { isReadOnly } from "#shared/env.ts";
import { requireRequestPrivateKey } from "#shared/session-private-key.ts";
import { isOwnerRole } from "#shared/types.ts";
Expand Down Expand Up @@ -201,8 +202,8 @@ export const attendeePage: EntityPage<LoadedAttendee> = defineEntityPage({
attendeeBanner({
attendee,
isOwner: ctx.session.adminLevel === "owner",
notes: await getNotesForAttendee(
attendee.id,
notes: await getNotesFor(
attendeeNotes(attendee.id),
await requireRequestPrivateKey(),
),
statuses: await attendeeStatuses.getAll(),
Expand Down
20 changes: 12 additions & 8 deletions src/features/admin/attendees-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,17 @@ import { logActivity } from "#shared/db/activityLog.ts";
import { decryptAttendeeOrNull } from "#shared/db/attendees/pii.ts";
import { getAttendeeRaw } from "#shared/db/attendees/queries.ts";
import { queryOne } from "#shared/db/client.ts";
import {
createSystemNote,
deleteNote,
getNotesFor,
} from "#shared/db/notes/queries.ts";
import { attendeeNotes } from "#shared/db/notes/target.ts";
import {
getRefundPaymentReferencesForAttendee,
markPaymentReferencesProviderRefunded,
type RefundPaymentReference,
} from "#shared/db/payment-references.ts";
import {
createSystemNote,
deleteAttendeeNote,
getNotesForAttendee,
} from "#shared/db/system-notes.ts";
import type { FormParams } from "#shared/form-data.ts";
import { legMatches } from "#shared/ledger/legs.ts";
import type { PaymentProvider } from "#shared/payments.ts";
Expand Down Expand Up @@ -151,7 +152,10 @@ const recordConfirmedRefund = async (
// stale note could still be there if the previous cleanup failed).
await cleanupStaleManualRefundNote(attendeeId, privateKey);
if (isPlaceholder) {
await createSystemNote(attendeeId, t("note.placeholder_refund_confirmed"));
await createSystemNote(
attendeeNotes(attendeeId),
t("note.placeholder_refund_confirmed"),
);
}
return null;
};
Expand All @@ -164,10 +168,10 @@ const cleanupStaleManualRefundNote = async (
attendeeId: number,
privateKey: CryptoKey,
): Promise<void> => {
const notes = await getNotesForAttendee(attendeeId, privateKey);
const notes = await getNotesFor(attendeeNotes(attendeeId), privateKey);
for (const note of notes) {
if (note.type === "system" && note.note.includes("could NOT be refunded")) {
await deleteAttendeeNote(attendeeId, note.id);
await deleteNote(attendeeNotes(attendeeId), note.id);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/features/admin/attendees-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ import {
} from "#shared/db/attendees/queries.ts";
import { getActiveHolidays } from "#shared/db/holidays.ts";
import { getAllListings } from "#shared/db/listings/records.ts";
import { loadNotesForAttendees } from "#shared/db/notes/queries.ts";
import { settings } from "#shared/db/settings.ts";
import { loadNotesForAttendees } from "#shared/db/system-notes.ts";
import {
type ListingFilter,
listingCategory,
Expand Down
12 changes: 6 additions & 6 deletions src/features/admin/listing-page-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ import {
} from "#shared/db/listing-parents.ts";
import { getListingAggregateRecalculation } from "#shared/db/listings/aggregates.ts";
import { getAttendeesByListingIds } from "#shared/db/listings/attendees.ts";
import {
loadNotesForAttendees,
loadNotesForListing,
} from "#shared/db/notes/queries.ts";
import type { SystemNote } from "#shared/db/notes/types.ts";
import { getAttendeeIdsWithPaymentReference } from "#shared/db/payment-references.ts";
import { deleteAllStaleReservations } from "#shared/db/processed-payments.ts";
import { getListingChoiceAnswerMap } from "#shared/db/questions/attendee-answers/reads.ts";
import { getQuestionsForListing } from "#shared/db/questions/queries.ts";
import { settings } from "#shared/db/settings.ts";
import {
loadNotesForAttendees,
loadNotesForListing,
type SystemNote,
} from "#shared/db/system-notes.ts";
import { listingLedgerHref } from "#shared/ledger-links.ts";
import { requireRequestPrivateKey } from "#shared/session-private-key.ts";
import {
Expand Down Expand Up @@ -189,7 +189,7 @@ const noteAuthorNames = async (
notes.length === 0
? new Map()
: getAttendeeNamesByIds(
unique(notes.map((note) => note.attendee_id)),
unique(notes.map((note) => note.entity_id)),
await requireRequestPrivateKey(),
);

Expand Down
5 changes: 3 additions & 2 deletions src/features/api/payment-processing/store-refund.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ import { bookingDateFields } from "#shared/booking-date-fields.ts";
import { logActivity } from "#shared/db/activityLog.ts";
import { attendeesApi } from "#shared/db/attendees/api.ts";
import { settleAttendeeBalance } from "#shared/db/attendees/balance.ts";
import { createSystemNote } from "#shared/db/notes/queries.ts";
import { attendeeNotes } from "#shared/db/notes/target.ts";
import { balanceFinalizeStatements } from "#shared/db/payment-finalize.ts";
import { createSystemNote } from "#shared/db/system-notes.ts";
import { ErrorCode, logError } from "#shared/logger.ts";
import { sendNtfyError } from "#shared/ntfy.ts";
import type { BookingItem, ValidatedPaymentSession } from "#shared/payments.ts";
Expand Down Expand Up @@ -195,7 +196,7 @@ export const storeRefundedBooking = async (
});
}
await createSystemNote(
attendeeId,
attendeeNotes(attendeeId),
refundedNoteText(attendeeId, spec, refunded, session.paymentReference),
);
// Status 200: a fully-handled terminal outcome (booking kept, money returned or
Expand Down
12 changes: 8 additions & 4 deletions src/shared/db/attendees/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type SqlStatement,
} from "#shared/db/client.ts";
import { ticketCountSumExpr } from "#shared/db/migrations/schema/listing-aggregates.ts";
import { noteDeleteStatement } from "#shared/db/notes/queries.ts";

type DeleteAttendeeOptions = { releaseBookings?: boolean };
type ListingContribution = {
Expand Down Expand Up @@ -63,7 +64,6 @@ const DEPENDENT_ROW_TARGETS = [
{ field: "attendee_id", table: "processed_payments" },
{ field: "attendee_id", table: "attendee_answers" },
{ field: "attendee_id", table: "listing_attendees" },
{ field: "attendee_id", table: "system_notes" },
{ field: "servicing_attendee_id", table: "service_costs" },
] as const;

Expand All @@ -83,10 +83,14 @@ export const checkoutStageDeleteStatement = (
/** Build the common dependent-row deletes for one or many attendee ids. */
export const attendeeDependentDeleteStatements = (
attendeeIds: SqlStatement,
): SqlStatement[] =>
DEPENDENT_ROW_TARGETS.map((target) =>
): SqlStatement[] => [
...DEPENDENT_ROW_TARGETS.map((target) =>
dependentDeleteStatement(target, attendeeIds),
);
),
// Notes are named by the kind of record they are about, so the notes module
// builds this one rather than the plain "column = id" shape above.
noteDeleteStatement("attendee", attendeeIds),
];

/** Delete an attendee and all dependent data tied to the attendee record. */
const purgeAttendee = (
Expand Down
3 changes: 1 addition & 2 deletions src/shared/db/migrations/2026-06-23_system_notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { schemaMigration } from "./define.ts";

export default schemaMigration(
"2026-06-23_system_notes",
"Add system_notes table of per-attendee operator-visible notes (encrypted: system notes with DB_ENCRYPTION_KEY, owner notes with the owner public key)",
"Add system_notes table of per-attendee operator-visible notes (encrypted: system notes with DB_ENCRYPTION_KEY, owner notes with the owner public key). (This historically also owned an attendee_id column and its idx_system_notes_attendee_id index, since replaced — a note now names the kind of record it is about and which one; see 2026-07-28_note_entities.)",
{
indexes: ["idx_system_notes_attendee_id"],
newTables: ["system_notes"],
},
);
37 changes: 37 additions & 0 deletions src/shared/db/migrations/2026-07-28_note_entities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { bareSchemaMigration } from "./define.ts";

/**
* Notes used to belong to an attendee and nothing else. They now name the kind
* of record they are about and which one, so any record can carry notes.
*
* The two new columns are added with a default so the database accepts them on
* a table that already has rows; the rebuild at the end drops `attendee_id` and
* takes the columns' final form from SCHEMA, which has no default. Each step is
* skipped when it has already been done, so a re-run after a failed verify is a
* cheap no-op.
*/
export default bareSchemaMigration(
"2026-07-28_note_entities",
"Replace system_notes.attendee_id with entity_type + entity_id, so notes can be about any record and not only an attendee. Existing notes become notes about an attendee",
async ({ getDb, recreateTable, syncIndexes }) => {
const info = await getDb().execute("PRAGMA table_info(system_notes)");
const columns = new Set(info.rows.map((row) => String(row.name)));
if (!columns.has("attendee_id")) return;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if (!columns.has("entity_type")) {
await getDb().execute(
"ALTER TABLE system_notes ADD COLUMN entity_type TEXT NOT NULL DEFAULT 'attendee'",
);
}
if (!columns.has("entity_id")) {
await getDb().execute(
"ALTER TABLE system_notes ADD COLUMN entity_id INTEGER NOT NULL DEFAULT 0",
);
}
await getDb().execute(
"UPDATE system_notes SET entity_type = 'attendee', entity_id = attendee_id",
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
);
await recreateTable("system_notes"); // rebuild from SCHEMA, dropping attendee_id
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
await syncIndexes(); // idx_system_notes_entity in place of the attendee one
},
);
4 changes: 4 additions & 0 deletions src/shared/db/migrations/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,10 @@ export const MIGRATION_REGISTRY: MigrationRegistryEntry[] = [
"2026-07-22_maintenance_completion",
() => import("./2026-07-22_maintenance_completion.ts"),
),
entry(
"2026-07-28_note_entities",
() => import("./2026-07-28_note_entities.ts"),
),
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
];
/* jscpd:ignore-end */

Expand Down
23 changes: 18 additions & 5 deletions src/shared/db/migrations/schema/tables-questions.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
/** Form tables: questions, answers, attributes, built sites, notes. */

import { NOTE_ENTITIES } from "#shared/db/notes/target.ts";
import { createdColumn, sortOrderColumn } from "./scalar-columns.ts";
import type { Table } from "./types.ts";

/** The record kinds a note may be about, as a CHECK the database enforces. */
const noteEntityCheck = `entity_type IN (${NOTE_ENTITIES.map(
(entity) => `'${entity}'`,
).join(", ")})`;

export const questionTables: [name: string, table: Table][] = [
[
"questions",
Expand Down Expand Up @@ -211,18 +217,22 @@ export const questionTables: [name: string, table: Table][] = [
],

[
// Per-attendee notes the operator sees on the attendee record. `note` is
// always stored encrypted — a `system` note (auto-generated, e.g. the
// Notes the operator sees on a record, named by which kind of record they
// are about (`entity_type`) and which one (`entity_id`). `note` is always
// stored encrypted — a `system` note (auto-generated, e.g. the
// refunded-but-stored booking warning) with the symmetric DB_ENCRYPTION_KEY
// so a key-less system path can both write and read it back, an `owner` note
// (operator-authored) with the owner public key so only the owner can read
// it. System notes are kept PII-free by convention. No FKs — the attendee
// it. System notes are kept PII-free by convention. No FKs — each record's
// delete path prunes these rows explicitly.
"system_notes",
{
columns: [
["id", "INTEGER PRIMARY KEY AUTOINCREMENT"],
["attendee_id", "INTEGER NOT NULL"],
// The kinds come from NOTE_ENTITIES, so the stored values and the ones
// the code accepts cannot drift apart.
["entity_type", `TEXT NOT NULL CHECK (${noteEntityCheck})`],
["entity_id", "INTEGER NOT NULL"],
[
"type",
"TEXT NOT NULL DEFAULT 'system' CHECK (type IN ('system', 'owner'))",
Expand All @@ -231,7 +241,10 @@ export const questionTables: [name: string, table: Table][] = [
createdColumn,
],
indexes: [
{ columns: ["attendee_id"], name: "idx_system_notes_attendee_id" },
{
columns: ["entity_type", "entity_id"],
name: "idx_system_notes_entity",
},
],
},
],
Expand Down
Loading