File size: 152,213 Bytes
19b91ce
 
 
dec006b
19b91ce
dec006b
ce9586e
816fa8a
92127d3
dec006b
07a68d0
2e7e617
 
 
 
 
19b91ce
 
dec006b
 
2e7e617
19b91ce
8873406
07a68d0
19b91ce
ce9586e
19b91ce
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
82cdb59
 
 
 
 
 
 
103a492
 
 
 
 
82cdb59
 
 
 
 
07a68d0
f462120
07a68d0
 
 
 
 
 
 
dec006b
 
 
 
8cbc29f
 
07a68d0
8cbc29f
07a68d0
 
8cbc29f
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92127d3
8cbc29f
 
92127d3
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92127d3
 
8cbc29f
 
 
07a68d0
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
07a68d0
 
8133df9
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
19b91ce
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
f462120
816fa8a
 
 
f462120
 
816fa8a
 
 
 
 
 
f462120
 
 
 
 
 
 
 
816fa8a
dec006b
816fa8a
 
 
 
 
 
07a68d0
 
816fa8a
 
f462120
 
816fa8a
f462120
 
 
 
 
 
 
816fa8a
 
3fac176
 
 
 
 
 
 
 
 
 
 
 
 
f462120
3fac176
 
 
 
816fa8a
 
 
 
 
3fac176
dec006b
 
 
816fa8a
 
 
8cbc29f
 
 
07a68d0
8cbc29f
07a68d0
 
 
 
 
 
 
8cbc29f
 
 
 
dec006b
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
19b91ce
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
dec006b
 
 
8873406
dec006b
 
19b91ce
 
 
 
 
 
 
ce9586e
 
dec006b
 
 
 
 
 
 
 
19b91ce
 
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
19b91ce
 
8873406
 
 
8133df9
 
8873406
 
 
 
 
 
 
 
 
 
 
 
8133df9
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95fb175
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
 
95fb175
 
 
 
8873406
 
 
 
 
8133df9
 
8873406
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
8873406
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
8133df9
8873406
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
816fa8a
 
 
 
dec006b
19b91ce
 
 
 
dec006b
 
19b91ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
19b91ce
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
19b91ce
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
07a68d0
8cbc29f
dec006b
 
82cdb59
 
 
07a68d0
 
f462120
07a68d0
 
 
 
 
82cdb59
07a68d0
8cbc29f
07a68d0
8cbc29f
07a68d0
82cdb59
07a68d0
82cdb59
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
dec006b
 
82cdb59
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
dec006b
82cdb59
 
 
 
 
 
dec006b
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
19b91ce
95fb175
8873406
dec006b
 
 
 
19b91ce
 
 
95fb175
 
19b91ce
95fb175
19b91ce
 
 
07a68d0
 
 
 
 
8873406
 
 
 
8133df9
 
8873406
2e7e617
816fa8a
 
2e7e617
dec006b
 
19b91ce
 
 
 
 
 
2eae9f0
 
 
 
 
 
 
 
07a68d0
 
2eae9f0
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
2eae9f0
 
 
19b91ce
816fa8a
 
19b91ce
 
95fb175
19b91ce
8873406
 
 
07a68d0
 
8133df9
 
 
95fb175
 
 
 
 
 
dec006b
 
816fa8a
 
95fb175
816fa8a
95fb175
07a68d0
8873406
 
 
 
 
19b91ce
 
 
 
 
95fb175
19b91ce
2eae9f0
 
 
 
 
 
 
19b91ce
 
 
8133df9
 
 
8729c1d
 
8133df9
 
 
 
 
 
2e7e617
816fa8a
 
2e7e617
f462120
 
2e7e617
 
 
 
8133df9
2e7e617
 
 
816fa8a
 
2e7e617
 
ce9586e
dec006b
ce9586e
19b91ce
82cdb59
8cbc29f
82cdb59
 
 
 
19b91ce
 
2e7e617
07a68d0
dec006b
19b91ce
 
82cdb59
 
 
8cbc29f
19b91ce
 
 
 
82cdb59
19b91ce
 
82cdb59
8cbc29f
 
dec006b
 
 
ce9586e
 
 
dec006b
 
 
 
 
 
 
8873406
 
816fa8a
 
 
 
8873406
dec006b
816fa8a
 
dec006b
 
8873406
 
 
 
816fa8a
dec006b
 
816fa8a
dec006b
816fa8a
 
 
 
 
dec006b
 
816fa8a
dec006b
 
 
 
 
816fa8a
dec006b
 
 
 
 
816fa8a
 
8873406
dec006b
 
 
 
816fa8a
 
 
8873406
 
 
 
 
 
 
 
 
 
 
f462120
 
8873406
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
f462120
 
8873406
 
8133df9
 
 
ce9586e
 
dec006b
ce9586e
f462120
 
 
 
 
dec006b
 
 
19b91ce
 
f462120
07a68d0
 
19b91ce
f462120
 
 
 
 
 
3fac176
 
 
f462120
 
 
3fac176
 
f462120
 
3fac176
 
 
 
 
f462120
 
3fac176
f462120
 
 
 
 
 
dec006b
 
 
 
19b91ce
 
816fa8a
 
ce9586e
 
 
816fa8a
 
 
 
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
3fac176
 
816fa8a
 
 
07a68d0
3fac176
816fa8a
 
07a68d0
3fac176
816fa8a
 
07a68d0
 
3fac176
 
816fa8a
 
 
 
 
 
 
 
 
ce9586e
816fa8a
ce9586e
 
 
 
 
 
 
 
 
8873406
ce9586e
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
ce9586e
 
 
 
8873406
07a68d0
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
ce9586e
 
 
3fac176
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fac176
8133df9
3fac176
 
 
 
 
 
 
 
 
8133df9
 
3fac176
 
8133df9
 
3fac176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
3fac176
 
 
 
 
 
 
8133df9
3fac176
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
3fac176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
19b91ce
dec006b
 
 
 
 
82cdb59
dec006b
2e7e617
82cdb59
 
 
 
19b91ce
dec006b
 
19b91ce
 
816fa8a
07a68d0
dec006b
8cbc29f
 
82cdb59
19b91ce
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
19b91ce
 
dec006b
 
 
 
 
19b91ce
 
 
103a492
 
 
dec006b
07a68d0
 
 
dec006b
19b91ce
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
19b91ce
 
 
dec006b
 
 
 
19b91ce
2e7e617
19b91ce
8873406
 
dec006b
 
 
 
 
 
 
 
19b91ce
 
 
dec006b
 
19b91ce
 
816fa8a
07a68d0
dec006b
82cdb59
19b91ce
82cdb59
07a68d0
 
82cdb59
07a68d0
 
82cdb59
 
dec006b
f462120
816fa8a
 
 
 
 
07a68d0
 
816fa8a
07a68d0
816fa8a
dec006b
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
816fa8a
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
07a68d0
 
dec006b
 
 
 
 
 
 
 
816fa8a
 
19b91ce
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
816fa8a
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
19b91ce
 
 
816fa8a
07a68d0
dec006b
19b91ce
816fa8a
 
 
103a492
 
 
816fa8a
19b91ce
 
 
8873406
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
19b91ce
 
816fa8a
 
19b91ce
 
 
 
 
 
8873406
 
 
19b91ce
 
 
 
 
816fa8a
 
19b91ce
 
 
 
 
 
 
 
 
 
816fa8a
19b91ce
 
 
816fa8a
 
19b91ce
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
"""Tenant-level reusable Application assets and deterministic default resolution."""
from __future__ import annotations

import base64
import copy
import hashlib
import json
from core import shares, write_execution
from core.request_timing import raise_if_resource_error
import app_rules
import app_templates as _app_templates

from modules.finance_apps import (finance_application as _finance_application,
                                  finance_applications as _finance_applications,
                                  finance_group as _finance_group)
from modules.finance_spine import fact_specs as _finance_fact_specs


APPLICATION_TYPES = ("chart", "route", "map", "code")
# Finance descriptors remain available to the governed fact routes.
FINANCE_TEMPLATE_KIND = "finance"
_KEY = "applications_v1"
_RECORD_PREFIX = "applications_v1_app/"
#: D-8392 (R58): the most live Apps one account may create. The cap counts per account, never per tenant.
_MAX = 500
_MAX_DISPLAY_BYTES = 512 * 1024

