Skip to content

feat(memos): the enrollment surface, its gates and the consent record - #1558

Merged
hrustalq merged 4 commits into
devfrom
feat/1554-voice-enrollment
Dec 3, 2026
Merged

hrustalq merged 4 commits into
devfrom
feat/1554-voice-enrollment

Conversation

@hrustalq

@hrustalq hrustalq commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Closes #1554
Refs #1403
Refs #1400

The API half of 2.2: the person's enrollment surface, the three gates, two quality refusals, the consent row and the sample hand-off. Nothing here computes an embedding and nothing here mounts a UI — the ONNX graph, the vector write, voice.enrolled and the sample purge after embedding are #1557.

The row is the consent record, and the API writes it

voice_profiles (#1553) already holds one row per (workspace, user) with the pinned model/dimension pair, the consent version and revoked_at. This PR fills it: POST /v1/me/voice-profile upserts on that pair — model and dimension from the constants, sample_count: 1, consented_at: now, revoked_at: null — so a re-enroll updates the one row and clears a withdrawal instead of colliding with its own key. The doc's GET has two states, enrolled and not, so the row is written at enrollment time and the vector lands asynchronously; enrolled therefore means "a consent record exists and has not been withdrawn", which is what the contract's JSDoc says. A failed embedding leaves a row that cannot match, and re-enrolling fixes it — the doc's "no sweeper" already accepts that shape.

The row, the object and the job are one act from the reader's side: if putObjectBytes or the enqueue throws, the row is removed again and the error rethrown, so nothing reads as enrolled that will never be embedded.

The workspace rides the query

All three routes declare @Access('viewer', 'query') and @SessionOnly(). A multipart body is parsed by an interceptor that runs after the guards, so 'body' cannot resolve the workspace on the POST — the same reason memory-upload.guard.ts exists. @SessionOnly() keeps a kn_ API key out of a biometric write: enrollment is an authenticated session act (doc 89 § Open questions), and a key outlives the browser it was minted in. A guest fails viewer. The person's id comes only from the principal: there is no id in the path and none accepted from the request, which is the admin boundary in its strongest form — there is nothing to point at somebody else.

Three gates, read on execution

  1. VOICE_PROFILES_ENABLED (the platform ceiling, default false).
  2. workspace_settings.voice_profiles — 'allow' is the only value that opens it; null and anything else close it.
  3. The person's own act: the POST's consentVersion must equal VOICE_CONSENT_VERSION, else 409 consent-version.

Either of the first two answers a bare 404 on all three routes, the notes routes' rule and doc 89 § Fallback's "no enrollment route" — a workspace with recognition off must not confirm that the feature exists. Nothing is read or written behind the refusal.

Two quality checks, the third deferred

voice-quality.ts holds the duration band (30–60 s inclusive), the signal level (mean below −45 dB is silence, peak above −0.1 dB is clipped) and the unreadable case, as pure parsers plus one injectable seam, so the unit suite never needs ffmpeg — the speech/audio.ts parsePauses precedent. Each refusal is a stable kebab reason (sample-too-short, sample-too-long, sample-silent, sample-clipped, sample-unreadable, plus the service's sample-missing and consent-version) with error.voice.* copy in en and ru, because 2.3 branches on the reason and renders the message. The upload is written to a throwaway copy for ffprobe/ffmpeg and the directory is removed on every path, refusals included.

The one-voice check is #1557's: it compares two halves of the embedding and needs the model this task does not load.

Real files, one manual pass through the built gate (ffmpeg 8.0.1, 16 kHz mono):

good.wav      1280078 B → accepted
short.wav      640078 B → sample-too-short
long.wav      2560078 B → sample-too-long
silent.wav    1280078 B → sample-silent
clipped.wav   1280078 B → sample-clipped
notaudio.wav       24 B → sample-unreadable

The sample key and the version purge

storage.voiceSampleKey(ws, userId, profileId, ext) → workspaces/{ws}/voice/{userId}/{profileId}.{ext}, the extension lower-cased from the client's filename (bin when absent, and anything that is not a short alphanumeric run is replaced — an extension is a path segment). One object per profile, under the workspace prefix, so a teardown purges it and a re-enroll overwrites it.

A delete cannot rebuild the exact key: the extension is not stored on the row (the table has no filename column, and this PR adds none). So the purge is purgePrefix over the profile's own …/{profileId}. — a UUID, so it can only match that profile's one object — and it removes every version of it, never a delete marker. That is decision 11's substance: a versioned bucket keeps every byte of an overwritten object.

Both delete shapes remove the vector first (GraphService.deleteVoiceProfile, DELETE FROM VoiceProfile WHERE profileId = … AND workspaceId = … — both predicates; DELETE VERTEX does not parse on the pinned ArcadeDB), then the sample, then the row (?mode=withdraw sets revokedAt instead). Nothing writes a vertex until #1557, so the vector delete is a no-op today and is called anyway: the row and the vector die together.

Two audit actions

AUDIT_ACTIONS gains voice.consent and voice.revoked, and not voice.enrolled — #1557 writes that one when the embedding lands, and the audit spec fails on a value no src file writes. voice.consent carries the workspace, the person, the consent version and ok; voice.revoked carries the mode (withdraw or delete). Neither carries the embedding, the vector, the sample, the file name or the consent text. Both fall under auditCategoryOf's default 'data', so no prefix map changed.

The queue without a consumer

VOICE_QUEUE ('voice'), VoiceQueueModule and VoiceProducer in the memos-queue.module.ts shape: enqueue(profileId) adds { profileId } with jobId: profileId, so one profile has one pending job and a finished one can be added again. MONITORED_QUEUES names it, because a queue with no consumer must be visible rather than hidden. The processor is #1557, and VOICE_PROFILES_ENABLED defaults false, so no deployment can queue one.

Leaving a workspace

WorkspacesService.removeMember removes that workspace's profile (vector, sample versions, row) through VoiceProfileService.removeForMember — one owner for the delete order. Only this workspace's row is in scope; the same person's profile elsewhere is untouched, proved by a fake that applies the (workspaceId, userId) predicate.

It runs after the guarded membership removal, not before: removeMemberGuarded refuses a last admin, and a profile deleted ahead of a refused removal would be a worse loss than the window the doc already accepts ("matching skips a profile whose owner is no longer a member even before that delete runs").

The migration

One additive, nullable column, generated with prisma migrate diff --from-schema-datamodel against dev's schema and replayed by hand (the app role does not own _prisma_migrations):

ALTER TABLE
ALTER TABLE "workspace_settings" ADD COLUMN     "voice_profiles" TEXT;
           Column            |           Type           | Collation | Nullable |     Default
 voice_profiles              | text                     |           |          |
DROP TABLE

scratch_1554 was created for it and dropped afterwards. No default, no backfill, no index; a rollback drops the column and leaves every row as it was.

Per-criterion table — #1403's acceptance rows this task touches

#1403 criterion status evidence
Enroll, re-enroll and delete work; a deleted profile leaves no vector met for the row and the delete call; vector itself deferred to #1557 writes one row, one object and one job, re-enrolls in place…, withdraws: the vector and every version of the sample go…; deleteVoiceProfile carries both predicates and is a no-op until a vertex exists
A second user cannot enroll for another; an admin sees only enrolled/not enrolled, never the vector met no id in path and none accepted from the request (never answers another workspace's or another person's row…); the state is exactly five fields (carries no embedding…)
A bad sample is refused with a reason; no raw audio remains after processing met for the refusal; the post-embedding purge is #1557 five refusal reasons with 422 and nothing written; the sample object exists only for #1557 and every delete purges all its versions
With the workspace feature off, enrollment is unavailable and no profile is written met answer a bare 404 on all three routes when …, three gate cases, nothing written
Specs cover consent version, deletion, cross-workspace isolation and the admin boundary met refuses a consent version…, deletes: the same order…, removeForMember…leaves the same person's profile elsewhere, never answers another workspace's…
make verify met exit 0, 352 files / 5483 tests

Divergences and deferrals

  • workspace_settings.voice_profiles lands here, though doc 89 § Operations tags it 2.3. The gate that reads it is this task's, and the column is what feat(memos): call participants 2.1 — voice_profiles, the VoiceProfile vertex and the deletion inventory #1553's decision 2 recorded. No writer ships: 2.3 adds the admin PATCH.
  • Two rows of doc 89 § Operations corrected (the audit actions and the column, 2.1/2.3 → 2.2, with voice.enrolled/the writer named). A phase label the next worker would trust.
  • voice.enrolled is feat(memos): call participants 2.2 — the ONNX voice embedding, the profile vector and the sample purge #1557's; one-voice is feat(memos): call participants 2.2 — the ONNX voice embedding, the profile vector and the sample purge #1557's. Only the two actions this code writes joined AUDIT_ACTIONS.
  • The delete purges the sample by prefix, not by exact key — the extension is not stored, and a stored one would need a column the doc does not have.
  • removeMember deletes the profile after the guarded membership removal, not before — the doc explicitly tolerates the window, and the reverse order can destroy a profile for a member whose removal was refused.
  • The OpenAPI document describes the POST body as EnrollVoiceDto, not as multipart/form-data. A multipart/form-data content key in this schema makes the generated client's useMutation(apiMutationOptions(…)) infer its variables as undefined: measured, KnowledgeHealthPage.vue fails typecheck with the key present and passes without it, and a $ref body under that key fails the same way. Teaching the shared client a non-JSON body is its own change; the handler and its JSDoc are the truth about the encoding until then.
  • apps/web/src/shared/i18n/messages/{en,ru}.json gain the two audit labels, which the issue's file list omits: security-labels.spec.ts fails every AUDIT_ACTIONS value without a label in both languages.
  • i18n.generated.ts regen carries only this group — the run also surfaced three note.quota* keys a merged task never regenerated; they are reverted so the file's diff is this feature's.
  • Deferred: a membership removal through RoleSyncService (IdP group sync, SCIM) does not purge the profile. This task was given removeMember; a non-member's profile is never matched because PG is the truth on read, and the purge belongs with the read side (feat(memos): call participants 2.2 — the ONNX voice embedding, the profile vector and the sample purge #1557) or a follow-up.

Review

Independent review before opening this PR: spec + work, fresh context, the committed range sliced by area (service, controller, quality gate, four spec slices, module wiring, removeMember, graph/storage primitives, contracts/migration, i18n, changelog/doc, the documented contract — the last three re-run after their first child timed out). make verify exited 0 on every head that was reviewed, and each fix round was re-reviewed as a delta.

Fixed

  • voice-quality.ts — the clipped-peak JSDoc promised "at or above" while the rule is max > -0.1. Corrected the sentence (exactly −0.1 dB passes) rather than the rule the brief fixes, and named it here because the code would otherwise contradict its own comment. → 73db2fba
  • The spec proved the bare 404 body on GET only; it now asserts the same { message: 'Not Found', statusCode: 404 } on all three routes, and that no row, vector, sample version, job or audit row is touched behind the gate. → 73db2fba
  • The gated test asserted no upsert but not that update, delete, deleteVoiceProfile or the sample purge stayed quiet. → 73db2fba
  • A missing consent version only asserted the exception class; it now answers the same 409 consent-version body as a stale one (73db2fba) and audits nothing (f8c51b36).
  • The successful enrollment asserted the calls but not their count; it now pins exactly one upsert, one object, one job and one audit row. → 73db2fba
  • The bare delete asserted the order but not the targets; it now names the vector id and the sample prefix it purges. → 73db2fba
  • The key builders were proved on one literal; two profiles now, so the interpolation of every segment is exercised. → 73db2fba
  • The duration band was driven through the constants under test, so a changed bound would have carried its cases with it; the table is literal and one case pins 30 s, 60 s, the 25 MiB cap, −45 dB and −0.1 dB. → 2d5bff55
  • The temp-copy cleanup was asserted on the accepted path only; both refusal exits (the duration short-circuit and a silent sample) now prove the file is gone. → 2d5bff55

Rejected

  • "No spec file — band edges, silent/clipped pair and cleanup unproven" on the quality slice: a slicing artefact. The spec shipped in this PR (test/voice-quality.spec.ts) and was reviewed by its own child, which then found the two real gaps above.

Deferred — the items under Divergences and deferrals: the vector write, voice.enrolled, the one-voice check and the post-embedding sample purge (#1557); the profile purge on an IdP/SCIM removal; teaching the shared client a non-JSON body before 2.3 calls this POST.

net: eight files under apps/api/src/voice plus their two specs, no new dependency, no processor, no UI, no new env var; the delete order exists once and both callers share it.

`GET | POST | DELETE /v1/me/voice-profile` is the person's own surface in one
workspace: three gates read on execution (the env ceiling, the workspace's
`voice_profiles` column, the person's echoed consent version), two quality
checks over the upload, the `voice_profiles` row as the consent record, the
sample object and the queue job as one act, and a delete that purges the vector
and every version of the sample before the row.

The embedding, the `VoiceProfile` write and the sample purge stay with #1557;
`VOICE_PROFILES_ENABLED` keeps the whole feature dark until then.

Refs #1554
…e targets

Independent review of the spec found six places where a case only proved the
class of a refusal or the fact of a call: the bare 404 body is now asserted on
all three routes (and that no row, vector, sample version, job or audit row was
touched behind the gate), a missing consent version answers the same
409 `consent-version` body as a wrong one, the successful enrollment pins
exactly one upsert, one object, one job and one audit row, the bare delete names
the vector and the purge target, and the key builders are interpolated on two
profiles.

Also corrects the clipped-peak JSDoc: the rule is `max > -0.1`, so exactly
-0.1 dB passes and "at or above" was a sentence the code contradicted.

Refs #1554
…sals

The second review round found the band read from the constants under test —
so a changed bound would carry its cases with it — and the cleanup asserted on
the accepted path only. The bounds are now literal and the constants pinned to
them, and both refusal exits (the duration short-circuit and a silent sample)
prove the temp copy is gone.

Refs #1554
The delta review of the previous fix found the one assertion the other
refusals already carried: a stale or missing consent version writes no audit
row either.

Refs #1554
@hrustalq
hrustalq merged commit 9bb0e9a into dev Dec 3, 2026
2 checks passed
@hrustalq
hrustalq deleted the feat/1554-voice-enrollment branch December 3, 2026 18:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant