{
  "id": "submission-program-readiness-review",
  "title": "Review a SAS submission program line by line before it goes out",
  "study": {
    "name": "CDISCPILOT01 (CDISC SDTM/ADaM Pilot Project, xanomeline TTS in Alzheimer's disease)",
    "source_url": "https://github.com/cdisc-org/sdtm-adam-pilot-project",
    "licence_note": "adam_adae.sas and the xpt datasets are CDISC Pilot Project materials, used unmodified and attributed to CDISC under the Terms of Use in the repository README (no modification, no sale of the data, attribution required). The study is a CDISC mock submission with fictional dates. Not legal advice."
  },
  "task": "Review a real submission program, adam_adae.sas from the CDISC Pilot, for reviewer-readiness. Every finding must give the line number and quote the line. Findings are split into objective points (hard-coded values, missing comments, dead code, a path that only works on one machine), possible issues that need a data check, and preference. A finding counts as a bug only if a wrong value can be shown with the real ADAE and ADSL files in R; no finding was labelled a bug. SAS was not available, so the program was NOT run in SAS: points that depend on SAS behaviour (sort stability, macro %if with blank values) stay unproven, and the data checks use the SAS-produced adam_adae.xpt as published by CDISC. There is no hidden answer key: the check is whether each finding survives a reading of the file, the real data (R 4.6.1, haven) and the CSR and define.xml. Nothing in this example is invented; the model's hypothetical examples are marked as such in the verification.",
  "time_to_try_minutes": "About 30 minutes (estimate, not measured) to paste the program and prompt and read the answer; plus time to run the data checks in your own environment",
  "good": {
    "input_excerpt": "INPUT: the whole of adam_adae.sas (CDISCPILOT01, CDISC Pilot Project), lines 1-144 of 145 (line 145 is blank). Tabs shown as 4 spaces, trailing blanks trimmed, nothing else changed. The 'NNN|' prefix is added for this example and is not part of the SAS code. The whole file is used because a readiness review needs every line (about 700 words, above the 300-600 word guide). setup.sas (%include on line 5) is not in the repository.\n\n  1| *--------------------------------------------------------------\n  2| ** pch, 1/22/12 -- added amendment 1 coding vars;\n  3| **                 re-arranged variable ordering;\n  4| *--------------------------------------------------------------;\n  5| %include \"..\\setup.sas\";\n  6| \n  7| proc sort data=sdtmnew.AE OUT=AE;\n  8| by USUBJID AESEQ;\n  9| run;\n 10| data AE;\n 11|     set AE;\n 12|     by USUBJID AESEQ;\n 13|     ASTDT=input(strip(AESTDTC),?? yymmdd10.);\n 14|     AENDT=input(strip(AEENDTC),?? yymmdd10.);\n 15|     if ASTDT>.z and AENDT>.z then ADUR=AENDT-ASTDT+1;\n 16|     format ASTDT AENDT DATE9.;\n 17| run;\n 18| \n 19| proc sort data=adamnew.ADSL OUT=TEMP(keep=SITEID USUBJID TRT01A TRT01AN AGE AGEGR1 AGEGR1N RACE RACEN SEX SAFFL\n 20| TRTSDT TRTEDT RENAME=(TRT01A=TRTA TRT01AN=TRTAN));\n 21| by USUBJID;\n 22| run;\n 23| \n 24| data AE;\n 25|     merge AE(in=inAE) TEMP;\n 26|     by USUBJID;\n 27|     if inAE;\n 28|     if ASTDT=. and length(AESTDTC)=7 /*and input(strip(substr(AESTDTC,1,4)),?? best.)=year(TRTSDT)*/ then do;\n 29|         ASTDT=input(compress(AESTDTC||'-01'), yymmdd10.);\n 30|         ASTDTF='D';\n 31|     end;\n 32|     length CQ01NAM $25;\n 33|     IF ASTDT>=TRTSDT>.z then ASTDY=ASTDT-TRTSDT+1;\n 34|     ELSE IF TRTSDT>ASTDT>.z then ASTDY=ASTDT-TRTSDT;\n 35|     IF AENDT>=TRTSDT>.z then AENDY=AENDT-TRTSDT+1;\n 36|     ELSE IF TRTSDT>AENDT>.z then AENDY=AENDT-TRTSDT;\n 37|     IF ASTDT>.z and TRTSDT>.z then ANLSTDY=ASTDT-TRTSDT+1;\n 38|     *IF .z<TRTSDT<=ASTDT<=TRTEDT then ONTRTFL='Y';\n 39|     *ELSE ONTRTFL='N';\n 40|     IF (ASTDT>=TRTSDT>.z) then TRTEMFL='Y';\n 41|     ELSE TRTEMFL='N';\n 42|     IF index(aedecod,'APPLICATION') or\n 43|     index(aedecod,'DERMATITIS') or\n 44|     index(aedecod,'ERYTHEMA') or\n 45|     index(aedecod,'BLISTER') or\n 46|     (aebodsys='SKIN AND SUBCUTANEOUS TISSUE DISORDERS' and aedecod not in ('COLD SWEAT','HYPERHIDROSIS','ALOPECIA'))\n 47|     then  CQ01NAM='DERMATOLOGIC EVENTS';\n 48| run;\n 49| /*\n 50| proc freq data=AE;\n 51| tables TRTEMFL*ATRTEMFL / missing list;\n 52| run;\n 53| */\n 54| %macro flagfrst(inds=,sortvars=, invar=,outvar=,outds=, ser=, derm=);\n 55| \n 56| proc sort data=&inds out=ds01;\n 57|      by usubjid &sortvars ASTDT;\n 58|      where trtemfl='Y'\n 59|                %if &invar ne %then and &invar ne '';\n 60|                %if &ser ne %then and aeser='Y';\n 61|                %if &derm ne %then and CQ01NAM='DERMATOLOGIC EVENTS';\n 62|      ;\n 63| run;\n 64| \n 65| data ds02(keep=usubjid &outvar aeseq);\n 66|      set ds01;\n 67|          by usubjid &sortvars ASTDT;\n 68|      if %if &invar= %then first.usubjid; %else first.&invar; then do ;\n 69|         &outvar='Y';\n 70|         output;\n 71|      end;\n 72| run;\n 73| proc sort data=ds02 out=&outds;\n 74|      by usubjid aeseq;\n 75| run;\n 76| %mend flagfrst;\n 77| \n 78| %* Create first ae flag;\n 79| \n 80| %flagfrst(inds=ae,sortvars=,invar=,outvar=AOCCFL,outds=aea);\n 81| %flagfrst(inds=ae,sortvars=aebodsys,invar=aebodsys,outvar=AOCCSFL,outds=aeb);\n 82| %flagfrst(inds=ae,sortvars=aebodsys aedecod,invar=aedecod,outvar=AOCCPFL,outds=aec);\n 83| \n 84| *%flagfrst(inds=ae,sortvars=,invar=,outvar=SAEFL,outds=saea, ser=Y);\n 85| *%flagfrst(inds=ae,sortvars=aebodsys,invar=aebodsys,outvar=SBODFL,outds=saeb,ser=Y);\n 86| *%flagfrst(inds=ae,sortvars=aebodsys aedecod,invar=aedecod,outvar=SDECODFL,outds=saec,ser=Y);\n 87| %flagfrst(inds=ae,sortvars=,invar=,outvar=AOCC02FL,outds=saea, ser=Y);\n 88| %flagfrst(inds=ae,sortvars=aebodsys,invar=aebodsys,outvar=AOCC03FL,outds=saeb,ser=Y);\n 89| %flagfrst(inds=ae,sortvars=aebodsys aedecod,invar=aedecod,outvar=AOCC04FL,outds=saec,ser=Y);\n 90| %flagfrst(inds=ae,sortvars=,invar=,outvar=AOCC01FL,outds=derm, ser=,derm=Y);\n 91| \n 92| proc sort data=AE;\n 93| by usubjid aeseq;\n 94| run;\n 95| data AE;\n 96|     merge AE AEA AEB AEC SAEA SAEB SAEC DERM;\n 97|     by usubjid aeseq;\n 98|     label /*AESERN = 'Serious Event (N)'*/\n 99|           /*ONTRTFL = 'On or Off Study Treatment Flag'*/\n100|           TRTEMFL = 'Treatment Emergent Analysis Flag'\n101|           AOCCFL = '1st Occurrence of Any AE Flag'\n102|           AOCCSFL = '1st Occurrence of SOC Flag'\n103|           AOCCPFL = '1st Occurrence of Preferred Term Flag'\n104|           /*SAEFL = '1st Serious Occurrence Flag'\n105|           SBODFL = '1st Serious Ocurrence of SOC Flag'\n106|           SDECODFL = '1st Serious Ocurrence of Term Flag'*/\n107|           ASTDT = 'Analysis Start Date'\n108|           ASTDTF = 'Analysis Start Date Imputation Flag'\n109|           ASTDY = 'Analysis Start Relative Day'\n110|           /*ANLSTDY = 'Analysis Start Day'*/\n111|           AENDT = 'Analysis End Date'\n112|           AENDY = 'Analysis End Relative Day'\n113|           TRTA = 'Actual Treatment'\n114|           TRTAN = 'Actual Treatment (N)'\n115|           CQ01NAM='Customized Query 01 Name'\n116|           AOCC02FL='1st Occurrence 02 Flag for Serious'\n117|           AOCC03FL='1st Occurrence 03 Flag for Serious SOC'\n118|           AOCC04FL='1st Occurrence 04 Flag for Serious PT'\n119|           AOCC01FL='1st Occurrence 01 Flag for CQ01'\n120|           ADUR='AE Duration (days)'\n121|           ;\n122| run;\n123| data AE;\n124|     retain STUDYID SITEID USUBJID TRTA TRTAN AGE AGEGR1 AGEGR1N RACE RACEN SEX SAFFL TRTSDT TRTEDT\n125|     ASTDT ASTDTF ASTDY AENDT AENDY ADUR AETERM\n126| AELLT AELLTCD AEDECOD AEPTCD AEHLT AEHLTCD AEHLGT AEHLGTCD AEBODSYS AESOC AESOCCD AESEV AESER AESCAN AESCONG AESDISAB AESDTH AESHOSP AESLIFE AESOD AEREL AEACN\n127| AEOUT AESEQ TRTEMFL AOCCFL AOCCSFL AOCCPFL AOCC02FL AOCC03FL AOCC04FL CQ01NAM AOCC01FL ;\n128|     set AE(keep=STUDYID SITEID USUBJID /*SUBJID*/ TRTAN TRTA AESEQ /*AESPID*/ AETERM AELLT: AEDECOD AEPTCD AEHL: AEBODSYS AESOC: AESEV AESER AEACN AEREL AEOUT AESCAN AESCONG AESDISAB\n129| AESDTH AESHOSP AESLIFE AESOD /*AEDTC AESTDTC AEENDTC AESTDY AEENDY*/   TRTEMFL /*AESERN*/ ASTDT AENDT\n130| ASTDTF CQ01NAM ASTDY AENDY /*ANLSTDY ONTRTFL*/ AOCCFL AOCCSFL AOCCPFL /*SAEFL SBODFL SDECODFL*/ AOCC01FL AOCC02FL AOCC03FL AOCC04FL\n131| AGE AGEGR1 AGEGR1N RACE RACEN SEX SAFFL TRTSDT TRTEDT ADUR);\n132|     by usubjid aeseq;\n133| run;\n134| data adamnew.ADAE(label='Adverse Events Analysis Dataset');\n135|     set AE;\n136|     by USUBJID AESEQ;\n137|     format TRTSDT TRTEDT ASTDT AENDT DATE9.;\n138| run;\n139| \n140| endsas;\n141| ods rtf file=\"C:\\Documents and Settings\\kam39347\\My Documents\\CDISC Pilot\\SDTM\\ADAE.rtf\";\n142| proc contents data=AE varnum;\n143| run;\n144| ods rtf close;",
    "prompt": "TASK\nReview the SAS program below for submission readiness. Someone else (a QC programmer or an agency reviewer) will open this file cold. The program builds the analysis adverse event dataset ADAE from SDTM AE and ADSL for a three-arm placebo-controlled trial of a transdermal patch (so application-site events are expected). Line numbers are shown before each line as \"NNN|\"; the line number is not part of the SAS code.\n\nRULES\n1. Every finding must give the line number(s) and quote the line exactly as it appears after the \"|\". If you cannot quote it, do not report it.\n2. Put findings in two sections. OBJECTIVE: hard-coded values, missing or misleading comments, dead or commented-out code, hard-coded paths, things the file cannot reproduce on its own. PREFERENCE: style and readability opinions that a reasonable programmer could reject.\n3. Do not call anything a bug or an error unless you can say which input values would give a wrong result. Otherwise label it \"possible issue, needs a data check\" and say what data check would settle it.\n4. You cannot run SAS here. Do not say you ran it. State your assumptions.\n5. Do not invent lines or variables. If a point depends on a document you have not seen (SAP, define.xml), say so instead of guessing.\n6. End with a short list of questions for the programmer.\n\nPROGRAM (adam_adae.sas)",
    "output": "**Assumptions:** I did not run SAS. I read only the text given. I have not seen the SAP, define.xml, setup.sas, or the SDTM/ADSL specs. Anything that depends on them is flagged.\n\n## OBJECTIVE\n\n**1. Hard-coded path outside the project (line 141)**\n`ods rtf file=\"C:\\Documents and Settings\\kam39347\\My Documents\\CDISC Pilot\\SDTM\\ADAE.rtf\";`\nThis is a personal user path. It will not exist for anyone else. It sits after `endsas;` (line 140), so it never runs. It is dead code.\n\n**2. Dead code after `endsas;` (lines 140-144)**\n`endsas;` is followed by `ods rtf`, `proc contents data=AE varnum;` and `ods rtf close;`. None of it runs. Either remove it or move it into a separate QC program.\n\n**3. Relative include with an unseen dependency (line 5)**\n`%include \"..\\setup.sas\";`\nThe file cannot reproduce on its own. The path depends on the working directory. The libnames `sdtmnew` and `adamnew` (lines 7, 19, 134) must come from setup.sas, which I have not seen. Windows backslashes also make it non-portable.\n\n**4. Commented-out and unused code (many lines)**\n- Line 28: `/*and input(strip(substr(AESTDTC,1,4)),?? best.)=year(TRTSDT)*/`\n- Lines 38-39: `*IF .z<TRTSDT<=ASTDT<=TRTEDT then ONTRTFL='Y';` and `*ELSE ONTRTFL='N';`\n- Lines 49-53: the commented-out `proc freq`. It refers to `ATRTEMFL`, which is never created.\n- Lines 84-86: the old `*%flagfrst(...SAEFL...)` calls.\n- Lines 98-99 and 104-106: commented label entries.\n- Line 110: `/*ANLSTDY = 'Analysis Start Day'*/`\n- Lines 128-131: commented keep items such as `/*SUBJID*/`, `/*AESPID*/` and `/*ANLSTDY ONTRTFL*/`.\n\nA cold reader cannot tell what was dropped on purpose and what was left by accident. The commented-out `ONTRTFL` is a question in itself. The final dataset has no on-treatment flag. Check this against the SAP.\n\n**5. ANLSTDY is computed but not kept (line 37, lines 128-131)**\n`IF ASTDT>.z and TRTSDT>.z then ANLSTDY=ASTDT-TRTSDT+1;`\n`ANLSTDY` is computed, labelled only in a comment (line 110), and left out of the keep list. It also differs from `ASTDY` (lines 33-34), which has no day 0. Having both is confusing. If it is unused, delete it.\n\n**6. Header comment is thin and misleading (lines 1-4)**\n`** pch, 1/22/12 -- added amendment 1 coding vars;`\n- The header gives no program name, study, purpose, inputs, outputs, or author and date of creation. It has only one change entry.\n- \"Amendment 1 coding vars\" is not defined. A reader cannot tell which variables it means.\n- Line 1 opens `*---...` and has no `;` until line 4, which works. The `**` on lines 2-3 sits inside that comment and is harmless.\n\n**7. Derived-variable logic with no comments (lines 42-47)**\n```\nIF index(aedecod,'APPLICATION') or\n...\n(aebodsys='SKIN AND SUBCUTANEOUS TISSUE DISORDERS' and aedecod not in ('COLD SWEAT','HYPERHIDROSIS','ALOPECIA'))\nthen  CQ01NAM='DERMATOLOGIC EVENTS';\n```\n- The query definition is hard-coded as text strings. No comment gives its source (SAP, a named MedDRA query, or the amendment). The inclusion list and the three exclusions have no stated rationale.\n- This is a patch trial, so application-site events are expected. Matching `'APPLICATION'` in `aedecod` is a text match, not a MedDRA code match. It may capture terms that are not application-site reactions. It could also miss any that are spelled differently. Case and MedDRA version matter here (see 11).\n- `CQ01NAM` is set only for matches. It is never set to blank otherwise, which is fine, but the label (line 115) is only 'Customized Query 01 Name'.\n- There is no `CQ01` flag or code variable, and no check that the exclusions match the real SOC wording.\n\n**8. Hard-coded values**\n- Line 13 and line 14: `ASTDT=input(strip(AESTDTC),?? yymmdd10.);` and `AENDT=input(strip(AEENDTC),?? yymmdd10.);`\n- Line 28: `length(AESTDTC)=7`, with the `'-01'` append on line 29: `ASTDT=input(compress(AESTDTC||'-01'), yymmdd10.);`\n- Line 30: `ASTDTF='D';`\n- Line 32: `length CQ01NAM $25;`\n\nThese are fixed assumptions. Details are under PREFERENCE and POSSIBLE ISSUES below.\n\n**9. Labels are missing or inconsistent (lines 98-121)**\n- `TRTSDT`, `TRTEDT`, `TRTEMFL` and others: `TRTSDT` and `TRTEDT` have no label here. They may inherit one from ADSL. That is unseen.\n- Line 100: `TRTEMFL = 'Treatment Emergent Analysis Flag'`.\n- Lines 116-119: `AOCC02FL`..`AOCC04FL` are labelled \"Serious\" and `AOCC01FL` is labelled \"CQ01\". The numbering is the reverse of the logical order. The dermatologic flag is 01 yet is created last (line 90), and the serious flags are 02-04.\n- Line 117: `AOCC03FL='1st Occurrence 03 Flag for Serious SOC'`.\n- Lines 105-106 contain misspellings (\"Ocurrence\"), but they sit inside a comment.\n- `ASTDT`..`AENDY` labels are fine.\n\n**10. Variable-name checks that depend on unseen specs**\n`TRTA` and `TRTAN` are renamed from `TRT01A` and `TRT01AN` (line 20). Whether ADAM requires `TRTA`/`TRTAN` is a spec question. I cannot confirm from this file. The same applies to the dataset label on line 134 and the variable set.\n\n## POSSIBLE ISSUES, NEEDS A DATA CHECK\n\n**A. Partial-date imputation (lines 28-31).**\n`if ASTDT=. and length(AESTDTC)=7 ... then do; ASTDT=input(compress(AESTDTC||'-01'), yymmdd10.); ASTDTF='D'; end;`\n- Only the `YYYY-MM` form is handled. A start date of only `YYYY`, length 4, stays missing. Those events then get `TRTEMFL='N'` (see C).\n- The flag value `'D'` for a month-only date is a convention choice (ADaM uses 'D' for day imputed), but the imputation rule is not documented in the file.\n- Imputing to the 1st of the month can set an AE before treatment start when the true date was after it. Example: `AESTDTC='2012-03'` and `TRTSDT=15MAR2012` gives `ASTDT=01MAR2012`, which is before TRTSDT. That event would be flagged `TRTEMFL='N'` even though the true date may be on or after treatment start. The commented-out year check on line 28 suggests this was discussed.\n- Data check: list `AESTDTC` with `length<10` and compare against `TRTSDT` month. Confirm the rule in the SAP.\n\n**B. `AENDT` has no partial-date handling.**\nLine 14 parses `AEENDTC` with `??`, so any partial or invalid string silently becomes missing. `ADUR` (line 15) is then missing without notice.\nData check: count records where `AEENDTC` is non-blank and `AENDT` is missing.\n\n**C. `TRTEMFL` logic (lines 40-41).**\n`IF (ASTDT>=TRTSDT>.z) then TRTEMFL='Y'; ELSE TRTEMFL='N';`\n- If `ASTDT` is missing, the condition is false and the flag is `'N'`. A missing start date is therefore treated as not treatment-emergent. Many SAPs treat an unknown start as emergent. Needs the SAP.\n- There is no upper bound using `TRTEDT` (the commented ONTRTFL on line 38 had one). Events after the end of treatment plus any follow-up window count as emergent. Check against the SAP definition.\n- If `TRTSDT` is missing (for example a subject not treated), `TRTEMFL='N'`. Data check: count records with missing `TRTSDT`.\n\n**D. Mixed numeric comparison chain (lines 33-36).**\n`IF ASTDT>=TRTSDT>.z then ...` is valid SAS and evaluates as two comparisons, so I do not call it an error. The `ELSE IF TRTSDT>ASTDT>.z` branch gives a negative day with no day 0, which is the standard ADaM convention. This works only if both dates are non-missing. No `ELSE` is needed there.\n\n**E. Merge with ADSL (lines 24-27).**\n`merge AE(in=inAE) TEMP; by USUBJID; if inAE;`\n- A subject in AE but not in ADSL would keep missing `TRT`, `TRTSDT` and so on. No check or message flags this.\n- The AE file has already been sorted by `USUBJID AESEQ`. ADSL is sorted by `USUBJID` in the same step. If ADSL had duplicate `USUBJID`, the merge would give a many-to-many warning and wrong carry-down. Data check: `proc sort nodupkey` on ADSL and compare counts.\n- AEs are also not subset to the safety population. `SAFFL` is carried but not applied. Check against the SAP.\n\n**F. `flagfrst` macro (lines 54-76).**\n- Line 59: `%if &invar ne %then and &invar ne '';` The `where` clause is built from macro text. With `invar=aebodsys` it becomes `and aebodsys ne ''`, which drops records with a blank SOC or term. Those events then can never get the flag. Data check: any blank `AEBODSYS` or `AEDECOD`.\n- Line 57 sorts `by usubjid &sortvars ASTDT`. With ties on `ASTDT` (including missing, excluded by `trtemfl='Y'`), which record is first depends on the sort order of the input. Two AEs on the same date could be chosen arbitrarily. `AESEQ` is not in the sort key, so the result may differ between runs. Data check: count subject/term groups with more than one record on the earliest date.\n- Line 68: `if %if &invar= %then first.usubjid; %else first.&invar; then do ;` is hard to read. It works for `first.aebodsys` and `first.aedecod`.\n- For `aedecod` (line 82), `sortvars=aebodsys aedecod` and `invar=aedecod`, first.aedecod within `usubjid aebodsys aedecod` is correct only if each term sits under one SOC. In the multi-SOC case, a PT that appears under two SOCs would get a first-flag for each. That may be intended. Check the SAP.\n- Lines 87-89: the `where` includes `trtemfl='Y'` and `aeser='Y'`. Line 90's call for the dermatologic flag passes `ser=,derm=Y`, so `&ser` is blank and works.\n- The macro has no comment block describing its parameters. The `%*` comment on line 78 is the only note: `%* Create first ae flag;`. It does not describe the serious or dermatologic calls.\n- Macro-call argument names such as `outds=saea` (line 87) reuse the names of the older commented-out calls (lines 84-86). The output datasets `AEA`..`DERM` are only created if the calls run.\n\n**G. Merge by `usubjid aeseq` (lines 95-97).**\n`merge AE AEA AEB AEC SAEA SAEB SAEC DERM; by usubjid aeseq;`\nThis depends on `usubjid aeseq` being unique in `AE`. If not, the flags would be spread wrongly. Data check: `nodupkey` on `usubjid aeseq`. Flags that have no `Y` are left missing (not `N`), which is a common ADaM choice but should be confirmed.\n\n**H. Final keep list vs retain list (lines 123-133).**\n- Line 124-127 `retain` includes `AEREL`, `AEACN`, etc. in the order given. Variables in the `retain` statement that are not in the keep list get created as missing. Compare the two lists. For example, `AESOCCD`, `AELLTCD`, `AEPTCD`, `AEHLTCD` and `AEHLGTCD`: the keep uses wildcards `AELLT:`, `AEHL:`, `AESOC:`, so `AELLTCD`, `AEHLTCD` etc. are kept only if present in SDTM AE. If SDTM AE does not have them, they will come out as all-missing variables from the retain statement. Data check: `proc contents` on ADAE.\n- `AEPTCD` is in both. `AEHLGT` and `AEHLGTCD` match `AEHL:`.\n- `AESDTH`, `AESHOSP`, `AESLIFE` etc. depend on SDTM.\n- `STUDYID` is retained and kept, but `STUDYID` is not in `TEMP` (it comes from AE), which is fine.\n- `AESTDTC`, `AEENDTC`, `AESTDY`, `AEENDY` are intentionally dropped (commented in the keep list). The SDTM variable `AEENDY` is dropped, but a derived `AENDY` is kept. The name is easy to confuse with `AEENDY`. Fine, but confusing.\n- `ASTDT` and `AENDT` formats: set at line 16 and again at line 137. The duplication is harmless.\n- `ADUR` (line 15): `AENDT-ASTDT+1`. If `ASTDT` was imputed (month only), the duration is based on an imputed start. Undocumented.\n\n**I. Sort order of the output.**\nLine 123 data step sorts nothing. The input `AE` is sorted by `usubjid aeseq` so the output is. Line 132 `by usubjid aeseq;` would error if it were not sorted, so it acts as a check.\n\n**J. Case of values.**\n`aedecod`, `aebodsys` comparisons (lines 42-46) are case-sensitive. `index(aedecod,'APPLICATION')` will miss 'Application site pruritus' if the dictionary values are mixed case. Data check: run `proc freq` on `AEDECOD` and `AEBODSYS` to see the case.\n\n## PREFERENCE\n\n1. Mixed upper and lower case keywords and variable names (lines 33-36 `IF`/`ELSE IF`, lines 42-47, vs lowercase elsewhere). A reasonable programmer could accept it.\n2. `length CQ01NAM $25;` (line 32) is placed in the middle of the step. Most would put it before first use. `'DERMATOLOGIC EVENTS'` is 19 characters, so $25 works, but it is a magic number.\n3. Dataset names reuse `AE` for every step (lines 10, 24, 95, 123). That makes the log hard to follow and means rerunning a single step is not possible. Consider distinct names.\n4. Macro parameter handling by `%if &invar ne %then` with empty values could use `%length` or `%sysevalf`; readability opinion.\n5. `proc sort ... OUT=` and `out=` with inconsistent case.\n6. The `keep` in the proc sort option on lines 19-20 is a long single line with the `RENAME` on the next line. Splitting it would help.\n7. `format ASTDT AENDT DATE9.;` (line 16) and again at line 137 along with `TRTSDT TRTEDT`; keep one.\n8. Line 140 `endsas;` as a bare statement is unusual in a delivered program.\n9. The flag naming (`AOCC01FL`..`AOCC04FL`) and the order in which they are labelled and created do not match. Consider ordering by number.\n10. Variable ordering depends on `retain` ahead of `set`, a known SAS trick. It works, but a `retain` list that is also the \"order\" statement is easy to misread. An `attrib` or a final `keep` order would be clearer.\n11. Lines 2-3 comment style (`**`) differs from the `*---` style on line 1 and the `/* */` blocks elsewhere.\n\n## Questions for the programmer\n\n1. What is the source and the exact definition of `CQ01NAM` (lines 42-47)? Is it from the SAP, a named MedDRA query, or Amendment 1? Why those three exclusions?\n2. What does the SAP say about treatment-emergent when `ASTDT` is missing or partial, and about an upper bound using `TRTEDT` or a follow-up window? Why was `ONTRTFL` removed?\n3. How are `YYYY`-only start dates and partial end dates meant to be handled? Why impute to the 1st of the month, and is `'D'` the right `ASTDTF` value?\n4. Is `ANLSTDY` needed? If not, remove it. If so, why is it not kept?\n5. Which of the `AELLTCD`, `AEPTCD`, `AEHLTCD`, `AEHLGTCD`, `AESOCCD` variables actually exist in SDTM AE? Does the retain list create any all-missing columns in ADAE?\n6. Are `USUBJID AESEQ` unique in SDTM AE and `USUBJID` unique in ADSL? Are there AE subjects not in ADSL? Is the safety population applied anywhere?\n7. How are ties on `ASTDT` broken in the first-occurrence flags, and do any blank `AEBODSYS` or `AEDECOD` values exist?\n8. Why are the flags numbered `AOCC01FL`..`AOCC04FL` in this order, and do they match define.xml and the shells? (I have not seen define.xml.)\n9. What does `setup.sas` define, and can the program run from a clean session? Can the dead code after `endsas;`, including the personal path, be deleted?\n10. Should the commented-out code and the stale header be cleaned up before submission, and should a full change history be added?",
    "trim_note": "No trimming: both outputs are verbatim. The input is the whole 144-line program (about 700 words) instead of a 300-600 word excerpt, because dead code, header and macro calls can only be judged in the whole file. The bad run was also given the whole program, without line numbers. One model, one run each, not a rate."
  },
  "bad": {
    "input": "Can you check our ADAE SAS program is ready to submit? Let me know if anything is wrong with it.\n\n[The whole program, lines 1-144, was pasted below the question, without line numbers.]",
    "output": "Not ready to submit yet. I only read the code and did not run it, so I can't speak to the log, and the macro issue in item 4 should be tested first.\n\n**Derivation problems**\n1. **ADUR is calculated before the start date is imputed.** Events with a month-only start date (for example \"2012-03\") get ADUR missing, even though ASTDT is filled in later. Calculate ADUR after the imputation step.\n2. **Partial dates are only partly handled.**\n   - Only 7-character start dates (YYYY-MM) are imputed. Year-only dates (length 4) stay missing.\n   - A missing ASTDT makes TRTEMFL = 'N'. That drops events that may be treatment emergent from every first-occurrence flag.\n   - End dates are never imputed, so AENDT, AENDY and ADUR are missing for partial end dates.\n3. **Imputing the day as 01 can misclassify events.** If an event starts in the same month as TRTSDT, the imputed date can fall before TRTSDT. The event is then flagged TRTEMFL = 'N'. The commented-out year check suggests you were aware of this. The usual rule is to use TRTSDT in that case, or to treat the event as treatment emergent. Confirm this against the SAP.\n4. **The macro may fail with empty parameters.** `%if &invar ne %then` and `%if &ser ne %then` can error with \"operand missing\" when the parameter is blank, and several calls leave them blank. Use `%if %length(&invar) %then ...` to be safe.\n5. **The first-occurrence sort is not deterministic.** It sorts by `ASTDT` only, so ties are broken by whatever order the data happens to be in. Add `AESEQ` to the sort and the BY statement.\n6. **There is no upper limit on the treatment-emergent window.** TRTEMFL only checks that the event starts on or after TRTSDT. If the SAP uses a window such as TRTEDT + 30 days, that is missing.\n7. **The dermatologic query (CQ01NAM) is hard-coded and case-sensitive.** `index()` and `=` only match uppercase terms. Check the term list against the SAP or the MedDRA query definition.\n\n**Cleanup before submitting**\n- Remove the trailing `endsas;` and the ODS RTF block. It contains a hard-coded `C:\\Documents and Settings\\kam39347\\...` path, which should not go out.\n- ANLSTDY is derived but never kept, so it is dead code. Delete it, or keep and label it.\n- Remove the large blocks of commented-out code: ONTRTFL, SAEFL, SBODFL, SDECODFL, AESERN and the TRTEMFL freq.\n- `%include \"..\\setup.sas\"` is a relative path. Make sure it resolves in the submission environment.\n- The header only mentions the 2012 amendment. Add a program name, purpose, inputs, outputs and a revision history.\n- Variable labels are missing for several derived or carried variables, such as ADUR's start-date partner and the AE variables. Check every variable against the define.xml specification.\n- AOCC01FL to AOCC04FL are numbered out of order with respect to the code. AOCC01FL is the dermatologic flag and AOCC02FL to AOCC04FL are the serious-event flags. Confirm the numbering matches the spec.\n\n**Before sign-off**\n- Run it and confirm the log has no errors, no warnings and no uninitialized variables. Check the merge for AE records with no ADSL match.\n- Do independent QC, for example a double-programmed comparison with PROC COMPARE.\n- Confirm the ADSL source variables (SAFFL, TRTSDT and so on) are what the spec expects.\n\nI can draft the corrected code for items 1 to 5 if you want it.",
    "what_went_wrong": [
      "The bad answer gives no line numbers and quotes no code, so a programmer has to hunt for every point. It also gives no objective/preference split.",
      "Its first and most prominent finding is wrong: it says to calculate ADUR after the start date is imputed. The delivered xpt keeps ADUR missing for month-only starts (ADURN equals the program's before-imputation formula in all 1191 rows in the earlier R run), so the advice would change the dataset away from what was delivered.",
      "It states two SAS behaviours as fact without being able to run SAS: that the macro test '%if &invar ne %then' may fail on blank values, and that the first-occurrence sort is not deterministic. Both are unproven here; the xpt flags are consistent with the macro working and with the lowest AESEQ winning every tie.",
      "Its case-sensitivity warning is a false alarm for this data (no lower-case letters in AEDECOD or AEBODSYS), and its imputed-day example never occurs (0 of 15 imputed dates fall in the treatment-start month).",
      "To be fair: it did find the dead code after endsas, the personal path, ANLSTDY, the thin header and the year-only dates. The gap is the evidence, not the topic list: nothing in it can be checked line by line."
    ]
  },
  "what_changed": [
    "Input: 'is it ready to submit?' became a defined reviewer task (an agency or QC programmer opening the file cold) and the program was given with line numbers.",
    "Rules: every finding needs a line number and an exact quote; objective points and preference are separated; 'bug' is banned unless the model can name the input values that give a wrong result.",
    "The model was told it cannot run SAS and must say what it assumed, and it was told not to guess at documents it had not seen (SAP, define.xml, setup.sas).",
    "Output: the answer became checkable. 44 of 44 non-abbreviated inline quotes were found in the file (8 other fragments were the model's own examples or macro expansions), and the cited lines were right.",
    "Checking added: the verifier ran the claims against adam_adae.xpt, sdtm_ae.xpt, adam_adsl.xpt, define.xml and CSR Table 12-2 in R. That is where the false alarms, the six all-blank columns and the CQ01 mismatch showed up."
  ],
  "check_before_trust": [
    "Open the file at the cited line and read it. All quoted lines here were on the line cited, but that was checked for this run only.",
    "Treat every statement about what SAS does as unproven until you run it. Here PROC SORT tie order and the blank-parameter %if could not be run.",
    "Ask for the data check, then run it. A risk such as 'imputing day 01 can move an event before treatment start' is real in general, but in this data 0 of 15 imputed dates fall in the treatment-start month, so no value is wrong.",
    "Compare the program with the dataset it produced, not only with itself. The model could not see that the delivered xpt has ADURN and ADURU where the program creates ADUR; only the comparison shows it.",
    "Check rule-based lists against the study documents. The model worried that the text match 'may capture terms that are not application-site reactions' without a list to test; comparing with CSR Table 12-2 found 3 extra preferred terms (5 events).",
    "Keep preference points out of the pass/fail count. A reasonable programmer can reject items such as keyword case or reusing the dataset name AE."
  ],
  "verification": {
    "answer_key": "Recomputed: no hidden answer key exists. Each finding was checked by reading the file at the cited line, then (for data claims) recomputed in R 4.6.1 from sdtm_ae.xpt, adam_adsl.xpt and the SAS-produced adam_adae.xpt, and compared with adam_define.xml and CSR Table 12-2 (p. 33). SAS was not run. Scripts are in submission-program-readiness-review_Rrun/ and submission-program-readiness-review_quotecheck.py.",
    "rows": [
      {
        "claim": "Line 141 holds a personal hard-coded path (ods rtf file=\"C:\\Documents and Settings\\...\") and it sits after endsas; on line 140, so it never runs.",
        "verdict": "correct (objective)",
        "cite": "adam_adae.sas lines 140-144; checks.R C8 finds the Windows path on line 141 and endsas on line 140."
      },
      {
        "claim": "Lines 140-144 are dead code after endsas;.",
        "verdict": "correct (objective)",
        "cite": "adam_adae.sas lines 140-144."
      },
      {
        "claim": "Line 5 %include \"..\\setup.sas\" means the file cannot be reproduced on its own; libnames sdtmnew and adamnew come from it (lines 7, 19, 134).",
        "verdict": "correct (objective); content of setup.sas not in source",
        "cite": "Lines 5, 7, 19, 134. PROVENANCE.md lists only two SAS programs in the repository, so setup.sas is not available."
      },
      {
        "claim": "Commented-out code at lines 28, 38-39, 49-53, 84-86, 98-99, 104-106, 110, 128-131, and the proc freq at 49-53 refers to ATRTEMFL, which is never created.",
        "verdict": "correct (objective)",
        "cite": "All ranges match the file. ATRTEMFL occurs only in the comment on line 51."
      },
      {
        "claim": "ANLSTDY is computed on line 37 but never kept (lines 128-131).",
        "verdict": "correct (objective)",
        "cite": "checks.R C7: ANLSTDY is not among the 55 columns of adam_adae.xpt."
      },
      {
        "claim": "The header (lines 1-4) has no program name, purpose, inputs or outputs and 'amendment 1 coding vars' is not defined.",
        "verdict": "correct (objective)",
        "cite": "Lines 1-4. The model also notes correctly that the comment is valid SAS even though line 1 has no semicolon."
      },
      {
        "claim": "The CQ01NAM rule (lines 42-47) is hard-coded text with no comment on its source.",
        "verdict": "correct (objective)",
        "cite": "Lines 42-47. adam_define.xml (ADAE.CQ01NAM) documents the same rule, so the source exists, but not in the program."
      },
      {
        "claim": "The 'APPLICATION' text match on line 42 may capture terms that are not application-site reactions.",
        "verdict": "partly: right worry, wrong line",
        "cite": "The over-capture is real but comes from ERYTHEMA (line 44), not APPLICATION: PHARYNGEAL ERYTHEMA (respiratory SOC, 2 events) is flagged. cq01_vs_csr_output.txt: 35 flagged PTs against 32 in CSR Table 12-2 (p. 33); extras are DERMATITIS ATOPIC (1), PHARYNGEAL ERYTHEMA (2), RASH PAPULAR (2). define.xml has the same rule, so the program is consistent with define.xml and inconsistent with the CSR list. No extra event is a first-occurrence AOCC01FL record (checks.R C10: 152 = 152, 0 differ)."
      },
      {
        "claim": "'There is no CQ01 flag or code variable' (item 7).",
        "verdict": "wrong",
        "cite": "AOCC01FL (lines 90 and 119) is the flag for dermatologic events; only a separate code variable is absent."
      },
      {
        "claim": "Item 8 lists input informats, 'D' and $25 as hard-coded values.",
        "verdict": "partly",
        "cite": "The literal 7, '-01', 'D' and $25 are hard-coded; the informat yymmdd10. is not a data value. The $25 on line 32 differs from Length=19 in define.xml (ADAE.CQ01NAM), a point the model did not make."
      },
      {
        "claim": "TRTSDT and TRTEDT have no label in the program (lines 98-121).",
        "verdict": "correct on the program; harmless in the data",
        "cite": "The xpt carries labels for both, inherited from ADSL."
      },
      {
        "claim": "Item 7 says 'Case and MedDRA version matter here (see 11)'.",
        "verdict": "wrong internal reference",
        "cite": "Objective list has 10 items; 11 is a preference item about comment style. Item J (case) was meant."
      },
      {
        "claim": "A. Year-only start dates (length 4) stay missing and get TRTEMFL='N'.",
        "verdict": "correct, no wrong value in this data",
        "cite": "checks.R C2: 11 year-only starts, all ASTDT missing and TRTEMFL='N'; none in the treatment-start year (0 of 11), all earlier. adam_define.xml (ADAE.ASTDT) says no imputation is done for these because they clearly precede treatment."
      },
      {
        "claim": "A. Imputing day 01 can move an event before TRTSDT (example 2012-03 vs 15MAR2012).",
        "verdict": "right risk; example is hypothetical; not shown in data",
        "cite": "checks.R C2: 15 month-only starts imputed (ASTDTF='D'), 0 in the same month as TRTSDT; 6 are TRTEMFL='Y', 9 are 'N' because the month is earlier. Demoted to a latent risk."
      },
      {
        "claim": "B. Partial end dates are silently set missing by ??.",
        "verdict": "false alarm for this data",
        "cite": "checks.R C2: AEENDTC has length 0 (473) or 10 (718), no partial values. The 473 missing AENDT are blank end dates."
      },
      {
        "claim": "C. A missing start date gives TRTEMFL='N'; there is no TRTEDT upper bound; missing TRTSDT gives 'N'.",
        "verdict": "correct as description; matches define.xml; no wrong value shown",
        "cite": "checks.R C3: 35 events with TRTEMFL='Y' start after TRTEDT (largest gap 14 days). adam_define.xml TRTEMFL comment: if ASTDT >= TRTSDT then 'Y'. Missing TRTSDT in ADSL: 0 (C6). Whether the rule suits the SAP is not answered by the files."
      },
      {
        "claim": "D. The chained comparison ASTDT>=TRTSDT>.z is valid SAS (not an error).",
        "verdict": "correct",
        "cite": "The R translation in sas-to-r-translation_Rrun reproduced all 53 shared columns exactly, including ASTDY, AENDY and TRTEMFL."
      },
      {
        "claim": "E. Subjects missing from ADSL, duplicate ADSL keys, SAFFL not applied.",
        "verdict": "false alarm for this data",
        "cite": "checks.R C6: ADSL USUBJID unique, 0 AE subjects absent from ADSL, SAFFL = 'Y' for all 1191 rows."
      },
      {
        "claim": "F. Ties on ASTDT mean the first-occurrence record 'may differ between runs'.",
        "verdict": "partly; unproven in SAS",
        "cite": "checks.R C5: the AESEQ tie-break reproduces all 218 AOCCFL records; a reverse tie-break would match only 95. The ties matter, and the program has no explicit AESEQ key. Whether SAS PROC SORT keeps input order within ties (its default EQUALS option) was not run; the verifier found the lowest AESEQ flagged in every tie group (123 any-AE, 229 SOC, 259 PT groups)."
      },
      {
        "claim": "F. Blank AEBODSYS/AEDECOD would drop events from the flags; a PT under two SOCs would get two flags.",
        "verdict": "false alarm for this data",
        "cite": "checks.R C4 and C9: 0 blank values, 0 PTs under more than one SOC."
      },
      {
        "claim": "F. '%if &invar ne %then' with blank parameters (preference 4).",
        "verdict": "unproven (no SAS)",
        "cite": "The xpt flags are consistent with the macro having worked (218 / 550 / 781 first-occurrence records)."
      },
      {
        "claim": "G. USUBJID+AESEQ must be unique for the final merge.",
        "verdict": "latent, holds",
        "cite": "checks.R C9: 0 duplicates in SDTM AE."
      },
      {
        "claim": "H. The retain/keep lists may create all-missing columns if SDTM AE lacks the code variables.",
        "verdict": "right risk, wrong mechanism",
        "cite": "codes_output.txt: AELLTCD, AEPTCD, AEHLTCD, AEHLGTCD, AESOCCD and also AEACN exist in SDTM AE and are blank in all 1191 ADAE rows (CSR p. 21: 'no numeric MedDRA codes are included in the databases'). The model did not list AEACN."
      },
      {
        "claim": "J. index() and = are case-sensitive and may miss mixed-case terms.",
        "verdict": "false alarm for this data",
        "cite": "checks.R C4: 0 lower-case letters in AEDECOD and AEBODSYS."
      },
      {
        "claim": "Preference items 1-11 (keyword case, reuse of dataset name AE, endsas as a bare statement, comment style and others).",
        "verdict": "preference",
        "cite": "Lines cited are right. Not scored as pass/fail; a reasonable programmer can reject any of them. Items 4 and 11 are weak."
      },
      {
        "claim": "Quotes and line numbers across the whole answer.",
        "verdict": "correct",
        "cite": "quotecheck: 44 of 44 non-abbreviated inline fragments are in the file; 8 fragments are the model's own examples or macro expansions (for example AESTDTC='2012-03'); every quote paired with a line number sits on that line."
      },
      {
        "claim": "NOT found by the model: the program creates ADUR (label 'AE Duration (days)', lines 15, 120, 125, 131) but the delivered adam_adae.xpt has ADURN and ADURU instead and no ADUR.",
        "verdict": "missed (needs the dataset; shown by comparison)",
        "cite": "checks.R C1; define.xml ADAE.ADURN comment 'ADURN=AENDT-ASTDT+1'. The values are equal (earlier R run: ADUR equals ADURN in all 1191 rows), so no wrong value; the program as stored does not reproduce the delivered variable names."
      }
    ],
    "errors_found": [
      "Item 7 refers to '(see 11)', which is a different point (internal reference error).",
      "Item H guessed that code variables might be absent from SDTM AE; they are present and empty, and AEACN was missed from the list of blank columns.",
      "Item F says the tie result 'may differ between runs'. The data show the lowest AESEQ is flagged every time, and SAS tie behaviour could not be run, so the sentence is unproven rather than correct.",
      "Item A's worked example (2012-03 against 15MAR2012) does not occur in the data; the risk is real but there is no instance.",
      "Items 3, 8 and 10 are padded or repeat other points; the 'no CQ01 flag' sentence is wrong (AOCC01FL).",
      "Missed: ADUR in the program versus ADURN and ADURU in the delivered dataset; $25 versus Length 19 for CQ01NAM; the 3 preferred terms beyond CSR Table 12-2; 35 events flagged treatment-emergent after TRTEDT (documented in define.xml)."
    ],
    "summary": "Answer key type: Recomputed (the claims about data were recomputed in R 4.6.1 from the real SDTM AE, ADSL and ADAE xpt files; the claims about the file were checked by reading it; there is no hidden answer key). Verified by a separate sub-agent that did not write the review, using its own R checks, plus the builder's saved scripts (checks.R, cq01_vs_csr.R, codes.R, the quote check). 27 rows checked: most statements about the file are correct; the rows with a wrong sentence ('no CQ01 flag', the '(see 11)' reference), a right risk with a wrong detail, 4 false alarms for this data, 1 unproven (macro) and 1 miss are listed one by one; the preference group is not scored. No finding is called a bug: no value produced by the program was shown wrong against its own definition. Three data points were demonstrated: six columns blank in all 1191 rows, 3 preferred terms (5 events) flagged dermatologic that are not in CSR Table 12-2, and a dataset that carries ADURN/ADURU where the program creates ADUR. Real SAS was not run, so every statement about SAS sort stability and macro behaviour is unproven. One model, one run each, not a rate."
  },
  "run": {
    "generated_by": "Claude (Anthropic), Sonnet class model, run as sub-agents on 2026-10-21: a bad run first, then a cold good run, then an independent verifier. The R checks were run by the builder in R 4.6.1 (haven 2.5.5, dplyr 1.2.1, stringr 1.6.0) on 2026-10-21. Real SAS was not run.",
    "not_tested_in": "Microsoft 365 Copilot",
    "contamination_note": "The good run came from a fresh sub-agent given only the numbered program text and the prompt, and told to use no tools and read no files. It was a general-purpose agent with tools available, so non-use is by instruction and could not be enforced; its report matches the supplied text only. The program is a public CDISC file that may exist in the model's training data. The bad run was done first and saved. Author of the answer key work and builder are the same person-agent for the R scripts; the claim-by-claim verdicts come from a separate verifier agent and were reconciled with the scripts. One model, one run each, not a rate."
  },
  "run_summary": [
    {
      "kind": "ok",
      "label": "Quotes held",
      "text": "44 of 44 non-abbreviated quotes were in the file and every quoted line was on the line number cited."
    },
    {
      "kind": "warn",
      "label": "Checked against data",
      "text": "Several of the model's risks (case, blanks, partial end dates, ADSL keys, imputed-month clash) were false alarms or latent in the real data. No finding qualifies as a bug."
    },
    {
      "kind": "fail",
      "label": "Not run in SAS",
      "text": "SAS was not available. Sort-tie order and the blank-parameter macro test are unproven. Three checks found things the model did not: 6 blank columns, 3 extra dermatologic terms, ADUR versus ADURN."
    }
  ]
}