# Routing and Catalog are the first authored App templates.  These are wire contracts, not
# executable module declarations: the client renders a trusted platform surface from the stored
# definition.  ``required`` is consumed by the creation flow and enforced again below, so a
# future client cannot weaken a template by skipping a wizard step.
_TEMPLATE_CONTRACTS = {
    "route": {
        "kind": "route",
        "label": "Routing",
        "applicationType": "route",
        "displayMode": "map",
        "fieldRoles": [
            {"key": "title", "label": "Record title", "required": True, "types": []},
            {"key": "latitude", "label": "Latitude", "required": False,
             "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
            {"key": "longitude", "label": "Longitude", "required": False,
             "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
            {"key": "address", "label": "Address", "required": False,
             "types": ["text"]},
        ],
        "defaultPlacement": {"section": "app", "order": 0},
    },
    "catalog": {
        "kind": "catalog",
        "label": "Catalog",
        # Catalog is a template discriminator over an existing trusted renderer contract.  The
        # client launches the Catalog surface from ``templateKind`` without growing the type
        # vocabulary shared by the registry and its consumers.
        "applicationType": "map",
        "displayMode": "map",
        "fieldRoles": [
            {"key": "key", "label": "Record key", "required": True, "types": []},
            {"key": "title", "label": "Record title", "required": True, "types": []},
            {"key": "image", "label": "Image", "required": False,
             "types": ["image", "attachment", "url", "text"]},
            {"key": "sku", "label": "SKU", "required": False, "types": []},
            {"key": "price", "label": "Price", "required": False,
             "types": ["int", "currency", "pct", "rating", "number", "float", "decimal"]},
            {"key": "category", "label": "Category", "required": False, "types": []},
            {"key": "description", "label": "Description", "required": False, "types": []},
        ],
        "defaultPlacement": {"section": "app", "order": 0},
    },
}

# C1 (S79-T01): every contract carries its catalogue row's wire metadata.
_C1_WIRE_KEYS = ("connector", "connectors", "purpose", "process", "mark", "view")
# R33: Routing and Catalog read their C1 source themselves, so the wizard asks for no database.
_BUNDLED_SOURCE_LABELS = {"customer_data": "Odoo customers", "product_data": "Odoo products"}
for _kind, _contract in _TEMPLATE_CONTRACTS.items():
    _contract.update({key: _app_templates.BY_KIND[_kind][key] for key in _C1_WIRE_KEYS})
    _contract.update(sourceDatabase=_app_templates.source(_kind),
                     sourceLabel=_BUNDLED_SOURCE_LABELS[_app_templates.source(_kind)])

# Keep stored copy identities readable after a template stops accepting new Apps.
APPLICATION_WIZARD_TEMPLATE_KINDS = tuple(_TEMPLATE_CONTRACTS)
APPLICATION_TEMPLATE_KINDS = tuple(_TEMPLATE_CONTRACTS)

#: S78-T17 (C4, R20, R21): templates offered only to a tenant that passes the kind's gate.
#: They stay out of the ungated tuples above, which other gates pin to Routing and Catalog.
#: S79-T01 (C1): every connector-gated kind in `app_templates.TEMPLATES` is one of them.
BRAND_ANALYTICS_DATABASE = "ut_amzn_brand_analytics"
# Wire fields a C1 row does not carry, per gated kind.
_GATED_WIRE = {
    "competitor_watch": {
        "fieldRoles": [
            {"key": "term", "label": "Search term", "required": True, "types": []},
        ],
        "sourceLabel": "Amazon brand analytics",
    },
}


def _source_label(database):
    """The connector table's label, so a refusal never names a `ut_` key."""
    try:
        from core import connector_spec
        return connector_spec.spec_for(database).label
    except Exception:                                                  # noqa: BLE001
        return None


def _gated_contract(row):
    # The screen reads the kind's own routes; the source names its connector database.
    if not _app_templates.validate_connectors(row):
        raise ValueError("An App template omits a source connector.")
    contract = {"kind": row["kind"], "label": row["label"],
                "applicationType": "map", "displayMode": "map", "fieldRoles": [],
                "defaultPlacement": {"section": "app", "order": 0},
                **{key: row[key] for key in _C1_WIRE_KEYS}}
    if row["sources"]:
        contract["sourceDatabase"] = row["sources"][0]
        contract["sourceLabel"] = _source_label(row["sources"][0])
    contract.update(copy.deepcopy(_GATED_WIRE.get(row["kind"], {})))
    return contract


_GATED_TEMPLATE_CONTRACTS = {row["kind"]: _gated_contract(row) for row in _app_templates.TEMPLATES
                             if row["kind"] not in _TEMPLATE_CONTRACTS}
GATED_TEMPLATE_KINDS = tuple(_GATED_TEMPLATE_CONTRACTS)


def _template_contract(kind):
    """The contract for an ungated or gated template kind, or None."""
    return _TEMPLATE_CONTRACTS.get(kind) or _GATED_TEMPLATE_CONTRACTS.get(kind)


def brand_analytics_holds(connected, enabled, refused):
    """R21: Amazon is connected, brand analytics is switched on and Amazon has not refused it."""
    return connected is True and enabled is True and refused is not True


def _brand_analytics_refused(runtime):
    """True when the mirror's last brand analytics pass was refused; unreadable is no evidence."""
    try:
        import duckdb
        from pathlib import Path
        from harness import amazon_store as az, datastore
        path = az._tenant_mirror_path(runtime.key, rt=runtime)
        if not path.is_file():
            return False
        query = "SELECT phase FROM _sync_state WHERE entity = ?"
        key = [az.entity_key("brand_analytics")]
        if path.resolve() == Path(datastore.DB_PATH).resolve():
            row = datastore.ro_cursor().execute(query, key).fetchone()
        else:
            with datastore.bounded_connection(duckdb.connect(str(path), read_only=True)) as cursor:
                row = cursor.execute(query, key).fetchone()
        return bool(row) and row[0] == "refused"
    except Exception as exc:                                           # noqa: BLE001
        raise_if_resource_error(exc)
        return False


def brand_analytics_offered(session):
    """R21 gate for the Competitor watch template. Any read failure withholds the template."""
    try:
        import connectors_amazon as cx
        from routes_connectors import _entry_types
        types, _scopes, failure = _entry_types(session.runtime, session.uname)
        connected = failure is None and cx.ENTRY_TYPE in set(types)
        enablement = cx.read_database_enablement(session.runtime)
        enabled = (enablement.get("available") is True
                   and (enablement.get("databases") or {}).get(BRAND_ANALYTICS_DATABASE) is True)
        refused = _brand_analytics_refused(session.runtime) if connected and enabled else None
        return brand_analytics_holds(connected, enabled, refused)
    except Exception as exc:                                           # noqa: BLE001
        raise_if_resource_error(exc)
        return False


def _connector_gate(connector):
    """C1 gate: the reader has the kind's connector (F25: the connector key, never a `ut_` prefix)."""
    def gate(session):
        return _app_templates.connector_present(connector, session)
    gate.connector = connector
    return gate


def _automation_offered(session):
    """Use Automation's current account and tenant wall without a connector requirement."""
    try:
        session.require("automation")
        return True
    except Exception as exc:
        raise_if_resource_error(exc)
        return False


# Competitor watch's gate already requires the Amazon connection; it adds brand analytics (R21).
_TEMPLATE_GATES = {kind: brand_analytics_offered if kind == "competitor_watch"
                   else _automation_offered if kind == "alerts"
                   else _connector_gate("amazon") if kind == "amazon_operator"
                   else _connector_gate(contract["connector"])
                   for kind, contract in _GATED_TEMPLATE_CONTRACTS.items()}
#: S79-T02 (instr 20): Routing and Catalog are offered only to a reader with Odoo.
_BUNDLED_GATES = {kind: _connector_gate(contract["connector"])
                  for kind, contract in _TEMPLATE_CONTRACTS.items()}


def template_offered(kind, session):
    """C1 offer predicate: the module imports, the router mounted and the kind's gate holds."""
    gate = _TEMPLATE_GATES.get(kind) or _BUNDLED_GATES.get(kind)
    if gate is None or _app_templates.held(kind) or not _app_templates.seams_ready(kind):
        return False
    try:
        return bool(gate(session))
    except Exception as exc:                                           # noqa: BLE001
        raise_if_resource_error(exc)
        return False


class ApplicationError(ValueError):
    pass


def account_capacity():
    """The per-account App cap. `AIOS_APP_CAPACITY` lowers it for one server, as a lane proof does."""
    import os
    raw = str(os.environ.get("AIOS_APP_CAPACITY") or "").strip()
    return min(int(raw), _MAX) if raw.isdigit() else _MAX


def capacity_refusal(doc, user):
    """D-8392: the sentence naming the cap when `user` already holds it, else None."""
    cap = account_capacity()
    held = sum(1 for app in (doc.get("applications") or {}).values()
               if isinstance(app, dict) and app.get("createdBy") == user and app.get("retired") is not True)
    if held < cap:
        return None
    return f"Your account can hold up to {cap} App{'' if cap == 1 else 's'}. Delete an App to add another."


class ApplicationRuleError(ApplicationError):
    """Expose an App rule refusal through every writer's existing error handler."""
    code = "app_rule"

    def __init__(self, refusal):
        self.rule = refusal.rule
        super().__init__(str(refusal))


APP_EXISTS_MESSAGE = "This App is already in this workspace. Ask its owner to share it."


class ApplicationExistsError(ApplicationError):
    """A live copy of this template App is in the tenant and the caller may not read it."""
    code = "template_app_exists"

    def __init__(self, existing=None):
        super().__init__(APP_EXISTS_MESSAGE)
        self.existing = existing


class _TemplateHeld(Exception):
    """A live copy of the template App holds the tenant's one slot."""

    def __init__(self, live):
        super().__init__("template App exists")
        self.live = live


def template_identity(app):
    """Return the grouping key for template copies, including each separate Finance template."""
    if not isinstance(app, dict):
        return None
    kind = str(app.get("templateKind") or "")
    if kind == FINANCE_TEMPLATE_KIND:
        key = str(app.get("financeKey") or "")
        return f"{FINANCE_TEMPLATE_KIND}:{key}" if key else None
    # S79-T05: a connector-gated copy is grouped too, so the App directory can show Added.
    return kind if kind in APPLICATION_WIZARD_TEMPLATE_KINDS + GATED_TEMPLATE_KINDS else None


def _refuse_template_held(applications, identity):
    """Raise `_TemplateHeld` with every live copy of `identity`, oldest first, when one exists."""
    if not identity:
        return
    live = sorted((app for app in applications.values()
                   if isinstance(app, dict) and app.get("retired") is not True
                   and template_identity(app) == identity),
                  key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
    if live:
        raise _TemplateHeld(live)


def _sole_holder(app, copies):
    """True when every other live copy of `app`'s template is its creator's own and unshared.

    Only then does a tenant share list no account a second copy of the template.
    """
    creator = app.get("createdBy")
    return all(other.get("id") == app.get("id")
               or (other.get("createdBy") == creator
                   and (other.get("share") or {}).get("mode") != "tenant"
                   and not (other.get("share") or {}).get("users"))
               for other in copies)


def own_template_apps(runtime, user, is_admin=False):
    """Return every template copy the App home lists for the caller, grouped by template identity.

    `is_admin` stays for the callers and is unused: the gallery's Added and the App home share `_listed`.
    """
    owned = {}
    apps = sorted((app for app in load(runtime)["applications"].values() if isinstance(app, dict)),
                  key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
    for app in apps:
        identity = template_identity(app)
        if identity and _listed(app, user):
            owned.setdefault(identity, []).append(
                {"id": app.get("id"), "name": app.get("name"),
                 "deepLink": app.get("deepLink"), "sourceDatabase": app.get("sourceDatabase")})
    return owned


def template_contracts(session=None):
    """The trusted renderer contracts offered by the Application creation flow.

    With a session, every template is offered only when the reader has its connector (instr 20).
    """
    if session is None:
        return _ungated_template_contracts()
    have = _app_templates.connectors_present(session)
    rows = [copy.deepcopy(contract) for contract in _TEMPLATE_CONTRACTS.values()
            if contract["connector"] in have]
    rows.extend(copy.deepcopy(contract) for kind, contract in _GATED_TEMPLATE_CONTRACTS.items()
                if template_offered(kind, session))
    return rows


def _ungated_template_contracts():
    return [copy.deepcopy(contract) for contract in _TEMPLATE_CONTRACTS.values()]


def finance_group():
    """The one immutable Finance group consumed by navigation and direct-link routes."""
    return _finance_group()


def finance_applications(may_open=None):
    """Six separately addressable Finance application descriptors."""
    return _finance_applications(may_open=may_open)


def finance_application_records(may_open=None):
    """Keep the retired Finance App projection empty for legacy callers."""
    return []


_FINANCE_SCOPES = {"business_unit", "hq_consolidated", "all_channel_inventory"}


def _require_unavailable(value, context):
    if not isinstance(value, dict) or value.get("state") != "unavailable":
        raise RuntimeError(f"{context} must be explicitly unavailable")
    if "value" in value or not value.get("missingSource"):
        raise RuntimeError(f"{context} cannot fabricate a missing value")


def validate_finance_application_contract(app):
    """Fail closed when an app bypasses its declared workflow/dashboard or fact boundary."""
    key = str(app.get("key") or "unknown")
    mode = app.get("mode")
    worklist = app.get("worklist")
    dashboard = app.get("dashboard")
    fact_keys = set(app.get("factKeys") or ())
    if mode not in {"workflow", "dashboard"}:
        raise RuntimeError(f"invalid Finance application mode for {key}")
    if mode == "workflow":
        if not isinstance(worklist, dict) or dashboard:
            raise RuntimeError(f"invalid Finance worklist contract for {key}")
        source_fact = worklist.get("sourceFact")
        if source_fact:
            if source_fact not in fact_keys:
                raise RuntimeError(f"invalid Finance worklist source for {key}")
            required = ("ownerField", "statusField", "dueDateField", "nextAction")
            if not all(worklist.get(name) for name in required):
                raise RuntimeError(f"incomplete Finance worklist fields for {key}")
        elif worklist.get("kind") == "unavailable_requirements":
            signals = worklist.get("signals")
            if not isinstance(signals, list) or not signals:
                raise RuntimeError(f"Finance requirements worklist {key} has no signals")
            for signal in signals:
                _require_unavailable(signal, f"Finance work signal in {key}")
                if signal.get("scope") not in _FINANCE_SCOPES:
                    raise RuntimeError(f"Finance work signal in {key} has no governed scope")
                if not all(signal.get(name) for name in (
                        "key", "label", "basisLabel", "sourceModule", "validationMethod",
                        "ownerRole", "status", "nextAction")):
                    raise RuntimeError(f"Finance work signal in {key} is ungrounded")
                if signal.get("status") != "unavailable":
                    raise RuntimeError(f"Finance work signal in {key} claims executable state")
        else:
            raise RuntimeError(f"Finance worklist {key} has no governed source")
    elif worklist or not isinstance(dashboard, dict):
        raise RuntimeError(f"invalid Finance dashboard contract for {key}")

    for section in (dashboard or {}).get("sections", []):
        for metric in section.get("metrics", []):
            if metric.get("sourceFact") and metric["sourceFact"] not in fact_keys:
                raise RuntimeError(f"dashboard {key} references an ungoverned source fact")
            if metric.get("state") == "unavailable":
                _require_unavailable(metric, f"dashboard metric in {key}")
                if metric.get("scope") not in _FINANCE_SCOPES:
                    raise RuntimeError(f"dashboard metric in {key} has no governed scope")
                if not metric.get("basisLabel") or not metric.get("validationMethod"):
                    raise RuntimeError(f"dashboard metric in {key} is ungrounded")
        for row in section.get("rows", []):
            for column in ("actual", "budget", "prior"):
                cell = row.get(column) or {}
                if cell.get("state") == "fact" and cell.get("factKey") not in fact_keys:
                    raise RuntimeError(f"dashboard {key} references an ungoverned fact")
        for row in section.get("planningRows", []):
            if row.get("scope") not in _FINANCE_SCOPES or not row.get("basisLabel"):
                raise RuntimeError(f"planning row in {key} is ungrounded")
            actual = row.get("actual") or {}
            if actual.get("state") != "fact" or actual.get("factKey") not in fact_keys:
                raise RuntimeError(f"planning row in {key} references an ungoverned actual")
            for column in ("plan", "variance", "driver"):
                _require_unavailable(row.get(column), f"planning {column} in {key}")
    return True


def finance_application(key, may_open=None):
    """Resolve one Finance application without constructing a Finance-home payload."""
    app = _finance_application(key, may_open=may_open)
    validate_finance_application_contract(app)
    app["facts"] = _finance_fact_specs(app["factKeys"])
    app["kpis"] = _finance_fact_specs(app["kpiKeys"])
    return app


def blank_doc():
    return {"schema": 1, "applications": {}, "defaults": {}}


def _stored_doc(raw):
    """Encode code App bytes for JSONB without changing the public text contract."""
    doc = copy.deepcopy(raw)
    applications = doc.get("applications") if isinstance(doc, dict) else None
    for app in (applications or {}).values():
        if not isinstance(app, dict) or app.get("type") != "code":
            continue
        display = (app.get("config") or {}).get("display") or {}
        html = display.get("html")
        if isinstance(html, str):
            display["html"] = {"encoding": "utf8-base64-v1",
                               "data": base64.b64encode(html.encode("utf-8")).decode("ascii")}
    return doc


def _update_document(runtime, mutate, *, key=_KEY):
    """Keep every registry write, including migrations, safe for JSONB storage."""
    def apply(raw):
        return _stored_doc(mutate(raw))
    return runtime.update(key, apply)


def _clean_doc(raw):
    doc = blank_doc()
    if isinstance(raw, dict):
        if isinstance(raw.get("applications"), dict):
            doc["applications"] = copy.deepcopy(raw["applications"])
        if isinstance(raw.get("defaults"), dict):
            doc["defaults"] = copy.deepcopy(raw["defaults"])
        if isinstance(raw.get("migrations"), dict):
            doc["migrations"] = copy.deepcopy(raw["migrations"])
    for app in doc["applications"].values():
        if not isinstance(app, dict) or app.get("type") != "code":
            continue
        display = (app.get("config") or {}).get("display") or {}
        html = display.get("html")
        if (isinstance(html, dict) and set(html) == {"encoding", "data"}
                and html["encoding"] == "utf8-base64-v1"):
            display["html"] = base64.b64decode(html["data"], validate=True).decode("utf-8")
    return doc


def _app_projection(app):
    row = _app_templates.bound(app)
    if isinstance(row, dict):
        contract = _template_contract(str(row.get("templateKind") or ""))
        if contract and contract.get("view") and not contract.get("fieldRoles"):
            row = dict(row)
            row.setdefault("fieldMap", {})
    return row


def _record_documents(runtime):
    """Read independent App records through the tenant's existing document doors."""
    listing = getattr(runtime, "list_keys", None)
    if not callable(listing):
        return {}  # Legacy stores without document enumeration retain their original format.
    keys = listing(_RECORD_PREFIX)
    reader = getattr(runtime, "get_many", None)
    records = reader(keys) if keys and callable(reader) else None
    if records is None:
        records = {key: _read_strict(runtime, key) for key in keys}
    result = {}
    for key in keys:
        doc = _clean_doc(records.get(key))
        if len(doc["applications"]) > 1:
            raise ApplicationError("an App record must contain one App")
        for identity, app in doc["applications"].items():
            if (not isinstance(app, dict) or app.get("id") != identity
                    or app.get("tenant") != runtime.key):
                raise ApplicationError("the App record does not match its tenant")
        result[key] = doc
    return result


def _application_key(runtime, app_id):
    for key, doc in _record_documents(runtime).items():
        if app_id in doc["applications"]:
            return key
    return _KEY


def _request_memo():
    """`(accumulator, table, epoch)` for one registry read per request, or None outside a request.

    The epoch is taken before the read: a store write moves it, so a later load reads again."""
    from core import request_timing
    acc = request_timing.CURRENT.get()
    if acc is None or acc.closed or acc.read_memo_ended:
        return None
    with acc.lock:
        return acc, acc.__dict__.setdefault("application_registry_memo", {}), acc.read_memo_epoch


def load(runtime, *, strict=False):
    """The read door: a Routing or Catalog App carries its C1 binding (`app_templates.bound`)."""
    memo, key = _request_memo(), (getattr(runtime, "key", None), id(runtime))
    if memo is not None:
        acc, table, epoch = memo
        with acc.lock:
            hit = table.get(key)
            if hit and hit[0] == epoch == acc.read_memo_epoch:
                return copy.deepcopy(hit[1])
    try:
        doc = _clean_doc(runtime.get(_KEY))
        for record in _record_documents(runtime).values():
            doc["applications"].update(record["applications"])
    except Exception as exc:
        if strict:
            raise
        raise_if_resource_error(exc)
        return blank_doc()
    doc["applications"] = {app_id: _app_projection(app)
                           for app_id, app in doc["applications"].items()}
    if memo is not None:
        with acc.lock:
            table[key] = (epoch, copy.deepcopy(doc))
    return doc


_AVAILABILITY_MESSAGES = {
    "router_unavailable": "This App cannot open because its routes are unavailable.",
    "no_grant": "Your access limit prevents this App from reading its source.",
    "not_connected": "Connect the App's connector in Connectors to open this App.",
    "refreshing": "This App's source is refreshing and opens when the refresh ends",
    "no_rows": "This App has no source rows yet.",
    "source_unavailable": "This App cannot read its source right now.",
    "held": "This App is not available yet.",
}


def availability_reason(state, connector=None):
    """The public reason vocabulary contains no exception or configuration text."""
    message = _AVAILABILITY_MESSAGES.get(state)
    if state == "not_connected":
        label = {"amazon": "Amazon", "amazon_ads": "Amazon Ads", "odoo": "Odoo"}.get(connector)
        if label:
            message = f"Connect {label} in Connectors to open this App."
    return {"state": state, "message": message,
            "lock": "Access limit" if state == "no_grant" else None}


def _mount_reason(kind):
    catalogue = _app_templates.BY_KIND.get(str(kind or ""))
    if catalogue and catalogue["router"] in _app_templates.router_failures():
        return availability_reason("router_unavailable")
    return None


def _source_rows_exist(session, sources):
    """Probe at most one row per declared mirror source in the session's tenant."""
    import contextlib
    import stat
    import duckdb
    from pathlib import Path
    from core import connector_spec
    from harness import amazon_store, datastore

    specs = [connector_spec.spec_for(source) for source in sources]
    if any(spec is None for spec in specs):
        raise RuntimeError("App source is not a declared mirror table")
    path = amazon_store._tenant_mirror_path(session.tenant, rt=session.runtime)
    try:
        mode = path.stat().st_mode
    except FileNotFoundError:
        return False
    if not stat.S_ISREG(mode):
        raise RuntimeError("App mirror is not a database file")
    shared = path.resolve() == Path(datastore.DB_PATH).resolve()
    cursor = (datastore.ro_cursor() if shared else
              datastore.bounded_connection(duckdb.connect(str(path), read_only=True)))
    with contextlib.closing(cursor):
        for spec in specs:
            present = cursor.execute(
                "SELECT 1 FROM information_schema.tables WHERE table_schema = 'main' "
                "AND table_name = ? LIMIT 1", [spec.source]).fetchone()
            if present:
                table = '"' + spec.source.replace('"', '""') + '"'
                if cursor.execute(f"SELECT 1 FROM {table} LIMIT 1").fetchone():
                    return True
    return False


def _reports_readable(runtime, user, is_admin):
    """Report grants admit the Reports App independently of its App sharing record."""
    try:
        from modules import reports
    except Exception as exc:  # A failed Reports import withholds its App.
        raise_if_resource_error(exc)
        return False
    return bool(is_admin or reports.granted_keys(runtime, user))


def _readable_template_app(session, app_id):
    """Resolve App identity before reading any source or exposing a refusal."""
    from deps import err
    if (session.tenant != getattr(session.runtime, "key", None)
            or session.tenant != getattr(getattr(session.runtime, "tenant", None), "key", None)):
        raise err(404, "app_not_found", "This App is unavailable or is not shared with you.")
    try:
        app = load(session.runtime, strict=True)["applications"].get(app_id)
    except Exception:
        raise err(503, "app_unavailable", "This App cannot be read right now.") from None
    if (not isinstance(app, dict) or app.get("id") != app_id or app.get("tenant") != session.tenant
            or app.get("retired") is True
            or not (_reports_readable(session.runtime, session.uname, session.admin)
                    if app.get("templateKind") == "reports"
                    else may_read(app, session.uname, session.admin))):
        raise err(404, "app_not_found", "This App is unavailable or is not shared with you.")
    kind = app.get("templateKind")
    catalogue = _app_templates.BY_KIND.get(str(kind or ""))
    if not catalogue or not catalogue["view"]:
        raise err(404, "app_not_found", "This App is unavailable or is not shared with you.")
    if kind == "alerts":
        session.require("automation")
    return app, catalogue


#: R62: App kinds whose readers apply a source row and field wall to their own rows.
#: Any other kind refuses its App while such a wall applies, because it cannot narrow.
NARROWING_KINDS = frozenset({"account_health", "opportunity_finder", "ranking_diagnostic", "repeat_buyers"})


def app_access(user, runtime, app, sources):
    """R46, R62: the one source-wall answer for an App, its Dashboard and its readers.

    Takes a user record, not a session, so a digest can ask for any recipient. Returns
    `app` and `dashboard` ("ready" or refused), the Dashboard refusal's `status`, `code`
    and one-line `message`, and `narrow`: per source, the row wall and hidden field keys.
    """
    from core import perm_scope, perms, route_system, user_tables
    from core.request_timing import remaining_budget

    user = user if isinstance(user, dict) else {}
    kind = app.get("templateKind") if isinstance(app, dict) else None
    granted = may_read(app, user.get("username"), perms.is_admin(user))
    refusal = []

    def refuse(status, code, message):
        refusal.append((status, code, message))

    all_units = "All" in perms.allowed_bu_labels(user)
    raw_units = user.get("bus", "all")
    if raw_units != "all":
        from core import users
        by_label = {label: key for key, label in users.BU_LABELS.items()}
        identities = []
        valid_units = isinstance(raw_units, (tuple, list)) and bool(raw_units)
        for unit in raw_units if valid_units else ():
            if type(unit) is int and unit in users.BU_LABELS:
                identities.append(unit)
            elif isinstance(unit, str) and unit in by_label:
                identities.append(by_label[unit])
            elif unit != "All":
                valid_units = False
        all_units = bool(valid_units and identities) and "All" in perms.allowed_bu_labels(dict(user, bus=identities))
    if not all_units:
        refuse(403, "app_dashboard_scope", "The Dashboard needs access to every business unit.")
    elif perms.scope_agent(user) is not None:
        refuse(403, "app_dashboard_scope", "The Dashboard needs access to every salesperson's records.")
    if not isinstance(sources, (tuple, list)) or not sources:
        refuse(503, "app_dashboard_sources", "The Dashboard has no source to read.")
        sources = ()
    config = getattr(getattr(runtime, "tenant", None), "config", None) or {}
    enabled = config.get("modules", "all")
    narrow = {}
    for source in sources:
        remaining_budget()
        label = _source_label(source) or "a source database"
        definition = user_tables.get_definition(source, st=runtime)
        fields = definition.get("fields") if isinstance(definition, dict) else None
        declared = perm_scope.entry(user, source) or {}
        walled = bool(perm_scope.wall_declared(user, source, st=runtime, defn=definition))
        rows = bool(declared.get("filter")) or bool(
            fields and perm_scope.row_scope_applies(user, source, st=runtime, defn=definition))
        hidden = set(declared.get("hiddenFields") or ()) | set(
            perm_scope.hidden_keys(user, source, fields, st=runtime) if fields else ())
        narrow[source] = {"rows": rows or (walled and not hidden), "hidden": tuple(sorted(map(str, hidden)))}
        # The Dashboard totals the raw source, so it keeps the source grant and refuses any narrowing.
        if (enabled != "all" and source not in (enabled or ())) or not perm_scope.may_read(user, source, st=runtime):
            refuse(403, "app_dashboard_source", f"The Dashboard needs read access to {label}.")
        elif not fields:
            refuse(503, "app_dashboard_source", f"The Dashboard cannot read {label} right now.")
        elif (declared.get("access") is False or walled or rows or hidden
              or route_system.is_managed(definition) or route_system.is_managed(source)):
            refuse(403, "app_dashboard_scope", f"The Dashboard needs {label} without a row or field limit.")
    narrowed = any(wall["rows"] or wall["hidden"] for wall in narrow.values())
    status, code, message = refusal[0] if refusal else (None, None, None)
    return {"app": "ready" if granted and (kind in NARROWING_KINDS or not narrowed) else "no_grant",
            "dashboard": "ready" if not refusal else "refused",
            "status": status, "code": code, "message": message, "narrow": narrow}


def app_source_scope(user, runtime, source, *, app, records=None):
    """Return source fields and row identities after live admission of the named App."""
    from core import perm_scope
    # Importing the API adapter registers the core admission callback.
    import routes_app_dashboard
    fields, rows = perm_scope.scoped_app_source(
        user, source, st=runtime, app_id=app.get("id") if isinstance(app, dict) else None, records=records)
    identity = "__scope_key" if records is not None else "pid"
    return {str(field["key"]) for field in fields if field.get("key")}, {
        str(row[identity]) for row in rows if identity in row}


def readable_app(runtime, tenant, uname, is_admin, kind):
    """The caller's live readable App of `kind` in `tenant`, their own copy first, or None."""
    apps = [row for _key, row in sorted(load(runtime)["applications"].items())
            if isinstance(row, dict) and row.get("templateKind") == kind and row.get("tenant") == tenant
            and row.get("retired") is not True and may_read(row, uname, is_admin)]
    return next((row for row in apps if row.get("createdBy") == uname), apps[0] if apps else None)


def admit_app(session, app, sources, *, code):
    """R62: admit an App read on the App grant plus `app_access`, never the source open grant."""
    from deps import err
    if (session.tenant != getattr(session.runtime, "key", None)
            or session.user.get("tenant", session.tenant) != session.tenant
            or not isinstance(app, dict) or app.get("tenant") != session.tenant
            or app.get("retired") is True or not may_read(app, session.uname, session.admin)):
        raise err(404, f"{code}_app_not_found", "This App is unavailable or is not shared with you.")
    access = app_access(session.user, session.runtime, app, sources)
    if access["app"] != "ready":
        raise err(403, f"{code}_limited", "This App cannot apply your access limit on its source.")
    return access


def _availability_for_app(session, app, catalogue):
    kind = app["templateKind"]
    if _app_templates.held(kind):
        return availability_reason("held")
    mount = _mount_reason(kind)
    if mount:
        return mount
    if not _app_templates.seams_ready(kind):
        return availability_reason("router_unavailable")
    if kind == "alerts":
        return availability_reason("ready" if _automation_offered(session) else "no_grant")
    from routes_connectors import _entry_types
    amazon = catalogue.get("connector") in ("amazon", "amazon_ads")
    dashboard = {"state": "source_unavailable", "message": _AVAILABILITY_MESSAGES["source_unavailable"]}

    def reason(state, connector=None):
        result = availability_reason(state, connector)
        return {**result, "dashboard": dashboard} if amazon else result

    try:
        sources = catalogue["sources"]
        if amazon:
            # Availability and the Dashboard use one source-wall answer.
            access = app_access(session.user, session.runtime, app, sources)
            dashboard = {"state": "ready" if access["dashboard"] == "ready" else
                         "no_grant" if access["status"] == 403 else "source_unavailable",
                         "message": access["message"]}
            if access["app"] != "ready":
                return reason("no_grant")
        else:
            from core import perm_scope
            for source in sources:
                if (not perm_scope.may_read(session.user, source, st=session.runtime)
                        or perm_scope.wall_declared(session.user, source, st=session.runtime)):
                    return reason("no_grant")
        types, _scopes, failure = _entry_types(session.runtime, session.uname)
        if failure is not None:
            return reason("source_unavailable")
        connected = _app_templates.entry_type(catalogue["connector"]) in set(types or ())
        if not connected and catalogue["connector"] == "odoo":
            from routes_keychain import env_odoo_available
            connected = env_odoo_available(session.runtime)
        if not connected:
            return reason("not_connected", catalogue["connector"])
        row_sources = ((*sources, *catalogue.get("optional_sources", ()))
                       if kind == "repeat_buyers" else sources)
        if amazon:
            from harness.mirror_store import restore_in_progress
            if restore_in_progress(session.tenant, catalogue["connector"]):
                return reason("refreshing")
        if row_sources and not _source_rows_exist(session, row_sources):
            return reason("no_rows")
    except Exception as exc:                                           # noqa: BLE001
        if amazon:
            raise_if_resource_error(exc)
        return reason("source_unavailable")
    return reason("ready")


def availability(session, app_id):
    """Resolve a named App without weakening its tenant, sharing or source permissions."""
    app, catalogue = _readable_template_app(session, app_id)
    return _availability_for_app(session, app, catalogue)


def opening(session, app_id):
    """Return only frame metadata and availability for a standalone template App."""
    app, catalogue = _readable_template_app(session, app_id)
    return {"application": {
        "id": app["id"], "name": app["name"], "templateKind": catalogue["kind"],
        "templateView": catalogue["view"], "templateMark": catalogue["mark"],
        "templateConnector": catalogue["connector"], "fieldMap": {},
        "capabilities": {"read": True, "edit": may_edit(app, session.uname, session.admin)},
    }, "availability": _availability_for_app(session, app, catalogue)}


def _server_origin(origin_door=None, via=None):
    """Stamp the authenticated server door without inferring it from a display label."""
    door = "app" if origin_door is None and via is None else origin_door
    if door not in ("app", "mcp", "loopy"):
        raise ApplicationError("Set origin_door from the authenticated call path.")
    if door == "mcp":
        if not isinstance(via, str) or not via.strip():
            raise ApplicationError("An MCP App needs its credential's label.")
        label = via
    else:
        label = "Loopy" if door == "loopy" else "App"
    return {"door": door, "label": label}


def count_by_origin(runtime, tenant):
    """Count this tenant's stored Apps per door, treating older Apps as personal builds."""
    counts = {"app": 0, "mcp": 0, "loopy": 0}
    for app in load(runtime)["applications"].values():
        if not isinstance(app, dict) or str(app.get("tenant")) != str(tenant):
            continue
        origin = app.get("origin")
        door = origin.get("door") if isinstance(origin, dict) else "app"
        if door in counts:
            counts[door] += 1
    return counts


def _users(raw):
    out=[]
    for item in raw if isinstance(raw, (list, tuple)) else ():
        got=str(item or "").strip()[:120]
        if got and got not in out: out.append(got)
    return out


def may_read(app, user, is_admin=False):
    if not isinstance(app, dict): return False
    if is_admin or app.get("createdBy") == user: return True
    share=app.get("share") if isinstance(app.get("share"), dict) else {}
    return share.get("mode") == "tenant" or user in set(share.get("users") or ())


def may_edit(app, user, is_admin=False):
    return bool(is_admin or (isinstance(app, dict) and app.get("createdBy") == user))


def _listed(app, user):
    """R102: the App home lists what the caller owns or was shared, for an Administrator too."""
    if not isinstance(app, dict) or app.get("retired") is True:
        return False
    if app.get("createdBy") == user:
        return True
    share = app.get("share") if isinstance(app.get("share"), dict) else {}
    return share.get("mode") == "tenant" or user in set(share.get("users") or ())


def _is_finance(app):
    return isinstance(app, dict) and app.get("templateKind") == FINANCE_TEMPLATE_KIND


def _database_free_code(app):
    """A code App can open without a database binding."""
    return (isinstance(app, dict) and app.get("type") == "code"
            and not app.get("compatibleDatabases"))


def _database_free(app):
    """A code App, or an App whose C1 kind names no source, opens without a database binding."""
    if _database_free_code(app):
        return True
    row = _app_templates.BY_KIND.get(str(app.get("templateKind") or "")) if isinstance(app, dict) else None
    return bool(row and not row["sources"] and not app.get("compatibleDatabases"))


def _finance_permission(app):
    try:
        return _finance_application(str(app.get("financeKey") or ""))["permissionKey"]
    except KeyError:
        return None


def _account_wall(runtime, user_record):
    """The `deps.Session.require` predicate for one account, without a request."""
    from core import perm_scope
    config = getattr(getattr(runtime, "tenant", None), "config", None) or {}
    modules = config.get("modules", "all") if isinstance(config, dict) else "all"

    def may_open(key):
        if not perm_scope.nav_may_open(user_record, key, st=runtime):
            return False
        return modules == "all" or str(key) in {str(item) for item in (modules or [])}
    return may_open


def _user_wall(runtime, user):
    """Resolve one username's wall from the account registry; fail closed on any read error."""
    try:
        from core import users
        record = (users.registry() or {}).get(user)
        if not isinstance(record, dict) or record.get("active") is False:
            return lambda _key: False
        public = users._public(user, record)
        if public.get("tenant") != getattr(runtime, "key", None):
            return lambda _key: False
        return _account_wall(runtime, public)
    except Exception:
        return lambda _key: False


def _compat(raw, *, allow_empty=False):
    values=[]
    for item in raw if isinstance(raw, (list, tuple)) else ():
        key=str(item or "").strip()[:120]
        if key and key not in values: values.append(key)
    if not values and not allow_empty:
        raise ApplicationError("at least one compatible database is required")
    return values


def _governed_bindings(raw, compatible, semantic_records):
    """Normalize role -> database -> approved field, refusing optimistic bindings."""
    if raw in (None, {}):
        return {}
    if not isinstance(raw, dict):
        raise ApplicationError("semanticRoleBindings must be an object")
    compatible = tuple(compatible or ())
    out = {}
    for raw_role, raw_binding in raw.items():
        role = str(raw_role or "").strip()[:80]
        if not role or not isinstance(raw_binding, dict):
            raise ApplicationError("every semantic role needs a binding object")
        # The first Wave shape was one flat binding.  Admit it only for one compatible database,
        # then store the canonical per-database shape.
        if "field" in raw_binding:
            database = str(raw_binding.get("database") or "").strip()
            if not database and len(compatible) == 1:
                database = compatible[0]
            bindings = {database: raw_binding} if database else {}
        else:
            bindings = raw_binding
        if set(bindings) != set(compatible):
            raise ApplicationError(
                f"semantic role {role!r} must be confirmed for every compatible database")
        per_database = {}
        for database in compatible:
            binding = bindings.get(database)
            if not isinstance(binding, dict) or binding.get("confirmed") is not True:
                raise ApplicationError(f"semantic role {role!r} is not confirmed for {database}")
            field = str(binding.get("field") or "").strip()[:120]
            records = semantic_records.get(database) if isinstance(semantic_records, dict) else None
            record = (records or {}).get(f"{database}::{field}") if field else None
            if not isinstance(record, dict) or record.get("state") != "approved":
                raise ApplicationError(
                    f"semantic role {role!r} needs an approved field in {database}")
            per_database[database] = {"field": field, "confirmed": True}
        out[role] = per_database
    return out


_CONFIG_MODE = {"chart": "chart", "route": "map", "map": "map", "code": "code"}


def _typed_config(kind, raw):
    if not isinstance(raw, dict):
        raise ApplicationError("config must be an object")
    if set(raw) - {"schemaVersion", "display"}:
        raise ApplicationError("config contains fields outside the typed Application contract")
    if raw.get("schemaVersion") != 1:
        raise ApplicationError("config schemaVersion must be 1")
    display = raw.get("display")
    if not isinstance(display, dict):
        raise ApplicationError("config.display must be an object")
    if str(display.get("mode") or "") != _CONFIG_MODE[kind]:
        raise ApplicationError(f"{kind} config has the wrong display mode")
    if kind == "code":
        html = display.get("html")
        if not isinstance(html, str):
            raise ApplicationError("App HTML must be text.")
        try:
            size = len(html.encode("utf-8"))
        except UnicodeEncodeError:
            raise ApplicationError("App HTML must be UTF-8 text.") from None
        if size > _MAX_DISPLAY_BYTES:
            raise ApplicationError("App HTML exceeds the 512 KB limit.")
        return {"schemaVersion": 1, "display": copy.deepcopy(display)}
    if kind == "chart":
        try:
            app_rules.validate_chart_display(display)
        except app_rules.RuleError as exc:
            raise ApplicationRuleError(exc) from None
    if len(json.dumps(display, ensure_ascii=False).encode("utf-8")) > _MAX_DISPLAY_BYTES:
        raise ApplicationError("The Application's layout is too large to save.")
    return {"schemaVersion": 1, "display": copy.deepcopy(display)}


def _allowed(compatible, allowed_databases):
    return (set(compatible or ()) if allowed_databases is None
            else set(compatible or ()) & set(allowed_databases))


def _contract_fields(database, semantic_records=None, field_contracts=None):
    """Return ``{field key: type}`` from a caller's already permission-scoped contract.

    The nav creation door supplies its served schema fields.  The older Application door supplies
    governed semantic records.  Supporting both here keeps one validator while never making this
    registry reach around either caller's database/field wall.
    """
    fields = {}
    raw = ((field_contracts or {}).get(database)
           if isinstance(field_contracts, dict) else None)
    if isinstance(raw, dict):
        raw = list(raw.values())
    for row in raw if isinstance(raw, (list, tuple)) else ():
        if not isinstance(row, dict):
            continue
        key = str(row.get("key") or row.get("field") or "").strip()
        if key:
            fields[key] = str(row.get("type") or row.get("dataType") or "").strip().lower()
    # A served schema is authoritative, including an empty or fully hidden field list.
    if isinstance(field_contracts, dict) and database in field_contracts:
        return fields
    records = ((semantic_records or {}).get(database)
               if isinstance(semantic_records, dict) else None)
    for row in (records or {}).values() if isinstance(records, dict) else ():
        if not isinstance(row, dict):
            continue
        key = str(row.get("field") or row.get("key") or "").strip()
        if key and key not in fields:
            fields[key] = str(row.get("dataType") or row.get("type") or "").strip().lower()
    return fields


class _ChartSchemaReader:
    """Keep schema reads on metadata doors, including inside a write preview."""
    def __init__(self, runtime):
        self._runtime = runtime
        self.schema_only = bool(getattr(runtime, "schema_only", False))

    def __getattr__(self, name):
        return getattr(self._runtime, name)

    def get(self, name, *args, **kwargs):
        if self.schema_only and name == "user_tables":
            raise AssertionError("chart schema cannot read row documents")
        return self._runtime.get(name, *args, **kwargs)

    def get_projection(self, name, drop=()):
        if self.schema_only and name == "user_tables" and "rows" not in drop:
            raise AssertionError("chart schema must omit rows")
        return self._runtime.get_projection(name, drop=drop)

    def get_entry(self, name, entry):
        if self.schema_only and (name == "user_tables" or entry in ("rows", "cells", "overlays")):
            raise AssertionError("chart schema cannot read row entries")
        return self._runtime.get_entry(name, entry)

    def _read_strict(self, name):
        if self.schema_only and name == "user_tables":
            raise AssertionError("chart schema cannot read row documents")
        return self._runtime._read_strict(name)


def chart_field_contracts(session, databases):
    """Borrow the caller's schema door with a strict reader that cannot load row documents."""
    from routes_customers import _AssemblyStore
    from routes_nav import nav_schema
    from core import user_tables

    scoped = copy.copy(session)
    scoped.runtime = _AssemblyStore(session.runtime, schema_only=True)
    # Preview projections load whole documents, so borrow unchanged schema from their source.
    if type(session.runtime).__name__ == "_PreviewRuntime":
        scoped.runtime = _AssemblyStore(session.runtime._real, schema_only=True)
    scoped.runtime = _ChartSchemaReader(scoped.runtime)
    contracts = {}
    for database in dict.fromkeys(databases or ()):
        fields = copy.deepcopy(nav_schema(database, session=scoped)["fields"])
        if database.startswith("ut_"):
            definitions = user_tables.all_defs(st=scoped.runtime)
            declared = {row["key"]: row for row in
                        (definitions.get(database) or {}).get("fields", [])}
            # The schema door chooses readable keys; declarations supply only their options.
            for field in fields:
                definition = declared.get(field.get("key"), {})
                for key in ("options", "choices"):
                    if key in definition:
                        field[key] = copy.deepcopy(definition[key])
        contracts[database] = fields
    return contracts


def _validate_chart_rules(app, *, semantic_records=None, field_contracts=None):
    """Check authored charts against caller-supplied field metadata, never stored row values."""
    if app.get("type") != "chart":
        return []
    display = (app.get("config") or {}).get("display") or {}
    if _is_finance(app) and not display.get("charts"):
        return []
    fields_by_database = {}
    for database in app.get("compatibleDatabases") or ():
        fields = {}
        records = (semantic_records or {}).get(database) or {}
        for row in records.values():
            if isinstance(row, dict) and row.get("state") == "approved":
                key = row.get("field") or row.get("key")
                if key:
                    fields[key] = row
        supplied = (field_contracts or {}).get(database) or []
        for row in supplied.values() if isinstance(supplied, dict) else supplied:
            if isinstance(row, dict):
                key = row.get("key") or row.get("field")
                if key:
                    fields[key] = row
        fields_by_database[database] = fields
    try:
        app_rules.validate_text(app.get("name"), "the App name")
        app_rules.validate_chart_display(display)
        return app_rules.validate_chart_bindings(display, fields_by_database)
    except app_rules.RuleError as exc:
        raise ApplicationRuleError(exc) from None


def _validate_catalog_rules(app):
    """Check Catalog content on writes while leaving saved records readable unchanged."""
    if app.get("templateKind") != "catalog":
        return
    try:
        app_rules.validate_catalog_display(app["config"]["display"])
    except app_rules.RuleError as exc:
        raise ApplicationRuleError(exc) from None


def _refuse_legacy_catalog_changes(app, config):
    """Freeze the old collection before or after its first migration to independent records."""
    if app.get("templateKind") != "catalog":
        return
    before = (app.get("config") or {}).get("display") or {}
    after = config["display"]
    # Compare JSON types too, so an authored numeric value cannot silently become a boolean.
    if (("catalogs" in before) == ("catalogs" in after)
            and json.dumps(before.get("catalogs"), sort_keys=True)
            == json.dumps(after.get("catalogs"), sort_keys=True)):
        return
    raise ApplicationError(
        "Catalogs now live in separate records, and config.display.catalogs migrates only once. "
        "Existing Catalog Apps cannot change that legacy collection. "
        f"Use POST /api/v1/apps/{app['id']}/catalogs or PATCH/DELETE /api/v1/catalogs/{{id}}, "
        "or catalog_build, to change catalog records.")


def _template_definition(kind, payload, *, semantic_records=None, field_contracts=None,
                         allowed_databases=None):
    """R33: a template App binds its C1 source and fixed field map; the caller names neither."""
    contract = _TEMPLATE_CONTRACTS.get(kind) or _GATED_TEMPLATE_CONTRACTS.get(kind)
    if contract is None:
        raise ApplicationError("application template kind is not recognized")
    template_kind = str(payload.get("templateKind") or "").strip().lower()
    if template_kind != kind:
        raise ApplicationError(f"{kind} applications require templateKind {kind!r}")
    named = str(payload.get("sourceDatabase") or "").strip()[:120]
    source = _app_templates.source(kind) or named
    # A C1 kind with no declared sources reads its own routes without a database binding.
    sourceless = kind in _app_templates.BY_KIND and not _app_templates.BY_KIND[kind]["sources"]
    if sourceless:
        if named or payload.get("compatibleDatabases"):
            raise ApplicationError(f"{contract['label']} reads no database. Remove the source database.")
    elif not source:
        raise ApplicationError("sourceDatabase is required")
    elif named and named != source:
        raise ApplicationError(f"{contract['label']} reads "
                               f"{contract.get('sourceLabel') or source} only. "
                               "Choose it as the source database.")
    elif source not in set(allowed_databases or ()):
        raise PermissionError("an Application cannot bind a database you cannot open")
    if not sourceless and "compatibleDatabases" in payload:
        compatible = _compat(payload.get("compatibleDatabases"))
        if compatible != [source]:
            raise ApplicationError("a template Application has exactly one sourceDatabase")
    # A legacy caller may still send a field map: the fixed binding replaces it.
    binding = {} if sourceless else _app_templates.field_binding(kind)
    if binding:
        available = _contract_fields(source, semantic_records, field_contracts)
        if not available:
            raise ApplicationError("the source database has no readable field contract")
        unreadable = sorted(role["label"] for role in contract["fieldRoles"]
                            if role["required"] and binding.get(role["key"]) not in available)
        if unreadable:
            raise ApplicationError(f"{contract['label']} needs fields your account cannot read: "
                                   + ", ".join(unreadable) + ". Ask an administrator for access.")

    raw_placement = payload.get("navPlacement") or contract["defaultPlacement"]
    if not isinstance(raw_placement, dict) or set(raw_placement) != {"section", "order"}:
        raise ApplicationError("navPlacement must contain section and order")
    section = str(raw_placement.get("section") or "").strip().lower()
    order = raw_placement.get("order")
    if section != "app":
        raise ApplicationError("template Applications must be placed in App")
    if isinstance(order, bool) or not isinstance(order, int) or not 0 <= order <= 999:
        raise ApplicationError("navPlacement order must be an integer from 0 to 999")
    definition = {"templateKind": kind, "compatibleDatabases": [] if sourceless else [source],
                  "navPlacement": {"section": "app", "order": order}}
    if kind not in _app_templates.BOUND_KINDS and not sourceless:
        definition.update(sourceDatabase=source, fieldMap=binding)
    return definition


def bound_application(app, available):
    """The App with its field map read against the caller's `{field: type}` schema.

    A C1 binding drops an optional role the caller cannot read. A stored map stays strict.
    """
    stored = bool(isinstance(app, dict) and app.get("fieldMap"))
    row = _app_templates.bound(app)
    contract = _template_contract(str(row.get("templateKind") or "")) or {}
    roles = {role["key"]: role for role in contract.get("fieldRoles") or ()}
    resolved = {}
    for role, field in (row.get("fieldMap") or {}).items():
        spec = roles.get(role)
        if spec is None:
            raise ApplicationError(f"fieldMap role {role!r} is outside the template contract")
        types = set(spec.get("types") or ())
        if field in available and (not types or available[field] in types):
            resolved[role] = field
        elif stored or spec["required"]:
            raise ApplicationError(f"fieldMap role {role!r} does not name a readable source field")
    return {**row, "fieldMap": resolved}


def validate_application(payload, tenant, *, semantic_records=None, field_contracts=None,
                         allowed_databases=None):
    """Validate the server-authored identity/tenant envelope and any template definition."""
    payload = payload if isinstance(payload, dict) else {}
    if "origin" in payload:
        raise ApplicationError("Loopable sets origin. Remove origin from the request.")
    if payload.get("id") not in (None, ""):
        raise ApplicationError("application id is server assigned")
    if "tenant" in payload and str(payload.get("tenant") or "") != str(tenant):
        raise PermissionError("an Application cannot be created for another tenant")
    template_kind = str(payload.get("templateKind") or "").strip().lower()
    gated = _GATED_TEMPLATE_CONTRACTS.get(template_kind)
    if gated is not None:
        if str(payload.get("type") or gated["applicationType"]).strip().lower() != gated["applicationType"]:
            raise ApplicationError(
                f"{template_kind} template Applications require type {gated['applicationType']!r}")
        return _template_definition(
            template_kind, payload, semantic_records=semantic_records,
            field_contracts=field_contracts, allowed_databases=allowed_databases)
    if template_kind and template_kind not in _TEMPLATE_CONTRACTS:
        raise ApplicationError("application template kind is not recognized")
    expected_type = (_TEMPLATE_CONTRACTS[template_kind]["applicationType"]
                     if template_kind else "")
    kind = str(payload.get("type") or expected_type).strip().lower()
    if kind not in APPLICATION_TYPES:
        raise ApplicationError("application type is not recognized")
    if kind == "chart":
        raw_config = payload.get("config")
        config = _typed_config(kind, raw_config)
        _validate_chart_rules(
            {"type": kind, "templateKind": template_kind, "name": payload.get("name"),
             "config": config, "compatibleDatabases": payload.get("compatibleDatabases")},
            semantic_records=semantic_records, field_contracts=field_contracts)
    if template_kind:
        if kind != expected_type:
            raise ApplicationError(
                f"{template_kind} template Applications require type {expected_type!r}")
        return _template_definition(
            template_kind, payload, semantic_records=semantic_records,
            field_contracts=field_contracts, allowed_databases=allowed_databases)
    if any(key in payload for key in ("sourceDatabase", "fieldMap", "navPlacement")):
        raise ApplicationError("only a template Application may carry template fields")
    return {}


def _public(app, user, is_admin=False, *, allowed_databases=None, target_database=None,
            is_default=False, readable=None):
    row=copy.deepcopy(_app_projection(app))
    row.setdefault("origin", None)
    if row.get("type") == "code":
        # Only the authenticated code door returns the body.
        row["config"]["display"].pop("html", None)
    compatible = [database for database in row.get("compatibleDatabases") or ()
                  if database in _allowed(row.get("compatibleDatabases"), allowed_databases)]
    row["compatibleDatabases"] = compatible
    app_readable = may_read(app, user, is_admin)
    row["capabilities"]={"read":app_readable if readable is None else readable,"edit":may_edit(app,user,is_admin),
                         "share":may_edit(app,user,is_admin),"delete":may_edit(app,user,is_admin),
                         "duplicate":app_readable,"star":app_readable,
                         "default":bool(is_admin)}
    row["starred"] = user in (app.get("starredBy") or ())
    row["isDefault"] = bool(is_default)
    catalogue = _app_templates.BY_KIND.get(str(row.get("templateKind") or ""))
    if catalogue and catalogue["view"]:
        # C2: the client mounts apps/<templateView>/AppView.tsx and fills the two marks.
        row.update(templateView=catalogue["view"], templateMark=catalogue["mark"],
                   templateConnector=catalogue["connector"])
        row["deepLink"] = f"/app/template/{row['id']}"
        mount = _mount_reason(row.get("templateKind"))
        if mount:
            row["availability"] = mount
        elif (catalogue.get("connector") not in ("amazon", "amazon_ads")
              and not _database_free(app) and not compatible):
            row["availability"] = availability_reason("no_grant")
    if row.get("templateKind") == FINANCE_TEMPLATE_KIND:
        # A Finance App is a user's own copy: owner controls apply. Defaults bind a database.
        row["capabilities"]["default"] = False
        row["isDefault"] = False
    if row.get("type") == "code":
        row["capabilities"]["default"] = False
    target_database = target_database if target_database in compatible else (compatible[0] if compatible else None)
    row["openTarget"]={"kind":"application","id":row["id"],"type":row["type"],
                       "database":target_database}
    return row


#: `core.table_store.RESERVED_MEMBERS`: workspace members that are registries, not users.
_RESERVED_WORKSPACE_MEMBERS = ("__shared__", "__assigned__", "__audit__")


def dependent_view_counts(runtime, database):
    """S67-T39 / R36: {app_id: number of saved Views on `database` bound to it}, over EVERY
    user's Views in that database's workspace. The Delete App dialog names this count before
    confirm. None when the workspace cannot be read, so the dialog never states a guessed 0.

    D-2233: it walks the Views `delete` clears, nested and `presentation` ones too, trash excepted.
    """
    from core.view_templates import workspace_key
    key = workspace_key(database)
    if not key:
        return {}
    try:
        doc = runtime.get(key)
    except Exception:
        return None
    counts = {}
    users = {member: bucket for member, bucket in (doc.items() if isinstance(doc, dict) else ())
             if member not in _RESERVED_WORKSPACE_MEMBERS}
    for view in _workspace_views(users, trash=False):
        for app_id in _view_app_ids(view):
            counts[app_id] = counts.get(app_id, 0) + 1
    return counts


def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starred=None,
              allowed_databases=None, may_open=None):
    """List Applications. Unfiltered is the App home; a database filter is how a View resolves."""
    doc = load(runtime)
    rows=[]
    reports_reader = None
    for app in doc["applications"].values():
        if (isinstance(app, dict) and getattr(runtime, "key", None)
                and app.get("tenant") != runtime.key):
            continue
        if _app_templates.held(app):
            continue
        if (isinstance(app, dict) and app.get("templateKind") == "alerts"
                and not (may_open or _user_wall(runtime, user))("automation")):
            continue
        report_app = isinstance(app, dict) and app.get("templateKind") == "reports"
        if report_app:
            if reports_reader is None:
                reports_reader = _reports_readable(runtime, user, is_admin)
            if not reports_reader or app.get("retired") is True:
                continue
        if isinstance(app, dict) and app.get("templateKind") in ("customer_card", FINANCE_TEMPLATE_KIND):
            continue
        if database:
            # A View resolves its App only through this read, so a retired seed stays listed here.
            if not report_app and not may_read(app,user,is_admin): continue
            if database not in (app.get("compatibleDatabases") or ()): continue
        elif not report_app and not _listed(app, user): continue
        if (not _database_free(app)
                and not _allowed(app.get("compatibleDatabases"), allowed_databases)):
            catalogue = _app_templates.BY_KIND.get(str(app.get("templateKind") or ""))
            # An owned or shared template may explain a lost source grant without serving data.
            if database or not catalogue or not catalogue["view"]:
                continue
        if kind and app.get("type") != kind: continue
        if starred is not None and bool(user in (app.get("starredBy") or ())) != bool(starred): continue
        default_key = f"{database}::{app.get('type')}" if database else ""
        rows.append(_public(app,user,is_admin,allowed_databases=allowed_databases,
                            target_database=database,
                            readable=True if report_app else None,
                            is_default=bool(default_key and doc["defaults"].get(default_key)==app.get("id"))))
    # S67-T39: the dependent-View count rides a DATABASE-filtered read only, and only for rows
    # the caller may delete, so the unfiltered nav read (App home tiles) pays nothing for it.
    deletable = [row for row in rows if row["capabilities"].get("delete")]
    if database and deletable:
        counts = dependent_view_counts(runtime, database)
        for row in deletable:
            row["dependentViews"] = None if counts is None else counts.get(row["id"], 0)
    return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)


def _nav_placement(app, index):
    """Put default Project management entries first without rewriting stored placements."""
    placement = app.get("navPlacement")
    # Every install stores the template default {"section": "app", "order": 0}, so order 0 is the
    # default here, not a choice; any other stored placement wins.
    if (app.get("templateKind") == "amazon_profit"
            and (not placement or placement == {"section": "app", "order": 0})):
        return {"section": "app", "order": -1}
    return placement or {"section": "app", "order": index}


def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_databases=None):
    """The App home read: stored records the caller owns or was shared, never a code projection."""
    return [{"id": app["id"], "name": app.get("name"),
             "type": app.get("type"), "templateKind": app.get("templateKind"),
             "templateConnector": (_app_templates.BY_KIND.get(
                 str(app.get("templateKind") or "")) or {}).get("connector"),
             "deepLink": app.get("deepLink"),
             "origin": "tenant",
             "compatibleDatabases": app.get("compatibleDatabases") or [],
             "openTarget": app.get("openTarget"),
             "navPlacement": _nav_placement(app, index),
             "capabilities": app.get("capabilities"), "starred": app.get("starred"),
             "isDefault": app.get("isDefault")}
            for index, app in enumerate(list_apps(runtime, user, is_admin,
                                                 allowed_databases=allowed_databases,
                                                 may_open=may_open))]


def _build_application(tenant, user, payload, *, semantic_records=None, field_contracts=None,
                       allowed_databases=None, origin_door=None, via=None):
    """Build the same validated record for authored Apps and boot migrations."""
    payload=payload if isinstance(payload,dict) else {}
    template_kind=str(payload.get("templateKind") or "").strip().lower()
    expected_type = (_template_contract(template_kind) or {}).get("applicationType")
    kind=str(payload.get("type") or expected_type or "").strip().lower()
    definition = validate_application(
        payload, tenant, semantic_records=semantic_records, field_contracts=field_contracts,
        allowed_databases=allowed_databases)
    name=" ".join(str(payload.get("name") or "").split())[:120]
    if not name: raise ApplicationError("application name is required")
    app_id=f"app_{write_execution.new_id()[:16]}"; now=write_execution.utcnow().isoformat()
    compatible = (list(definition["compatibleDatabases"]) if definition
                  else _compat(payload.get("compatibleDatabases"), allow_empty=kind == "code"))
    if _allowed(compatible, allowed_databases) != set(compatible):
        raise PermissionError("an Application cannot bind a database you cannot open")
    raw_config = payload.get("config")
    if definition and raw_config is None:
        raw_config = {"schemaVersion": 1,
                      "display": {"mode": _template_contract(template_kind)["displayMode"]}}
    app={"id":app_id,"tenant":str(tenant),"type":kind,"name":name,
         "compatibleDatabases":compatible,
         "semanticRoleBindings":_governed_bindings(
             payload.get("semanticRoleBindings"), compatible, semantic_records or {}),
         "config":_typed_config(kind, raw_config),
         "share":{"mode":"private","users":[]},"starredBy":[],"createdBy":user,
         "createdAt":now,"updatedAt":now,"revision":1}
    app.update(definition)
    if definition and _template_contract(template_kind).get("deepLink"):
        app["deepLink"] = _template_contract(template_kind)["deepLink"].replace("<id>", app_id)
    if kind == "code":
        app.update(deepLink=f"/app/code/{app_id}", origin=None)
    app["origin"] = _server_origin(origin_door, via)
    return app


def _code_audit_config(app):
    """Project code configuration into body-free activity metadata."""
    html = app["config"]["display"]["html"].encode("utf-8")
    return {"schemaVersion": 1, "display": {"mode": "code", "htmlBytes": len(html),
                                           "htmlSha256": hashlib.sha256(html).hexdigest()}}


def _update_with_activity(runtime, app_id, user, mutate, *, via=None, on_behalf_of=None,
                          document_key=_KEY):
    """Log the final committed App change once, excluding previews and unbound legacy stores."""
    from core.user_tables import _activity_writer
    append = _activity_writer(runtime, user)
    if append is None:
        return _update_document(runtime, mutate, key=document_key)
    app_ids = (app_id,) if isinstance(app_id, str) else tuple(app_id)
    pending = {}

    def snapshot(doc, identity):
        app = copy.deepcopy((doc.get("applications") or {}).get(identity) or {})
        if not app and document_key == _KEY:
            key = _application_key(runtime, identity)
            if key != _KEY:
                app = _clean_doc(_read_strict(runtime, key))["applications"].get(identity, {})
        if app:
            if app.get("type") == "code":
                app["config"] = _code_audit_config(app)
            app["defaults"] = {key: value for key, value in (doc.get("defaults") or {}).items()
                               if value == identity}
        return app

    def apply(raw):
        # A store replay replaces its candidate event instead of appending another one.
        pending.clear()
        old_doc = _clean_doc(raw)
        before = {identity: snapshot(old_doc, identity) for identity in app_ids}
        result = mutate(raw)
        new_doc = _clean_doc(result)
        for identity in app_ids:
            old, after = before[identity], snapshot(new_doc, identity)
            if old == after:
                continue
            # Keep the App name even when a large configuration exhausts C5's byte budget.
            changes = {"name": {"before": old.get("name"), "after": after.get("name")}}
            for key in sorted(old.keys() | after.keys()):
                if key != "name" and (key not in old or key not in after or old[key] != after[key]):
                    changes[key] = {"before": old.get(key), "after": after.get(key)}
            pending[identity] = changes
        return result

    result = _update_document(runtime, apply, key=document_key)
    if result is not False:
        for identity, changes in pending.items():
            append(kind="app", object={"app": identity, "id": identity}, by=user,
                   via=via, on_behalf_of=on_behalf_of, changes=changes)
    return result


class _AppSlotOccupied(Exception):
    pass


def _create_record(runtime, app, user, *, via=None, on_behalf_of=None):
    """Claim one independently locked App slot without a registry or index write."""
    legacy = _clean_doc(_read_strict(runtime, _KEY))
    records = _record_documents(runtime)
    combined = _clean_doc(legacy)
    for record in records.values():
        combined["applications"].update(record["applications"])
    identity = template_identity(app)
    _refuse_template_held(combined["applications"], identity)
    refusal = capacity_refusal(combined, user)
    if refusal:
        raise ApplicationError(refusal)
    if identity:
        # One tenant-wide key chain per template: racing creates of one template lock the same record.
        chain = f"{_RECORD_PREFIX}template/{hashlib.sha256(identity.encode('utf-8')).hexdigest()}/"
        for index in range(_MAX):
            def claim(raw):
                doc = _clean_doc(raw)
                _refuse_template_held(doc["applications"], identity)
                if doc["applications"]:
                    raise _AppSlotOccupied()  # a retired copy keeps this link of the chain
                doc["applications"] = {app["id"]: app}
                return doc
            try:
                saved = _update_with_activity(runtime, app["id"], user, claim, via=via,
                                              on_behalf_of=on_behalf_of,
                                              document_key=chain + str(index))
            except _AppSlotOccupied:
                continue
            if saved is False:
                raise ApplicationError("the App was not saved")
            return
        raise ApplicationError("the App was not saved")
    owner = hashlib.sha256(user.encode("utf-8")).hexdigest()
    prefix = f"{_RECORD_PREFIX}{owner}/"
    occupied = {int(key[len(prefix):]) for key, doc in records.items()
                if key.startswith(prefix) and key[len(prefix):].isdigit() and doc["applications"]}
    legacy_count = sum(isinstance(row, dict) and row.get("createdBy") == user
                       and row.get("retired") is not True for row in legacy["applications"].values())
    # Existing slots above a lowered capacity still consume that account's allowance.
    limit = account_capacity() - legacy_count
    while True:
        reduced = account_capacity() - legacy_count - sum(slot >= limit for slot in occupied)
        if reduced == limit:
            break
        limit = reduced
    slots = [slot for slot in range(max(0, limit)) if slot not in occupied]
    # Different creates start at different records, including when their reads race.
    slots.sort(key=lambda slot: hashlib.sha256(f"{app['id']}:{slot}".encode()).digest())
    for slot in slots:
        def apply(raw):
            doc = _clean_doc(raw)
            if doc["applications"]:
                raise _AppSlotOccupied()
            doc["applications"][app["id"]] = app
            return doc
        try:
            saved = _update_with_activity(runtime, app["id"], user, apply, via=via,
                                          on_behalf_of=on_behalf_of, document_key=prefix + str(slot))
        except _AppSlotOccupied:
            continue
        if saved is False:
            raise ApplicationError("the App was not saved")
        return
    cap = account_capacity()
    raise ApplicationError(f"Your account can hold up to {cap} App{'' if cap == 1 else 's'}. Delete an App to add another.")


def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
           allowed_databases=None, via=None, on_behalf_of=None, origin_door=None, is_admin=False):
    """Create one App. A template App is one live copy per tenant: a second add returns the first."""
    if getattr(runtime, "key", tenant) != tenant or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant:
        raise PermissionError("an Application cannot be created for another tenant")
    if (isinstance(payload, dict) and str(payload.get("templateKind") or "").strip().lower() == "alerts"
            and not _user_wall(runtime, user)("automation")):
        raise PermissionError("Your current rights do not allow Automation.")
    app = _build_application(
        tenant, user, payload, semantic_records=semantic_records, field_contracts=field_contracts,
        allowed_databases=allowed_databases, origin_door=origin_door, via=via)
    app_id = app["id"]
    identity = template_identity(app)
    if identity and not workspace_share_needs_approval(app, is_admin):
        # The one template copy is listed for the whole tenant. Source walls still gate its data.
        # An AI door's non-admin copy stays private until an Administrator approves the share.
        app["share"] = {"mode": "tenant", "users": []}
    advice = _validate_chart_rules(
        app, semantic_records=semantic_records, field_contracts=field_contracts)
    _validate_catalog_rules(app)
    def apply(raw):
        doc=_clean_doc(raw)
        _refuse_template_held(doc["applications"], identity)
        refusal = capacity_refusal(doc, user)
        if refusal: raise ApplicationError(refusal)
        doc["applications"][app_id]=app; return doc
    try:
        if callable(getattr(runtime, "list_keys", None)):
            _create_record(runtime, app, user, via=via, on_behalf_of=on_behalf_of)
        else:
            _update_with_activity(runtime, app_id, user, apply, via=via, on_behalf_of=on_behalf_of)
    except _TemplateHeld as exc:
        # A copy the caller already lists answers first: answering another would list it a second one.
        listed = next((held for held in exc.live if _listed(held, user)), None)
        readable = listed or next((held for held in exc.live if may_read(held, user, is_admin)), None)
        if readable is None:
            raise ApplicationExistsError() from None
        result = None
        if (listed is None and is_admin and readable.get("createdBy") != user
                and template_identity(readable) != "route"
                and not workspace_share_needs_approval(readable, is_admin)):
            # The tenant's one copy is listed for everyone; an admin's add shares a private legacy copy.
            # Beside another account's copy it grants the admin alone, so nobody lists two.
            # Routing is one private copy per account, as in `_template_share_plan`.
            held_share = readable.get("share") if isinstance(readable.get("share"), dict) else {}
            share = ({"mode": "tenant", "users": []} if _sole_holder(readable, exc.live)
                     else {"mode": "users", "users": sorted({*(held_share.get("users") or ()), user})})
            try:
                result = mutate(runtime, readable["id"], user, is_admin,
                                {"share": share}, allowed_databases=allowed_databases)
            except Exception:
                result = None
        if result is None:
            result = _public(readable, user, is_admin, allowed_databases=allowed_databases)
        result["existing"] = True
        return result
    result = _public(app,user,allowed_databases=allowed_databases)
    if app["type"] == "chart":
        result["advice"] = advice
    return result


