reqtable 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1670 @@
1
+ """Offline traceability model and report controls for opted-in CSVs."""
2
+
3
+ from .glossary import GLOSSARY_COLUMNS, GLOSSARY_MODEL_JS, GLOSSARY_UI_JS
4
+ from .values import VALUE_COLUMNS, VALUE_MODEL_JS
5
+
6
+ TRACE_COLUMNS = (
7
+ "Type",
8
+ "Name",
9
+ "Requirement",
10
+ "Part of",
11
+ "Allocated to",
12
+ "Owner",
13
+ "Derived from",
14
+ "Source refs",
15
+ "Verified by",
16
+ "Test plan",
17
+ "Affects",
18
+ "Change status",
19
+ "Reference",
20
+ "Origin",
21
+ "Rationale",
22
+ *GLOSSARY_COLUMNS,
23
+ *VALUE_COLUMNS,
24
+ )
25
+
26
+ TRACE_MODEL_JS = (
27
+ GLOSSARY_MODEL_JS
28
+ + VALUE_MODEL_JS
29
+ + r"""
30
+ const traceFields={
31
+ "Part of": {from:["System"],to:["System"],single:true},
32
+ "Allocated to": {from:["Requirement"],to:["System"]},
33
+ "Owner": {from:["Requirement"],to:["System"],single:true},
34
+ "Derived from": {from:["Requirement"],to:["Requirement"]},
35
+ "Source refs": {from:["Requirement","Need","Term"],to:["Need","Source"]},
36
+ "Verified by": {from:["Requirement"],to:["Test"]},
37
+ "Test plan": {from:["Test"],to:["Test plan"],single:true},
38
+ "Affects": {from:["Change request"],to:["Requirement","System","Need","Source","Term","Value","Field","Test","Test plan"]}
39
+ };
40
+ function traceType(row){
41
+ const value=String(row.Type??"").trim();
42
+ return value||"Requirement";
43
+ }
44
+ function traceIds(value){
45
+ return String(value??"").split(";").map(id=>id.trim()).filter(Boolean);
46
+ }
47
+ function traceTargetTypes(field,type){
48
+ return field==="Source refs"&&type!=="Requirement"?["Source"]:traceFields[field].to;
49
+ }
50
+ function definedValues(rule,cell){
51
+ const text=String(cell??"").trim();
52
+ return [...new Set((rule.multiple?traceIds(text):text?[text]:[])
53
+ .map(part=>rule.values.has(part)?part:rule.aliases.get(part)?.row.Name.trim()??part))];
54
+ }
55
+ const verificationStates={
56
+ Compliance: {appliesTo:"Requirement",plural:"requirements",states:["Not verified","Compliant","Partially compliant","Non-compliant","Waived"]},
57
+ Result: {appliesTo:"Test",plural:"tests",states:["Not run","Passed","Failed","Blocked"]},
58
+ "Change status": {appliesTo:"Change request",plural:"change requests",states:["Proposed","Approved","Rejected","Implemented"]}
59
+ };
60
+ const approvedChangeStates=["Approved","Implemented"];
61
+ function verificationState(values,column,cell){
62
+ const rule=values.get(column),text=String(cell??"").trim();
63
+ return rule?definedValues(rule,text)[0]??"":text;
64
+ }
65
+ function verificationMethodMarks(rule,cell){
66
+ const present=new Set(definedValues(rule,cell));
67
+ return [...rule.values.keys()].map(name=>({name,letter:name.trim().charAt(0).toUpperCase(),filled:present.has(name)}));
68
+ }
69
+ function buildVerificationMatrix(records,values,idColumn){
70
+ const names=column=>[...(values.get(column)?.values.keys()??[])];
71
+ const methods=names("Verification Method"),levels=names("Verification Level");
72
+ const split=(record,column,known)=>{
73
+ const rule=values.get(column),cell=record.row[column];
74
+ const parts=rule?definedValues(rule,cell):traceIds(cell);
75
+ return [parts.filter(part=>known.includes(part)),parts.filter(part=>!known.includes(part))];
76
+ };
77
+ const totals={methods:Object.fromEntries(methods.map(name=>[name,0])),levels:Object.fromEntries(levels.map(name=>[name,0])),compliance:{}};
78
+ const rows=[...records].map(record=>{
79
+ const [rowMethods,extraMethods]=split(record,"Verification Method",methods);
80
+ const [rowLevels,extraLevels]=split(record,"Verification Level",levels);
81
+ const compliance=verificationState(values,"Compliance",record.row.Compliance);
82
+ const tests=(record.outgoing.get("Verified by")??[]).filter(test=>test.type==="Test")
83
+ .map(test=>({id:test.id,name:test.row.Name?.trim()||test.id,result:verificationState(values,"Result",test.row.Result)}));
84
+ for(const name of rowMethods)totals.methods[name]++;
85
+ for(const name of rowLevels)totals.levels[name]++;
86
+ const key=compliance||"No compliance";
87
+ totals.compliance[key]=(totals.compliance[key]??0)+1;
88
+ return {id:record.id??record.row[idColumn],requirement:record.row.Name?.trim()||record.row.Requirement?.trim()||"",
89
+ methods:rowMethods,levels:rowLevels,tests,compliance,extraMethods,extraLevels};
90
+ });
91
+ return {methods,levels,rows,totals};
92
+ }
93
+ function verificationMatrixMarks(row,kind,names){
94
+ const extra=kind==="methods"?row.extraMethods:row.extraLevels;
95
+ return names.map((name,i)=>[row[kind].includes(name)?"X":"",i===names.length-1?extra.join("; "):""]);
96
+ }
97
+ function verificationMatrixLabels(names){
98
+ const upper=names.map(name=>name.trim().toUpperCase());
99
+ return upper.map(name=>{
100
+ for(let length=1;length<name.length;length++){
101
+ const label=name.slice(0,length);
102
+ if(!label.endsWith(" ")&&upper.every(other=>other===name||!other.startsWith(label)))return label;
103
+ }
104
+ return name;
105
+ });
106
+ }
107
+ function verificationMatrixTest(test){return `${test.id} (${test.result||"No result"})`;}
108
+ function verificationMatrixCsvRows(matrix){
109
+ const marks=(row,kind,names)=>verificationMatrixMarks(row,kind,names).map(parts=>parts.filter(Boolean).join("; "));
110
+ return [["ID","Requirement",...matrix.methods,...matrix.levels,"Tests","Compliance"],
111
+ ...matrix.rows.map(row=>[row.id,row.requirement,...marks(row,"methods",matrix.methods),...marks(row,"levels",matrix.levels),
112
+ row.tests.map(verificationMatrixTest).join("; "),row.compliance])];
113
+ }
114
+ function checkVerification(records,values,issue){
115
+ const state=(record,column)=>verificationState(values,column,record.row[column]);
116
+ const sentence=parts=>parts.length>1?`${parts.slice(0,-1).join(", ")} and ${parts.at(-1)}`:parts[0];
117
+ for(const record of records.values()){
118
+ for(const [column,{appliesTo,plural}] of Object.entries(verificationStates)){
119
+ if(record.type!==appliesTo&&String(record.row[column]??"").trim())issue(record.id,column,`${column} applies to ${plural}.`);
120
+ }
121
+ if(record.type!=="Requirement"||state(record,"Compliance")!=="Compliant")continue;
122
+ const unmet=(record.outgoing.get("Verified by")??[]).map(test=>[test.id,state(test,"Result")]).filter(([,result])=>result!=="Passed");
123
+ if(unmet.length){
124
+ issue(record.id,"Compliance",`Compliant, but ${sentence(unmet.map(([id,result])=>result?`${id} is “${result}”`:`${id} has no result`))}.`);
125
+ }
126
+ }
127
+ }
128
+ function checkTestCoverage(records,values,issue){
129
+ const quote=names=>names.map(name=>`“${name}”`).join(", ");
130
+ for(const record of records.values()){
131
+ const tests=record.outgoing.get("Verified by")??[];
132
+ for(const [field,rule] of tests.length?values:[]){
133
+ const planned=definedValues(rule,record.row[field]);
134
+ const covered=new Set(tests.flatMap(test=>definedValues(rule,test.row[field])));
135
+ const missing=planned.filter(name=>!covered.has(name));
136
+ if(covered.size&&missing.length){
137
+ issue(record.id,field,`No test in Verified by covers ${quote(missing)}. Its tests have ${quote([...covered])}.`);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ function checkChanges(rows,identify,records,values,headers,schema,issue){
143
+ const {baselines,records:controlled}=schema.controls,idColumn=schema.idColumn??"ID";
144
+ const authorised=new Set();
145
+ for(const record of records.values()){
146
+ if(record.type==="Change request"&&approvedChangeStates.includes(verificationState(values,"Change status",record.row["Change status"]))){
147
+ for(const target of traceIds(record.row.Affects))authorised.add(target);
148
+ }
149
+ }
150
+ const scopes=baselines.map(baseline=>baselineScopeIds(rows,idColumn,baseline.system,baseline.includes));
151
+ const text=value=>String(value??"");
152
+ for(const row of rows){
153
+ const id=identify(row);
154
+ if(authorised.has(id))continue;
155
+ if(Object.hasOwn(controlled,id)){
156
+ const {baseline:name,row:old}=controlled[id],baseline=baselines.find(item=>item.name===name);
157
+ const ignored=baseline.capturesStatus?[]:baseline.statusColumns;
158
+ const changed=[...new Set([...headers,...Object.keys(old),...Object.keys(row)])]
159
+ .filter(column=>!ignored.includes(column)&&text(old[column])!==text(row[column]));
160
+ if(changed.length)issue(id,changed[0],`Changed since ${name} (${changed.join(", ")}) without an approved change request.`);
161
+ continue;
162
+ }
163
+ let latest=null;
164
+ baselines.forEach((baseline,position)=>{
165
+ if(scopes[position].has(id)&&(!latest||baseline.created>latest.created))latest=baseline;
166
+ });
167
+ if(latest)issue(id,idColumn,`Added since ${latest.name} without an approved change request.`);
168
+ }
169
+ const present=new Set(rows.map(identify));
170
+ for(const [id,{baseline}] of Object.entries(controlled)){
171
+ if(!present.has(id)&&!authorised.has(id))issue(id,idColumn,`Removed since ${baseline} without an approved change request.`);
172
+ }
173
+ }
174
+ function buildTraceIndex(rows,identify,schema={}){
175
+ const headers=schema.headers??[...new Set(rows.flatMap(row=>Object.keys(row)))];
176
+ const records=new Map(rows.map(row=>{
177
+ const id=identify(row);
178
+ return [id,{id,row,type:traceType(row),outgoing:new Map(),incoming:[]}];
179
+ }));
180
+ const issues=[];
181
+ const issue=(id,field,message)=>issues.push({id,field,message});
182
+ const systems=[];
183
+ for(const record of records.values()){
184
+ const {id,row,type}=record;
185
+ if(id.includes(";"))issue(id,"ID","A traceable ID cannot contain a semicolon.");
186
+ if(type==="System")systems.push(record);
187
+ if(!["System","Requirement","Need","Source","Term","Value","Field","Test","Test plan","Change request"].includes(type))issue(id,"Type",`Unknown record type “${type}”.`);
188
+ if(type==="Requirement"&&row.Origin?.trim()==="Self-derived"&&!row.Rationale?.trim()){
189
+ issue(id,"Rationale","Explain why this self-derived requirement is needed.");
190
+ }
191
+ for(const [field,rule] of Object.entries(traceFields)){
192
+ const ids=traceIds(row[field]);
193
+ if(!ids.length)continue;
194
+ if(!rule.from.includes(type)){
195
+ issue(id,field,`${field} does not apply to ${type} records.`);
196
+ continue;
197
+ }
198
+ if(rule.single&&ids.length>1)issue(id,field,"Select at most one target.");
199
+ const seen=new Set(),targets=[];
200
+ for(const targetId of ids){
201
+ if(seen.has(targetId)){
202
+ issue(id,field,`Duplicate reference to ${targetId}.`);
203
+ continue;
204
+ }
205
+ seen.add(targetId);
206
+ const target=records.get(targetId);
207
+ if(targetId===id)issue(id,field,"A record cannot link to itself.");
208
+ else if(!target){
209
+ if(!(field==="Affects"&&schema.controls&&Object.hasOwn(schema.controls.records,targetId)))issue(id,field,`Target ${targetId} is missing.`);
210
+ }
211
+ else if(!traceTargetTypes(field,type).includes(target.type)){
212
+ issue(id,field,`Target ${targetId} has type ${target.type}. Expected ${traceTargetTypes(field,type).join(" or ")}.`);
213
+ }else{
214
+ targets.push(target);
215
+ if(!rule.single||ids.length===1)target.incoming.push({field,record});
216
+ }
217
+ }
218
+ record.outgoing.set(field,targets);
219
+ }
220
+ }
221
+ const roots=systems.filter(({row})=>!traceIds(row["Part of"]).length);
222
+ if(roots.length!==1)issue(null,"Part of",`Expected one top-level system. Found ${roots.length}.`);
223
+
224
+ for(const field of ["Part of","Derived from"]){
225
+ const done=new Set(),active=new Set();
226
+ for(const start of records.values()){
227
+ if(done.has(start))continue;
228
+ const stack=[{record:start,targets:(start.outgoing.get(field)??[]).values()}];
229
+ active.add(start.id);
230
+ while(stack.length){
231
+ const frame=stack.at(-1),{value:target,done:exhausted}=frame.targets.next();
232
+ if(exhausted){
233
+ active.delete(frame.record.id);
234
+ done.add(frame.record.id);
235
+ stack.pop();
236
+ }else if(active.has(target.id)){
237
+ const cycle=stack.slice(stack.findIndex(item=>item.record===target)).map(item=>item.record.id);
238
+ issue(frame.record.id,field,`Cycle: ${[...cycle,target.id].join(" → ")}.`);
239
+ }else if(!done.has(target.id)){
240
+ active.add(target.id);
241
+ stack.push({record:target,targets:(target.outgoing.get(field)??[]).values()});
242
+ }
243
+ }
244
+ }
245
+ }
246
+ const glossary=buildGlossary(records.values(),issue);
247
+ const values=buildValueRules(records.values(),headers,schema.idColumn,issue);
248
+ checkTestCoverage(records,values,issue);
249
+ checkVerification(records,values,issue);
250
+ if(schema.controls)checkChanges(rows,identify,records,values,headers,schema,issue);
251
+ return {records,systems,roots,issues,glossary,values};
252
+ }
253
+ // The columns buildTraceIndex reads, or null when it reads every column (change controls compare whole rows).
254
+ // An edit confined to other columns leaves the index's links, findings, glossary and value rules as they were.
255
+ function traceIndexColumns(values,idColumn,controlled){
256
+ if(controlled)return null;
257
+ return new Set([idColumn,"Type","Name","Origin","Rationale","Definition","Aliases","Auto Link","Field","Multiple",
258
+ ...Object.keys(traceFields),...Object.keys(verificationStates),...values.keys()]);
259
+ }
260
+ function groupFindingsByCell(issues){
261
+ const cells=new Map();
262
+ for(const finding of issues){
263
+ if(!finding.id)continue;
264
+ const columns=cells.get(finding.id)??new Map();
265
+ columns.set(finding.field,[...(columns.get(finding.field)??[]),finding]);
266
+ cells.set(finding.id,columns);
267
+ }
268
+ return cells;
269
+ }
270
+ function traceCanLink(record,field,target){
271
+ const rule=traceFields[field];
272
+ if(record===target||record.id.includes(";")||target.id.includes(";")||!rule.from.includes(record.type)
273
+ ||!traceTargetTypes(field,record.type).includes(target.type)
274
+ ||traceIds(record.row[field]).includes(target.id))return false;
275
+ if(field!=="Part of"&&field!=="Derived from")return true;
276
+ const seen=new Set(),pending=[target];
277
+ while(pending.length){
278
+ const next=pending.pop();
279
+ if(next===record)return false;
280
+ if(seen.has(next))continue;
281
+ seen.add(next);
282
+ // Inspect all typed references, including a malformed single-parent field.
283
+ pending.push(...(next.outgoing.get(field)??[]));
284
+ }
285
+ return true;
286
+ }
287
+ function traceIncomingChanges(rows,oldId,newId){
288
+ const changes=[];
289
+ for(const row of rows){
290
+ for(const field of Object.keys(traceFields)){
291
+ const value=row[field]??"";
292
+ const parts=value.split(";");
293
+ if(!parts.some(part=>part.trim()===oldId))continue;
294
+ const updated=newId
295
+ ?parts.map(part=>part.trim()===oldId?part.replace(oldId,()=>newId):part)
296
+ :parts.filter(part=>part.trim()!==oldId);
297
+ const first=newId?updated.findIndex(part=>part.trim()===newId):-1;
298
+ const valueAfter=updated.filter((part,i)=>part.trim()!==newId||i===first).join(";").trim();
299
+ changes.push({row,field,value:valueAfter});
300
+ }
301
+ }
302
+ return changes;
303
+ }
304
+ function traceLocationHash(place){
305
+ const params=new URLSearchParams();
306
+ const put=(key,value,fallback)=>{if(value!==fallback)params.set(key,value);};
307
+ put("view",place.view,"requirements");
308
+ if(place.view==="glossary")put("kind",place.kind,"terms");
309
+ put("mode",place.mode??"","");
310
+ put("system",place.system??"","");
311
+ put("unallocated",place.unallocated?"1":"0","0");
312
+ put("descendants",place.descendants===false?"0":"1","1");
313
+ put("record",place.record??"","");
314
+ const text=params.toString();
315
+ return text?"#"+text:"";
316
+ }
317
+ function parseTraceLocation(hash){
318
+ const params=new URLSearchParams(String(hash??"").replace(/^#/,""));
319
+ const text=key=>params.get(key)??"";
320
+ const flag=(key,fallback)=>{const value=params.get(key);return value==="1"?true:value==="0"?false:fallback;};
321
+ return {view:text("view")||"requirements",kind:text("kind")==="values"?"values":"terms",mode:text("mode"),system:text("system"),
322
+ unallocated:flag("unallocated",false),descendants:flag("descendants",true),record:text("record")};
323
+ }
324
+ const workspaceAddActions={requirements:"trace-view-add",sources:"trace-source-actions",tests:"trace-test-actions",
325
+ changes:"trace-change-actions",glossary:{terms:"trace-term-add",values:"trace-value-add"}};
326
+ const workspaceControlIds=["trace-scope","trace-descendants","trace-glossary-kind","trace-view-mode",
327
+ "trace-view-add","trace-term-add","trace-value-add","trace-source-actions","trace-test-actions","trace-change-actions","trace-selected-links"];
328
+ function workspaceControls({view,develop,systemScope,modes,matrix,system,glossaryKind}){
329
+ const shown=[];
330
+ if(systemScope&&view!=="gates")shown.push("trace-scope",...system?["trace-descendants"]:[]);
331
+ if(view==="glossary")shown.push("trace-glossary-kind");
332
+ if(modes)shown.push("trace-view-mode");
333
+ const add=workspaceAddActions[view];
334
+ if(develop&&add)shown.push(typeof add==="string"?add:add[glossaryKind]);
335
+ if(view!=="systems"&&view!=="gates"&&!matrix)shown.push("trace-selected-links");
336
+ return shown;
337
+ }
338
+ """
339
+ )
340
+
341
+ TRACE_UI_JS = (
342
+ GLOSSARY_UI_JS
343
+ + r"""
344
+ const trace=(()=>{
345
+ const panel=$("#trace-panel"),detail=$("#trace-record"),tree=$("#trace-tree");
346
+ const editor=$("#trace-editor"),picker=$("#trace-picker"),deletion=$("#trace-delete");
347
+ const viewBar=$("#trace-views"),systemSelect=$("#trace-system"),status=$("#trace-status");
348
+ const wrap=$(".table-wrap"),systemsPage=$("#trace-systems"),matrixPage=$("#trace-matrix"),modeBar=$("#trace-view-mode");
349
+ const selectedLinks=$("#trace-selected-links"),gatesPage=$("#trace-gates"),gatesList=$("#trace-gates-list"),gatesSystem=$("#trace-gates-system");
350
+ const gates=data.gates??[];
351
+ let gateEvaluations=[];
352
+ const requirementsDefaults=new Set([
353
+ data.meta.idColumn,"Category","Requirement","Priority","Acceptance Criteria","Verification Method"
354
+ ]);
355
+ const sourceColumns=new Set([data.meta.idColumn,"Type","Name","Requirement","Reference"]);
356
+ const sourceLayout={
357
+ defaults:new Map([[data.meta.idColumn,100],["Type",84],["Name",168],["Requirement",240],["Reference",260]]),
358
+ flexible:new Set(["Requirement","Reference"]),
359
+ overrides:new Map(),
360
+ };
361
+ const testTypes=["Test","Test plan"];
362
+ const constrainedByIndex=new WeakMap();
363
+ const constrainedColumns=types=>{
364
+ const current=syncIndex(),cache=constrainedByIndex.get(current)??new Map(),key=types.join("\u0000");
365
+ constrainedByIndex.set(current,cache);
366
+ if(!cache.has(key)){
367
+ const records=[...current.records.values()].filter(record=>types.includes(record.type));
368
+ cache.set(key,[...current.values.keys()].filter(name=>records.some(record=>record.row[name]?.trim())));
369
+ }
370
+ return cache.get(key);
371
+ };
372
+ const testColumnOrder=()=>[data.meta.idColumn,"Type","Name","Test plan",...constrainedColumns(testTypes),"Reference","Requirement"];
373
+ const testLayout={
374
+ defaults:new Map([[data.meta.idColumn,110],["Type",84],["Name",168],["Test plan",110],["Reference",220],["Requirement",260]]),
375
+ flexible:new Set(["Requirement","Reference"]),
376
+ overrides:new Map(),
377
+ };
378
+ const verificationColumns=()=>[data.meta.idColumn,"Requirement","Verification Method","Verification Level","Verified by","Compliance"];
379
+ const verificationLayout={
380
+ defaults:new Map([[data.meta.idColumn,110],["Requirement",280],["Verification Method",120],["Verification Level",120],["Verified by",240],["Compliance",130]]),
381
+ flexible:new Set(["Requirement"]),
382
+ overrides:new Map(),
383
+ };
384
+ const changesColumns=()=>[data.meta.idColumn,"Name","Change status","Affects","Requirement","Reference"];
385
+ const changesLayout={
386
+ defaults:new Map([[data.meta.idColumn,110],["Name",200],["Change status",120],["Affects",200],["Requirement",280],["Reference",220]]),
387
+ flexible:new Set(["Requirement","Reference"]),
388
+ overrides:new Map(),
389
+ };
390
+ const listViews={
391
+ sources:{types:["Need","Source"],columns:sourceColumns,layout:sourceLayout,summary:count=>`${count} needs and sources`},
392
+ tests:{types:testTypes,get columns(){return new Set(testColumnOrder());},layout:testLayout,order:testColumnOrder,summary:count=>`${count} test records`},
393
+ verification:{types:["Requirement"],systemScope:true,get columns(){return new Set(verificationColumns());},order:verificationColumns,
394
+ layout:verificationLayout,summary:count=>`${count} requirements`,modes:{grid:"Grid",matrix:"Matrix"},
395
+ cells:{"Verification Method":methodCell,"Verified by":verifiedByCell},strip:verificationStrip},
396
+ changes:{types:["Change request"],get columns(){return new Set(changesColumns());},layout:changesLayout,order:changesColumns,
397
+ summary:count=>`${count} change ${count===1?"request":"requests"}`},
398
+ gates:{types:[],systemScope:true,columns:new Set([data.meta.idColumn]),summary:()=>`${gates.length} ${gates.length===1?"gate":"gates"}`},
399
+ };
400
+ const glossaryFields=["Definition","Aliases","Auto Link"];
401
+ const traceMetadata=new Set([...Object.keys(traceFields),"Type","Name","Reference","Origin","Field","Multiple","Change status",...glossaryFields]);
402
+ const glossaryKinds={
403
+ terms:{types:["Term"],columns:new Set([data.meta.idColumn,"Name",...glossaryFields]),
404
+ summary:count=>`${count} glossary ${count===1?"term":"terms"}`},
405
+ values:{types:["Value","Field"],
406
+ columns:new Set([data.meta.idColumn,"Type","Field","Name","Definition","Multiple","Aliases","Reference"]),
407
+ summary:count=>`${count} value ${count===1?"record":"records"}`},
408
+ };
409
+ const glossaryPopover=createGlossaryPopover(id=>navigate(id));
410
+ const labels={
411
+ "Part of":["Parent system","Move to…"],
412
+ "Allocated to":["Applies to","Allocate to…"],
413
+ "Owner":["Owner","Set owner…"],
414
+ "Derived from":["Parent requirements","Link parent requirement…"],
415
+ "Source refs":["Needs and sources","Link need or source…"],
416
+ "Verified by":["Verified by","Link test…"],
417
+ "Test plan":["Test plan","Set test plan…"],
418
+ "Affects":["Affects","Link affected record…"],
419
+ };
420
+ const removedSince=id=>data.controls&&Object.hasOwn(data.controls.records,id)?data.controls.records[id].baseline:null;
421
+ let index,indexVersion=null,view="requirements",glossaryKind="terms",system="",unallocated=false,descendants=true;
422
+ const syncIndex=()=>{
423
+ if(indexVersion!==dataVersion){
424
+ index=buildTraceIndex(state.currentRows,rowId,{headers:data.source.new.headers,idColumn:data.meta.idColumn,controls:data.controls});
425
+ indexVersion=dataVersion;
426
+ }
427
+ return index;
428
+ };
429
+ let selected=null,selectedSystem=null,revealed=null,pending=null;
430
+ let scope=new Set(),recordEdit=null,linkEdit=null,deleteEdit=null;
431
+
432
+ const label=record=>record.row.Name?.trim()||record.id;
433
+ const caption=record=>label(record)===record.id?record.id:`${label(record)} (${record.id})`;
434
+ const writable=()=>developMode()&&!state.editingCell;
435
+ const visible=id=>displayIndex(id)>=0;
436
+ const children=record=>record.incoming.filter(edge=>edge.field==="Part of").map(edge=>edge.record);
437
+ const link=(id,text)=>`<button type="button" class="trace-link" data-trace-jump="${escapeHtml(id)}">${escapeHtml(text)}</button>`;
438
+ const focusControl=(container,attribute,value)=>{
439
+ [...container.querySelectorAll(`[${attribute}]`)].find(button=>button.getAttribute(attribute)===value)?.focus();
440
+ };
441
+
442
+ const usesScope=()=>view==="requirements"||!!listViews[view]?.systemScope;
443
+ const viewModes=new Map();
444
+ const viewMode=()=>{const modes=listViews[view]?.modes;return modes?viewModes.get(view)??Object.keys(modes)[0]:"";};
445
+ const matrixShown=()=>viewMode()==="matrix";
446
+ let matrixRecords=[];
447
+ function methodCell(record){
448
+ const rule=index.values.get("Verification Method");
449
+ if(!rule)return null;
450
+ const cell=record.row["Verification Method"]??"";
451
+ const marks=verificationMethodMarks(rule,cell);
452
+ const extra=(rule.multiple?traceIds(cell):[cell.trim()]).filter(part=>part&&!rule.values.has(part)&&!rule.aliases.has(part));
453
+ const listed=[...marks.filter(mark=>mark.filled).map(mark=>mark.name),...extra];
454
+ const slots=marks.map(mark=>`<span class="vcrm-slot${mark.filled?" on":""}" aria-hidden="true">${escapeHtml(mark.letter)}</span>`).join("");
455
+ return `<span class="vcrm-methods" role="img" aria-label="Methods: ${escapeHtml(listed.join(", ")||"none")}">${slots}</span>`
456
+ +extra.map(part=>` <span class="vcrm-extra">${escapeHtml(part)}</span>`).join("");
457
+ }
458
+ function verifiedByCell(record){
459
+ const ids=[...new Set(traceIds(record.row["Verified by"]))];
460
+ if(!ids.length)return null;
461
+ return ids.map(id=>{
462
+ const test=index.records.get(id);
463
+ if(test?.type!=="Test")return `<span class="vcrm-test">${escapeHtml(id)}</span>`;
464
+ const result=verificationState(index.values,"Result",test.row.Result);
465
+ const tone=result?"vcrm-result-"+result.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"vcrm-result-none";
466
+ return `<span class="vcrm-test">${escapeHtml(label(test))} <span class="vcrm-result ${tone}">${escapeHtml(result||"No result")}</span></span>`;
467
+ }).join("");
468
+ }
469
+ function verificationStrip(records){
470
+ const compliance=record=>verificationState(index.values,"Compliance",record.row.Compliance);
471
+ const count=test=>records.filter(test).length;
472
+ const states=data.source.new.headers.includes("Compliance")?verificationStates.Compliance.states:[];
473
+ return [...states.map(name=>[name,count(record=>compliance(record)===name)]),
474
+ ["No compliance",count(record=>!compliance(record))],
475
+ ["No method",count(record=>!record.row["Verification Method"]?.trim())],
476
+ ["No linked tests",count(record=>!(record.outgoing.get("Verified by")??[]).length)]];
477
+ }
478
+ function paintMatrix(){
479
+ const matrix=buildVerificationMatrix(matrixRecords,index.values,data.meta.idColumn);
480
+ const cols=(names,group)=>names.length?`<th scope="colgroup" colspan="${names.length}">${group}</th>`:"";
481
+ const marks=(row,kind,names)=>verificationMatrixMarks(row,kind,names)
482
+ .map(([mark,extra])=>`<td class="vcrm-mark">${mark}${extra?` <span class="vcrm-extra">${escapeHtml(extra)}</span>`:""}</td>`).join("");
483
+ const count=(totals,names)=>names.map(name=>`<td class="vcrm-mark">${totals[name]}</td>`).join("");
484
+ const head=names=>{
485
+ const labels=verificationMatrixLabels(names);
486
+ return names.map((name,i)=>`<th scope="col" class="vcrm-mark"><abbr title="${escapeHtml(name)}">${escapeHtml(labels[i])}</abbr></th>`).join("");
487
+ };
488
+ const legend=(names,group)=>{
489
+ const labels=verificationMatrixLabels(names);
490
+ return names.length?`<span>${group}: ${names.map((name,i)=>`<b>${escapeHtml(labels[i])}</b> ${escapeHtml(name)}`).join(", ")}</span>`:"";
491
+ };
492
+ const scopeText=filters().map(([text])=>text).join(" · ");
493
+ $("#trace-matrix-table").innerHTML=`<caption>${matrix.rows.length} ${matrix.rows.length===1?"requirement":"requirements"}${scopeText?" · "+escapeHtml(scopeText):""}<span class="vcrm-legend">${legend(matrix.methods,"Method")}${legend(matrix.levels,"Level")}</span></caption>
494
+ <thead><tr><th scope="col" rowspan="2">ID</th><th scope="col" rowspan="2">Requirement</th>${cols(matrix.methods,"Method")}${cols(matrix.levels,"Level")}<th scope="col" rowspan="2">Tests</th><th scope="col" rowspan="2">Compliance</th></tr>
495
+ <tr>${head(matrix.methods)}${head(matrix.levels)}</tr></thead>
496
+ <tbody>${matrix.rows.map(row=>`<tr><th scope="row">${escapeHtml(row.id)}</th><td>${escapeHtml(row.requirement)}</td>${marks(row,"methods",matrix.methods)}${marks(row,"levels",matrix.levels)}<td>${row.tests.map(test=>`<span class="vcrm-test"><span class="vcrm-nowrap">${escapeHtml(test.id)}</span> <span class="vcrm-nowrap">(${escapeHtml(test.result||"No result")})</span></span>`).join("")}</td><td>${escapeHtml(row.compliance)}</td></tr>`).join("")}</tbody>
497
+ <tfoot><tr><th scope="row" colspan="2">Totals</th>${count(matrix.totals.methods,matrix.methods)}${count(matrix.totals.levels,matrix.levels)}<td></td><td>${escapeHtml(Object.entries(matrix.totals.compliance).map(([name,total])=>`${name} ${total}`).join(" · "))}</td></tr></tfoot>`;
498
+ }
499
+ function downloadMatrix(){
500
+ const delimiter=data.options.csvDelimiter||",";
501
+ const lines=verificationMatrixCsvRows(buildVerificationMatrix(matrixRecords,index.values,data.meta.idColumn))
502
+ .map(row=>row.map(field=>csvField(field,delimiter)).join(delimiter));
503
+ downloadBlob(new Blob(["\ufeff"+lines.join("\r\n")+"\r\n"],{type:"text/csv;charset=utf-8"}),`${data.meta.baseFilename}-vcrm.csv`);
504
+ }
505
+ function paintStrip(){
506
+ const records=grid.display.map(row=>index.records.get(row.id)).filter(Boolean);
507
+ const box=$("#trace-verification-summary"),items=listViews[view]?.strip?.(records);
508
+ matrixRecords=records;
509
+ if(matrixShown())paintMatrix();
510
+ box.hidden=!items;
511
+ box.replaceChildren(...(items??[]).map(([name,count])=>{
512
+ const item=document.createElement("span");
513
+ item.textContent=`${name} ${count}`;
514
+ return item;
515
+ }));
516
+ }
517
+
518
+ function columnAvailable(name){
519
+ if(view==="requirements")return !traceMetadata.has(name);
520
+ if(listViews[view])return listViews[view].columns.has(name);
521
+ if(view==="glossary")return glossaryKinds[glossaryKind].columns.has(name);
522
+ return true;
523
+ }
524
+ function defaultHidden(){
525
+ const shown=new Set([...requirementsDefaults,...constrainedColumns(["Requirement"])]);
526
+ return new Set(data.columns.filter(({name,hidden})=>name===data.meta.idColumn
527
+ ?view==="glossary":hidden||(view==="requirements"&&!shown.has(name))).map(({name})=>name));
528
+ }
529
+ const viewStates=new Map();
530
+ const collapsed=new Set();
531
+ const stateKey=(name,kind)=>name==="glossary"?`glossary:${kind}`:name;
532
+ const kindOf=id=>glossaryKinds.values.types.includes(index.records.get(id)?.type)?"values":"terms";
533
+ function switchView(next,reveal=null,kind=glossaryKind){
534
+ if(view===next&&(next!=="glossary"||kind===glossaryKind))return false;
535
+ viewStates.set(stateKey(view,glossaryKind),{hidden:state.hidden,filters:state.filters,valueFilters:state.valueFilters,
536
+ sort:state.sort,focus:state.focus,scroll:[wrap.scrollLeft,wrap.scrollTop],
537
+ commentsOnly:state.commentsOnly,idFilter:state.idFilter,qualityOnly:quality.only});
538
+ view=next;
539
+ if(next==="glossary")glossaryKind=kind;
540
+ const saved=viewStates.get(stateKey(next,glossaryKind));
541
+ state.hidden=saved?.hidden??defaultHidden();
542
+ state.filters=saved?.filters??new Map();
543
+ state.valueFilters=saved?.valueFilters??new Map();
544
+ state.sort=saved?.sort??null;
545
+ state.focus=saved?.focus??{row:0,column:0};
546
+ state.commentsOnly=saved?.commentsOnly??false;
547
+ state.idFilter=saved?.idFilter??null;
548
+ quality.only=saved?.qualityOnly??false;
549
+ revealed=reveal;
550
+ pending=null;
551
+ closeValueFilter();
552
+ wrap.hidden=view==="systems";
553
+ render();
554
+ [wrap.scrollLeft,wrap.scrollTop]=saved?.scroll??[0,0];
555
+ return true;
556
+ }
557
+ function canNavigate(){
558
+ if(!state.editingCell){
559
+ status.textContent="";
560
+ return true;
561
+ }
562
+ status.textContent="Apply or cancel the cell edit before changing views or editing links.";
563
+ return false;
564
+ }
565
+ function selectView(next){
566
+ if(view===next||!canNavigate())return;
567
+ close();
568
+ step(()=>switchView(next));
569
+ }
570
+ function matches(row){
571
+ if(view==="all")return true;
572
+ if(view==="systems")return false;
573
+ const record=index.records.get(row.id);
574
+ const type=record?.type||(row.cells.Type?.old?.trim()||"Requirement");
575
+ if(view==="glossary")return glossaryKinds[glossaryKind].types.includes(type);
576
+ if(!(listViews[view]?.types??["Requirement"]).includes(type))return false;
577
+ if(listViews[view]&&!listViews[view].systemScope)return true;
578
+ if(!system&&!unallocated)return true;
579
+ const allocated=record?(record.outgoing.get("Allocated to")??[]).map(target=>target.id)
580
+ :traceIds(row.cells["Allocated to"]?.old);
581
+ return unallocated?!allocated.length:allocated.some(id=>scope.has(id));
582
+ }
583
+ function refresh(){
584
+ glossaryPopover.close();
585
+ syncIndex();
586
+ if(index.records.get(system)?.type!=="System")system="";
587
+ if(revealed&&!index.records.has(revealed)&&!data.rows.some(row=>row.id===revealed))revealed=null;
588
+ scope=new Set();
589
+ const queue=system?[index.records.get(system)]:[];
590
+ for(let i=0;i<queue.length;i++){
591
+ const record=queue[i];
592
+ if(scope.has(record.id))continue;
593
+ scope.add(record.id);
594
+ if(descendants)queue.push(...children(record));
595
+ }
596
+ renderWorkspace();
597
+ if(!panel.hidden)renderIssues();
598
+ }
599
+ function filters(){
600
+ const result=[];
601
+ if(usesScope()){
602
+ if(system)result.push([`System: ${caption(index.records.get(system))}${descendants?" and subsystems":""}`,
603
+ ()=>{system="";}]);
604
+ if(unallocated)result.push(["Unallocated requirements",()=>{unallocated=false;}]);
605
+ }
606
+ if(revealed)result.push([`Revealed record: ${revealed}`,()=>{revealed=null;}]);
607
+ return result;
608
+ }
609
+ function reset(){system="";unallocated=false;revealed=null;pending=null;}
610
+ function systemEntries(respectCollapse=false){
611
+ const visited=new Set(),entries=[];
612
+ const starts=[...index.roots,...index.systems.filter(record=>!record.outgoing.get("Part of")?.length),...index.systems];
613
+ for(const root of starts){
614
+ const stack=[[root,0]];
615
+ while(stack.length){
616
+ const [record,depth]=stack.pop();
617
+ if(visited.has(record.id))continue;
618
+ visited.add(record.id);
619
+ entries.push([record,depth]);
620
+ for(const child of children(record).reverse())stack.push([child,depth+1]);
621
+ }
622
+ }
623
+ if(!respectCollapse)return entries;
624
+ let collapsedDepth=Infinity;
625
+ return entries.filter(([record,depth])=>{
626
+ if(depth>collapsedDepth)return false;
627
+ collapsedDepth=collapsed.has(record.id)?depth:Infinity;
628
+ return true;
629
+ });
630
+ }
631
+ function renderWorkspace(){
632
+ for(const button of viewBar.querySelectorAll("[data-trace-view]")){
633
+ button.setAttribute("aria-pressed",String(button.dataset.traceView===view));
634
+ }
635
+ const inSystems=view==="systems",inGates=view==="gates",inPage=inSystems||inGates;
636
+ const inMatrix=matrixShown();
637
+ wrap.hidden=inPage||inMatrix;
638
+ systemsPage.hidden=!inSystems;
639
+ gatesPage.hidden=!inGates;
640
+ matrixPage.hidden=!inMatrix;
641
+ for(const button of modeBar.querySelectorAll("[data-view-mode]")){
642
+ button.setAttribute("aria-pressed",String(button.dataset.viewMode===viewMode()));
643
+ }
644
+ $("#columns-menu").hidden=inPage||inMatrix;
645
+ $("#filter-menu").hidden=inPage;
646
+ const shown=workspaceControls({view,develop:developMode(),systemScope:usesScope(),modes:!!listViews[view]?.modes,
647
+ matrix:inMatrix,system,glossaryKind});
648
+ for(const id of workspaceControlIds){
649
+ const control=$("#"+id);
650
+ (id==="trace-descendants"?control.closest("label"):control).hidden=!shown.includes(id);
651
+ }
652
+ $("#trace-controls").hidden=!shown.length;
653
+ for(const button of $("#trace-glossary-kind").querySelectorAll("[data-glossary-kind]")){
654
+ button.setAttribute("aria-pressed",String(button.dataset.glossaryKind===glossaryKind));
655
+ }
656
+ $("#trace-system-add").hidden=!developMode()||!!index.systems.length;
657
+ if(usesScope()){
658
+ const options=inGates?[new Option("No system chosen","all")]:[new Option("All requirements","all"),new Option("Unallocated requirements","unallocated")];
659
+ for(const [record,depth] of systemEntries())options.push(new Option("  ".repeat(Math.min(depth,8))+caption(record),"system:"+record.id));
660
+ const value=unallocated&&!inGates?"unallocated":system?"system:"+system:"all";
661
+ for(const select of [systemSelect,gatesSystem]){
662
+ select.replaceChildren(...options.map(option=>option.cloneNode(true)));
663
+ select.value=value;
664
+ }
665
+ $("#trace-descendants").checked=descendants;
666
+ }
667
+ if(inSystems)renderTree();
668
+ if(inGates)renderGates();
669
+ }
670
+ function renderGates(){
671
+ const headers=data.source.new.headers;
672
+ gateEvaluations=gates.map(gate=>gate.scope==="system"&&!system?null
673
+ :gate.checks.map(check=>evaluateGateCheck(check,state.currentRows,data.meta.idColumn,headers,gate.scope==="system"?system:null,index.issues,data.controls??null)));
674
+ gatesList.innerHTML=gates.length?gates.map((gate,gateIndex)=>{
675
+ const results=gateEvaluations[gateIndex];
676
+ const badge=results?(({tone,mark})=>`<span class="gate-badge ${tone}">${mark}</span>`)(gateBadgeLabel(results)):"";
677
+ const scopeText=gate.scope==="system"&&system?` · Scope: ${escapeHtml(caption(index.records.get(system)))}`:"";
678
+ const body=results?`<ul class="gate-checks">${results.map((result,checkIndex)=>gateCheckItem(result,gateIndex,checkIndex)).join("")}</ul>`
679
+ :'<p class="meta">Choose a system in the System selector to check this gate.</p>';
680
+ return `<section class="gate" data-gate="${escapeHtml(gate.id)}" aria-labelledby="gate-title-${gateIndex}">
681
+ <header><h2 id="gate-title-${gateIndex}">${escapeHtml(gate.name||gate.id)} <span class="meta">(${escapeHtml(gate.id)})</span></h2>${badge}</header>
682
+ <p class="meta">Produces: ${escapeHtml(gate.produces||"nothing recorded")}${scopeText}</p>${body}</section>`;
683
+ }).join(""):"<p>No gates are configured.</p>";
684
+ }
685
+ function gateCheckItem(result,gateIndex,checkIndex){
686
+ const {tone,mark}=gateCheckLabel(result);
687
+ const records=result.error?[]:result.failing.filter(Boolean);
688
+ const count=result.error?escapeHtml(result.error):`${result.failing.length} of ${result.total} failing`;
689
+ const show=records.length?` <button type="button" data-gate-show="${gateIndex}:${checkIndex}">Show records</button>`:"";
690
+ const table=result.global?.length?`<ul class="gate-table-findings"><li><strong>Table-level findings</strong> (${result.global.length}): ${result.global.map(escapeHtml).join(" ")}</li></ul>`:"";
691
+ return `<li data-check="${escapeHtml(result.id)}"><span class="gate-mark ${tone}">${mark}</span> ${escapeHtml(result.description||result.id)} <span class="meta">${count}</span>${show}${table}</li>`;
692
+ }
693
+ function gateDestination(ids){
694
+ const views=new Set(ids.map(id=>{
695
+ const type=index.records.get(id)?.type;
696
+ return type==="Requirement"?"requirements":viewForType(type);
697
+ }));
698
+ const [only]=views;
699
+ return views.size===1&&["requirements","tests","sources"].includes(only)?only:"all";
700
+ }
701
+ function showGateRecords(gate,check){
702
+ const result={...check,failing:check.failing.filter(Boolean)};
703
+ if(!canNavigate())return;
704
+ close();
705
+ step(()=>{
706
+ if(gate.scope==="system")descendants=true;
707
+ else{system="";unallocated=false;}
708
+ revealed=null;
709
+ switchView(gateDestination(result.failing));
710
+ showIdFilter(`Gate check ${result.id}: ${result.failing.length} ${result.failing.length===1?"record":"records"}`,result.failing);
711
+ render();
712
+ });
713
+ }
714
+ function renderTree(){
715
+ const entries=systemEntries(true);
716
+ if(!entries.some(([record])=>record.id===selectedSystem))selectedSystem=entries[0]?.[0].id??null;
717
+ tree.innerHTML=entries.length?entries.map(([record,depth])=>{
718
+ const count=record.incoming.filter(edge=>edge.field==="Allocated to").length;
719
+ const expanded=!collapsed.has(record.id);
720
+ const toggle=children(record).length?`<button type="button" data-trace-collapse="${escapeHtml(record.id)}"
721
+ aria-label="${expanded?"Collapse":"Expand"} ${escapeHtml(label(record))}" aria-expanded="${expanded}">${expanded?"▾":"▸"}</button>`:'<span class="trace-tree-leaf"></span>';
722
+ return `<li style="--trace-depth:${Math.min(depth,8)}">
723
+ <div class="trace-tree-node">
724
+ ${toggle}
725
+ <button type="button" data-trace-system="${escapeHtml(record.id)}" aria-pressed="${selectedSystem===record.id}">${escapeHtml(caption(record))}</button>
726
+ </div>
727
+ <span class="meta">${count} allocated</span></li>`;
728
+ }).join(""):"<li>No systems yet.</li>";
729
+ const record=index.records.get(selectedSystem),actions=$("#trace-system-actions");
730
+ actions.hidden=!record;
731
+ $("#trace-system-name").textContent=record?caption(record):"";
732
+ const parent=record?.outgoing.get("Part of")?.[0];
733
+ $("#trace-system-parent").textContent=record?(parent?`Parent system: ${caption(parent)}`:"Top-level system"):"";
734
+ $("#trace-system-edit").hidden=!developMode();
735
+ }
736
+ function renderIssues(){
737
+ $("#trace-findings").querySelector("summary").textContent=`Trace findings (${index.issues.length})`;
738
+ $("#trace-issues").innerHTML=index.issues.length?index.issues.map(({id,field,message})=>
739
+ `<li data-finding-id="${escapeHtml(id??"")}" data-finding-field="${escapeHtml(field)}">${id?(index.records.has(id)?link(id,id):escapeHtml(id))+" · ":""}<strong>${escapeHtml(field)}</strong><br>${escapeHtml(message)}</li>`
740
+ ).join(""):"<li>No trace findings.</li>";
741
+ }
742
+ function showFindings(id,column){
743
+ openPanel(id);
744
+ $("#trace-findings").open=true;
745
+ let first=null;
746
+ for(const item of $("#trace-issues").children){
747
+ const match=item.dataset.findingId===id&&item.dataset.findingField===column;
748
+ item.classList.toggle("trace-finding-active",match);
749
+ first??=match?item:null;
750
+ }
751
+ first?.scrollIntoView({block:"nearest"});
752
+ }
753
+ function paintMarkers(rows){
754
+ const cells=groupFindingsByCell(index.issues);
755
+ for(const row of rows){
756
+ const columns=cells.get(row.dataset.rowId);
757
+ if(!columns)continue;
758
+ for(const cell of row.querySelectorAll("[data-grid-cell]")){
759
+ const column=cell.dataset.column,issues=columns.get(column);
760
+ const wrapper=cell.querySelector(".cell-wrap");
761
+ if(!issues||!wrapper||wrapper.querySelector(".trace-marker"))continue;
762
+ const id=row.dataset.rowId;
763
+ const label=`${issues.length} trace ${issues.length===1?"finding":"findings"} for ${id}, ${column}`;
764
+ wrapper.append(findingMarker("trace-marker","⚑",label,marker=>findingPopover.open(marker,{
765
+ heading:`${id} · ${columnLabel(column)}`,
766
+ findings:issues.map(issue=>({detail:issue.message})),
767
+ actions:[{label:"Show in Links",run:()=>showFindings(id,column)}]
768
+ })));
769
+ }
770
+ }
771
+ }
772
+ function renderDetail(){
773
+ if(panel.hidden)return;
774
+ const record=index.records.get(selected);
775
+ const reveal=pending?`<div class="trace-reveal">${escapeHtml(pending)} is outside the current filters.
776
+ <button type="button" id="trace-reveal">Reveal in grid</button></div>`:"";
777
+ paintBack();
778
+ if(!record){
779
+ detail.innerHTML=reveal+"<p>Select a current record to see its links.</p>";
780
+ return;
781
+ }
782
+ const {id,row,type}=record;
783
+ const incomingLabels={"Part of":"Subsystems","Allocated to":"Allocated requirements","Owner":"Owned requirements",
784
+ "Derived from":"Child requirements","Source refs":"Referenced by","Verified by":"Verifies","Test plan":"Tests","Affects":"Change requests"};
785
+ const sections=[];
786
+ for(const [field,rule] of Object.entries(traceFields)){
787
+ const ids=[...new Set(traceIds(row[field]))];
788
+ if(!rule.from.includes(type)&&!ids.length)continue;
789
+ const [heading,action]=field==="Source refs"&&type==="Term"?["Sources","Link source…"]:labels[field];
790
+ const targets=ids.map(targetId=>{
791
+ const target=index.records.get(targetId);
792
+ const remove=writable()? ` <button type="button" class="trace-remove" data-trace-remove="${escapeHtml(field)}"
793
+ data-trace-target="${escapeHtml(targetId)}" aria-label="Remove ${escapeHtml(heading)} link to ${escapeHtml(targetId)}">×</button>`:"";
794
+ const gone=removedSince(targetId);
795
+ return `<li>${target?link(targetId,caption(target)):escapeHtml(targetId)+(gone?` (removed since ${escapeHtml(gone)})`:" (missing)")}${remove}</li>`;
796
+ });
797
+ const edit=writable()&&rule.from.includes(type)?` <button type="button" data-trace-pick="${escapeHtml(field)}">${action}</button>`:"";
798
+ sections.push(`<section><h4>${heading}</h4>${targets.length?`<ul>${targets.join("")}</ul>`:'<p class="meta">None</p>'}${edit}</section>`);
799
+ }
800
+ for(const [field,heading] of Object.entries(incomingLabels)){
801
+ const links=record.incoming.filter(edge=>edge.field===field);
802
+ const addChild=field==="Derived from"&&type==="Requirement"&&writable()
803
+ ?'<button type="button" id="trace-add-child">Add child requirement…</button>':"";
804
+ if(links.length||addChild||(field==="Derived from"&&type==="Requirement")){
805
+ const list=links.length?`<ul>${links.map(({record:source})=>`<li>${link(source.id,caption(source))}</li>`).join("")}</ul>`:'<p class="meta">None</p>';
806
+ sections.push(`<section><h4>${heading}</h4>${list}${addChild}</section>`);
807
+ }
808
+ }
809
+ const origin=row.Origin?.trim()||(traceIds(row["Source refs"]).length||traceIds(row["Derived from"]).length?"":"No origin recorded");
810
+ const notes=[row.Requirement,row.Definition,row.Reference,type==="Requirement"?origin:"",row.Rationale].filter(Boolean);
811
+ detail.innerHTML=reveal+`<h3 tabindex="-1">${escapeHtml(caption(record))}</h3><p class="meta">${escapeHtml(type)}</p>`
812
+ +notes.map(note=>`<p class="trace-note">${escapeHtml(note)}</p>`).join("")+sections.join("");
813
+ }
814
+ function syncSelection(id,force=false){
815
+ if(view==="systems")id=selectedSystem;
816
+ if(id===selected&&!force)return;
817
+ selected=id;
818
+ if(ready&&!guard&&!force&&id&&id!==recordId){recordId=id;writeHistory(false);}
819
+ selectedLinks.disabled=!index.records.has(id);
820
+ selectedLinks.title=selectedLinks.disabled?"Select a current record to see its links":`Links and trace findings for ${id}`;
821
+ selectedLinks.setAttribute("aria-label",selectedLinks.disabled?"Links and trace findings":`Links and trace findings for ${id}`);
822
+ pending=null;
823
+ renderDetail();
824
+ }
825
+ function viewForType(type){
826
+ if(type==="System")return "systems";
827
+ if(type==="Term"||type==="Value"||type==="Field")return "glossary";
828
+ if(type==="Requirement")return listViews[view]?.systemScope?view:"requirements";
829
+ return Object.keys(listViews).find(name=>listViews[name].types.includes(type))??"all";
830
+ }
831
+ const recordView=id=>viewForType(index.records.get(id)?.type);
832
+ const linksTarget=()=>view==="systems"?selectedSystem:view==="gates"||matrixShown()?null:selectedRequirementId();
833
+ function openPanel(id){
834
+ closeReview();
835
+ closeQuality();
836
+ panel.hidden=false;
837
+ $("#open-trace").setAttribute("aria-expanded","true");
838
+ selectedLinks.setAttribute("aria-expanded","true");
839
+ renderIssues();
840
+ syncSelection(id,true);
841
+ renderLayout();
842
+ (detail.querySelector("h3")??$("#trace-title")).focus({preventScroll:true});
843
+ }
844
+ function close(){
845
+ if(panel.hidden)return;
846
+ panel.hidden=true;
847
+ $("#open-trace").setAttribute("aria-expanded","false");
848
+ selectedLinks.setAttribute("aria-expanded","false");
849
+ renderLayout();
850
+ }
851
+ function focusRecord(id){
852
+ if(view==="systems"){
853
+ const seen=new Set([id]);
854
+ let parent=index.records.get(id)?.outgoing.get("Part of")?.[0];
855
+ while(parent&&!seen.has(parent.id)){
856
+ seen.add(parent.id);
857
+ collapsed.delete(parent.id);
858
+ parent=parent.outgoing.get("Part of")?.[0];
859
+ }
860
+ selectedSystem=id;
861
+ renderTree();
862
+ }else focusRequirement(id,data.meta.idColumn);
863
+ syncSelection(id,true);
864
+ (detail.querySelector("h3")??$("#trace-title")).focus({preventScroll:true});
865
+ }
866
+ function navigate(id){
867
+ if(!canNavigate())return;
868
+ const destination=recordView(id);
869
+ if(destination===view&&!visible(id)&&view!=="systems"){
870
+ pending=id;
871
+ renderDetail();
872
+ $("#trace-reveal").focus();
873
+ return;
874
+ }
875
+ step(()=>{
876
+ switchView(destination,null,kindOf(id));
877
+ if(view!=="systems"&&!visible(id)){revealed=id;render();}
878
+ focusRecord(id);
879
+ },id);
880
+ }
881
+ const historyOn=window.top===window&&!!history.pushState;
882
+ let guard=false,ready=false,histIndex=0,histHash="",recordId="";
883
+ const paintBack=()=>{$("#trace-back").hidden=!(histIndex>0);};
884
+ function place(){
885
+ const modes=listViews[view]?.modes,mode=viewMode();
886
+ return {view,kind:glossaryKind,mode:modes&&mode!==Object.keys(modes)[0]?mode:"",system,unallocated,descendants,record:recordId};
887
+ }
888
+ function writeHistory(push){
889
+ if(!ready)return;
890
+ const hash=traceLocationHash(place());
891
+ if(hash===histHash)return;
892
+ const next=histIndex+(push?1:0);
893
+ try{history[push?"pushState":"replaceState"]({reqtable:true,index:next,place:place()},"",hash||location.href.split("#")[0]);}
894
+ catch{return;}
895
+ histIndex=next;
896
+ histHash=hash;
897
+ paintBack();
898
+ }
899
+ function step(change,id=""){
900
+ guard=true;
901
+ try{change();}finally{guard=false;}
902
+ recordId=id;
903
+ writeHistory(true);
904
+ }
905
+ function applyPlace(target){
906
+ guard=true;
907
+ try{
908
+ const views=[...viewBar.querySelectorAll("[data-trace-view]")].map(button=>button.dataset.traceView);
909
+ const next=views.includes(target.view)?target.view:"requirements";
910
+ system=index.records.get(target.system)?.type==="System"?target.system:"";
911
+ unallocated=!system&&target.unallocated;
912
+ descendants=target.descendants;
913
+ const modes=listViews[next]?.modes;
914
+ if(modes)viewModes.set(next,target.mode in modes?target.mode:Object.keys(modes)[0]);
915
+ if(!switchView(next,null,target.kind))render();
916
+ recordId=index.records.has(target.record)?target.record:"";
917
+ if(recordId){
918
+ if(view!=="systems"&&!visible(recordId)){revealed=recordId;render();}
919
+ focusRecord(recordId);
920
+ }
921
+ }finally{guard=false;}
922
+ }
923
+ function goBack(){
924
+ if(canNavigate())history.back();
925
+ }
926
+ function restoreHistory(){
927
+ if(!historyOn)return;
928
+ const target=parseTraceLocation(location.hash);
929
+ if(traceLocationHash(target))applyPlace(target);
930
+ histIndex=history.state?.reqtable===true?history.state.index:0;
931
+ ready=true;
932
+ histHash="\0";
933
+ writeHistory(false);
934
+ }
935
+ function popHistory(event){
936
+ if(!ready)return;
937
+ const ours=event.state?.reqtable===true,known=ours?event.state.index:histIndex;
938
+ if(!canNavigate()){
939
+ history.pushState({reqtable:true,index:known+1,place:place()},"",traceLocationHash(place())||location.href.split("#")[0]);
940
+ histIndex=known+1;
941
+ paintBack();
942
+ return;
943
+ }
944
+ applyPlace(ours?event.state.place:parseTraceLocation(location.hash));
945
+ histIndex=ours?known:known+1;
946
+ histHash="\0";
947
+ writeHistory(false);
948
+ }
949
+ function restoreGridSelection(id,column){
950
+ const row=id?displayIndex(id):-1;
951
+ state.focus.row=row>=0&&visibleColumns().some(item=>item.name===column)?row:0;
952
+ setRovingFocus();
953
+ }
954
+ function changeScope(id,onlyUnallocated=false){
955
+ const current=selectedRequirementId(),column=visibleColumns()[state.focus.column]?.name;
956
+ step(()=>{
957
+ system=id;
958
+ unallocated=onlyUnallocated;
959
+ revealed=null;
960
+ if(!switchView(usesScope()?view:"requirements"))render();
961
+ });
962
+ restoreGridSelection(current,column);
963
+ }
964
+ function updateLink(record,field,value){
965
+ if(!writable()||!record||record.row[field]===value)return;
966
+ remember();
967
+ record.row[field]=value;
968
+ updateDirty();
969
+ render();
970
+ if(view==="systems")focusRecord(record.id);
971
+ else syncSelection(record.id,true);
972
+ if(!panel.hidden)focusControl(detail,"data-trace-pick",field);
973
+ else if(view==="systems")focusControl(tree,"data-trace-system",record.id);
974
+ }
975
+ function showCandidates(){
976
+ const {id,field,checked}=linkEdit,record=index.records.get(id);
977
+ const query=$("#trace-query").value.trim().toLocaleLowerCase();
978
+ const matches=text=>text.toLocaleLowerCase().includes(query);
979
+ const detailOf=target=>String(target.row.Requirement||target.row.Definition||"").replace(/\s+/g," ").trim();
980
+ const targets=[...index.records.values()].filter(target=>(matches(caption(target))||matches(detailOf(target)))
981
+ &&(checked?.has(target.id)||traceCanLink(record,field,target)));
982
+ const names=new Map(targets.map(target=>[target.id,caption(target)]));
983
+ const details=new Map(targets.map(target=>[target.id,detailOf(target)]));
984
+ const body=(id,name)=>{
985
+ const detail=details.get(id)??"";
986
+ return `<span class="trace-candidate-name">${escapeHtml(name)}</span>`
987
+ +(detail?`<span class="trace-candidate-detail" title="${escapeHtml(detail)}">${escapeHtml(detail)}</span>`:"");
988
+ };
989
+ if(field==="Affects"){
990
+ for(const removedId of Object.keys(data.controls?.records??{})){
991
+ const label=`${removedId} (removed since ${removedSince(removedId)})`;
992
+ if(!index.records.has(removedId)&&!traceIds(record.row.Affects).includes(removedId)&&matches(label))names.set(removedId,label);
993
+ }
994
+ }
995
+ if(checked){
996
+ for(const id of checked){
997
+ const target=index.records.get(id);
998
+ if(!target&&matches(id))names.set(id,`${id} (missing)`);
999
+ }
1000
+ }
1001
+ $("#trace-candidates").innerHTML=names.size?[...names].map(([id,name])=>checked
1002
+ ?`<li><label><input type="checkbox" data-trace-target="${escapeHtml(id)}" ${checked.has(id)?"checked":""}> ${body(id,name)}</label></li>`
1003
+ :`<li><button type="button" data-trace-target="${escapeHtml(id)}">${body(id,name)}</button></li>`
1004
+ ).join(""):"<li>No eligible targets match.</li>";
1005
+ }
1006
+ function editLink(field,id=selected){
1007
+ if(!writable()||!index.records.has(id))return;
1008
+ const checked=field==="Allocated to"?new Set(traceIds(index.records.get(id).row[field])):null;
1009
+ linkEdit={id,field,checked};
1010
+ $("#trace-picker-title").textContent=field==="Source refs"&&index.records.get(id).type==="Term"
1011
+ ?"Link source":labels[field][1].replace("…","");
1012
+ $("#trace-query").value="";
1013
+ $("#trace-picker-apply").hidden=!checked;
1014
+ showCandidates();
1015
+ picker.showModal();
1016
+ $("#trace-query").focus();
1017
+ }
1018
+ function editRecord(type,{record=null,parent=null}={}){
1019
+ if(!writable())return;
1020
+ recordEdit={type,record,parent};
1021
+ $("#trace-editor-title").textContent=record?"Rename system":parent?(type==="System"?"Add subsystem":"Add child requirement"):`Add ${type.toLowerCase()}`;
1022
+ const idInput=$("#trace-record-id");
1023
+ const generatedId=type==="Term"||type==="Value";
1024
+ $("#trace-record-id-field").hidden=idInput.disabled=generatedId;
1025
+ $("#trace-value-field-label").hidden=type!=="Value";
1026
+ $("#trace-value-aliases-label").hidden=type!=="Value";
1027
+ $("#trace-value-aliases").value="";
1028
+ if(type==="Value")fillValueFields();
1029
+ idInput.value=record?.id??(type==="Requirement"?nextRecordId():"");
1030
+ idInput.readOnly=!!record;
1031
+ $("#trace-record-name").value=record?.row.Name??"";
1032
+ $("#trace-record-name").required=type!=="Requirement";
1033
+ $("#trace-record-name-field").hidden=type==="Requirement";
1034
+ $("#trace-record-content").value="";
1035
+ $("#trace-record-content").required=type==="Requirement"||type==="Term"||type==="Value";
1036
+ $("#trace-test-plan-label").hidden=type!=="Test";
1037
+ if(type==="Test")optionList($("#trace-test-plan"),[...index.records.values()].filter(({type})=>type==="Test plan"),"No test plan");
1038
+ $("#trace-record-content-field").hidden=type==="System";
1039
+ $("#trace-record-content-label").textContent=type==="Term"||type==="Value"?"Definition":type==="Source"?"Citation":type==="Need"?"Need statement":type==="Test"||type==="Test plan"||type==="Change request"?"Description":"Requirement statement";
1040
+ $("#trace-term-options").hidden=type!=="Term";
1041
+ $("#trace-term-aliases").value="";
1042
+ $("#trace-term-single-word").checked=false;
1043
+ editor.showModal();
1044
+ if(type==="Value")$("#trace-value-field").focus();
1045
+ else if(!$("#trace-record-id").disabled&&!$("#trace-record-id-field").hidden)$("#trace-record-id").focus();
1046
+ else $("#trace-record-name").focus();
1047
+ }
1048
+ function fillValueFields(){
1049
+ const names=valueFieldNames(data.source.new.headers,data.meta.idColumn);
1050
+ const open=data.source.new.headers.filter(name=>!traceMetadata.has(name)&&!valueColumnProblem(name,names));
1051
+ const defined=open.filter(name=>index.values.has(name));
1052
+ $("#trace-value-field").replaceChildren(...[...defined,...open.filter(name=>!index.values.has(name))]
1053
+ .map(name=>new Option(name,name)));
1054
+ }
1055
+ function takenIds(){
1056
+ return new Set([...state.currentRows,...state.savedRows,...(data.source.old?.rows??[])].map(rowId));
1057
+ }
1058
+ function optionList(select,choices,empty){
1059
+ select.replaceChildren(new Option(empty,""),...choices.map(record=>new Option(caption(record),record.id)));
1060
+ }
1061
+ function openDeletion(id){
1062
+ if(!writable())return;
1063
+ const record=index.records.get(id);
1064
+ if(record?.type!=="System")return;
1065
+ const changes=traceIncomingChanges(state.currentRows,id,null).filter(change=>change.row!==record.row);
1066
+ const fields=["Part of","Allocated to","Owner"];
1067
+ deleteEdit={id,changes};
1068
+ $("#trace-delete-title").textContent=`Delete system ${caption(record)}?`;
1069
+ const comments=state.comments.filter(comment=>comment.requirementId===id).length;
1070
+ $("#trace-delete-impact").textContent=`This affects ${changes.length} incoming links and deletes ${comments} attached comments.`;
1071
+ let described=0;
1072
+ for(const [i,field] of fields.entries()){
1073
+ const group=$("#trace-delete-group-"+i),select=group.querySelector("select");
1074
+ const related=changes.filter(change=>change.field===field&&traceFields[field].from.includes(traceType(change.row)));
1075
+ described+=related.length;
1076
+ const eligible=index.systems.filter(target=>target!==record&&(
1077
+ field!=="Part of"||related.every(change=>traceCanLink(index.records.get(rowId(change.row)),field,target))));
1078
+ group.hidden=!related.length;
1079
+ group.querySelector("span").textContent=`${related.length} ${["direct subsystems","requirement allocations","requirement owners"][i]}`;
1080
+ optionList(select,eligible,["Make top-level","Remove this allocation","Clear owner"][i]);
1081
+ if(field==="Part of"){
1082
+ const parent=record.outgoing.get(field)?.[0];
1083
+ if(eligible.includes(parent))select.value=parent.id;
1084
+ }
1085
+ }
1086
+ $("#trace-delete-other").textContent=described<changes.length?"Other invalid references to this system will also be cleared.":"";
1087
+ deletion.showModal();
1088
+ }
1089
+ function clearCopy(clone){
1090
+ clone.querySelector("#glossary-definition").hidden=true;
1091
+ for(const id of ["glossary-definition-title","glossary-definition-content","glossary-definition-sources"]){
1092
+ clone.querySelector("#"+id).replaceChildren();
1093
+ }
1094
+ clone.querySelector("#trace-panel").hidden=true;
1095
+ clone.querySelector("#trace-back").hidden=true;
1096
+ clone.querySelector(".table-wrap").hidden=false;
1097
+ clone.querySelector("#trace-systems").hidden=true;
1098
+ clone.querySelector("#trace-gates").hidden=true;
1099
+ clone.querySelector("#trace-gates").replaceChildren();
1100
+ clone.querySelector("#trace-matrix").hidden=true;
1101
+ clone.querySelector("#trace-matrix-table").replaceChildren();
1102
+ clone.querySelector("#open-trace").setAttribute("aria-expanded","false");
1103
+ clone.querySelector("#trace-selected-links").setAttribute("aria-expanded","false");
1104
+ for(const id of ["trace-tree","trace-record","trace-issues","trace-candidates","trace-status","trace-system",
1105
+ "trace-system-name","trace-system-parent","trace-verification-summary","trace-delete-impact","trace-delete-other"]){
1106
+ clone.querySelector("#"+id).replaceChildren();
1107
+ }
1108
+ clone.querySelector("#trace-delete-title").textContent="Delete system?";
1109
+ clone.querySelectorAll("#trace-delete-form select").forEach(select=>select.replaceChildren());
1110
+ for(const id of ["trace-editor","trace-picker","trace-delete","trace-findings"]){
1111
+ clone.querySelector("#"+id).removeAttribute("open");
1112
+ }
1113
+ }
1114
+
1115
+ if(!gates.length)viewBar.querySelector('[data-trace-view="gates"]').remove();
1116
+ gatesPage.addEventListener("click",event=>{
1117
+ const [gateIndex,checkIndex]=(event.target.closest("[data-gate-show]")?.dataset.gateShow??"").split(":").map(Number);
1118
+ if(gateIndex>=0)showGateRecords(gates[gateIndex],gateEvaluations[gateIndex][checkIndex]);
1119
+ });
1120
+ syncIndex();
1121
+ if(!data.controls&&!data.source.new.headers.some(name=>name==="Change status"||name==="Affects")
1122
+ &&![...index.records.values()].some(record=>record.type==="Change request")){
1123
+ viewBar.querySelector('[data-trace-view="changes"]').remove();
1124
+ }
1125
+ state.hidden=defaultHidden();
1126
+ wrap.hidden=false;
1127
+ viewBar.addEventListener("click",event=>{
1128
+ const button=event.target.closest("[data-trace-view]");
1129
+ if(button)selectView(button.dataset.traceView);
1130
+ });
1131
+ for(const select of [systemSelect,gatesSystem]){
1132
+ select.addEventListener("change",()=>{
1133
+ if(!canNavigate()){renderWorkspace();return;}
1134
+ const value=select.value;
1135
+ changeScope(value.startsWith("system:")?value.slice(7):"",value==="unallocated");
1136
+ });
1137
+ }
1138
+ $("#trace-descendants").addEventListener("change",event=>{
1139
+ if(!canNavigate()){event.target.checked=descendants;return;}
1140
+ descendants=event.target.checked;
1141
+ changeScope(system);
1142
+ });
1143
+ $("#trace-view-add").addEventListener("click",()=>{if(canNavigate())addRequirement("end");});
1144
+ $("#trace-need-add").addEventListener("click",()=>editRecord("Need"));
1145
+ $("#trace-source-add").addEventListener("click",()=>editRecord("Source"));
1146
+ $("#trace-test-plan-add").addEventListener("click",()=>editRecord("Test plan"));
1147
+ $("#trace-test-add").addEventListener("click",()=>editRecord("Test"));
1148
+ $("#trace-change-add").addEventListener("click",()=>editRecord("Change request"));
1149
+ $("#trace-term-add").addEventListener("click",()=>editRecord("Term"));
1150
+ $("#trace-value-add").addEventListener("click",()=>editRecord("Value"));
1151
+ $("#trace-glossary-kind").addEventListener("click",event=>{
1152
+ const kind=event.target.closest("[data-glossary-kind]")?.dataset.glossaryKind;
1153
+ if(!kind||kind===glossaryKind||!canNavigate())return;
1154
+ close();
1155
+ step(()=>switchView("glossary",null,kind));
1156
+ });
1157
+ modeBar.addEventListener("click",event=>{
1158
+ const mode=event.target.closest("[data-view-mode]")?.dataset.viewMode;
1159
+ if(!mode||mode===viewMode()||!canNavigate())return;
1160
+ step(()=>{
1161
+ viewModes.set(view,mode);
1162
+ renderWorkspace();
1163
+ paintStrip();
1164
+ });
1165
+ });
1166
+ $("#trace-matrix-print").addEventListener("click",()=>window.print());
1167
+ $("#trace-matrix-csv").addEventListener("click",downloadMatrix);
1168
+ $("#trace-system-add").addEventListener("click",()=>editRecord("System"));
1169
+ $("#trace-subsystem-add").addEventListener("click",()=>editRecord("System",{parent:selectedSystem}));
1170
+ $("#trace-system-rename").addEventListener("click",()=>editRecord("System",{record:index.records.get(selectedSystem)}));
1171
+ $("#trace-system-move").addEventListener("click",()=>editLink("Part of",selectedSystem));
1172
+ $("#trace-system-delete").addEventListener("click",()=>openDeletion(selectedSystem));
1173
+ $("#trace-system-requirements").addEventListener("click",()=>{
1174
+ if(!canNavigate())return;
1175
+ close();
1176
+ changeScope(selectedSystem);
1177
+ systemSelect.focus();
1178
+ });
1179
+ $("#trace-system-links").addEventListener("click",()=>openPanel(selectedSystem));
1180
+ tree.addEventListener("click",event=>{
1181
+ const toggle=event.target.closest("[data-trace-collapse]");
1182
+ if(toggle){
1183
+ const id=toggle.dataset.traceCollapse;
1184
+ if(collapsed.has(id))collapsed.delete(id);
1185
+ else collapsed.add(id);
1186
+ renderTree();
1187
+ syncSelection(selectedSystem);
1188
+ focusControl(tree,"data-trace-collapse",id);
1189
+ return;
1190
+ }
1191
+ const button=event.target.closest("[data-trace-system]");
1192
+ if(!button)return;
1193
+ selectedSystem=button.dataset.traceSystem;
1194
+ renderTree();
1195
+ syncSelection(selectedSystem);
1196
+ focusControl(tree,"data-trace-system",selectedSystem);
1197
+ });
1198
+ $("#open-trace").addEventListener("click",()=>{
1199
+ if(!canNavigate())return;
1200
+ if(panel.hidden)openPanel(linksTarget());
1201
+ else {close();restoreSelectedCell();}
1202
+ });
1203
+ selectedLinks.addEventListener("click",()=>{
1204
+ if(!canNavigate())return;
1205
+ openPanel(linksTarget());
1206
+ });
1207
+ for(const dialog of [editor,picker,deletion])dialog.addEventListener("keydown",event=>event.stopPropagation());
1208
+ $("#close-trace").addEventListener("click",()=>{
1209
+ close();
1210
+ if(view==="systems")focusControl(tree,"data-trace-system",selectedSystem);
1211
+ else restoreSelectedCell();
1212
+ });
1213
+ $("#trace-back").addEventListener("click",goBack);
1214
+ panel.addEventListener("click",event=>{
1215
+ const button=event.target.closest("button");
1216
+ if(!button)return;
1217
+ const {traceJump,tracePick,traceRemove,traceTarget}=button.dataset;
1218
+ const record=index.records.get(selected);
1219
+ if(traceJump!==undefined)navigate(traceJump);
1220
+ else if(tracePick)editLink(tracePick);
1221
+ else if(traceRemove&&record)updateLink(record,traceRemove,traceIds(record.row[traceRemove])
1222
+ .filter(id=>id!==traceTarget).join("; "));
1223
+ else if(button.id==="trace-add-child")editRecord("Requirement",{parent:selected});
1224
+ else if(button.id==="trace-reveal"&&pending&&canNavigate()){
1225
+ const id=pending;
1226
+ step(()=>{
1227
+ revealed=id;
1228
+ render();
1229
+ focusRecord(id);
1230
+ },id);
1231
+ }
1232
+ });
1233
+ $("#trace-query").addEventListener("input",showCandidates);
1234
+ picker.addEventListener("keydown",event=>{
1235
+ if(event.key!=="ArrowDown"&&event.key!=="ArrowUp")return;
1236
+ const query=$("#trace-query"),options=[...$("#trace-candidates").querySelectorAll("[data-trace-target]")];
1237
+ const at=options.indexOf(document.activeElement);
1238
+ if(document.activeElement!==query&&at<0)return;
1239
+ event.preventDefault();
1240
+ const next=document.activeElement===query?(event.key==="ArrowDown"?0:-1):at+(event.key==="ArrowDown"?1:-1);
1241
+ if(next<0)query.focus();
1242
+ else options[Math.min(next,options.length-1)]?.focus();
1243
+ });
1244
+ $("#trace-picker-cancel").addEventListener("click",()=>picker.close());
1245
+ $("#trace-picker-apply").addEventListener("click",()=>{
1246
+ const {id,field,checked}=linkEdit;
1247
+ picker.close();
1248
+ updateLink(index.records.get(id),field,[...checked].join("; "));
1249
+ });
1250
+ $("#trace-candidates").addEventListener("change",event=>{
1251
+ const input=event.target.closest("input[data-trace-target]");
1252
+ if(!input||!linkEdit?.checked)return;
1253
+ if(input.checked)linkEdit.checked.add(input.dataset.traceTarget);
1254
+ else linkEdit.checked.delete(input.dataset.traceTarget);
1255
+ });
1256
+ $("#trace-candidates").addEventListener("click",event=>{
1257
+ const targetId=event.target.closest("button[data-trace-target]")?.dataset.traceTarget;
1258
+ if(!targetId||!linkEdit)return;
1259
+ const {id,field}=linkEdit,record=index.records.get(id),target=index.records.get(targetId);
1260
+ const removed=field==="Affects"&&!target&&removedSince(targetId)!==null&&!traceIds(record?.row.Affects).includes(targetId);
1261
+ if(!writable()||!record||!(removed||(target&&traceCanLink(record,field,target))))return;
1262
+ picker.close();
1263
+ const value=traceFields[field].single?targetId:[...traceIds(record.row[field]),targetId].join("; ");
1264
+ updateLink(record,field,value);
1265
+ });
1266
+ $("#trace-editor-cancel").addEventListener("click",()=>editor.close());
1267
+ $("#trace-record-form").addEventListener("submit",event=>{
1268
+ event.preventDefault();
1269
+ if(!writable())return;
1270
+ const {type,record,parent}=recordEdit;
1271
+ const name=$("#trace-record-name").value.trim(),content=$("#trace-record-content").value.trim();
1272
+ const valueField=$("#trace-value-field").value;
1273
+ if(type==="Value"&&!valueField){
1274
+ $("#trace-value-field").focus();
1275
+ return;
1276
+ }
1277
+ const id=record?.id??(type==="Term"?nextRecordId("TERM-"):type==="Value"?valueRecordId(valueField,name,takenIds())
1278
+ :validateNewId($("#trace-record-id").value));
1279
+ if(!id)return;
1280
+ if((type==="Requirement"||type==="Term"||type==="Value")&&!content){
1281
+ $("#trace-record-content").focus();
1282
+ return;
1283
+ }
1284
+ if(type!=="Requirement"&&!name){
1285
+ $("#trace-record-name").focus();
1286
+ return;
1287
+ }
1288
+ editor.close();
1289
+ if(record?.row.Name===name)return;
1290
+ remember();
1291
+ if(record)record.row.Name=name;
1292
+ else{
1293
+ const row={...newRequirement(id),Type:type,Name:name};
1294
+ if(type==="System"&&parent)row["Part of"]=parent;
1295
+ if(type==="Requirement"){
1296
+ row["Derived from"]=parent;
1297
+ if(system)row["Allocated to"]=system;
1298
+ }
1299
+ if(type!=="System")row[{Term:"Definition",Value:"Definition",Source:"Reference"}[type]??"Requirement"]=content;
1300
+ if(type==="Test")row["Test plan"]=$("#trace-test-plan").value;
1301
+ if(type==="Change request"&&"Change status" in row)row["Change status"]="Proposed";
1302
+ if(type==="Value"){
1303
+ row.Field=valueField;
1304
+ row.Aliases=$("#trace-value-aliases").value.trim();
1305
+ }
1306
+ if(type==="Term"){
1307
+ row.Aliases=$("#trace-term-aliases").value.trim();
1308
+ row["Auto Link"]=$("#trace-term-single-word").checked?"Yes":"";
1309
+ }
1310
+ state.currentRows.push(row);
1311
+ }
1312
+ updateDirty();
1313
+ const destination=viewForType(type);
1314
+ if(type==="System")selectedSystem=id;
1315
+ if(!switchView(destination,null,type==="Value"?"values":"terms"))render();
1316
+ if(view!=="systems"&&!visible(id)){revealed=id;render();}
1317
+ focusRecord(id);
1318
+ if(panel.hidden&&view==="systems")focusControl(tree,"data-trace-system",id);
1319
+ });
1320
+ $("#trace-delete-cancel").addEventListener("click",()=>deletion.close());
1321
+ $("#trace-delete-form").addEventListener("submit",event=>{
1322
+ event.preventDefault();
1323
+ if(!writable())return;
1324
+ const {id,changes}=deleteEdit;
1325
+ const targets=Object.fromEntries(["Part of","Allocated to","Owner"].map((field,i)=>
1326
+ [field,$("#trace-delete-group-"+i+" select").value]));
1327
+ const updated=changes.map(change=>{
1328
+ const {row,field,value}=change,target=targets[field];
1329
+ if(!target||!traceFields[field].from.includes(traceType(row)))return change;
1330
+ const ids=traceFields[field].single?[target]:[...new Set([...traceIds(value),target])];
1331
+ return {...change,value:ids.join("; ")};
1332
+ });
1333
+ deletion.close();
1334
+ deleteRecord(id,updated);
1335
+ if(view==="systems")focusControl(tree,"data-trace-system",selectedSystem);
1336
+ });
1337
+
1338
+ function followValueRename(row,column,before){
1339
+ if(column!=="Name"||traceType(row)!=="Value")return;
1340
+ const field=row.Field?.trim(),rule=index.values.get(field),old=before.trim(),name=row.Name.trim();
1341
+ if(!rule||!old||!name||old===name||rule.values.get(old)?.row!==row)return;
1342
+ const changes=renameValueUses(state.currentRows,field,rule.multiple,old,name);
1343
+ if(!changes.length)return;
1344
+ const n=changes.length;
1345
+ if(!confirm(`Rename “${old}” to “${name}” in ${n} ${n===1?"row that uses":"rows that use"} it?`))return;
1346
+ for(const change of changes)change.row[field]=change.value;
1347
+ }
1348
+
1349
+ if(historyOn){
1350
+ window.addEventListener("popstate",popHistory);
1351
+ queueMicrotask(restoreHistory);
1352
+ }
1353
+
1354
+ return {recordType:id=>index.records.get(id)?.type,refresh,followValueRename,paintMarkers,valueRule:column=>index.values.get(column),matches,filters,reset,syncSelection,close,clearCopy,columnAvailable,defaultHidden,openDeletion,
1355
+ // Null (every column) unless the index was built from the data as of `since`.
1356
+ indexColumns:since=>indexVersion===since?traceIndexColumns(index.values,data.meta.idColumn,Boolean(data.controls)):null,
1357
+ // Records keep their identity through edits and undo, so an index current at `since` stays current after
1358
+ // a change confined to columns outside indexColumns(since).
1359
+ keepIndex:since=>{if(indexVersion===since)indexVersion=dataVersion;},
1360
+ columnLayout:()=>listViews[view]?.layout??null,
1361
+ columnRank:name=>view==="glossary"&&glossaryKind==="values"?[...glossaryKinds.values.columns].indexOf(name)
1362
+ :listViews[view]?.order?.().indexOf(name)??0,
1363
+ linkGlossary:rows=>glossaryPopover.decorate(index.glossary,rows),
1364
+ viewKey:()=>[view,glossaryKind,viewMode()].join(":"),
1365
+ cellDisplay:(id,column)=>{
1366
+ const record=index.records.get(id);
1367
+ return record&&listViews[view]?.cells?.[column]?.(record)||null;
1368
+ },
1369
+ paintStrip,
1370
+ revealed:id=>view!=="systems"&&id===revealed,
1371
+ scoped:()=>view==="systems"||view==="glossary"||!!listViews[view]||(view==="requirements"&&(!!system||unallocated))||!!revealed,
1372
+ rowOrderIds:()=>view==="requirements"?state.currentRows.filter(row=>traceType(row)==="Requirement").map(rowId):null,
1373
+ entry:()=>view==="requirements"||view==="all",
1374
+ pageView:()=>view==="systems"||view==="gates",
1375
+ recordNoun:()=>view==="requirements"?"requirements":view==="all"?"records":view==="changes"?"change requests":"records",
1376
+ gridSummary:count=>{
1377
+ if(view==="systems")return `${index.systems.length} systems`;
1378
+ if(listViews[view])return listViews[view].summary(count);
1379
+ if(view==="glossary")return glossaryKinds[glossaryKind].summary(count);
1380
+ if(view==="all")return `${count} of ${data.rows.length} records`;
1381
+ return `${count} requirements`;
1382
+ },
1383
+ rowMarker:id=>{
1384
+ const record=index.records.get(id);
1385
+ if(!record||(!record.incoming.length&&!Object.keys(traceFields).some(field=>traceIds(record.row[field]).length)))return "";
1386
+ return '<span class="trace-row-marker" role="img" aria-label="Has links" title="Has links"></span>';
1387
+ },
1388
+ rename:(oldId,newId)=>{
1389
+ if(system===oldId)system=newId;
1390
+ if(selectedSystem===oldId)selectedSystem=newId;
1391
+ if(collapsed.delete(oldId))collapsed.add(newId);
1392
+ if(revealed===oldId)revealed=newId;
1393
+ if(recordId===oldId)recordId=newId;
1394
+ },
1395
+ incomingChanges:(oldId,newId)=>traceIncomingChanges(state.currentRows,oldId,newId),
1396
+ isRequirement:row=>traceType(row)==="Requirement",
1397
+ allocate:row=>{if(view==="requirements"&&system)row["Allocated to"]=system;},
1398
+ reveal:(id,column)=>{
1399
+ const destination=recordView(id);
1400
+ if(view!=="all"&&(view!==destination||(destination==="glossary"&&glossaryKind!==kindOf(id))))
1401
+ switchView(destination==="systems"?"all":destination,null,kindOf(id));
1402
+ if(view==="systems"||(column&&!columnAvailable(column)))switchView("all");
1403
+ revealed=id;
1404
+ },
1405
+ panel};
1406
+ })();
1407
+ """
1408
+ )
1409
+
1410
+ TRACE_MENU = '<button id="open-trace" aria-expanded="false" aria-controls="trace-panel" aria-label="Links and trace findings">Links</button>'
1411
+
1412
+ TRACE_WORKSPACE = """
1413
+ <section id="trace-workspace" aria-label="Traceability workspace">
1414
+ <nav id="trace-views" aria-label="Record views">
1415
+ <div role="group" aria-label="Define">
1416
+ <button type="button" data-trace-view="sources" aria-pressed="false">Needs &amp; sources</button>
1417
+ <button type="button" data-trace-view="requirements" aria-pressed="true">Requirements</button>
1418
+ <button type="button" data-trace-view="systems" aria-pressed="false">Systems</button>
1419
+ </div>
1420
+ <div role="group" aria-label="Verify">
1421
+ <button type="button" data-trace-view="tests" aria-pressed="false">Tests</button>
1422
+ <button type="button" data-trace-view="verification" aria-pressed="false">Verification</button>
1423
+ <button type="button" data-trace-view="gates" aria-pressed="false">Gates</button>
1424
+ <button type="button" data-trace-view="changes" aria-pressed="false">Change requests</button>
1425
+ </div>
1426
+ <div role="group" aria-label="Reference">
1427
+ <button type="button" data-trace-view="glossary" aria-pressed="false">Glossary</button>
1428
+ <button type="button" data-trace-view="all" aria-pressed="false">All fields</button>
1429
+ </div>
1430
+ </nav>
1431
+ <div id="trace-controls">
1432
+ <div id="trace-scope">
1433
+ <label>System <select id="trace-system"><option>All requirements</option></select></label>
1434
+ <label><input type="checkbox" id="trace-descendants" checked> Include subsystems</label>
1435
+ </div>
1436
+ <button id="trace-view-add" type="button" hidden>Add requirement…</button>
1437
+ <span id="trace-glossary-kind" role="group" aria-label="Glossary content" hidden>
1438
+ <button type="button" data-glossary-kind="terms" aria-pressed="true">Terms</button>
1439
+ <button type="button" data-glossary-kind="values" aria-pressed="false">Values</button>
1440
+ </span>
1441
+ <span id="trace-view-mode" role="group" aria-label="Layout" hidden>
1442
+ <button type="button" data-view-mode="grid" aria-pressed="true">Grid</button>
1443
+ <button type="button" data-view-mode="matrix" aria-pressed="false">Matrix</button>
1444
+ </span>
1445
+ <button id="trace-term-add" type="button" hidden>Add term…</button>
1446
+ <button id="trace-value-add" type="button" hidden>Add value…</button>
1447
+ <span id="trace-source-actions" hidden>
1448
+ <button id="trace-need-add" type="button">Add need…</button>
1449
+ <button id="trace-source-add" type="button">Add source…</button>
1450
+ </span>
1451
+ <span id="trace-test-actions" hidden>
1452
+ <button id="trace-test-plan-add" type="button">Add test plan…</button>
1453
+ <button id="trace-test-add" type="button">Add test…</button>
1454
+ </span>
1455
+ <span id="trace-change-actions" hidden>
1456
+ <button id="trace-change-add" type="button">Add change request…</button>
1457
+ </span>
1458
+ <button id="trace-selected-links" type="button" aria-controls="trace-panel" aria-expanded="false" disabled>Links</button>
1459
+ </div>
1460
+ <p id="trace-status" class="meta" role="status"></p>
1461
+ <p id="trace-verification-summary" class="meta" hidden></p>
1462
+ </section>
1463
+ """
1464
+
1465
+ TRACE_SYSTEMS = """
1466
+ <section id="trace-matrix" aria-label="Verification cross-reference matrix" hidden>
1467
+ <div class="trace-matrix-actions">
1468
+ <button type="button" id="trace-matrix-print">Print…</button>
1469
+ <button type="button" id="trace-matrix-csv">Download CSV</button>
1470
+ </div>
1471
+ <div class="trace-matrix-scroll"><table id="trace-matrix-table"></table></div>
1472
+ </section>
1473
+ <section id="trace-gates" aria-label="Gate readiness" hidden>
1474
+ <div id="trace-gates-scope"><label>System <select id="trace-gates-system"></select></label></div>
1475
+ <div id="trace-gates-list"></div>
1476
+ </section>
1477
+ <section id="trace-systems" aria-label="System hierarchy" hidden>
1478
+ <div>
1479
+ <h2>System hierarchy</h2>
1480
+ <button type="button" id="trace-system-add" hidden>Add system…</button>
1481
+ <ul id="trace-tree" aria-label="Systems"></ul>
1482
+ </div>
1483
+ <div id="trace-system-actions" hidden>
1484
+ <h2 id="trace-system-name" tabindex="-1"></h2>
1485
+ <p class="meta" id="trace-system-parent"></p>
1486
+ <div class="trace-actions">
1487
+ <button type="button" id="trace-system-requirements">Allocated requirements</button>
1488
+ <button type="button" id="trace-system-links" aria-controls="trace-panel">Links</button>
1489
+ </div>
1490
+ <div class="trace-actions" id="trace-system-edit" hidden>
1491
+ <button type="button" id="trace-subsystem-add">Add subsystem…</button>
1492
+ <button type="button" id="trace-system-rename">Rename…</button>
1493
+ <button type="button" id="trace-system-move">Move to…</button>
1494
+ <button type="button" id="trace-system-delete">Delete system…</button>
1495
+ </div>
1496
+ </div>
1497
+ </section>
1498
+ """
1499
+
1500
+ TRACE_HTML = """
1501
+ <aside id="trace-panel" class="review-panel" hidden aria-labelledby="trace-title">
1502
+ <div class="review-head"><h2 id="trace-title" tabindex="-1">Links</h2><button id="close-trace">Close</button></div>
1503
+ <div class="review-body">
1504
+ <button type="button" id="trace-back" hidden>Back to previous record</button>
1505
+ <div id="trace-record"></div>
1506
+ <details id="trace-findings"><summary>Trace findings</summary><ul id="trace-issues"></ul></details>
1507
+ </div>
1508
+ </aside>
1509
+ <dialog id="trace-picker" class="help-dialog" aria-labelledby="trace-picker-title">
1510
+ <div class="help-head"><h2 id="trace-picker-title">Choose target</h2><button type="button" id="trace-picker-cancel">Cancel</button></div>
1511
+ <div class="help-body"><label for="trace-query">Search by ID, name or text</label>
1512
+ <input type="search" id="trace-query" autofocus><ul id="trace-candidates" aria-label="Eligible targets"></ul>
1513
+ <button type="button" id="trace-picker-apply" class="primary" hidden>Apply allocations</button>
1514
+ </div>
1515
+ </dialog>
1516
+ <dialog id="trace-editor" class="help-dialog" aria-labelledby="trace-editor-title">
1517
+ <form id="trace-record-form">
1518
+ <div class="help-head"><h2 id="trace-editor-title">Add record</h2><button type="button" id="trace-editor-cancel">Cancel</button></div>
1519
+ <div class="help-body">
1520
+ <label id="trace-value-field-label" hidden>Field <select id="trace-value-field"></select></label>
1521
+ <label id="trace-record-id-field">ID <input id="trace-record-id" required></label>
1522
+ <label id="trace-record-name-field">Name <input id="trace-record-name"></label>
1523
+ <label id="trace-record-content-field"><span id="trace-record-content-label"></span>
1524
+ <textarea id="trace-record-content" rows="3"></textarea></label>
1525
+ <label id="trace-test-plan-label" hidden>Test plan <select id="trace-test-plan"></select></label>
1526
+ <label id="trace-value-aliases-label" hidden>Aliases (separated by semicolons) <input id="trace-value-aliases"></label>
1527
+ <div id="trace-term-options" hidden>
1528
+ <label>Aliases (separated by semicolons) <input id="trace-term-aliases"></label>
1529
+ <label><input type="checkbox" id="trace-term-single-word"> Also link single-word Title Case spellings</label>
1530
+ </div>
1531
+ <button type="submit" class="primary">Apply</button>
1532
+ </div>
1533
+ </form>
1534
+ </dialog>
1535
+ <dialog id="trace-delete" class="help-dialog" aria-labelledby="trace-delete-title">
1536
+ <form id="trace-delete-form">
1537
+ <div class="help-head"><h2 id="trace-delete-title">Delete system?</h2><button type="button" id="trace-delete-cancel">Cancel</button></div>
1538
+ <div class="help-body">
1539
+ <p id="trace-delete-impact"></p>
1540
+ <label id="trace-delete-group-0"><span></span><select></select></label>
1541
+ <label id="trace-delete-group-1"><span></span><select></select></label>
1542
+ <label id="trace-delete-group-2"><span></span><select></select></label>
1543
+ <p class="meta" id="trace-delete-other"></p>
1544
+ <button type="submit" class="primary">Delete system</button>
1545
+ </div>
1546
+ </form>
1547
+ </dialog>
1548
+ """
1549
+
1550
+ TRACE_CSS = """
1551
+ #trace-workspace {display:flex;align-items:center;flex-wrap:wrap;gap:6px 12px;padding:5px 12px;background:var(--panel);border-bottom:1px solid var(--line);flex:none}
1552
+ #trace-views,#trace-scope,#trace-glossary-kind,#trace-view-mode,.trace-actions {display:flex;flex-wrap:wrap;align-items:center;gap:5px}
1553
+ #trace-views button[aria-pressed="true"],#trace-glossary-kind button[aria-pressed="true"],#trace-view-mode button[aria-pressed="true"],#trace-tree button[aria-pressed="true"] {background:var(--selected);border-color:var(--accent)}
1554
+ #trace-views [role="group"] {display:flex;flex-wrap:wrap;align-items:center;gap:5px}
1555
+ #trace-views {gap:5px 12px}
1556
+ #trace-controls {display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:6px 12px;margin-inline-start:auto}
1557
+ #trace-views [role="group"]+[role="group"] {padding-inline-start:12px;border-inline-start:1px solid var(--line)}
1558
+ #trace-system {max-width:min(24ch,60vw)}
1559
+ #trace-status {flex-basis:100%;margin:0}
1560
+ #trace-status:empty {display:none}
1561
+ #trace-systems {display:grid;grid-template-columns:minmax(14rem,1fr) minmax(16rem,1fr);gap:16px;padding:14px 18px;overflow:auto}
1562
+ #trace-systems h2 {font-size:1.08em;margin:0 0 8px}
1563
+ #trace-gates {display:grid;gap:14px;align-content:start;padding:14px 18px;overflow:auto}
1564
+ #trace-gates-list {display:grid;gap:14px}
1565
+ #trace-gates-system {max-width:min(24ch,60vw)}
1566
+ .gate {border:1px solid var(--line);border-radius:6px;padding:12px;background:var(--panel)}
1567
+ .gate header {display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px 12px}
1568
+ .gate h2 {font-size:1.08em;margin:0}
1569
+ .gate-checks,.gate-table-findings {list-style:none;padding:0;margin:8px 0 0}
1570
+ .gate-checks>li {padding:6px 0;border-top:1px solid var(--line)}
1571
+ .gate-table-findings {margin-inline-start:1.5rem}
1572
+ .gate-badge,.gate-mark {display:inline-block;padding:0 8px;border:1px solid var(--line);border-radius:9px;font-size:.88em;font-weight:600;white-space:nowrap;color:var(--text)}
1573
+ .gate-pass {background:var(--add);border-color:var(--addStrong)}
1574
+ .gate-fail {background:var(--remove);border-color:var(--removeStrong)}
1575
+ .gate-error,.gate-advisory {background:var(--changed)}
1576
+ #trace-system-actions {align-self:start;border:1px solid var(--line);border-radius:6px;padding:12px;background:var(--panel)}
1577
+ .trace-actions+.trace-actions {margin-top:8px}
1578
+ #trace-tree,#trace-record ul,#trace-candidates {list-style:none;padding:0;margin:4px 0 8px}
1579
+ #trace-tree {display:grid;grid-template-columns:minmax(0,1fr) max-content;gap:4px 6px}
1580
+ #trace-tree li {display:grid;grid-column:1/-1;grid-template-columns:subgrid;align-items:center}
1581
+ .trace-tree-node {
1582
+ display:flex;align-items:center;gap:6px;min-width:0;
1583
+ padding-inline-start:calc(var(--trace-depth,0) * .8rem);
1584
+ }
1585
+ #trace-tree [data-trace-system] {flex:1;min-width:0;text-align:start;overflow-wrap:anywhere}
1586
+ #trace-tree [data-trace-collapse],.trace-tree-leaf {width:26px;flex:none}
1587
+ #trace-tree .meta {white-space:nowrap;text-align:end;font-variant-numeric:tabular-nums}
1588
+ #trace-verification-summary {display:flex;flex-wrap:wrap;gap:2px 14px;flex-basis:100%;margin:0}
1589
+ #trace-verification-summary[hidden] {display:none}
1590
+ .vcrm-methods {display:inline-flex;gap:3px;vertical-align:middle}
1591
+ .vcrm-slot {display:inline-grid;place-items:center;width:20px;height:20px;border:1px dashed var(--line);border-radius:4px;color:var(--muted);font-size:.8em;font-weight:700}
1592
+ .vcrm-slot.on {border:1px solid var(--accent);background:var(--accent);color:var(--panel)}
1593
+ .vcrm-test {display:block;margin-bottom:3px}
1594
+ .vcrm-result {display:inline-block;padding:0 6px;border:1px solid var(--line);border-radius:9px;font-size:.85em;background:var(--panel);color:var(--text)}
1595
+ .vcrm-result-passed {background:var(--add);border-color:var(--addStrong)}
1596
+ .vcrm-result-failed {background:var(--remove);border-color:var(--removeStrong)}
1597
+ .vcrm-result-blocked {background:var(--changed)}
1598
+ .vcrm-result-none {border-style:dashed;color:var(--muted)}
1599
+ .trace-row-marker {position:absolute;inset-block-start:5px;inset-inline-end:4px;width:5px;height:5px;border-radius:50%;background:var(--accent)}
1600
+ #trace-panel {width:min(380px,100vw)}
1601
+ #trace-panel h3 {font-size:1.05em;margin:8px 0 4px}
1602
+ #trace-record {margin:8px 0;overflow-wrap:anywhere}
1603
+ #trace-record h4 {font-size:inherit;margin:0}
1604
+ #trace-record section {border-top:1px solid var(--line);padding:7px 0}
1605
+ #trace-record p {margin:4px 0}
1606
+ #trace-record li {margin-bottom:3px}
1607
+ .trace-link {text-align:start;color:var(--accent);overflow-wrap:anywhere}
1608
+ .trace-note {white-space:pre-wrap}
1609
+ .trace-remove {min-width:24px}
1610
+ .trace-reveal {background:var(--selected);padding:6px;border-radius:4px}
1611
+ #trace-findings summary {cursor:pointer}
1612
+ #trace-issues {padding-inline-start:20px;overflow-wrap:anywhere}
1613
+ #trace-issues li {margin-bottom:6px}
1614
+ #trace-issues li.trace-finding-active {background:var(--selected);outline:2px solid var(--accent);border-radius:4px;padding:2px 4px}
1615
+ :root {--trace-finding:#b42318}
1616
+ @media(prefers-color-scheme:dark) {:root {--trace-finding:#ff9a8f}}
1617
+ .cell-wrap:has(.trace-marker) {padding-right:24px}
1618
+ .cell-wrap:has(.quality-marker):has(.trace-marker) {padding-right:46px}
1619
+ .trace-marker {
1620
+ position:absolute; top:-4px; right:0; width:22px; height:24px;
1621
+ border:0; padding:0; background:transparent; color:var(--trace-finding); font-weight:700;
1622
+ }
1623
+ .quality-marker~.trace-marker {right:22px}
1624
+ #trace-query {display:block;width:100%}
1625
+ #trace-picker {width:min(900px,calc(100vw - 24px));max-height:calc(100vh - 80px)}
1626
+ #trace-candidates button,#trace-candidates label {display:flex;align-items:baseline;gap:12px;width:100%;text-align:start;margin-top:4px}
1627
+ .trace-candidate-name {flex:none;max-width:60%;overflow-wrap:anywhere}
1628
+ .trace-candidate-detail {flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted)}
1629
+ #trace-record-form label,#trace-delete-form label {display:grid;gap:3px;margin-bottom:10px}
1630
+ #trace-matrix {padding:14px 18px;background:var(--panel)}
1631
+ .trace-matrix-actions {display:flex;gap:6px;margin-bottom:10px}
1632
+ .trace-matrix-scroll {overflow:auto}
1633
+ #trace-matrix-table {table-layout:auto;border-collapse:collapse;min-width:0;width:100%;border:1px solid var(--line)}
1634
+ #trace-matrix-table caption {position:static;clip:auto;text-align:left;font-weight:700;padding:0 0 6px}
1635
+ #trace-matrix-table th,#trace-matrix-table td {border:1px solid var(--line);padding:4px 8px}
1636
+ #trace-matrix-table thead th {position:static;height:auto;text-align:center}
1637
+ #trace-matrix-table thead th[rowspan] {text-align:left}
1638
+ #trace-matrix-table tbody th,#trace-matrix-table tfoot th {text-align:left;background:var(--panel);color:var(--text);font-weight:600}
1639
+ #trace-matrix-table tfoot {font-weight:600;background:var(--bg)}
1640
+ #trace-matrix-table .vcrm-mark {text-align:center;font-weight:700}
1641
+ #trace-matrix-table .vcrm-extra {font-weight:400;color:var(--muted);font-size:.85em}
1642
+ #trace-matrix-table th,#trace-matrix-table td:last-child {overflow-wrap:normal;white-space:nowrap}
1643
+ #trace-matrix-table .vcrm-mark {width:2.4em;min-width:2.4em;padding-inline:2px}
1644
+ #trace-matrix-table abbr {text-decoration:none;cursor:help}
1645
+ #trace-matrix-table .vcrm-nowrap {white-space:nowrap}
1646
+ .vcrm-legend {display:flex;flex-wrap:wrap;gap:2px 18px;font-weight:400;color:var(--muted);margin-top:3px}
1647
+ #trace-matrix-table tbody td:nth-child(2) {min-width:12rem;width:100%}
1648
+ #trace-matrix[hidden],#trace-controls[hidden],#trace-view-mode[hidden],#trace-systems[hidden],#trace-gates[hidden],#trace-scope[hidden],#trace-glossary-kind[hidden],.trace-actions[hidden],#trace-record-form label[hidden],#trace-delete-form label[hidden] {display:none}
1649
+ @media screen and (min-width:901px) {body:has(#trace-panel:not([hidden])) .page {margin-right:380px}}
1650
+ @media screen and (max-width:650px) {#trace-systems {grid-template-columns:1fr}}
1651
+ @page matrix {size:landscape}
1652
+ @media print {
1653
+ body:has(#trace-matrix:not([hidden])) {page:matrix}
1654
+ body:has(#trace-matrix:not([hidden])),body:has(#trace-matrix:not([hidden])) .page {background:#fff}
1655
+ body:has(#trace-matrix:not([hidden])) .print-details,body:has(#trace-matrix:not([hidden])) .mode-badge,.trace-matrix-actions {display:none}
1656
+ body:has(#trace-matrix:not([hidden])) .report-identity h1 {color:#000}
1657
+ #trace-matrix {padding:0;background:none}
1658
+ .trace-matrix-scroll {overflow:visible}
1659
+ #trace-matrix-table {color:#000;width:100%}
1660
+ #trace-matrix-table caption,.vcrm-legend {color:#000}
1661
+ #trace-matrix-table th,#trace-matrix-table td {border:1px solid #000;font-size:8.5pt;padding:2px 4px}
1662
+ #trace-matrix-table thead th,#trace-matrix-table tbody th,#trace-matrix-table tfoot th {background:none;color:#000}
1663
+ #trace-matrix-table td:last-child {white-space:normal}
1664
+ #trace-matrix-table tbody td:nth-child(2) {min-width:0}
1665
+ #trace-matrix-table thead {display:table-header-group}
1666
+ #trace-matrix-table tfoot {display:table-row-group}
1667
+ #trace-matrix-table tr {break-inside:avoid}
1668
+ }
1669
+ @media print {#trace-workspace,#trace-panel,.trace-row-marker,.trace-marker,#trace-system-edit,#trace-system-add,.trace-actions {display:none}}
1670
+ """