@davoodmehraban89 / LifeMate / commits / b58c2a9
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(qa): reviewable atomic private schema migration from original 0011-0020

davoodmehraban89 committed Oct 15, 2026 at 01:25 UTC b58c2a9047b5a3f08bfa05b69e37db4ea25246d4
1 file changed +990
supabase/migrations/202610150002_lifeguide_qa_app_schema_0011_0020.sql new
+990
@@ -0,0 +1,990 @@
1 +begin;
2 +set local lock_timeout='5s';
3 +set local statement_timeout='120s';
4 +set local search_path=lifeguide_qa,extensions,pg_catalog;
5 +do $preflight$ begin
6 + if current_database()<>'postgres'
7 + or to_regnamespace('lifeguide_qa') is null
8 + or to_regclass('lifeguide_qa.schema_migration') is null
9 + or (select count(*) from lifeguide_qa.schema_migration)<>10
10 + or has_schema_privilege('anon','lifeguide_qa','USAGE')
11 + or has_schema_privilege('authenticated','lifeguide_qa','USAGE')
12 + then raise exception 'lifeguide_qa_second_phase_preflight_denied'; end if;
13 +end $preflight$;
14 +-- Original LifeGuide migration 0011_profile_category.sql
15 +
16 +
17 +alter table profile add column profile_category text;
18 +
19 +-- Legacy presentation choices are the only migration hint. Family membership
20 +-- and guardian permissions never define a person's independent category.
21 +update profile set profile_category=case theme_preference
22 + when 'girl_pink' then 'girl_minor'
23 + when 'boy_blue' then 'boy_minor'
24 + else 'adult'
25 +end;
26 +
27 +alter table profile alter column profile_category set default 'adult';
28 +alter table profile alter column profile_category set not null;
29 +alter table profile add constraint profile_category_allowed
30 + check(profile_category in ('girl_minor','boy_minor','adult'));
31 +
32 +
33 +insert into lifeguide_qa.schema_migration(filename,sha256)
34 +values ('0011_profile_category.sql',encode(digest(convert_to($qa_original_0011$begin;
35 +
36 +alter table profile add column profile_category text;
37 +
38 +-- Legacy presentation choices are the only migration hint. Family membership
39 +-- and guardian permissions never define a person's independent category.
40 +update profile set profile_category=case theme_preference
41 + when 'girl_pink' then 'girl_minor'
42 + when 'boy_blue' then 'boy_minor'
43 + else 'adult'
44 +end;
45 +
46 +alter table profile alter column profile_category set default 'adult';
47 +alter table profile alter column profile_category set not null;
48 +alter table profile add constraint profile_category_allowed
49 + check(profile_category in ('girl_minor','boy_minor','adult'));
50 +
51 +commit;
52 +$qa_original_0011$,'UTF8'),'sha256'),'hex'));
53 +-- Original LifeGuide migration 0012_school_archive.sql
54 +
55 +
56 +alter table subject add column archived_at timestamptz;
57 +alter table subject add column updated_at timestamptz;
58 +update subject set updated_at=created_at;
59 +alter table subject alter column updated_at set default now();
60 +alter table subject alter column updated_at set not null;
61 +create index subject_active_owner_idx on subject(student_user_id,created_at desc) where archived_at is null;
62 +
63 +alter table class_session add column archived_at timestamptz;
64 +alter table class_session add column updated_at timestamptz;
65 +update class_session set updated_at=created_at;
66 +alter table class_session alter column updated_at set default now();
67 +alter table class_session alter column updated_at set not null;
68 +create index class_session_active_subject_idx on class_session(subject_id,weekday,starts_at) where archived_at is null;
69 +
70 +alter table learning_checkin add column archived_at timestamptz;
71 +alter table learning_checkin add column updated_at timestamptz;
72 +alter table learning_checkin add column occurred_at timestamptz;
73 +update learning_checkin set updated_at=created_at,occurred_at=created_at;
74 +alter table learning_checkin alter column updated_at set default now();
75 +alter table learning_checkin alter column updated_at set not null;
76 +alter table learning_checkin alter column occurred_at set default now();
77 +alter table learning_checkin alter column occurred_at set not null;
78 +alter table learning_checkin add column source text not null default 'self_reported' check(source='self_reported');
79 +create index learning_checkin_active_owner_idx on learning_checkin(owner_user_id,occurred_at desc) where archived_at is null;
80 +
81 +
82 +insert into lifeguide_qa.schema_migration(filename,sha256)
83 +values ('0012_school_archive.sql',encode(digest(convert_to($qa_original_0012$begin;
84 +
85 +alter table subject add column archived_at timestamptz;
86 +alter table subject add column updated_at timestamptz;
87 +update subject set updated_at=created_at;
88 +alter table subject alter column updated_at set default now();
89 +alter table subject alter column updated_at set not null;
90 +create index subject_active_owner_idx on subject(student_user_id,created_at desc) where archived_at is null;
91 +
92 +alter table class_session add column archived_at timestamptz;
93 +alter table class_session add column updated_at timestamptz;
94 +update class_session set updated_at=created_at;
95 +alter table class_session alter column updated_at set default now();
96 +alter table class_session alter column updated_at set not null;
97 +create index class_session_active_subject_idx on class_session(subject_id,weekday,starts_at) where archived_at is null;
98 +
99 +alter table learning_checkin add column archived_at timestamptz;
100 +alter table learning_checkin add column updated_at timestamptz;
101 +alter table learning_checkin add column occurred_at timestamptz;
102 +update learning_checkin set updated_at=created_at,occurred_at=created_at;
103 +alter table learning_checkin alter column updated_at set default now();
104 +alter table learning_checkin alter column updated_at set not null;
105 +alter table learning_checkin alter column occurred_at set default now();
106 +alter table learning_checkin alter column occurred_at set not null;
107 +alter table learning_checkin add column source text not null default 'self_reported' check(source='self_reported');
108 +create index learning_checkin_active_owner_idx on learning_checkin(owner_user_id,occurred_at desc) where archived_at is null;
109 +
110 +commit;
111 +$qa_original_0012$,'UTF8'),'sha256'),'hex'));
112 +-- Original LifeGuide migration 0013_aparat_learning_library.sql
113 +
114 +alter table education_profile add column track_code text;
115 +update education_profile set track_code='common' where national_grade<10;
116 +alter table education_profile add constraint education_profile_track_check check ((national_grade<10 and track_code='common') or (national_grade>=10 and (track_code is null or track_code in ('math','experimental','humanities'))));
117 +alter table curriculum_subject add column subject_code text;
118 +alter table textbook_catalog add column stable_book_key text unique, add column book_code text, add column track_codes text[] not null default '{common}', add column variant text not null default 'standard' check(variant in('standard','experimental','religious_variant','gifted')), add column edition_verification text not null default 'unverified' check(edition_verification in('verified','unverified')), add column sequence_verification text not null default 'unverified' check(sequence_verification in('official_toc','provider_index','unverified')), add column source_evidence_url text, add column alignment_notes_fa text not null default 'چاپ و انطباق منابع تأیید نشده است.';
119 +create table learning_unit (
120 + id uuid primary key default gen_random_uuid(),textbook_id uuid not null references textbook_catalog(id),unit_key text not null check(unit_key~'^[a-z0-9][a-z0-9-]{0,79}$'),title_fa text not null,order_index integer not null check(order_index>0),index_kind text not null check(index_kind in('page','lesson','chapter')),source_evidence_url text not null,active boolean not null default true,unique(textbook_id,unit_key)
121 +);
122 +create index learning_unit_order_idx on learning_unit(textbook_id,order_index,unit_key);
123 +create table learning_video_resource (
124 + id uuid primary key default gen_random_uuid(),unit_id uuid not null references learning_unit(id),aparat_id text not null check(aparat_id~'^[A-Za-z0-9]{5,64}$'),canonical_aparat_id text check(canonical_aparat_id is null or canonical_aparat_id~'^[A-Za-z0-9]{5,64}$'),title_fa text not null,creator_name text not null,creator_url text not null check(creator_url~'^https://www\.aparat\.com/[A-Za-z0-9_.-]+$'),source_evidence_url text not null,verification_status text not null check(verification_status in('index_verified','metadata_verified','embed_verified')),pedagogical_review text not null default 'unverified' check(pedagogical_review in('unverified','full_reviewed')),duration_seconds integer check(duration_seconds is null or duration_seconds>0),free_access boolean,checked_at timestamptz not null,quality_notes_fa text not null,publication_status text not null default 'draft' check(publication_status in('draft','published','withdrawn')),review_record jsonb,material_hash text not null check(material_hash~'^[a-f0-9]{64}$'),unique(unit_id,aparat_id),
125 + constraint full_review_before_publication check(publication_status<>'published' or (
126 + free_access is true and pedagogical_review='full_reviewed' and verification_status in('metadata_verified','embed_verified') and jsonb_typeof(review_record)='object'
127 + and length(trim(coalesce(review_record->>'reviewerName','')))>0 and length(trim(coalesce(review_record->>'reviewedAt','')))>0
128 + and coalesce(review_record->>'watchedEntireVideo'='true',false) and coalesce(review_record->>'editionAligned'='true',false)
129 + and coalesce(review_record->>'accuracyApproved'='true',false) and coalesce(review_record->>'suitabilityApproved'='true',false)
130 + and coalesce(review_record->>'embedRightsApproved'='true',false) and coalesce(review_record->>'questionCoverageReviewed'='true',false)
131 + and length(trim(coalesce(review_record->>'alignmentNotes','')))>0 and length(trim(coalesce(review_record->>'accuracyNotes','')))>0
132 + and length(trim(coalesce(review_record->>'suitabilityNotes','')))>0 and length(trim(coalesce(review_record->>'embedRightsEvidence','')))>0
133 + and length(trim(coalesce(review_record->>'questionCoverageNotes','')))>0
134 + ))
135 +);
136 +create index learning_video_unit_publication_idx on learning_video_resource(unit_id,publication_status);
137 +create function validate_learning_publication() returns trigger language plpgsql as $$
138 +declare book record; reviewed timestamptz;
139 +begin
140 + if new.publication_status='published' then
141 + select t.book_code,t.edition_verification,t.source_evidence_url book_evidence_url,s.school_year,u.unit_key,u.source_evidence_url unit_evidence_url,u.active into book from learning_unit u join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id where u.id=new.unit_id;
142 + if not book.active or new.review_record->>'materialHash' is distinct from new.material_hash or new.review_record->>'bookEvidenceUrl' is distinct from book.book_evidence_url or new.review_record->>'unitEvidenceUrl' is distinct from book.unit_evidence_url or book.edition_verification<>'verified' or book.school_year='unknown' or new.review_record->>'bookCode' is distinct from book.book_code or new.review_record->>'schoolYear' is distinct from book.school_year or new.review_record->>'unitKey' is distinct from book.unit_key then raise exception 'full review must match verified book edition and unit' using errcode='23514'; end if;
143 + begin reviewed:=(new.review_record->>'reviewedAt')::timestamptz; exception when others then raise exception 'invalid review timestamp' using errcode='23514'; end;
144 + if reviewed is null or reviewed>now() then raise exception 'invalid review timestamp' using errcode='23514'; end if;
145 + end if;
146 + return new;
147 +end $$;
148 +create trigger learning_publication_guard before insert or update on learning_video_resource for each row execute function validate_learning_publication();
149 +create table learning_progress (
150 + owner_user_id uuid not null references app_user(id) on delete cascade,unit_id uuid not null references learning_unit(id),status text not null check(status in('not_started','in_progress','completed')),source text not null check(source='self_reported'),version bigint not null check(version>0),updated_at timestamptz not null default now(),primary key(owner_user_id,unit_id)
151 +);
152 +create table learning_progress_mutation (
153 + owner_user_id uuid not null references app_user(id) on delete cascade,mutation_id uuid not null,unit_id uuid not null references learning_unit(id),request_hash text not null check(length(request_hash)=64),acknowledgement jsonb not null,accepted_at timestamptz not null default now(),primary key(owner_user_id,mutation_id)
154 +);
155 +alter table plan_item add column learning_unit_id uuid references learning_unit(id);
156 +
157 +insert into lifeguide_qa.schema_migration(filename,sha256)
158 +values ('0013_aparat_learning_library.sql',encode(digest(convert_to($qa_original_0013$begin;
159 +alter table education_profile add column track_code text;
160 +update education_profile set track_code='common' where national_grade<10;
161 +alter table education_profile add constraint education_profile_track_check check ((national_grade<10 and track_code='common') or (national_grade>=10 and (track_code is null or track_code in ('math','experimental','humanities'))));
162 +alter table curriculum_subject add column subject_code text;
163 +alter table textbook_catalog add column stable_book_key text unique, add column book_code text, add column track_codes text[] not null default '{common}', add column variant text not null default 'standard' check(variant in('standard','experimental','religious_variant','gifted')), add column edition_verification text not null default 'unverified' check(edition_verification in('verified','unverified')), add column sequence_verification text not null default 'unverified' check(sequence_verification in('official_toc','provider_index','unverified')), add column source_evidence_url text, add column alignment_notes_fa text not null default 'چاپ و انطباق منابع تأیید نشده است.';
164 +create table learning_unit (
165 + id uuid primary key default gen_random_uuid(),textbook_id uuid not null references textbook_catalog(id),unit_key text not null check(unit_key~'^[a-z0-9][a-z0-9-]{0,79}$'),title_fa text not null,order_index integer not null check(order_index>0),index_kind text not null check(index_kind in('page','lesson','chapter')),source_evidence_url text not null,active boolean not null default true,unique(textbook_id,unit_key)
166 +);
167 +create index learning_unit_order_idx on learning_unit(textbook_id,order_index,unit_key);
168 +create table learning_video_resource (
169 + id uuid primary key default gen_random_uuid(),unit_id uuid not null references learning_unit(id),aparat_id text not null check(aparat_id~'^[A-Za-z0-9]{5,64}$'),canonical_aparat_id text check(canonical_aparat_id is null or canonical_aparat_id~'^[A-Za-z0-9]{5,64}$'),title_fa text not null,creator_name text not null,creator_url text not null check(creator_url~'^https://www\.aparat\.com/[A-Za-z0-9_.-]+$'),source_evidence_url text not null,verification_status text not null check(verification_status in('index_verified','metadata_verified','embed_verified')),pedagogical_review text not null default 'unverified' check(pedagogical_review in('unverified','full_reviewed')),duration_seconds integer check(duration_seconds is null or duration_seconds>0),free_access boolean,checked_at timestamptz not null,quality_notes_fa text not null,publication_status text not null default 'draft' check(publication_status in('draft','published','withdrawn')),review_record jsonb,material_hash text not null check(material_hash~'^[a-f0-9]{64}$'),unique(unit_id,aparat_id),
170 + constraint full_review_before_publication check(publication_status<>'published' or (
171 + free_access is true and pedagogical_review='full_reviewed' and verification_status in('metadata_verified','embed_verified') and jsonb_typeof(review_record)='object'
172 + and length(trim(coalesce(review_record->>'reviewerName','')))>0 and length(trim(coalesce(review_record->>'reviewedAt','')))>0
173 + and coalesce(review_record->>'watchedEntireVideo'='true',false) and coalesce(review_record->>'editionAligned'='true',false)
174 + and coalesce(review_record->>'accuracyApproved'='true',false) and coalesce(review_record->>'suitabilityApproved'='true',false)
175 + and coalesce(review_record->>'embedRightsApproved'='true',false) and coalesce(review_record->>'questionCoverageReviewed'='true',false)
176 + and length(trim(coalesce(review_record->>'alignmentNotes','')))>0 and length(trim(coalesce(review_record->>'accuracyNotes','')))>0
177 + and length(trim(coalesce(review_record->>'suitabilityNotes','')))>0 and length(trim(coalesce(review_record->>'embedRightsEvidence','')))>0
178 + and length(trim(coalesce(review_record->>'questionCoverageNotes','')))>0
179 + ))
180 +);
181 +create index learning_video_unit_publication_idx on learning_video_resource(unit_id,publication_status);
182 +create function validate_learning_publication() returns trigger language plpgsql as $$
183 +declare book record; reviewed timestamptz;
184 +begin
185 + if new.publication_status='published' then
186 + select t.book_code,t.edition_verification,t.source_evidence_url book_evidence_url,s.school_year,u.unit_key,u.source_evidence_url unit_evidence_url,u.active into book from learning_unit u join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id where u.id=new.unit_id;
187 + if not book.active or new.review_record->>'materialHash' is distinct from new.material_hash or new.review_record->>'bookEvidenceUrl' is distinct from book.book_evidence_url or new.review_record->>'unitEvidenceUrl' is distinct from book.unit_evidence_url or book.edition_verification<>'verified' or book.school_year='unknown' or new.review_record->>'bookCode' is distinct from book.book_code or new.review_record->>'schoolYear' is distinct from book.school_year or new.review_record->>'unitKey' is distinct from book.unit_key then raise exception 'full review must match verified book edition and unit' using errcode='23514'; end if;
188 + begin reviewed:=(new.review_record->>'reviewedAt')::timestamptz; exception when others then raise exception 'invalid review timestamp' using errcode='23514'; end;
189 + if reviewed is null or reviewed>now() then raise exception 'invalid review timestamp' using errcode='23514'; end if;
190 + end if;
191 + return new;
192 +end $$;
193 +create trigger learning_publication_guard before insert or update on learning_video_resource for each row execute function validate_learning_publication();
194 +create table learning_progress (
195 + owner_user_id uuid not null references app_user(id) on delete cascade,unit_id uuid not null references learning_unit(id),status text not null check(status in('not_started','in_progress','completed')),source text not null check(source='self_reported'),version bigint not null check(version>0),updated_at timestamptz not null default now(),primary key(owner_user_id,unit_id)
196 +);
197 +create table learning_progress_mutation (
198 + owner_user_id uuid not null references app_user(id) on delete cascade,mutation_id uuid not null,unit_id uuid not null references learning_unit(id),request_hash text not null check(length(request_hash)=64),acknowledgement jsonb not null,accepted_at timestamptz not null default now(),primary key(owner_user_id,mutation_id)
199 +);
200 +alter table plan_item add column learning_unit_id uuid references learning_unit(id);
201 +commit;
202 +$qa_original_0013$,'UTF8'),'sha256'),'hex'));
203 +-- Original LifeGuide migration 0014_learning_feedback.sql
204 +
205 +
206 +-- A consented, explicitly chosen summary, never a copy of private chat/notes.
207 +-- Withdrawal redacts the summary while preserving retry and rate-limit receipts.
208 +create table learning_content_feedback (
209 + id uuid primary key default gen_random_uuid(),
210 + owner_user_id uuid not null references app_user(id) on delete cascade,
211 + mutation_id uuid not null,
212 + request_hash text not null check(request_hash ~ '^[0-9a-f]{64}$'),
213 + unit_id uuid references learning_unit(id),
214 + category text not null check(category in
215 + ('inaccurate','edition_mismatch','broken_video','unclear','topic_request')),
216 + summary text,
217 + share_with_content_team boolean not null,
218 + consented_at timestamptz not null default now(),
219 + status text not null default 'received'
220 + check(status in ('received','triaged','planned','released','declined')),
221 + version integer not null default 1 check(version > 0),
222 + created_at timestamptz not null default now(),
223 + updated_at timestamptz not null default now(),
224 + withdrawn_at timestamptz,
225 + unique(owner_user_id,mutation_id),
226 + check (
227 + (withdrawn_at is null and share_with_content_team=true and summary is not null
228 + and char_length(summary) between 1 and 1000 and length(trim(summary))>0)
229 + or
230 + (withdrawn_at is not null and share_with_content_team=false and summary is null)
231 + )
232 +);
233 +
234 +create index learning_feedback_owner_time_idx
235 + on learning_content_feedback(owner_user_id,created_at desc,id desc);
236 +
237 +
238 +insert into lifeguide_qa.schema_migration(filename,sha256)
239 +values ('0014_learning_feedback.sql',encode(digest(convert_to($qa_original_0014$begin;
240 +
241 +-- A consented, explicitly chosen summary, never a copy of private chat/notes.
242 +-- Withdrawal redacts the summary while preserving retry and rate-limit receipts.
243 +create table learning_content_feedback (
244 + id uuid primary key default gen_random_uuid(),
245 + owner_user_id uuid not null references app_user(id) on delete cascade,
246 + mutation_id uuid not null,
247 + request_hash text not null check(request_hash ~ '^[0-9a-f]{64}$'),
248 + unit_id uuid references learning_unit(id),
249 + category text not null check(category in
250 + ('inaccurate','edition_mismatch','broken_video','unclear','topic_request')),
251 + summary text,
252 + share_with_content_team boolean not null,
253 + consented_at timestamptz not null default now(),
254 + status text not null default 'received'
255 + check(status in ('received','triaged','planned','released','declined')),
256 + version integer not null default 1 check(version > 0),
257 + created_at timestamptz not null default now(),
258 + updated_at timestamptz not null default now(),
259 + withdrawn_at timestamptz,
260 + unique(owner_user_id,mutation_id),
261 + check (
262 + (withdrawn_at is null and share_with_content_team=true and summary is not null
263 + and char_length(summary) between 1 and 1000 and length(trim(summary))>0)
264 + or
265 + (withdrawn_at is not null and share_with_content_team=false and summary is null)
266 + )
267 +);
268 +
269 +create index learning_feedback_owner_time_idx
270 + on learning_content_feedback(owner_user_id,created_at desc,id desc);
271 +
272 +commit;
273 +$qa_original_0014$,'UTF8'),'sha256'),'hex'));
274 +-- Original LifeGuide migration 0015_learning_assessment.sql
275 +
276 +create table learning_assessment (
277 + id uuid primary key default gen_random_uuid(),
278 + unit_id uuid not null references learning_unit(id),
279 + version integer not null default 1 check(version>0),
280 + questions jsonb not null check(jsonb_typeof(questions)='array' and jsonb_array_length(questions) between 1 and 20),
281 + content_hash text not null check(content_hash~'^[a-f0-9]{64}$'),
282 + context_hash text not null check(context_hash~'^[a-f0-9]{64}$'),
283 + publication_status text not null default 'draft' check(publication_status in('draft','published','withdrawn')),
284 + review_record jsonb,
285 + created_at timestamptz not null default now(),
286 + check(publication_status<>'published' or coalesce(
287 + jsonb_typeof(review_record)='object' and length(trim(review_record->>'reviewerName'))>0
288 + and (review_record->>'accuracyApproved')='true' and (review_record->>'suitabilityApproved')='true'
289 + and (review_record->>'editionAligned')='true' and (review_record->>'objectiveCoverageApproved')='true'
290 + and (review_record->>'contentHash')=content_hash and (review_record->>'contextHash')=context_hash
291 + and length(trim(review_record->>'reviewNotes'))>0,false))
292 +);
293 +create index learning_assessment_unit_idx on learning_assessment(unit_id,publication_status,version desc);
294 +create function validate_learning_assessment_publication() returns trigger language plpgsql as $$
295 +declare b record; reviewed timestamptz;
296 +begin
297 + if TG_OP='UPDATE' and new.questions is distinct from old.questions then
298 + if new.publication_status='published' or new.version<=old.version or new.content_hash=old.content_hash then
299 + raise exception 'changed assessment needs a new version/hash and draft review' using errcode='23514';
300 + end if;
301 + end if;
302 + if new.publication_status='published' then
303 + select t.book_code,t.edition_verification,s.school_year,u.unit_key into b
304 + from learning_unit u join textbook_catalog t on t.id=u.textbook_id
305 + join curriculum_subject s on s.id=t.curriculum_subject_id where u.id=new.unit_id and u.active;
306 + if b.edition_verification is distinct from 'verified' or b.school_year='unknown'
307 + or new.review_record->>'bookCode' is distinct from b.book_code
308 + or new.review_record->>'schoolYear' is distinct from b.school_year
309 + or new.review_record->>'unitKey' is distinct from b.unit_key then
310 + raise exception 'assessment must match reviewed verified book edition and unit' using errcode='23514';
311 + end if;
312 + begin reviewed:=(new.review_record->>'reviewedAt')::timestamptz;
313 + exception when others then raise exception 'invalid assessment review timestamp' using errcode='23514'; end;
314 + if reviewed is null or reviewed>now() then raise exception 'invalid assessment review timestamp' using errcode='23514'; end if;
315 + end if;
316 + return new;
317 +end $$;
318 +create trigger learning_assessment_publication_guard before insert or update on learning_assessment
319 + for each row execute function validate_learning_assessment_publication();
320 +create table learning_assessment_attempt (
321 + id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references app_user(id) on delete cascade,
322 + mutation_id uuid not null,assessment_id uuid not null references learning_assessment(id),
323 + unit_id uuid not null references learning_unit(id),assessment_version integer not null,
324 + request_hash text not null check(request_hash~'^[a-f0-9]{64}$'),answers jsonb not null,
325 + confidence text not null check(confidence in('unsure','somewhat','confident')),
326 + question_snapshot jsonb not null,acknowledgement jsonb not null,
327 + created_at timestamptz not null default now(),unique(owner_user_id,mutation_id)
328 +);
329 +create index learning_attempt_owner_idx on learning_assessment_attempt(owner_user_id,unit_id,created_at desc);
330 +create table learning_review_schedule (
331 + owner_user_id uuid not null references app_user(id) on delete cascade,unit_id uuid not null references learning_unit(id),
332 + last_attempt_id uuid not null references learning_assessment_attempt(id),next_review_at timestamptz not null,
333 + schedule_policy text not null default 'pilot-1-or-3-days' check(schedule_policy='pilot-1-or-3-days'),
334 + primary key(owner_user_id,unit_id)
335 +);
336 +
337 +insert into lifeguide_qa.schema_migration(filename,sha256)
338 +values ('0015_learning_assessment.sql',encode(digest(convert_to($qa_original_0015$begin;
339 +create table learning_assessment (
340 + id uuid primary key default gen_random_uuid(),
341 + unit_id uuid not null references learning_unit(id),
342 + version integer not null default 1 check(version>0),
343 + questions jsonb not null check(jsonb_typeof(questions)='array' and jsonb_array_length(questions) between 1 and 20),
344 + content_hash text not null check(content_hash~'^[a-f0-9]{64}$'),
345 + context_hash text not null check(context_hash~'^[a-f0-9]{64}$'),
346 + publication_status text not null default 'draft' check(publication_status in('draft','published','withdrawn')),
347 + review_record jsonb,
348 + created_at timestamptz not null default now(),
349 + check(publication_status<>'published' or coalesce(
350 + jsonb_typeof(review_record)='object' and length(trim(review_record->>'reviewerName'))>0
351 + and (review_record->>'accuracyApproved')='true' and (review_record->>'suitabilityApproved')='true'
352 + and (review_record->>'editionAligned')='true' and (review_record->>'objectiveCoverageApproved')='true'
353 + and (review_record->>'contentHash')=content_hash and (review_record->>'contextHash')=context_hash
354 + and length(trim(review_record->>'reviewNotes'))>0,false))
355 +);
356 +create index learning_assessment_unit_idx on learning_assessment(unit_id,publication_status,version desc);
357 +create function validate_learning_assessment_publication() returns trigger language plpgsql as $$
358 +declare b record; reviewed timestamptz;
359 +begin
360 + if TG_OP='UPDATE' and new.questions is distinct from old.questions then
361 + if new.publication_status='published' or new.version<=old.version or new.content_hash=old.content_hash then
362 + raise exception 'changed assessment needs a new version/hash and draft review' using errcode='23514';
363 + end if;
364 + end if;
365 + if new.publication_status='published' then
366 + select t.book_code,t.edition_verification,s.school_year,u.unit_key into b
367 + from learning_unit u join textbook_catalog t on t.id=u.textbook_id
368 + join curriculum_subject s on s.id=t.curriculum_subject_id where u.id=new.unit_id and u.active;
369 + if b.edition_verification is distinct from 'verified' or b.school_year='unknown'
370 + or new.review_record->>'bookCode' is distinct from b.book_code
371 + or new.review_record->>'schoolYear' is distinct from b.school_year
372 + or new.review_record->>'unitKey' is distinct from b.unit_key then
373 + raise exception 'assessment must match reviewed verified book edition and unit' using errcode='23514';
374 + end if;
375 + begin reviewed:=(new.review_record->>'reviewedAt')::timestamptz;
376 + exception when others then raise exception 'invalid assessment review timestamp' using errcode='23514'; end;
377 + if reviewed is null or reviewed>now() then raise exception 'invalid assessment review timestamp' using errcode='23514'; end if;
378 + end if;
379 + return new;
380 +end $$;
381 +create trigger learning_assessment_publication_guard before insert or update on learning_assessment
382 + for each row execute function validate_learning_assessment_publication();
383 +create table learning_assessment_attempt (
384 + id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references app_user(id) on delete cascade,
385 + mutation_id uuid not null,assessment_id uuid not null references learning_assessment(id),
386 + unit_id uuid not null references learning_unit(id),assessment_version integer not null,
387 + request_hash text not null check(request_hash~'^[a-f0-9]{64}$'),answers jsonb not null,
388 + confidence text not null check(confidence in('unsure','somewhat','confident')),
389 + question_snapshot jsonb not null,acknowledgement jsonb not null,
390 + created_at timestamptz not null default now(),unique(owner_user_id,mutation_id)
391 +);
392 +create index learning_attempt_owner_idx on learning_assessment_attempt(owner_user_id,unit_id,created_at desc);
393 +create table learning_review_schedule (
394 + owner_user_id uuid not null references app_user(id) on delete cascade,unit_id uuid not null references learning_unit(id),
395 + last_attempt_id uuid not null references learning_assessment_attempt(id),next_review_at timestamptz not null,
396 + schedule_policy text not null default 'pilot-1-or-3-days' check(schedule_policy='pilot-1-or-3-days'),
397 + primary key(owner_user_id,unit_id)
398 +);
399 +commit;
400 +$qa_original_0015$,'UTF8'),'sha256'),'hex'));
401 +-- Original LifeGuide migration 0016_content_review.sql
402 +
403 +
404 +-- Explicit content-operation capabilities are independent of family/profile/JWT roles.
405 +-- No default grants and no application HTTP grant endpoint.
406 +create table content_capability_grant (
407 + user_id uuid not null references app_user(id) on delete cascade,
408 + permission text not null check(permission in ('feedback.read','feedback.review','brief.prepare')),
409 + granted_at timestamptz not null default now(),
410 + expires_at timestamptz not null,
411 + revoked_at timestamptz,
412 + primary key(user_id,permission),
413 + check(expires_at>granted_at)
414 +);
415 +
416 +-- Operator-only privilege history contains no copied feedback or contact details.
417 +create table content_capability_audit (
418 + id uuid primary key default gen_random_uuid(),
419 + target_user_id uuid not null references app_user(id) on delete cascade,
420 + permission text not null check(permission in ('feedback.read','feedback.review','brief.prepare')),
421 + action text not null check(action in ('grant','revoke')),
422 + occurred_at timestamptz not null default now(),
423 + expires_at timestamptz
424 +);
425 +
426 +create table content_review_brief (
427 + id uuid primary key default gen_random_uuid(),
428 + actor_user_id uuid not null references app_user(id) on delete cascade,
429 + source_count integer not null check(source_count between 1 and 20),
430 + created_at timestamptz not null default now()
431 +);
432 +create table content_review_brief_source (
433 + brief_id uuid not null references content_review_brief(id) on delete cascade,
434 + feedback_id uuid not null references learning_content_feedback(id) on delete cascade,
435 + feedback_version integer not null check(feedback_version>0),
436 + primary key(brief_id,feedback_id)
437 +);
438 +
439 +-- Store only references/hashes: retries always reconstruct CURRENT consenting state.
440 +create table content_review_mutation (
441 + actor_user_id uuid not null references app_user(id) on delete cascade,
442 + mutation_id uuid not null,
443 + operation text not null check(operation in ('review','brief')),
444 + request_hash text not null check(request_hash~'^[0-9a-f]{64}$'),
445 + feedback_id uuid references learning_content_feedback(id) on delete cascade,
446 + brief_id uuid references content_review_brief(id) on delete cascade,
447 + accepted_at timestamptz not null default now(),
448 + primary key(actor_user_id,mutation_id),
449 + check((operation='review' and feedback_id is not null and brief_id is null)
450 + or (operation='brief' and feedback_id is null and brief_id is not null))
451 +);
452 +create table content_review_audit (
453 + id uuid primary key default gen_random_uuid(),
454 + actor_user_id uuid not null references app_user(id) on delete cascade,
455 + feedback_id uuid not null references learning_content_feedback(id) on delete cascade,
456 + before_status text not null check(before_status in ('received','triaged','planned','declined')),
457 + after_status text not null check(after_status in ('triaged','planned','declined')),
458 + before_version integer not null check(before_version>0),
459 + after_version integer not null check(after_version=before_version+1),
460 + occurred_at timestamptz not null default now()
461 +);
462 +create index content_review_visible_idx on learning_content_feedback(status,created_at desc,id desc)
463 + where withdrawn_at is null and share_with_content_team=true;
464 +create index content_review_brief_feedback_idx on content_review_brief_source(feedback_id);
465 +
466 +
467 +insert into lifeguide_qa.schema_migration(filename,sha256)
468 +values ('0016_content_review.sql',encode(digest(convert_to($qa_original_0016$begin;
469 +
470 +-- Explicit content-operation capabilities are independent of family/profile/JWT roles.
471 +-- No default grants and no application HTTP grant endpoint.
472 +create table content_capability_grant (
473 + user_id uuid not null references app_user(id) on delete cascade,
474 + permission text not null check(permission in ('feedback.read','feedback.review','brief.prepare')),
475 + granted_at timestamptz not null default now(),
476 + expires_at timestamptz not null,
477 + revoked_at timestamptz,
478 + primary key(user_id,permission),
479 + check(expires_at>granted_at)
480 +);
481 +
482 +-- Operator-only privilege history contains no copied feedback or contact details.
483 +create table content_capability_audit (
484 + id uuid primary key default gen_random_uuid(),
485 + target_user_id uuid not null references app_user(id) on delete cascade,
486 + permission text not null check(permission in ('feedback.read','feedback.review','brief.prepare')),
487 + action text not null check(action in ('grant','revoke')),
488 + occurred_at timestamptz not null default now(),
489 + expires_at timestamptz
490 +);
491 +
492 +create table content_review_brief (
493 + id uuid primary key default gen_random_uuid(),
494 + actor_user_id uuid not null references app_user(id) on delete cascade,
495 + source_count integer not null check(source_count between 1 and 20),
496 + created_at timestamptz not null default now()
497 +);
498 +create table content_review_brief_source (
499 + brief_id uuid not null references content_review_brief(id) on delete cascade,
500 + feedback_id uuid not null references learning_content_feedback(id) on delete cascade,
501 + feedback_version integer not null check(feedback_version>0),
502 + primary key(brief_id,feedback_id)
503 +);
504 +
505 +-- Store only references/hashes: retries always reconstruct CURRENT consenting state.
506 +create table content_review_mutation (
507 + actor_user_id uuid not null references app_user(id) on delete cascade,
508 + mutation_id uuid not null,
509 + operation text not null check(operation in ('review','brief')),
510 + request_hash text not null check(request_hash~'^[0-9a-f]{64}$'),
511 + feedback_id uuid references learning_content_feedback(id) on delete cascade,
512 + brief_id uuid references content_review_brief(id) on delete cascade,
513 + accepted_at timestamptz not null default now(),
514 + primary key(actor_user_id,mutation_id),
515 + check((operation='review' and feedback_id is not null and brief_id is null)
516 + or (operation='brief' and feedback_id is null and brief_id is not null))
517 +);
518 +create table content_review_audit (
519 + id uuid primary key default gen_random_uuid(),
520 + actor_user_id uuid not null references app_user(id) on delete cascade,
521 + feedback_id uuid not null references learning_content_feedback(id) on delete cascade,
522 + before_status text not null check(before_status in ('received','triaged','planned','declined')),
523 + after_status text not null check(after_status in ('triaged','planned','declined')),
524 + before_version integer not null check(before_version>0),
525 + after_version integer not null check(after_version=before_version+1),
526 + occurred_at timestamptz not null default now()
527 +);
528 +create index content_review_visible_idx on learning_content_feedback(status,created_at desc,id desc)
529 + where withdrawn_at is null and share_with_content_team=true;
530 +create index content_review_brief_feedback_idx on content_review_brief_source(feedback_id);
531 +
532 +commit;
533 +$qa_original_0016$,'UTF8'),'sha256'),'hex'));
534 +-- Original LifeGuide migration 0017_learning_goal_mutations.sql
535 +alter table learning_goal add column version integer not null default 1 check(version > 0);
536 +alter table learning_goal add column archived_at timestamptz;
537 +update learning_goal set archived_at=updated_at where status='archived';
538 +alter table learning_goal add constraint learning_goal_archive_state check((status='archived')=(archived_at is not null));
539 +alter table learning_goal add constraint learning_goal_id_owner_unique unique(id,owner_user_id);
540 +
541 +create table learning_goal_mutation (
542 + owner_user_id uuid not null references app_user(id) on delete cascade,
543 + mutation_id uuid not null,
544 + goal_id uuid not null,
545 + operation text not null check(operation in ('create','update','archive')),
546 + request_hash text not null check(request_hash ~ '^[a-f0-9]{64}$'),
547 + applied_version integer not null check(applied_version > 0),
548 + accepted_at timestamptz not null default now(),
549 + primary key(owner_user_id,mutation_id),
550 + foreign key(goal_id,owner_user_id) references learning_goal(id,owner_user_id) on delete cascade
551 +);
552 +create index learning_goal_mutation_goal_idx on learning_goal_mutation(owner_user_id,goal_id);
553 +insert into lifeguide_qa.schema_migration(filename,sha256)
554 +values ('0017_learning_goal_mutations.sql',encode(digest(convert_to($qa_original_0017$alter table learning_goal add column version integer not null default 1 check(version > 0);
555 +alter table learning_goal add column archived_at timestamptz;
556 +update learning_goal set archived_at=updated_at where status='archived';
557 +alter table learning_goal add constraint learning_goal_archive_state check((status='archived')=(archived_at is not null));
558 +alter table learning_goal add constraint learning_goal_id_owner_unique unique(id,owner_user_id);
559 +
560 +create table learning_goal_mutation (
561 + owner_user_id uuid not null references app_user(id) on delete cascade,
562 + mutation_id uuid not null,
563 + goal_id uuid not null,
564 + operation text not null check(operation in ('create','update','archive')),
565 + request_hash text not null check(request_hash ~ '^[a-f0-9]{64}$'),
566 + applied_version integer not null check(applied_version > 0),
567 + accepted_at timestamptz not null default now(),
568 + primary key(owner_user_id,mutation_id),
569 + foreign key(goal_id,owner_user_id) references learning_goal(id,owner_user_id) on delete cascade
570 +);
571 +create index learning_goal_mutation_goal_idx on learning_goal_mutation(owner_user_id,goal_id);
572 +$qa_original_0017$,'UTF8'),'sha256'),'hex'));
573 +-- Original LifeGuide migration 0018_family_lifecycle.sql
574 +
575 +
576 +alter table family_membership add column version integer not null default 1 check(version>0),
577 + add column updated_at timestamptz not null default now();
578 +update family_membership set updated_at=joined_at;
579 +create function membership_lifecycle_revision() returns trigger language plpgsql as $$
580 +begin
581 + if new.role is distinct from old.role or new.is_admin is distinct from old.is_admin
582 + or new.ended_at is distinct from old.ended_at or new.joined_at is distinct from old.joined_at then
583 + new.version:=old.version+1;
584 + new.updated_at:=statement_timestamp();
585 + else
586 + new.version:=old.version;
587 + new.updated_at:=old.updated_at;
588 + end if;
589 + return new;
590 +end $$;
591 +create trigger family_membership_lifecycle_revision before update on family_membership
592 + for each row execute function membership_lifecycle_revision();
593 +
594 +alter table family_invitation add column version integer not null default 1 check(version>0),
595 + add column updated_at timestamptz not null default now();
596 +update family_invitation set updated_at=created_at;
597 +create function invitation_lifecycle_revision() returns trigger language plpgsql as $$
598 +begin
599 + if new.status is distinct from old.status or new.expires_at is distinct from old.expires_at
600 + or new.intended_role is distinct from old.intended_role or new.intended_theme is distinct from old.intended_theme
601 + or new.invited_email_normalized is distinct from old.invited_email_normalized
602 + or new.invited_phone_normalized is distinct from old.invited_phone_normalized
603 + or new.invited_by is distinct from old.invited_by or new.token_digest is distinct from old.token_digest
604 + or new.accepted_by is distinct from old.accepted_by or new.accepted_at is distinct from old.accepted_at then
605 + new.version:=old.version+1;
606 + new.updated_at:=statement_timestamp();
607 + else
608 + new.version:=old.version;
609 + new.updated_at:=old.updated_at;
610 + end if;
611 + return new;
612 +end $$;
613 +create trigger family_invitation_lifecycle_revision before update on family_invitation
614 + for each row execute function invitation_lifecycle_revision();
615 +
616 +create table family_lifecycle_mutation (
617 + actor_user_id uuid not null references app_user(id) on delete cascade,
618 + mutation_id uuid not null,
619 + family_id uuid not null references family_workspace(id) on delete cascade,
620 + operation text not null check(operation in ('role','admin_transfer','invitation_revoke')),
621 + request_hash text not null check(request_hash~'^[0-9a-f]{64}$'),
622 + target_id uuid not null,
623 + accepted_at timestamptz not null default now(),
624 + primary key(actor_user_id,mutation_id)
625 +);
626 +
627 +
628 +insert into lifeguide_qa.schema_migration(filename,sha256)
629 +values ('0018_family_lifecycle.sql',encode(digest(convert_to($qa_original_0018$begin;
630 +
631 +alter table family_membership add column version integer not null default 1 check(version>0),
632 + add column updated_at timestamptz not null default now();
633 +update family_membership set updated_at=joined_at;
634 +create function membership_lifecycle_revision() returns trigger language plpgsql as $$
635 +begin
636 + if new.role is distinct from old.role or new.is_admin is distinct from old.is_admin
637 + or new.ended_at is distinct from old.ended_at or new.joined_at is distinct from old.joined_at then
638 + new.version:=old.version+1;
639 + new.updated_at:=statement_timestamp();
640 + else
641 + new.version:=old.version;
642 + new.updated_at:=old.updated_at;
643 + end if;
644 + return new;
645 +end $$;
646 +create trigger family_membership_lifecycle_revision before update on family_membership
647 + for each row execute function membership_lifecycle_revision();
648 +
649 +alter table family_invitation add column version integer not null default 1 check(version>0),
650 + add column updated_at timestamptz not null default now();
651 +update family_invitation set updated_at=created_at;
652 +create function invitation_lifecycle_revision() returns trigger language plpgsql as $$
653 +begin
654 + if new.status is distinct from old.status or new.expires_at is distinct from old.expires_at
655 + or new.intended_role is distinct from old.intended_role or new.intended_theme is distinct from old.intended_theme
656 + or new.invited_email_normalized is distinct from old.invited_email_normalized
657 + or new.invited_phone_normalized is distinct from old.invited_phone_normalized
658 + or new.invited_by is distinct from old.invited_by or new.token_digest is distinct from old.token_digest
659 + or new.accepted_by is distinct from old.accepted_by or new.accepted_at is distinct from old.accepted_at then
660 + new.version:=old.version+1;
661 + new.updated_at:=statement_timestamp();
662 + else
663 + new.version:=old.version;
664 + new.updated_at:=old.updated_at;
665 + end if;
666 + return new;
667 +end $$;
668 +create trigger family_invitation_lifecycle_revision before update on family_invitation
669 + for each row execute function invitation_lifecycle_revision();
670 +
671 +create table family_lifecycle_mutation (
672 + actor_user_id uuid not null references app_user(id) on delete cascade,
673 + mutation_id uuid not null,
674 + family_id uuid not null references family_workspace(id) on delete cascade,
675 + operation text not null check(operation in ('role','admin_transfer','invitation_revoke')),
676 + request_hash text not null check(request_hash~'^[0-9a-f]{64}$'),
677 + target_id uuid not null,
678 + accepted_at timestamptz not null default now(),
679 + primary key(actor_user_id,mutation_id)
680 +);
681 +
682 +commit;
683 +$qa_original_0018$,'UTF8'),'sha256'),'hex'));
684 +-- Original LifeGuide migration 0019_school_lifecycle.sql
685 +
686 +
687 +alter table life_context add column version integer not null default 1 check(version>0);
688 +alter table life_context add column updated_at timestamptz not null default now();
689 +alter table academic_year add column version integer not null default 1 check(version>0);
690 +alter table academic_year add column updated_at timestamptz not null default now();
691 +alter table academic_term add column active boolean not null default true;
692 +alter table academic_term add column version integer not null default 1 check(version>0);
693 +alter table academic_term add column updated_at timestamptz not null default now();
694 +
695 +create table school_lifecycle_mutation (
696 + owner_user_id uuid not null references app_user(id) on delete cascade,
697 + mutation_id uuid not null,
698 + entity_type text not null check(entity_type in('contexts','years','terms')),
699 + entity_id uuid not null,
700 + operation text not null check(operation in('create','update','archive')),
701 + request_hash text not null check(char_length(request_hash)=64),
702 + applied_version integer not null check(applied_version>0),
703 + accepted_at timestamptz not null default now(),
704 + primary key(owner_user_id,mutation_id)
705 +);
706 +
707 +-- The same owner-row lock is used by the new router and these guards. It
708 +-- serializes ancestor archival/date edits against the old create APIs too.
709 +create function school_lifecycle_context_guard() returns trigger language plpgsql set search_path=lifeguide_qa,pg_catalog as $$
710 +begin
711 + perform 1 from app_user where id=new.user_id for update;
712 + if tg_op='UPDATE' then
713 + if new.user_id<>old.user_id then raise exception 'school_owner_immutable' using errcode='23514'; end if;
714 + if new.kind<>old.kind and exists(select 1 from academic_year where life_context_id=old.id) then
715 + raise exception 'school_context_kind_in_use' using errcode='23514';
716 + end if;
717 + new.version=old.version+1; new.updated_at=clock_timestamp();
718 + end if;
719 + return new;
720 +end $$;
721 +create trigger school_lifecycle_context_guard before insert or update on life_context for each row execute function school_lifecycle_context_guard();
722 +
723 +create function school_lifecycle_year_guard() returns trigger language plpgsql set search_path=lifeguide_qa,pg_catalog as $$
724 +declare context_row life_context;
725 +begin
726 + perform 1 from app_user where id=new.student_user_id for update;
727 + if tg_op='UPDATE' and (new.student_user_id<>old.student_user_id or new.life_context_id<>old.life_context_id) then
728 + raise exception 'school_parent_immutable' using errcode='23514';
729 + end if;
730 + select * into context_row from life_context where id=new.life_context_id for share;
731 + if context_row.id is null or context_row.user_id<>new.student_user_id or context_row.kind<>'student' then
732 + raise exception 'school_parent_forbidden' using errcode='23514';
733 + end if;
734 + if new.active and not context_row.active then raise exception 'school_parent_inactive' using errcode='23514'; end if;
735 + if char_length(trim(new.title)) not between 1 and 120 then raise exception 'school_invalid_title' using errcode='23514'; end if;
736 + if tg_op='UPDATE' then
737 + if exists(select 1 from academic_term where academic_year_id=old.id and (starts_on<new.starts_on or ends_on>new.ends_on)) then
738 + raise exception 'school_dates_in_use' using errcode='23514';
739 + end if;
740 + new.version=old.version+1; new.updated_at=clock_timestamp();
741 + end if;
742 + return new;
743 +end $$;
744 +create trigger school_lifecycle_year_guard before insert or update on academic_year for each row execute function school_lifecycle_year_guard();
745 +
746 +create function school_lifecycle_term_guard() returns trigger language plpgsql set search_path=lifeguide_qa,pg_catalog as $$
747 +declare year_row academic_year; context_row life_context;
748 +begin
749 + select * into year_row from academic_year where id=new.academic_year_id;
750 + perform 1 from app_user where id=year_row.student_user_id for update;
751 + select * into year_row from academic_year where id=new.academic_year_id for share;
752 + select * into context_row from life_context where id=year_row.life_context_id for share;
753 + if tg_op='UPDATE' and new.academic_year_id<>old.academic_year_id then raise exception 'school_parent_immutable' using errcode='23514'; end if;
754 + if year_row.id is null or context_row.id is null or context_row.user_id<>year_row.student_user_id or context_row.kind<>'student' then
755 + raise exception 'school_parent_forbidden' using errcode='23514';
756 + end if;
757 + if new.active and (not year_row.active or not context_row.active) then raise exception 'school_parent_inactive' using errcode='23514'; end if;
758 + if new.starts_on<year_row.starts_on or new.ends_on>year_row.ends_on then raise exception 'school_dates_outside_parent' using errcode='23514'; end if;
759 + if char_length(trim(new.title)) not between 1 and 120 then raise exception 'school_invalid_title' using errcode='23514'; end if;
760 + if tg_op='UPDATE' then
761 + if exists(select 1 from class_session c join subject s on s.id=c.subject_id where s.academic_term_id=old.id and c.recurrence_until is not null and (c.recurrence_until<new.starts_on or c.recurrence_until>new.ends_on)) then
762 + raise exception 'school_dates_in_use' using errcode='23514';
763 + end if;
764 + new.version=old.version+1; new.updated_at=clock_timestamp();
765 + end if;
766 + return new;
767 +end $$;
768 +create trigger school_lifecycle_term_guard before insert or update on academic_term for each row execute function school_lifecycle_term_guard();
769 +
770 +create function school_lifecycle_subject_guard() returns trigger language plpgsql set search_path=lifeguide_qa,pg_catalog as $$
771 +declare parent_row record;
772 +begin
773 + perform 1 from app_user where id=new.student_user_id for update;
774 + if tg_op='UPDATE' and new.student_user_id<>old.student_user_id then raise exception 'school_owner_immutable' using errcode='23514'; end if;
775 + select t.active as term_active,y.active as year_active,l.active as context_active,y.student_user_id,l.user_id,l.kind
776 + into parent_row from academic_term t join academic_year y on y.id=t.academic_year_id join life_context l on l.id=y.life_context_id where t.id=new.academic_term_id for share of t,y,l;
777 + if not found or parent_row.student_user_id<>new.student_user_id or parent_row.user_id<>new.student_user_id then
778 + raise exception 'school_parent_forbidden' using errcode='23514';
779 + end if;
780 + if new.archived_at is null and (not parent_row.term_active or not parent_row.year_active or not parent_row.context_active or parent_row.kind<>'student') then
781 + raise exception 'school_parent_inactive' using errcode='23514';
782 + end if;
783 + return new;
784 +end $$;
785 +create trigger school_lifecycle_subject_guard before insert or update on subject for each row execute function school_lifecycle_subject_guard();
786 +
787 +create function school_lifecycle_class_guard() returns trigger language plpgsql set search_path=lifeguide_qa,pg_catalog as $$
788 +declare parent_row record; owner_id uuid;
789 +begin
790 + select student_user_id into owner_id from subject where id=new.subject_id;
791 + perform 1 from app_user where id=owner_id for update;
792 + select s.archived_at,t.active as term_active,y.active as year_active,l.active as context_active,t.starts_on,t.ends_on
793 + into parent_row from subject s join academic_term t on t.id=s.academic_term_id join academic_year y on y.id=t.academic_year_id join life_context l on l.id=y.life_context_id where s.id=new.subject_id for share of s,t,y,l;
794 + if not found then raise exception 'school_parent_forbidden' using errcode='23514'; end if;
795 + if new.archived_at is null then
796 + if parent_row.archived_at is not null or not parent_row.term_active or not parent_row.year_active or not parent_row.context_active then
797 + raise exception 'school_parent_inactive' using errcode='23514';
798 + end if;
799 + if new.recurrence_until is not null and (new.recurrence_until<parent_row.starts_on or new.recurrence_until>parent_row.ends_on) then
800 + raise exception 'school_dates_outside_parent' using errcode='23514';
801 + end if;
802 + end if;
803 + return new;
804 +end $$;
805 +create trigger school_lifecycle_class_guard before insert or update on class_session for each row execute function school_lifecycle_class_guard();
806 +
807 +
808 +insert into lifeguide_qa.schema_migration(filename,sha256)
809 +values ('0019_school_lifecycle.sql',encode(digest(convert_to($qa_original_0019$begin;
810 +
811 +alter table life_context add column version integer not null default 1 check(version>0);
812 +alter table life_context add column updated_at timestamptz not null default now();
813 +alter table academic_year add column version integer not null default 1 check(version>0);
814 +alter table academic_year add column updated_at timestamptz not null default now();
815 +alter table academic_term add column active boolean not null default true;
816 +alter table academic_term add column version integer not null default 1 check(version>0);
817 +alter table academic_term add column updated_at timestamptz not null default now();
818 +
819 +create table school_lifecycle_mutation (
820 + owner_user_id uuid not null references app_user(id) on delete cascade,
821 + mutation_id uuid not null,
822 + entity_type text not null check(entity_type in('contexts','years','terms')),
823 + entity_id uuid not null,
824 + operation text not null check(operation in('create','update','archive')),
825 + request_hash text not null check(char_length(request_hash)=64),
826 + applied_version integer not null check(applied_version>0),
827 + accepted_at timestamptz not null default now(),
828 + primary key(owner_user_id,mutation_id)
829 +);
830 +
831 +-- The same owner-row lock is used by the new router and these guards. It
832 +-- serializes ancestor archival/date edits against the old create APIs too.
833 +create function school_lifecycle_context_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
834 +begin
835 + perform 1 from app_user where id=new.user_id for update;
836 + if tg_op='UPDATE' then
837 + if new.user_id<>old.user_id then raise exception 'school_owner_immutable' using errcode='23514'; end if;
838 + if new.kind<>old.kind and exists(select 1 from academic_year where life_context_id=old.id) then
839 + raise exception 'school_context_kind_in_use' using errcode='23514';
840 + end if;
841 + new.version=old.version+1; new.updated_at=clock_timestamp();
842 + end if;
843 + return new;
844 +end $$;
845 +create trigger school_lifecycle_context_guard before insert or update on life_context for each row execute function school_lifecycle_context_guard();
846 +
847 +create function school_lifecycle_year_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
848 +declare context_row life_context;
849 +begin
850 + perform 1 from app_user where id=new.student_user_id for update;
851 + if tg_op='UPDATE' and (new.student_user_id<>old.student_user_id or new.life_context_id<>old.life_context_id) then
852 + raise exception 'school_parent_immutable' using errcode='23514';
853 + end if;
854 + select * into context_row from life_context where id=new.life_context_id for share;
855 + if context_row.id is null or context_row.user_id<>new.student_user_id or context_row.kind<>'student' then
856 + raise exception 'school_parent_forbidden' using errcode='23514';
857 + end if;
858 + if new.active and not context_row.active then raise exception 'school_parent_inactive' using errcode='23514'; end if;
859 + if char_length(trim(new.title)) not between 1 and 120 then raise exception 'school_invalid_title' using errcode='23514'; end if;
860 + if tg_op='UPDATE' then
861 + if exists(select 1 from academic_term where academic_year_id=old.id and (starts_on<new.starts_on or ends_on>new.ends_on)) then
862 + raise exception 'school_dates_in_use' using errcode='23514';
863 + end if;
864 + new.version=old.version+1; new.updated_at=clock_timestamp();
865 + end if;
866 + return new;
867 +end $$;
868 +create trigger school_lifecycle_year_guard before insert or update on academic_year for each row execute function school_lifecycle_year_guard();
869 +
870 +create function school_lifecycle_term_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
871 +declare year_row academic_year; context_row life_context;
872 +begin
873 + select * into year_row from academic_year where id=new.academic_year_id;
874 + perform 1 from app_user where id=year_row.student_user_id for update;
875 + select * into year_row from academic_year where id=new.academic_year_id for share;
876 + select * into context_row from life_context where id=year_row.life_context_id for share;
877 + if tg_op='UPDATE' and new.academic_year_id<>old.academic_year_id then raise exception 'school_parent_immutable' using errcode='23514'; end if;
878 + if year_row.id is null or context_row.id is null or context_row.user_id<>year_row.student_user_id or context_row.kind<>'student' then
879 + raise exception 'school_parent_forbidden' using errcode='23514';
880 + end if;
881 + if new.active and (not year_row.active or not context_row.active) then raise exception 'school_parent_inactive' using errcode='23514'; end if;
882 + if new.starts_on<year_row.starts_on or new.ends_on>year_row.ends_on then raise exception 'school_dates_outside_parent' using errcode='23514'; end if;
883 + if char_length(trim(new.title)) not between 1 and 120 then raise exception 'school_invalid_title' using errcode='23514'; end if;
884 + if tg_op='UPDATE' then
885 + if exists(select 1 from class_session c join subject s on s.id=c.subject_id where s.academic_term_id=old.id and c.recurrence_until is not null and (c.recurrence_until<new.starts_on or c.recurrence_until>new.ends_on)) then
886 + raise exception 'school_dates_in_use' using errcode='23514';
887 + end if;
888 + new.version=old.version+1; new.updated_at=clock_timestamp();
889 + end if;
890 + return new;
891 +end $$;
892 +create trigger school_lifecycle_term_guard before insert or update on academic_term for each row execute function school_lifecycle_term_guard();
893 +
894 +create function school_lifecycle_subject_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
895 +declare parent_row record;
896 +begin
897 + perform 1 from app_user where id=new.student_user_id for update;
898 + if tg_op='UPDATE' and new.student_user_id<>old.student_user_id then raise exception 'school_owner_immutable' using errcode='23514'; end if;
899 + select t.active as term_active,y.active as year_active,l.active as context_active,y.student_user_id,l.user_id,l.kind
900 + into parent_row from academic_term t join academic_year y on y.id=t.academic_year_id join life_context l on l.id=y.life_context_id where t.id=new.academic_term_id for share of t,y,l;
901 + if not found or parent_row.student_user_id<>new.student_user_id or parent_row.user_id<>new.student_user_id then
902 + raise exception 'school_parent_forbidden' using errcode='23514';
903 + end if;
904 + if new.archived_at is null and (not parent_row.term_active or not parent_row.year_active or not parent_row.context_active or parent_row.kind<>'student') then
905 + raise exception 'school_parent_inactive' using errcode='23514';
906 + end if;
907 + return new;
908 +end $$;
909 +create trigger school_lifecycle_subject_guard before insert or update on subject for each row execute function school_lifecycle_subject_guard();
910 +
911 +create function school_lifecycle_class_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
912 +declare parent_row record; owner_id uuid;
913 +begin
914 + select student_user_id into owner_id from subject where id=new.subject_id;
915 + perform 1 from app_user where id=owner_id for update;
916 + select s.archived_at,t.active as term_active,y.active as year_active,l.active as context_active,t.starts_on,t.ends_on
917 + into parent_row from subject s join academic_term t on t.id=s.academic_term_id join academic_year y on y.id=t.academic_year_id join life_context l on l.id=y.life_context_id where s.id=new.subject_id for share of s,t,y,l;
918 + if not found then raise exception 'school_parent_forbidden' using errcode='23514'; end if;
919 + if new.archived_at is null then
920 + if parent_row.archived_at is not null or not parent_row.term_active or not parent_row.year_active or not parent_row.context_active then
921 + raise exception 'school_parent_inactive' using errcode='23514';
922 + end if;
923 + if new.recurrence_until is not null and (new.recurrence_until<parent_row.starts_on or new.recurrence_until>parent_row.ends_on) then
924 + raise exception 'school_dates_outside_parent' using errcode='23514';
925 + end if;
926 + end if;
927 + return new;
928 +end $$;
929 +create trigger school_lifecycle_class_guard before insert or update on class_session for each row execute function school_lifecycle_class_guard();
930 +
931 +commit;
932 +$qa_original_0019$,'UTF8'),'sha256'),'hex'));
933 +-- Original LifeGuide migration 0020_content_publication_audit.sql
934 +
935 +
936 +-- Identifier/hash-only journal. No chosen feedback, reviewer prose or private
937 +-- learner data is copied. HTTP runtime receives SELECT only on this table.
938 +create table content_publication_audit (
939 + mutation_id uuid primary key,
940 + entity_type text not null check(entity_type in ('video','assessment')),
941 + entity_id uuid not null,
942 + operation text not null check(operation in ('publish','withdraw','draft_assessment')),
943 + request_hash text not null check(request_hash ~ '^[a-f0-9]{64}$'),
944 + applied_content_hash text not null check(applied_content_hash ~ '^[a-f0-9]{64}$'),
945 + applied_context_hash text not null check(applied_context_hash ~ '^[a-f0-9]{64}$'),
946 + applied_version integer check(applied_version is null or applied_version>0),
947 + applied_status text not null check(applied_status in ('draft','published','withdrawn')),
948 + operator_role text not null,
949 + accepted_at timestamptz not null default statement_timestamp(),
950 + synthetic_only boolean not null default true check(synthetic_only)
951 +);
952 +
953 +
954 +insert into lifeguide_qa.schema_migration(filename,sha256)
955 +values ('0020_content_publication_audit.sql',encode(digest(convert_to($qa_original_0020$begin;
956 +
957 +-- Identifier/hash-only journal. No chosen feedback, reviewer prose or private
958 +-- learner data is copied. HTTP runtime receives SELECT only on this table.
959 +create table content_publication_audit (
960 + mutation_id uuid primary key,
961 + entity_type text not null check(entity_type in ('video','assessment')),
962 + entity_id uuid not null,
963 + operation text not null check(operation in ('publish','withdraw','draft_assessment')),
964 + request_hash text not null check(request_hash ~ '^[a-f0-9]{64}$'),
965 + applied_content_hash text not null check(applied_content_hash ~ '^[a-f0-9]{64}$'),
966 + applied_context_hash text not null check(applied_context_hash ~ '^[a-f0-9]{64}$'),
967 + applied_version integer check(applied_version is null or applied_version>0),
968 + applied_status text not null check(applied_status in ('draft','published','withdrawn')),
969 + operator_role text not null,
970 + accepted_at timestamptz not null default statement_timestamp(),
971 + synthetic_only boolean not null default true check(synthetic_only)
972 +);
973 +
974 +commit;
975 +$qa_original_0020$,'UTF8'),'sha256'),'hex'));
976 +revoke all on schema lifeguide_qa from public,anon,authenticated,service_role;
977 +revoke all on all tables in schema lifeguide_qa from public,anon,authenticated,service_role;
978 +revoke all on all sequences in schema lifeguide_qa from public,anon,authenticated,service_role;
979 +revoke all on all functions in schema lifeguide_qa from public,anon,authenticated,service_role;
980 +alter default privileges in schema lifeguide_qa revoke all on tables from public,anon,authenticated,service_role;
981 +alter default privileges in schema lifeguide_qa revoke all on sequences from public,anon,authenticated,service_role;
982 +alter default privileges in schema lifeguide_qa revoke execute on functions from public,anon,authenticated,service_role;
983 +do $lockdown$ declare rowrecord record; begin
984 + for rowrecord in select c.relname from pg_class c join pg_namespace n on n.oid=c.relnamespace
985 + where n.nspname='lifeguide_qa' and c.relkind in ('r','p') loop
986 + execute format('alter table %I.%I enable row level security','lifeguide_qa',rowrecord.relname);
987 + execute format('alter table %I.%I force row level security','lifeguide_qa',rowrecord.relname);
988 + end loop;
989 +end $lockdown$;
990 +commit;
\ No newline at end of file