def _read_strict(runtime, key):
    """Read one document so that a failure RAISES; the lenient `runtime.get` answers {} instead."""
    # ⛔ D-260: `runtime.get` is the LENIENT display read. A failed hub read there answers {},
    # which counted as 0 routes and wrote the one-shot marker as "no_routes", so a tenant WITH
    # routes never got its App. Read STRICTLY (the timeseries_retirement._read door) so a failure
    # raises into the retryable skip. Only a double exposing no strict door reads via get.
    strict = getattr(runtime, "_read_strict", None)
    if callable(strict):
        return strict(key)
    if callable(getattr(runtime, "_store", None)) and callable(getattr(runtime, "store_key", None)):
        return runtime._store()._read_strict(runtime.store_key(key))
    return runtime.get(key)


RETURNS_SPLIT_MARKER = "applications_returns_split_v1"
_RETURNS_LEGACY_KEYS = ("returns_repeat_settings", "returns_repeat_items", "returns_repeat_history")


class ReturnsSplitConflict(ApplicationError):
    code = "returns_split_existing_returns"


def migrate_returns_split(runtime, tenant):
    """Copy legacy Returns state and split installed Apps at tenant startup or maintenance only."""
    if (getattr(runtime, "key", None) != tenant
            or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant):
        raise PermissionError("The App migration belongs to another tenant.")
    marker = _read_strict(runtime, RETURNS_SPLIT_MARKER)
    if isinstance(marker, dict) and marker.get("version") == 1 and marker.get("state") == "done":
        return {"outcome": "unchanged", "itemIds": copy.deepcopy(marker.get("itemIds", {}))}
    if marker is not None and not isinstance(marker, dict):
        raise ApplicationError("The Returns migration marker must be an object.")

    def save(key, mutate):
        if runtime.update(key, mutate) is False:
            raise ApplicationError("The Returns migration was not saved.")

    base = _read_strict(runtime, _KEY)
    if base is not None and (not isinstance(base, dict)
                             or not isinstance(base.get("applications", {}), dict)):
        raise ApplicationError("The App registry must be an object.")
    documents = {_KEY: _clean_doc(base), **_record_documents(runtime)}
    apps, locations = {}, {}
    for key, doc in documents.items():
        for identity, app in doc["applications"].items():
            if (not isinstance(app, dict) or app.get("id") != identity or app.get("tenant") != tenant):
                raise ApplicationError("The App record does not match its tenant.")
            if identity in apps:
                raise ApplicationError("The App registry contains a duplicate id.")
            apps[identity], locations[identity] = app, key
    originals = [app for app in apps.values() if app.get("templateKind") == "returns_repeat"]
    original_ids = {app["id"] for app in originals}
    original_ids.update(row["original"]["id"] for row in (marker or {}).get("apps", []))
    if original_ids and any(app.get("templateKind") == "returns_refunds" and app["id"] not in original_ids
                            for app in apps.values()):
        raise ReturnsSplitConflict("The Returns split needs a contract decision for an existing Returns and refunds App.")

    if not marker:
        plan = []
        if originals:
            from importlib import import_module
            returns = import_module("modules.returns_refunds")
            repeat = import_module("modules.repeat_buyers")
            repeat_id = next((app["id"] for app in apps.values()
                              if app.get("templateKind") == "repeat_buyers"), None)
            for app in originals:
                replacement = returns.migrate_legacy_app(copy.deepcopy(app))
                if replacement.get("id") != app["id"] or replacement.get("templateKind") != "returns_refunds":
                    raise ApplicationError("The Returns migration must retain the original App id.")
                repeat_record = None
                if repeat_id is None:
                    identity = "app_" + hashlib.sha256(
                        (tenant + "\0returns_split\0" + app["id"]).encode("utf-8")).hexdigest()[:24]
                    if identity in apps:
                        raise ApplicationError("The Repeat buyers App id is already occupied.")
                    repeat_record = repeat.migrate_legacy_app(copy.deepcopy(app), app_id=identity)
                    repeat_id = identity
                plan.append({"key": locations[app["id"]], "original": copy.deepcopy(app),
                             "returns": replacement, "repeat": repeat_record,
                             "repeatKey": (_RECORD_PREFIX + repeat_id
                                           if callable(getattr(runtime, "list_keys", None)) else _KEY)})
        # Strict legacy reads finish before the first write, including the resumable plan.
        legacy = [_read_strict(runtime, key) for key in _RETURNS_LEGACY_KEYS]
        if any(value is not None and not isinstance(value, dict) for value in legacy):
            raise ApplicationError("Legacy Returns documents must be objects.")
        proposed = {"version": 1, "state": "planned", "apps": plan}
        save(RETURNS_SPLIT_MARKER, lambda current: current if current else copy.deepcopy(proposed))
        marker = _read_strict(runtime, RETURNS_SPLIT_MARKER)
    else:
        legacy = [_read_strict(runtime, key) for key in _RETURNS_LEGACY_KEYS]
    if marker.get("version") != 1 or marker.get("state") not in ("planned", "done"):
        raise ApplicationError("The Returns migration marker is unsupported.")
    if marker["state"] == "done":
        return {"outcome": "unchanged", "itemIds": copy.deepcopy(marker.get("itemIds", {}))}

    copied = {"itemIds": {}}
    if marker["apps"] or any(legacy):
        from importlib import import_module
        returns = import_module("modules.returns_refunds")
        copied = returns.migrate_legacy_data(tenant, legacy_settings=legacy[0], legacy_items=legacy[1],
                                            legacy_history=legacy[2], st=runtime)
    changes = {}
    repeat_ids = {app["id"] for app in apps.values() if app.get("templateKind") == "repeat_buyers"}
    for row in marker["apps"]:
        changes.setdefault(row["key"], []).append((row["original"]["id"], row["returns"], True))
        if row["repeat"] is not None and (not repeat_ids or row["repeat"]["id"] in repeat_ids):
            changes.setdefault(row["repeatKey"], []).append((row["repeat"]["id"], row["repeat"], False))
            repeat_ids.add(row["repeat"]["id"])
    for key, records in changes.items():
        def apply(raw, records=records):
            doc = _clean_doc(raw)
            for identity, app, replacing in records:
                current = doc["applications"].get(identity)
                if replacing:
                    if not isinstance(current, dict) or current.get("tenant") != tenant:
                        raise ApplicationError("The original Returns App is unavailable.")
                    if current.get("templateKind") == "returns_refunds":
                        continue
                    original = next(row["original"] for row in marker["apps"]
                                    if row["original"]["id"] == identity)
                    if current != original:
                        raise ApplicationError("The original Returns App changed during migration.")
                elif current is not None:
                    if current != app:
                        raise ApplicationError("The Repeat buyers App id is already occupied.")
                    continue
                doc["applications"][identity] = copy.deepcopy(app)
            return _stored_doc(doc)
        save(key, apply)

    def complete(current):
        if current != marker:
            if isinstance(current, dict) and current.get("state") == "done":
                return current
            raise ApplicationError("The Returns migration plan changed.")
        return {**copy.deepcopy(marker), "state": "done", "itemIds": copy.deepcopy(copied["itemIds"])}
    save(RETURNS_SPLIT_MARKER, complete)
    return {"outcome": "migrated", "itemIds": copy.deepcopy(copied["itemIds"])}


#: Marker of the one-copy step: each removed later copy and the kept copy that holds its slot now.
TEMPLATE_ONE_COPY_MARKER = "templateOneCopy"
#: The one-copy step deletes as the account Loopable seeds Apps under.
_ONE_COPY_ACTOR = "loopable"


def _template_double_plan(documents):
    """`[(identity, (key, kept), [(key, later), ...])]` per tenant-wide template with two live copies.

    Copies sort as `_refuse_template_held` sorts them. Routing is one private copy per account by design.
    """
    groups = {}
    for key, doc in documents.items():
        for app_id, app in doc["applications"].items():
            if not isinstance(app, dict) or app.get("retired") is True:
                continue
            identity = template_identity(app)
            if identity and identity != "route":
                groups.setdefault(identity, {}).setdefault(app_id, (key, app))
    plan = []
    for identity, copies in sorted(groups.items()):
        rows = sorted(copies.values(), key=lambda row: (str(row[1].get("createdAt") or ""),
                                                         str(row[1].get("id") or "")))
        if len(rows) > 1:
            plan.append((identity, rows[0], rows[1:]))
    return plan


def _fold_template_copy(runtime, kept_key, kept_id, later):
    """Give the kept copy the later copy's readers and stars, and repoint its defaults."""
    def fold(raw):
        doc = _clean_doc(raw)
        app = doc["applications"].get(kept_id)
        if not isinstance(app, dict) or app.get("retired") is True:
            raise ApplicationError("The kept App copy is unavailable.")
        before = copy.deepcopy(app)
        share = app.get("share") if isinstance(app.get("share"), dict) else {}
        other = later.get("share") if isinstance(later.get("share"), dict) else {}
        if share.get("mode") != "tenant":
            if other.get("mode") == "tenant":
                app["share"] = {"mode": "tenant", "users": []}
            else:
                users = [user for user in _users([
                    *(share.get("users") or () if share.get("mode") == "users" else ()),
                    *(other.get("users") or () if other.get("mode") == "users" else ()),
                    later.get("createdBy")]) if user != app.get("createdBy")]
                if users:
                    app["share"] = {"mode": "users", "users": users}
        stars = {*(app.get("starredBy") or ()), *(later.get("starredBy") or ())}
        if stars != set(app.get("starredBy") or ()):
            app["starredBy"] = sorted(stars)
        if app != before:
            app["revision"] = int(app.get("revision") or 0) + 1
            app["updatedAt"] = write_execution.utcnow().isoformat()
            return doc
        return raw
    _update_document(runtime, fold, key=kept_key)

    def repoint(raw):
        doc = _clean_doc(raw)
        names = [name for name, value in doc["defaults"].items() if value == later.get("id")]
        if not names:
            return raw
        for name in names:
            doc["defaults"][name] = kept_id
        return doc
    if later.get("id") in _clean_doc(_read_strict(runtime, _KEY))["defaults"].values():
        _update_document(runtime, repoint)
    index = _read_strict(runtime, _APP_INDEX_KEY)
    owners = index.get("users") if isinstance(index, dict) else None
    if isinstance(owners, dict):
        _move_placements(runtime, {name: {later["id"]: kept_id} for name in owners})


def remove_template_doubles(runtime, tenant):
    """Keep the oldest live copy of each tenant-wide template and delete every later copy.

    `delete` keeps the later copy's databases, Views and records. A second run writes nothing.
    Never raises: a failed copy is reported and retried at the next boot.
    """
    if (getattr(runtime, "key", None) != tenant
            or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant):
        return {"outcome": "skipped", "removed": {}, "reason": "the runtime belongs to another tenant"}
    try:
        documents = {_KEY: _clean_doc(_read_strict(runtime, _KEY))}
        documents.update(_record_documents(runtime))
    except Exception as exc:
        return {"outcome": "skipped", "removed": {},
                "reason": f"registry read failed: {type(exc).__name__}: {exc}"}
    removed, failed = {}, []
    for identity, (kept_key, kept), later in _template_double_plan(documents):
        for _key, app in later:
            try:
                _fold_template_copy(runtime, kept_key, kept["id"], app)
                delete(runtime, app["id"], _ONE_COPY_ACTOR, True)
            except Exception as exc:
                failed.append(f"{app['id']}: {type(exc).__name__}")
                print(f"[aios-api] one template copy {tenant}: {app['id']} not removed: "
                      f"{type(exc).__name__}")
                continue
            removed[app["id"]] = kept["id"]
            print(f"[aios-api] one template copy {tenant}: removed {app['id']}, "
                  f"kept {kept['id']} ({identity})")
    if removed:
        def mark(raw):
            doc = _clean_doc(raw)
            migrations = doc.setdefault("migrations", {})
            marker = migrations.get(TEMPLATE_ONE_COPY_MARKER)
            marker = copy.deepcopy(marker) if isinstance(marker, dict) else {}
            held = marker.get("removed") if isinstance(marker.get("removed"), dict) else {}
            marker.update(removed={**held, **removed}, at=write_execution.utcnow().isoformat())
            migrations[TEMPLATE_ONE_COPY_MARKER] = marker
            return doc
        try:
            _update_document(runtime, mark)
        except Exception as exc:
            failed.append(f"marker: {type(exc).__name__}")
    outcome = "removed" if removed else ("failed" if failed else "unchanged")
    reason = ", ".join(f"{later_id} into {kept_id}" for later_id, kept_id in removed.items())
    return {"outcome": outcome, "removed": removed,
            "reason": "; ".join(part for part in (reason, ", ".join(failed)) if part)}


def ensure_route_application(runtime, tenant, *, accounts=None, wall=None):
    """R15: boot migrations, once per tenant, never from an Application read.

    Runs the Routing seed migration, `ensure_user_app_copies`, `migrate_c1_bindings` and
    `migrate_template_shares`, and folds them into one dict.
    """
    result = _ensure_route_seed(runtime, tenant)
    copies = ensure_user_app_copies(runtime, tenant, accounts=accounts, wall=wall)
    bindings = migrate_c1_bindings(runtime, tenant)
    shares = migrate_template_shares(runtime, tenant)
    folded = dict(result)
    folded["userCopies"] = copies
    folded["c1Bindings"] = bindings
    folded["templateShares"] = shares
    note = "user copies " + copies["outcome"] + (
        ": " + copies["reason"] if copies.get("reason") else "")
    note += "; C1 bindings " + bindings["outcome"] + (
        ": " + bindings["reason"] if bindings.get("reason") else "")
    note += "; template shares " + shares["outcome"] + (
        ": " + shares["reason"] if shares.get("reason") else "")
    folded["reason"] = result["reason"] + "; " + note if result.get("reason") else note
    return folded


def _ensure_route_seed(runtime, tenant):
    """R15: migrate route references once per tenant into the seeded Routing App."""
    from core import route_system

    # list_routes() suppresses read errors; an unknown count must remain retryable at boot.
    try:
        route_doc = _read_strict(runtime, route_system.STORE_KEY)
        if route_doc is None:
            routes = []
        elif isinstance(route_doc, dict):
            routes = route_doc.get("routes", [])
        else:
            raise ApplicationError("route store must be an object")
        if not isinstance(routes, list):
            raise ApplicationError("route store routes must be a list")
        route_count = len(routes)
        records = _record_documents(runtime)
    except Exception as exc:
        return {"outcome": "skipped", "reason": f"route read failed: {type(exc).__name__}: {exc}"}

    result = {}
    def apply(raw):
        nonlocal result
        doc = _clean_doc(raw)
        migrations = doc.setdefault("migrations", {})
        if "routeApplication" in migrations:
            result = {"outcome": "skipped", "reason": "route Application migration already applied"}
            return raw
        applications = dict(doc["applications"])
        for record in records.values():
            applications.update(record["applications"])
        existing = next((app for app in applications.values()
                         if isinstance(app, dict) and app.get("templateKind") == "route"), None)
        app_id = existing.get("id") if existing is not None else None
        outcome = "existing" if existing is not None else "no_routes"
        if existing is None and route_count:
            refusal = capacity_refusal({"applications": applications}, "loopable")
            if refusal:
                raise ApplicationError(refusal)
            app = _build_application(
                tenant, "loopable",
                {"name": "Routing", "templateKind": "route", "type": "route",
                 "navPlacement": {"section": "app", "order": 0}},
                field_contracts={"customer_data": [
                    {"key": "customer", "type": "text"}, {"key": "lat", "type": "text"},
                    {"key": "lon", "type": "text"}]},
                allowed_databases={"customer_data"})
            app["share"] = {"mode": "tenant", "users": []}
            app_id = app["id"]
            doc["applications"][app_id] = app
            outcome = "created"
        result = {"at": write_execution.utcnow().isoformat(), "outcome": outcome,
                  "appId": app_id, "routes": route_count}
        migrations["routeApplication"] = copy.deepcopy(result)
        return doc
    _update_document(runtime, apply)
    return result


#: Marker of the Command Center seed. Once written, a deleted Command Center App is never seeded again.
COMMAND_CENTER_MARKER = "commandCenterApplication"


def _migrate_project_management_names(runtime):
    """Rename only the two original defaults in each tenant-bound App document."""
    def original(app):
        return (isinstance(app, dict) and app.get("tenant") == runtime.key
                and app.get("templateKind") == "amazon_profit"
                and app.get("createdBy") == "loopable" and app.get("revision") == 1
                and app.get("name") in ("Command Center", "Amazon Command Center"))

    documents = {_KEY: _clean_doc(_read_strict(runtime, _KEY)), **_record_documents(runtime)}
    count = 0
    for key, snapshot in documents.items():
        if not any(original(app) for app in snapshot["applications"].values()):
            continue
        changed = []

        def apply(raw):
            changed.clear()
            doc = _clean_doc(raw)
            for app in doc["applications"].values():
                if original(app):
                    app["name"] = "Project management"
                    changed.append(app["id"])
            return doc

        if _update_document(runtime, apply, key=key) is False:
            raise ApplicationError("The Project management name was not saved.")
        count += len(changed)
    return count


def _adopt_project_field_order(runtime):
    """Move Projects beside each managed product ID without rewriting fields, rows or saved views."""
    from core import user_tables
    from modules import amazon_profit

    specs = amazon_profit.table_specs()

    def ordered(spec, definition):
        if not isinstance(definition, dict) or definition.get("source") != user_tables.AUTOMATION_SOURCE:
            return None
        fields = definition.get("fields") or []
        keys = [field.get("key") for field in fields]
        if len(keys) != len(set(keys)) or not keys or keys[0] != spec["keyColumn"]:
            return None
        identity = fields[0].get("automation") or {}
        if identity.get("flowId") != amazon_profit.VIA or "projects" not in keys:
            return None
        wanted = amazon_profit._project_field_order(keys)
        defaults = [field["key"] for field in spec["fields"] if field["key"] != "projects"]
        # A saved definition with another order belongs to its author.
        if [key for key in keys if key != "projects"] != defaults:
            return None
        return wanted if wanted != keys else None

    todo = [spec for spec in specs if ordered(spec, user_tables.get_definition(spec["key"], st=runtime))]
    if not todo:
        return 0
    changed = []

    def apply(raw):
        changed.clear()
        tables = raw if isinstance(raw, dict) else {}
        for spec in todo:
            table = tables.get(spec["key"])
            wanted = ordered(spec, table)
            if wanted:
                fields = {field["key"]: field for field in table["fields"]}
                table["fields"] = [fields[key] for key in wanted]
                changed.append(spec["key"])
        return tables

    if runtime.update(user_tables.STORE_KEY, apply, flush="sync") is False:
        raise ApplicationError("The Project management field order was not saved.")
    return len(changed)


def reconcile_project_management_defaults(runtime, tenant):
    """Correct only original App names and managed field defaults, without seeding or reading rows."""
    if (getattr(runtime, "key", None) != tenant
            or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant):
        raise PermissionError("The App migration belongs to another tenant.")
    return {"renamed": _migrate_project_management_names(runtime),
            "reordered": _adopt_project_field_order(runtime)}


def ensure_command_center_application(runtime, tenant):
    """Reconcile Project management defaults and seed one shared App when its table exists.

    A tenant without the table gets no marker, so a later boot seeds it once the table exists.
    """
    if (getattr(runtime, "key", None) != tenant
            or getattr(getattr(runtime, "tenant", None), "key", tenant) != tenant):
        raise PermissionError("The App migration belongs to another tenant.")
    from core import user_tables
    from modules.amazon_profit import TABLE_KEY

    corrected = reconcile_project_management_defaults(runtime, tenant)
    renamed, reordered = corrected["renamed"], corrected["reordered"]
    base = _clean_doc(_read_strict(runtime, _KEY))
    if COMMAND_CENTER_MARKER in (base.get("migrations") or {}):
        if renamed or reordered:
            return {"outcome": "migrated", "renamed": renamed, "reordered": reordered}
        return {"outcome": "unchanged"}
    records = _record_documents(runtime)

    def _held(doc):
        applications = dict(doc["applications"])
        for record in records.values():
            applications.update(record["applications"])
        existing = next((app for app in applications.values()
                         if isinstance(app, dict) and app.get("templateKind") == "amazon_profit"), None)
        return applications, existing

    _applications, existing = _held(base)
    if existing is None and not isinstance(user_tables.get_definition(TABLE_KEY, st=runtime), dict):
        return {"outcome": "no_table"}

    result = {}
    def apply(raw):
        nonlocal result
        doc = _clean_doc(raw)
        migrations = doc.setdefault("migrations", {})
        if COMMAND_CENTER_MARKER in migrations:
            result = {"outcome": "unchanged"}
            return raw
        applications, current = _held(doc)
        if current is not None:
            result = {"outcome": "existing", "appId": current.get("id")}
        else:
            refusal = capacity_refusal({"applications": applications}, "loopable")
            if refusal:
                result = {"outcome": "skipped", "reason": refusal}
                return raw
            app = _build_application(
                tenant, "loopable",
                {"name": "Project management", "templateKind": "amazon_profit",
                 "navPlacement": {"section": "app", "order": 0}})
            app["share"] = {"mode": "tenant", "users": []}
            doc["applications"][app["id"]] = app
            result = {"outcome": "created", "appId": app["id"]}
        migrations[COMMAND_CENTER_MARKER] = {"at": write_execution.utcnow().isoformat(), **result}
        return doc
    if _update_document(runtime, apply) is False:
        raise ApplicationError("The Project management App was not saved.")
    return result


#: Marker of the R33 migration: the binding each rewritten App held before, and the Apps it kept.
C1_BINDINGS_MARKER = "c1Bindings"


def _c1_rewrite(app):
    """A Routing or Catalog App rewritten to its C1 binding, or None when it must stay as stored.

    An App whose source or field map differs from C1 (`own_binding` non-empty) is never rewritten.
    """
    if not isinstance(app, dict) or app.get("templateKind") not in _app_templates.BOUND_KINDS:
        return None
    if "sourceDatabase" not in app and "fieldMap" not in app:
        return None
    if _app_templates.own_binding(app):
        return None
    source = _app_templates.source(app["templateKind"])
    row = copy.deepcopy(app)
    row.pop("sourceDatabase", None)
    row.pop("fieldMap", None)
    row["compatibleDatabases"] = [source, *(database for database in app.get("compatibleDatabases") or ()
                                            if database != source)]
    return row


def _c1_plan(doc, app_ids):
    """`{id: rewritten App}` plus the stored Apps that keep a binding of their own, for one document."""
    rewrites, kept = {}, []
    for app_id, app in sorted(doc["applications"].items()):
        if app_ids is not None and app_id not in app_ids:
            continue
        if not isinstance(app, dict) or app.get("templateKind") not in _app_templates.BOUND_KINDS:
            continue
        rewritten = _c1_rewrite(app)
        if rewritten is not None:
            rewrites[app_id] = rewritten
        elif _app_templates.own_binding(app):
            kept.append({"id": app_id, "templateKind": app["templateKind"], "name": app.get("name"),
                         "sourceDatabase": app.get("sourceDatabase"),
                         "fieldMap": copy.deepcopy(app.get("fieldMap"))})
    return rewrites, kept


def migrate_c1_bindings(runtime, tenant, *, app_ids=None):
    """R33: rewrite every stored Routing and Catalog App to its C1 binding.

    Writes only when an App still stores a binding equal to C1, so a second run changes nothing.
    An App with its own source or field map is kept and listed. A proof run
    passes `app_ids` to touch only the named Apps; the boot call never passes it.
    """
    scope = None if app_ids is None else set(app_ids)
    try:
        doc = _clean_doc(_read_strict(runtime, _KEY))
        records = _record_documents(runtime)
    except Exception as exc:
        return {"outcome": "skipped", "reason": f"registry read failed: {type(exc).__name__}: {exc}",
                "rewritten": [], "kept": []}
    rewrites, kept = _c1_plan(doc, scope)
    result = {"outcome": "unchanged", "rewritten": [], "kept": kept}
    if rewrites:
        def apply(raw):
            current = _clean_doc(raw)
            planned, held = _c1_plan(current, scope)
            result["kept"] = held
            if not planned:
                return raw
            marker = current.setdefault("migrations", {}).setdefault(
                C1_BINDINGS_MARKER, {"rewritten": {}, "kept": []})
            for app_id, app in planned.items():
                before = current["applications"][app_id]
                marker["rewritten"][app_id] = {key: copy.deepcopy(before[key]) for key in
                                               ("sourceDatabase", "fieldMap", "compatibleDatabases")
                                               if key in before}
                current["applications"][app_id] = app
            marker["kept"] = sorted({row["id"] for row in held} | set(marker.get("kept") or ()))
            marker["at"] = write_execution.utcnow().isoformat()
            result.update(outcome="migrated", rewritten=sorted(planned))
            return current
        _update_document(runtime, apply)
    for key, record in records.items():
        planned, held = _c1_plan(record, scope)
        result["kept"].extend(held)
        if not planned:
            continue
        rewritten = []

        def apply_record(raw):
            rewritten.clear()
            current = _clean_doc(raw)
            fresh, _held = _c1_plan(current, scope)
            if not fresh:
                return raw
            marker = current.setdefault("migrations", {}).setdefault(
                C1_BINDINGS_MARKER, {"rewritten": {}, "kept": []})
            for identity in fresh:
                before = current["applications"][identity]
                marker["rewritten"][identity] = {field: copy.deepcopy(before[field]) for field in
                                                ("sourceDatabase", "fieldMap", "compatibleDatabases")
                                                if field in before}
            marker["at"] = write_execution.utcnow().isoformat()
            current["applications"].update(fresh)
            rewritten.extend(sorted(fresh))
            return current
        _update_document(runtime, apply_record, key=key)
        if rewritten:
            result["rewritten"].extend(rewritten)
            result["outcome"] = "migrated"
    if result["rewritten"]:
        try:
            from catalog_store import migrate_snapshots
            result["catalogSnapshots"] = migrate_snapshots(runtime, result["rewritten"])
        except Exception as exc:
            result["catalogSnapshots"] = f"skipped: {type(exc).__name__}"
    parts = [f"{len(result['rewritten'])} rewritten"] if result["rewritten"] else []
    if result["kept"]:
        parts.append("kept with their own binding: " + ", ".join(row["id"] for row in result["kept"]))
    result["reason"] = "; ".join(parts)
    return result


#: Marker of the template share migration: the copy each shareless template identity now shares.
TEMPLATE_SHARES_MARKER = "templateShares"


def _template_share_plan(documents):
    """`{document key: {app id: identity}}`: the oldest live copy of each unshared identity one account holds."""
    groups = {}
    for key, doc in documents.items():
        for app_id, app in doc["applications"].items():
            if not isinstance(app, dict) or app.get("retired") is True:
                continue
            identity = template_identity(app)
            # Routing stays one private copy per account by design (`ensure_user_app_copies`).
            if identity and identity != "route":
                groups.setdefault(identity, []).append((key, app_id, app))
    plan = {}
    for identity, copies in sorted(groups.items()):
        if any((app.get("share") if isinstance(app.get("share"), dict) else {}).get("mode") == "tenant"
               for _key, _app_id, app in copies):
            continue
        key, app_id, app = min(copies, key=lambda row: (str(row[2].get("createdAt") or ""),
                                                        str(row[2].get("id") or "")))
        # Another account's copy would list beside the shared one: that account would see two.
        if _sole_holder(app, [row[2] for row in copies]):
            plan.setdefault(key, {})[app_id] = identity
    return plan


def migrate_template_shares(runtime, tenant):
    """Share with the tenant the oldest live copy of each unshared template identity one account holds.

    Writes only a document that holds a copy to share, so a second run writes nothing.
    """
    try:
        documents = {_KEY: _clean_doc(_read_strict(runtime, _KEY))}
        documents.update(_record_documents(runtime))
    except Exception as exc:
        return {"outcome": "skipped", "shared": [],
                "reason": f"registry read failed: {type(exc).__name__}: {exc}"}
    plan = _template_share_plan(documents)
    shared = []
    for key in sorted(plan, key=lambda name: (name != _KEY, name)):
        flips, landed = plan[key], []

        def apply(raw, flips=flips, landed=landed):
            landed.clear()
            current = _clean_doc(raw)
            for app_id, identity in sorted(flips.items()):
                app = current["applications"].get(app_id)
                if not isinstance(app, dict) or app.get("retired") is True:
                    continue
                share = app.get("share") if isinstance(app.get("share"), dict) else {}
                if share.get("mode") == "tenant":
                    continue
                app["share"] = {"mode": "tenant", "users": []}
                landed.append((identity, app_id))
            if not landed:
                return raw
            migrations = current.setdefault("migrations", {})
            marker = migrations.get(TEMPLATE_SHARES_MARKER)
            marker = copy.deepcopy(marker) if isinstance(marker, dict) else {}
            marker["shared"] = {**(marker.get("shared") if isinstance(marker.get("shared"), dict) else {}),
                                **dict(landed)}
            marker["at"] = write_execution.utcnow().isoformat()
            migrations[TEMPLATE_SHARES_MARKER] = marker
            return current
        _update_document(runtime, apply, key=key)
        shared.extend(app_id for _identity, app_id in landed)
    return {"outcome": "migrated" if shared else "unchanged", "shared": shared,
            "reason": ", ".join(shared)}


_COPIES = "userAppCopies"
_APP_INDEX_KEY = "module_index_app"


def _active_accounts(tenant):
    """`[(username, public user record)]` for this tenant's active accounts; raises if unreadable."""
    from core import users
    if not isinstance(users.registry(), dict):
        raise ApplicationError("the account registry is unreadable")
    return [(name, users._public(name, record)) for name, record in users._tenant_accounts(tenant)]


def _copy_id(tenant, old_id, username):
    """One stable id per (tenant, old App id, account), so a rerun cannot duplicate a copy."""
    import hashlib
    digest = hashlib.sha256(f"{tenant}\x1f{old_id}\x1f{username}".encode("utf-8")).hexdigest()
    return "app_" + digest[:16]


def _seed_route_app(doc):
    """The tenant-shared Routing App the route migration seeded, or None."""
    seed_id = ((doc.get("migrations") or {}).get("routeApplication") or {}).get("appId")
    seed = doc["applications"].get(seed_id) if seed_id else None
    if (isinstance(seed, dict) and seed.get("createdBy") == "loopable"
            and (seed.get("share") or {}).get("mode") == "tenant"):
        return seed
    return None


def _move_placements(runtime, moves):
    """Move each account's App-home folder placement from an old App id to its copy id."""
    doc = _read_strict(runtime, _APP_INDEX_KEY)
    owners = (doc or {}).get("users") if isinstance(doc, dict) else None
    if not isinstance(owners, dict):
        return 0
    if not any(old in ((owners.get(name) or {}).get("itemFolders") or {})
               for name, pairs in moves.items() for old in pairs):
        return 0
    moved = [0]

    def apply(raw):
        state = copy.deepcopy(raw) if isinstance(raw, dict) else raw
        buckets = state.get("users") if isinstance(state, dict) else None
        for name, pairs in moves.items():
            bucket = buckets.get(name) if isinstance(buckets, dict) else None
            placed = bucket.get("itemFolders") if isinstance(bucket, dict) else None
            if not isinstance(placed, dict):
                continue
            changed = False
            for old, new in pairs.items():
                if old in placed:
                    folder = placed.pop(old)
                    placed.setdefault(new, folder)
                    changed = True
                    moved[0] += 1
            if changed:
                # A client holding the old revision must reload before it writes folders again.
                bucket["rev"] = int(bucket.get("rev") or 0) + 1
        return state
    runtime.update(_APP_INDEX_KEY, apply)
    return moved[0]


def ensure_user_app_copies(runtime, tenant, *, accounts=None, wall=None):
    """Give every active account one private copy of the Routing seed, once per tenant.

    The seeded Routing App becomes one private copy per active account and is then retired: hidden
    from the App home but kept, so a View holding its id still resolves. Folder placements move to
    the copy ids. A failed read returns a retryable `skipped` and writes no marker.
    """
    try:
        current = _read_strict(runtime, _KEY)
        if current is not None and not isinstance(current, dict):
            raise ApplicationError("the Application registry must be an object")
    except Exception as exc:
        return {"outcome": "skipped", "reason": f"registry read failed: {type(exc).__name__}: {exc}"}
    migrations = _clean_doc(current).get("migrations") or {}
    marker = migrations.get(_COPIES)
    if isinstance(marker, dict) and marker.get("state") == "done":
        return {"outcome": "skipped", "reason": "user App copies already applied"}
    if "routeApplication" not in migrations:
        return {"outcome": "skipped", "reason": "route Application migration pending"}

    if isinstance(marker, dict) and isinstance(marker.get("moves"), dict):
        moves = copy.deepcopy(marker["moves"])
        copies = int(marker.get("copies") or 0)
    else:
        try:
            people = list(_active_accounts(tenant) if accounts is None else accounts)
            plan = [str(username) for username, _record in people]
        except Exception as exc:
            return {"outcome": "skipped",
                    "reason": f"account read failed: {type(exc).__name__}: {exc}"}
        if not plan:
            return {"outcome": "skipped", "reason": "no active accounts"}
        landed = {}

        def apply(raw):
            doc = _clean_doc(raw)
            state = doc.setdefault("migrations", {})
            if isinstance(state.get(_COPIES), dict):
                landed.update(copy.deepcopy(state[_COPIES]))
                return raw
            now = write_execution.utcnow().isoformat()
            seed = _seed_route_app(doc)
            moves, made = {}, 0
            for username in plan:
                pairs = moves.setdefault(username, {})
                if seed is not None:
                    new_id = _copy_id(tenant, seed["id"], username)
                    pairs[seed["id"]] = new_id
                    if new_id not in doc["applications"]:
                        record = copy.deepcopy(seed)
                        for key in ("retired", "retiredAt"):
                            record.pop(key, None)
                        record.update(
                            id=new_id, createdBy=username, share={"mode": "private", "users": []},
                            origin=_server_origin(),
                            starredBy=[username] if username in (seed.get("starredBy") or ()) else [],
                            createdAt=now, updatedAt=now, revision=1, migratedFrom=seed["id"])
                        doc["applications"][new_id] = record
                        made += 1
            if seed is not None:
                seed.update(retired=True, retiredAt=now)
                for key in [key for key, value in doc["defaults"].items() if value == seed["id"]]:
                    doc["defaults"].pop(key)
            state[_COPIES] = {"state": "copied", "at": now, "accounts": len(plan),
                              "copies": made, "seed": seed["id"] if seed else None,
                              "moves": moves}
            landed.update(copy.deepcopy(state[_COPIES]))
            return doc
        _update_document(runtime, apply)
        if landed.get("state") == "done":
            return {"outcome": "skipped", "reason": "user App copies already applied"}
        moves, copies = landed.get("moves") or {}, int(landed.get("copies") or 0)

    try:
        moved = _move_placements(runtime, moves)
    except Exception as exc:
        return {"outcome": "skipped",
                "reason": f"folder placement move failed: {type(exc).__name__}: {exc}"}
    def finish(raw):
        doc = _clean_doc(raw)
        state = (doc.get("migrations") or {}).get(_COPIES)
        if not isinstance(state, dict) or state.get("state") == "done":
            return raw
        state.update(state="done", moved=moved, doneAt=write_execution.utcnow().isoformat())
        return doc
    _update_document(runtime, finish)
    return {"outcome": "copied", "copies": copies, "accounts": len(moves), "moved": moved,
            "reason": f"{copies} copies for {len(moves)} accounts, {moved} folder placements moved"}


def workspace_share_needs_approval(app, is_admin=False):
    """Hold workspace sharing for an AI-built App until an Administrator answers."""
    origin = app.get("origin") if isinstance(app.get("origin"), dict) else {}
    return not is_admin and origin.get("door") in ("mcp", "loopy")


def _request_workspace_share(runtime, app, user):
    """Send one source-checked approval to the tenant's active Administrators."""
    import tickets
    from core import perms, users
    try:
        recipients = [name for name, record in users._tenant_accounts(runtime.key)
                      if perms.is_admin(record)]
        if not recipients:
            raise ApplicationError("No Administrator is available to approve this share.")
        request = tickets.send_request(
            runtime, user, recipients, "approval", "Share " + app["name"],
            "Share this App with the workspace?",
            source={"database": "applications", "record": app["id"]})
    except (ValueError, PermissionError) as exc:
        raise ApplicationError(str(exc)) from exc
    return {"state": "pending", "requestId": request["id"],
            "message": "This share waits for an Administrator."}


def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None, field_contracts=None,
           allowed_databases=None, target_database=None, expect=None, via=None, on_behalf_of=None,
           origin_door=None):
    """Apply a patch, optionally requiring the current share's mode and users to match `expect`."""
    patch=patch if isinstance(patch,dict) else {}; landed={}
    advice = []
    held_share = []
    if "origin" in patch:
        raise ApplicationError("Loopable sets origin. Remove origin from the request.")
    _server_origin(origin_door, via)
    immutable = sorted(set(patch) & {
        "id", "tenant", "type", "templateKind", "sourceDatabase", "navPlacement",
        "financeKey", "deepLink"
    })
    if immutable:
        raise ApplicationError("Application identity and template definition are immutable: "
                               + ", ".join(immutable))
    def apply(raw):
        held_share.clear()
        landed.clear()
        doc=_clean_doc(raw); app=doc["applications"].get(app_id)
        if not app: raise ApplicationError("application does not exist")
        if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
            if not _database_free(app):
                raise ApplicationError("application does not exist")
        if (app.get("templateKind") in APPLICATION_TEMPLATE_KINDS + GATED_TEMPLATE_KINDS
                and "compatibleDatabases" in patch):
            raise ApplicationError("a template Application's sourceDatabase is immutable")
        star_only = set(patch) <= {"starred"}
        if star_only:
            if not may_read(app,user,is_admin): raise PermissionError("application is not available")
        elif not may_edit(app,user,is_admin):
            raise PermissionError("application belongs to another user")
        if expect is not None:
            def share_state(value):
                value = value if isinstance(value, dict) else {}
                mode = str(value.get("mode") or "private")
                return mode, _users(value.get("users")) if mode == "users" else []
            # Compare the fresh share on every store replay before changing any Application field.
            if share_state(app.get("share")) != share_state(expect):
                raise shares.GrantsChanged(
                    'this item was shared with somebody else while you were editing, so nothing '
                    'was saved. Reopen the sharing panel to see who has access now, then make '
                    'your change again.')
        if "name" in patch:
            name=" ".join(str(patch["name"] or "").split())[:120]
            if app["type"] == "chart" and not _is_finance(app):
                try:
                    app_rules.validate_text(patch["name"], "the App name")
                except app_rules.RuleError as exc:
                    raise ApplicationRuleError(exc) from None
            if not name: raise ApplicationError("application name is required")
            app["name"]=name
        if "config" in patch:
            config = _typed_config(app["type"], patch["config"])
            _refuse_legacy_catalog_changes(app, config)
            app["config"] = config
        if "fieldMap" in patch:
            # R33: a template App reads the fields its template names.
            raise ApplicationError("This App reads the fields its template names. "
                                   "Its field map cannot change.")
        compatible = (_compat(patch["compatibleDatabases"], allow_empty=app["type"] == "code")
                      if "compatibleDatabases" in patch else app.get("compatibleDatabases") or [])
        if _allowed(compatible, allowed_databases) != set(compatible):
            raise PermissionError("an Application cannot bind a database you cannot open")
        if "semanticRoleBindings" in patch or "compatibleDatabases" in patch:
            bindings = patch.get("semanticRoleBindings", app.get("semanticRoleBindings"))
            app["semanticRoleBindings"]=_governed_bindings(
                bindings, compatible, semantic_records or {})
        app["compatibleDatabases"] = list(compatible)
        if "share" in patch:
            share=patch["share"] if isinstance(patch["share"],dict) else {}
            mode=str(share.get("mode") or "private")
            if mode not in ("private","users","tenant"): raise ApplicationError("share mode is not recognized")
            if mode == "tenant" and workspace_share_needs_approval(app, is_admin) \
                    and (app.get("share") or {}).get("mode") != "tenant":
                held_share.append(True)
            else:
                app["share"]={"mode":mode,"users":_users(share.get("users")) if mode=="users" else []}
        if "starred" in patch:
            stars=set(app.get("starredBy") or ())
            (stars.add if patch["starred"] else stars.discard)(user); app["starredBy"]=sorted(stars)
        if not star_only:
            advice[:] = _validate_chart_rules(
                app, semantic_records=semantic_records, field_contracts=field_contracts)
            _validate_catalog_rules(app)
        app["revision"]=int(app.get("revision") or 0)+1
        app["updatedAt"]=write_execution.utcnow().isoformat(); landed.update(app)
        return doc
    _update_with_activity(runtime, app_id, user, apply, via=via, on_behalf_of=on_behalf_of,
                          document_key=_application_key(runtime, app_id))
    result = _public(landed,user,is_admin,allowed_databases=allowed_databases,
                     target_database=target_database)
    if landed["type"] == "chart" and not set(patch) <= {"starred"}:
        result["advice"] = advice
    if held_share:
        result["shareApproval"] = _request_workspace_share(runtime, landed, user)
        result["message"] = result["shareApproval"]["message"]
    return result


def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records=None,
              field_contracts=None, allowed_databases=None, via=None, on_behalf_of=None,
              origin_door=None):
    app=load(runtime)["applications"].get(app_id)
    if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
    if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
        if not _database_free(app):
            raise ApplicationError("application does not exist")
    payload={"type":app["type"],"name":f"{app['name']} copy",
        "compatibleDatabases":app.get("compatibleDatabases"),
        "semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")}
    # R33: a template copy binds C1 itself, so neither the source nor the field map is copied.
    for key in ("templateKind", "navPlacement", "financeKey"):
        if key in app: payload[key]=copy.deepcopy(app[key])
    if app.get("templateKind") not in _app_templates.BOUND_KINDS and "sourceDatabase" in app:
        payload["sourceDatabase"] = app["sourceDatabase"]
    return create(runtime,tenant,user,payload,
        semantic_records=semantic_records, field_contracts=field_contracts,
        allowed_databases=allowed_databases, via=via, on_behalf_of=on_behalf_of,
        origin_door=origin_door, is_admin=is_admin)


_ANY_NAME = object()


def _workspace_views(doc, *, trash=True):
    """Every View in one workspace document: each member's Views, reserved members included.

    Descends into nested folders. With `trash`, each owner's trash entries are walked too.
    """
    def nested_views(rows):
        for row in (rows.values() if isinstance(rows, dict) else rows if isinstance(rows, list) else ()):
            if isinstance(row, dict) and ("config" in row or "presentation" in row):
                yield row
            elif isinstance(row, (dict, list)):
                yield from nested_views(row)

    for bucket in (doc.values() if isinstance(doc, dict) else ()):
        if not isinstance(bucket, dict):
            continue
        yield from nested_views(bucket.get("views"))
        held = bucket.get("trash") if trash else None
        for entry in (held.values() if isinstance(held, dict)
                      else held if isinstance(held, list) else ()):
            if isinstance(entry, dict) and isinstance(entry.get("view"), dict):
                yield entry["view"]


def _view_app_ids(view):
    """The distinct App ids a View's `config` or `presentation` names."""
    ids = []
    for key in ("config", "presentation"):
        config = view.get(key) if isinstance(view, dict) else None
        ref = config.get("application") if isinstance(config, dict) else None
        app_id = str(ref.get("id") or "") if isinstance(ref, dict) else ""
        if app_id and app_id not in ids:
            ids.append(app_id)
    return ids


def _strip_view_refs(doc, app_id):
    """Remove `config.application` naming `app_id` from every View in one workspace document.

    Walks every top-level member, reserved ones included, and each owner's trash entries.
    Returns the number of Views changed. Mutates `doc` in place.
    """
    cleared = 0
    if isinstance(doc, dict):
        for view in _workspace_views(doc):
            changed = False
            for key in ("config", "presentation"):
                config = view.get(key) if isinstance(view, dict) else None
                ref = config.get("application") if isinstance(config, dict) else None
                if isinstance(ref, dict) and str(ref.get("id") or "") == app_id:
                    config.pop("application")
                    changed = True
            if changed:
                cleared += 1
    return cleared


def clear_view_references(runtime, app_id, databases):
    """D-2233: drop a deleted App's id from saved Views so each opens as a plain View.

    Returns `(views cleared, reasons for databases not cleared)`. Never raises.
    """
    from core.view_templates import workspace_key
    cleared, failed = 0, []
    for database in dict.fromkeys(str(value or "") for value in databases or ()):
        key = workspace_key(database)
        if not key:
            continue
        try:
            # A strict read: a failed read is reported, never counted as no reference.
            if not _strip_view_refs(copy.deepcopy(_read_strict(runtime, key)), app_id):
                continue
            count = [0]

            def apply(raw):
                doc = copy.deepcopy(raw)
                count[0] = _strip_view_refs(doc, app_id)
                return doc if count[0] else raw
            saved = runtime.update(key, apply)
            if saved is False or _strip_view_refs(copy.deepcopy(_read_strict(runtime, key)), app_id):
                raise ApplicationError("the View reference cleanup was not saved")
            cleared += count[0]
        except Exception as exc:
            failed.append(f"{database}: {type(exc).__name__}")
    return cleared, failed


RETIRED_KINDS_MARKER = "retireNonRoutingCatalogApps"
RETIRE_KINDS_CONFIRM = "DELETE ALL APPS EXCEPT ROUTING AND CATALOG"


def retirement_store_guard(runtime=None, tenant=None):
    """Admit only the deployment's bound store, including reads of a retirement preview."""
    from core import activity_log, data_binding, store, store_pg

    if runtime is not None and (not isinstance(tenant, str) or not tenant
                                or getattr(runtime, "key", None) != tenant
                                or getattr(getattr(runtime, "tenant", None), "key", None) != tenant):
        raise ApplicationError("retirement runtime does not match its tenant")
    bound = runtime._store() if runtime is not None else store._d()
    shared = bound is store
    if bound is store:
        bound = store._d()
    if isinstance(bound, activity_log.FixtureAdapter):
        if tenant is not None and (getattr(bound, "tenant_slug", None) != tenant
                                   or runtime.store_namespace):
            raise ApplicationError("retirement runtime does not match its tenant store")
        return
    if isinstance(bound, store_pg.PgStore):
        slug = bound.tenant_slug
        if tenant is not None and (slug != tenant or runtime.key != tenant
                                   or runtime.store_namespace):
            raise ApplicationError("retirement runtime does not match its tenant store")
        if (not data_binding.is_production_deployment()
                and slug in store_pg.PRODUCTION_TENANTS
                and not store_pg.isolated_staging_database()):
            raise ApplicationError("retirement cannot read a live tenant from this deployment")
        refusal = store_pg.gate_write_refusal(slug) or store_pg.write_refusal(slug)
    else:
        repo = getattr(bound, "repo", None)
        if tenant is not None:
            configured_repo = (getattr(runtime.tenant, "config", {}) or {}).get("store_repo")
            namespace = "" if configured_repo or tenant == "royal-imports" else f"t/{tenant}/"
            if (not repo or runtime.store_namespace != namespace
                    or (repo != configured_repo if configured_repo else not shared)):
                raise ApplicationError("retirement runtime does not match its tenant store")
        if not data_binding.is_production_deployment() and repo in data_binding.PRODUCTION_STORES:
            raise ApplicationError("retirement cannot read a live store from this deployment")
        refusal = data_binding.gate_write_refusal(repo) or data_binding.write_refusal(repo)
    if refusal:
        raise ApplicationError(refusal)


def retirement_tenants():
    """Resolve every tenant from a strict control-plane snapshot without changing its records."""
    from core import store
    from harness import runtime

    retirement_store_guard()
    records = store._read_strict(runtime.TENANTS_KEY)
    if records is None:
        records = {}
    if not isinstance(records, dict) or any(not isinstance(rec, dict) for rec in records.values()):
        raise ApplicationError("the tenant registry must be an object of tenant records")
    found = []
    for slug in sorted(set(runtime._BUILDERS) | set(records)):
        rec = records.get(slug)
        if rec is not None and rec.get("status", "active") != "active" and slug not in runtime._BUILDERS:
            # Suspended logins do not exempt their stored Apps from an explicit retirement.
            repo = rec.get("store_repo")
            tenant = runtime._builder_from_record(slug, rec)()
            rt = runtime.TenantRuntime(
                key=slug, tenant=tenant,
                store_namespace="" if store.backend() == "pg" or repo else f"t/{slug}/",
                store_handle=store.handle(slug=slug) if store.backend() == "pg"
                else store.for_repo(repo) if repo else None)
        else:
            rt = runtime.get_runtime(slug)
        if rt.key != slug or getattr(rt.tenant, "key", None) != slug:
            raise ApplicationError("retirement runtime does not match its tenant")
        if rec is not None and slug not in runtime._BUILDERS:
            if (getattr(rt.tenant, "config", {}) or {}).get("store_repo") != (rec.get("store_repo") or None):
                raise ApplicationError("the tenant store binding changed; retry with a fresh runtime")
        retirement_store_guard(rt, slug)
        found.append((slug, rt))
    return found


def _retirement_read(runtime, key):
    raw = _read_strict(runtime, key)
    if raw is None:
        return {}
    if not isinstance(raw, dict):
        raise ApplicationError(f"{key} must be an object")
    return raw


def _retirement_view_count(workspaces):
    def count(node):
        if isinstance(node, list):
            return sum(count(value) for value in node)
        if not isinstance(node, dict):
            return 0
        if "id" in node and ("config" in node or "presentation" in node):
            return 1
        return sum(count(value) for value in node.values())
    return sum(count(doc) for doc in workspaces.values())


def _retirement_plan(runtime, tenant):
    from core import user_tables, view_templates

    retirement_store_guard(runtime, tenant)
    doc = _retirement_read(runtime, _KEY)
    for key in ("applications", "defaults", "migrations"):
        if not isinstance(doc.get(key, {}), dict):
            raise ApplicationError(f"Application {key} must be an object")
    applications = doc.get("applications", {})
    if any(not isinstance(app, dict) or app.get("tenant", tenant) != tenant
           for app in applications.values()):
        raise ApplicationError("the Application registry has an invalid tenant record")
    removed = {identity: app for identity, app in applications.items()
               if app.get("templateKind") not in ("route", "catalog", *GATED_TEMPLATE_KINDS)}
    tables = _retirement_read(runtime, user_tables.STORE_KEY)
    databases = {"customer_data", "product_data"} | {key for key in tables if key.startswith("ut_")}
    for app in applications.values():
        databases.update(app.get("compatibleDatabases") or ())
        if app.get("sourceDatabase"):
            databases.add(app["sourceDatabase"])
    workspaces = {key: _retirement_read(runtime, view_templates.workspace_key(key))
                  for key in sorted(databases) if view_templates.workspace_key(key)}
    tokens = _retirement_read(runtime, "customer_card_tokens")
    public_links = sum(1 for token in tokens.values() if isinstance(token, dict)
                       and token.get("application") in removed
                       and token.get("access") in ("public", "password"))
    return {"doc": doc, "removed": removed, "databases": sorted(workspaces),
            "counts": {"databases": 2 + sum(key.startswith("ut_") for key in tables),
                       "views": _retirement_view_count(workspaces)},
            "publicLinks": public_links}


def retire_kinds(runtime, tenant, user, *, is_admin=False, dry_run=True, confirm=None):
    """Preview or explicitly retire obsolete Apps while preserving every database and saved View."""
    if not is_admin:
        raise PermissionError("Only an Administrator may retire App kinds.")
    if type(dry_run) is not bool:
        raise ApplicationError("dry_run must be a boolean")
    if not dry_run and confirm != RETIRE_KINDS_CONFIRM:
        raise ApplicationError("Use the confirm phrase from the dry run.")
    result = {"tenant": tenant, "deleted": 0, "dry_run": dry_run,
              "confirm_phrase": RETIRE_KINDS_CONFIRM}
    try:
        plan = _retirement_plan(runtime, tenant)
        removed = plan["removed"]
        result.update(toDelete=len(removed), publicLinks=plan["publicLinks"],
                      before=plan["counts"], after=copy.deepcopy(plan["counts"]),
                      line=f"{tenant}: {len(removed)} Apps to delete")
        if dry_run:
            return dict(result, outcome="preview")
        marker = plan["doc"].get("migrations", {}).get(RETIRED_KINDS_MARKER)
        if isinstance(marker, dict) and marker.get("state") == "done":
            if removed:
                raise ApplicationError("retirement already completed but obsolete Apps were added")
            return dict(result, outcome="already_completed")
        from core.user_tables import _activity_writer
        if removed and _activity_writer(runtime, user) is None:
            raise ApplicationError("App retirement requires the tenant activity log")
        # Cleanup precedes the sole registry update, so a failed clear leaves deletion retryable.
        cleared = 0
        for identity in removed:
            count, failed = clear_view_references(runtime, identity, plan["databases"])
            cleared += count
            if failed:
                raise ApplicationError("View cleanup failed: " + "; ".join(failed))
        after = _retirement_plan(runtime, tenant)
        if after["counts"] != plan["counts"]:
            raise ApplicationError("Database or View counts changed during retirement; retry the dry run")

        def apply(raw):
            if (raw or {}) != plan["doc"]:
                raise ApplicationError("Apps changed during retirement; retry the dry run")
            doc = copy.deepcopy(raw or {})
            for identity in removed:
                doc.setdefault("applications", {}).pop(identity)
            for key, identity in list(doc.get("defaults", {}).items()):
                if identity in removed:
                    doc["defaults"].pop(key)
            doc.setdefault("migrations", {})[RETIRED_KINDS_MARKER] = {
                "state": "done", "at": write_execution.utcnow().isoformat(), "by": user,
                "deleted": len(removed), "publicLinks": plan["publicLinks"],
                "viewsCleared": cleared, "before": plan["counts"], "after": after["counts"]}
            return doc

        saved = _update_with_activity(runtime, tuple(removed), user, apply, via="App retirement")
        if saved is False:
            raise ApplicationError("the App retirement was not saved")
        return dict(result, outcome="retired", deleted=len(removed), viewsCleared=cleared,
                    after=after["counts"])
    except Exception as exc:
        return dict(result, outcome="skipped", reason=f"{type(exc).__name__}: {exc}")


def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None,
           confirm_name=_ANY_NAME, via=None, on_behalf_of=None):
    """Delete one App record. Its databases, Views and records stay; Views lose the dead id.

    `confirm_name`, when given, must equal the stored name inside the same atomic update.
    """
    removed = {}

    def apply(raw):
        doc=_clean_doc(raw); app=doc["applications"].get(app_id)
        if not app: raise ApplicationError("application does not exist")
        if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
            if not _database_free(app):
                raise ApplicationError("application does not exist")
        if not may_edit(app,user,is_admin): raise PermissionError("application belongs to another user")
        if confirm_name is not _ANY_NAME and (
                not isinstance(confirm_name, str) or confirm_name != app.get("name")):
            raise ApplicationError("enter the exact App name to confirm deletion")
        if app.get("templateKind") == "catalog":
            from catalog_store import migrate_legacy
            migrate_legacy(runtime, app)
        removed.update(doc["applications"].pop(app_id))
        for key in list(doc["defaults"]):
            if doc["defaults"][key]==app_id: doc["defaults"].pop(key)
        return doc
    document_key = _application_key(runtime, app_id)
    _update_with_activity(runtime, app_id, user, apply, via=via, on_behalf_of=on_behalf_of,
                          document_key=document_key)
    if document_key != _KEY:
        def clear_defaults(raw):
            doc = _clean_doc(raw)
            doc["defaults"] = {key: value for key, value in doc["defaults"].items() if value != app_id}
            return doc
        if app_id in _clean_doc(_read_strict(runtime, _KEY))["defaults"].values():
            _update_document(runtime, clear_defaults)
    result = {"deleted": app_id}
    # After the registry write: a failed clear is reported, never an undone delete.
    cleared, failed = clear_view_references(runtime, app_id, removed.get("compatibleDatabases"))
    if cleared:
        result["viewsCleared"] = cleared
    if failed:
        result["viewsNotCleared"] = "; ".join(failed)
    kind = removed.get("templateKind")
    contract = _app_templates.BY_KIND.get(kind)
    if contract and contract.get("module"):
        try:
            if not any(row.get("templateKind") == kind for row in load(runtime)["applications"].values()):
                from importlib import import_module
                module = import_module(contract["module"])
                cleanup = next((getattr(module, name) for name in
                                ("remove_app_data", "on_app_removed", "remove")
                                if callable(getattr(module, name, None))), None)
                if cleanup is not None:
                    cleanup(removed.get("tenant") or runtime.key, st=runtime)
        except Exception as exc:
            result["appDataNotCleared"] = type(exc).__name__
    return result


def set_default(runtime, database, kind, app_id, user, is_admin=False, *, allowed_databases=None,
                via=None, on_behalf_of=None):
    if kind not in APPLICATION_TYPES: raise ApplicationError("application type is not recognized")
    if not is_admin: raise PermissionError("only a tenant admin can change Application defaults")
    if database not in set(allowed_databases or ()):
        raise PermissionError("that database is not available")
    key=f"{database}::{kind}"
    def apply(raw):
        doc=_clean_doc(raw)
        record_key = _application_key(runtime, app_id)
        app = (doc if record_key == _KEY else _clean_doc(_read_strict(runtime, record_key)))["applications"].get(app_id)
        if (not isinstance(app, dict) or not may_edit(app,user,is_admin)
                or database not in (app.get("compatibleDatabases") or ())
                or app.get("type")!=kind):
            raise ApplicationError("application is not compatible with this default")
        doc["defaults"][key]=app_id; return doc
    _update_with_activity(runtime, app_id, user, apply, via=via, on_behalf_of=on_behalf_of)
    return resolve_default(
        runtime,database,kind,user,is_admin,allowed_databases=allowed_databases)


def resolve_default(runtime, database, kind, user, is_admin=False, *, allowed_databases=None):
    if kind not in APPLICATION_TYPES:
        raise ApplicationError("application type is not recognized")
    if database not in set(allowed_databases or ()):
        raise PermissionError("that database is not available")
    doc=load(runtime); explicit=doc["defaults"].get(f"{database}::{kind}")
    app=doc["applications"].get(explicit)
    if app and app.get("retired") is not True and may_read(app,user,is_admin) and database in (app.get("compatibleDatabases") or ()) and app.get("type")==kind:
        return {"resolution":"explicit","application":_public(
            app,user,is_admin,allowed_databases=allowed_databases,target_database=database,
            is_default=True)}
    # A retired seed still resolves by id but is never offered as the latest default.
    matches=[x for x in doc["applications"].values() if x.get("type")==kind and database in (x.get("compatibleDatabases") or ()) and may_read(x,user,is_admin) and x.get("retired") is not True]
    matches.sort(key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
    return {"resolution":"latest" if matches else "blank",
            "application":_public(matches[0],user,is_admin,allowed_databases=allowed_databases,
                                  target_database=database) if matches else None}