-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.html
More file actions
1782 lines (1700 loc) · 84.7 KB
/
Copy pathindex.html
File metadata and controls
1782 lines (1700 loc) · 84.7 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Countersign — RFP Response Studio</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,300..800&family=Instrument+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/docx@8.5.0/build/index.umd.min.js"></script>
<style>
:root{
--paper:#F3F3ED;
--card:#FFFFFF;
--ink:#1F231F;
--ink-soft:#5B6157;
--line:#D9DACD;
--line-strong:#B9BBA9;
--green:#2F6B4F;
--green-soft:#E4EFE8;
--amber:#A96F08;
--amber-soft:#F5ECD8;
--red:#AE3B2A;
--red-soft:#F6E4E0;
--blue:#2456A6;
--hover:#FBFBF7;
--subtle:#FDFDFA;
--btn-hover:#000000;
--green-hover:#255A41;
--mono:'IBM Plex Mono',monospace;
--sans:'Instrument Sans',sans-serif;
--disp:'Archivo',sans-serif;
}
[data-theme="dark"]{
--paper:#141613;
--card:#1C1F1A;
--ink:#E7E8DF;
--ink-soft:#A2A797;
--line:#2C2F28;
--line-strong:#464B40;
--green:#6FB08D;
--green-soft:#1E2C24;
--amber:#D9A24A;
--amber-soft:#33290F;
--red:#D46B58;
--red-soft:#361F1A;
--blue:#7CA1DC;
--hover:#22251F;
--subtle:#191C17;
--btn-hover:#F7F8F0;
--green-hover:#82BD9E;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%}
body{
font-family:var(--sans);
background:var(--paper);
color:var(--ink);
font-size:15px;
line-height:1.55;
-webkit-font-smoothing:antialiased;
}
::selection{background:var(--green);color:var(--paper)}
/* ---------- shell ---------- */
.shell{display:grid;grid-template-columns:232px 1fr;min-height:100vh}
.rail{
border-right:1px solid var(--line-strong);
background:var(--card);
padding:22px 18px;
display:flex;flex-direction:column;gap:6px;
position:sticky;top:0;height:100vh;
}
.wordmark{
font-family:var(--disp);
font-variation-settings:'wdth' 118;
font-weight:750;font-size:19px;letter-spacing:.01em;
display:flex;align-items:center;gap:9px;margin-bottom:4px;
}
.wordmark .seal{
width:26px;height:26px;border:2px solid var(--ink);border-radius:50%;
display:grid;place-items:center;font-family:var(--mono);font-size:11px;font-weight:600;
transform:rotate(-8deg);color:var(--green);border-color:var(--green);
}
.tagline{font-family:var(--mono);font-size:10.5px;color:var(--ink-soft);letter-spacing:.04em;margin-bottom:22px}
.step{
display:flex;gap:11px;align-items:flex-start;text-align:left;
padding:11px 10px;border:1px solid transparent;border-radius:8px;
background:none;cursor:pointer;width:100%;font-family:var(--sans);color:var(--ink);
}
.step:hover{background:var(--paper)}
.step.active{border-color:var(--ink);background:var(--paper)}
.step .num{
font-family:var(--mono);font-size:11px;font-weight:600;
border:1.5px solid var(--ink);border-radius:4px;min-width:22px;height:22px;
display:grid;place-items:center;margin-top:1px;
}
.step.done .num{background:var(--green);border-color:var(--green);color:var(--card)}
.step b{display:block;font-size:13.5px;font-weight:600}
.step span{font-size:11.5px;color:var(--ink-soft);display:block;line-height:1.35}
.rail-foot{margin-top:auto;display:flex;flex-direction:column;gap:10px}
.provider-chip{
font-family:var(--mono);font-size:10.5px;padding:7px 9px;border:1px dashed var(--line-strong);
border-radius:6px;color:var(--ink-soft);display:flex;gap:7px;align-items:center;
}
.provider-chip .dot{width:7px;height:7px;border-radius:50%;background:var(--green);flex:none}
/* ---------- main ---------- */
.main{padding:30px 38px 80px;max-width:1060px;width:100%}
.page{display:none}
.page.visible{display:block;animation:rise .25s ease}
@keyframes rise{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.eyebrow{font-family:var(--mono);font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--green);font-weight:600;margin-bottom:6px}
h1{font-family:var(--disp);font-variation-settings:'wdth' 112;font-weight:700;font-size:27px;letter-spacing:-.01em;margin-bottom:6px}
.lede{color:var(--ink-soft);max-width:620px;margin-bottom:26px;font-size:14.5px}
.card{background:var(--card);border:1px solid var(--line-strong);border-radius:10px;padding:20px;margin-bottom:18px}
.card h2{font-family:var(--disp);font-size:15px;font-weight:650;margin-bottom:12px;display:flex;align-items:center;gap:8px}
.hint{font-size:12.5px;color:var(--ink-soft)}
/* buttons */
.btn{
font-family:var(--disp);font-weight:600;font-size:13.5px;
border:1.5px solid var(--ink);border-radius:7px;background:var(--ink);color:#fff;
padding:9px 16px;cursor:pointer;display:inline-flex;align-items:center;gap:8px;
}
[data-theme="dark"] .btn{color:var(--paper)}
[data-theme="dark"] .btn.ghost{color:var(--ink)}
.btn:hover{background:var(--btn-hover)}
.btn:disabled{opacity:.45;cursor:not-allowed}
.btn.ghost{background:transparent;color:var(--ink)}
.btn.ghost:hover{background:var(--paper)}
.btn.green{background:var(--green);border-color:var(--green)}
.btn.green:hover{background:var(--green-hover)}
.btn.small{padding:5px 10px;font-size:12px;border-width:1px}
/* dropzone */
.drop{
border:2px dashed var(--line-strong);border-radius:10px;padding:38px 20px;text-align:center;
cursor:pointer;transition:border-color .15s,background .15s;background:var(--card);
}
.drop.over,.drop:hover{border-color:var(--green);background:var(--green-soft)}
.drop .big{font-family:var(--disp);font-weight:650;font-size:16px;margin-bottom:4px}
.drop .fmt{font-family:var(--mono);font-size:11px;color:var(--ink-soft);margin-top:8px}
/* doc table */
table{width:100%;border-collapse:collapse;font-size:13.5px}
th{font-family:var(--mono);font-size:10.5px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink-soft);text-align:left;padding:8px 10px;border-bottom:1.5px solid var(--ink)}
td{padding:10px;border-bottom:1px solid var(--line);vertical-align:middle}
tr:last-child td{border-bottom:none}
.ftype{font-family:var(--mono);font-size:10.5px;font-weight:600;padding:2px 7px;border-radius:4px;border:1px solid var(--line-strong)}
.ftype.pdf{color:var(--red);border-color:var(--red)}
.ftype.docx{color:var(--blue);border-color:var(--blue)}
.ftype.xlsx,.ftype.csv{color:var(--green);border-color:var(--green)}
.mono{font-family:var(--mono);font-size:12px}
.icon-btn{border:none;background:none;cursor:pointer;color:var(--ink-soft);font-size:15px;padding:4px}
.icon-btn:hover{color:var(--red)}
.meter{height:7px;background:var(--line);border-radius:99px;overflow:hidden;width:100%}
.meter i{display:block;height:100%;background:var(--green);border-radius:99px;transition:width .3s}
.meter.warn i{background:var(--amber)}
.meter.bad i{background:var(--red)}
/* question ledger — signature element */
.ledger{display:flex;flex-direction:column;gap:12px}
.q-row{background:var(--card);border:1px solid var(--line-strong);border-radius:10px;overflow:hidden}
.q-head{display:flex;gap:14px;align-items:flex-start;padding:14px 16px;cursor:pointer}
.q-head:hover{background:var(--hover)}
.clause{
font-family:var(--mono);font-size:11.5px;font-weight:600;color:var(--green);
border:1.5px solid var(--green);border-radius:5px;padding:3px 7px;white-space:nowrap;margin-top:1px;
}
.q-text{flex:1;font-weight:500;font-size:14px;line-height:1.45}
.q-meta{display:flex;flex-direction:column;align-items:flex-end;gap:6px;min-width:118px}
.stamp{
font-family:var(--mono);font-size:10px;font-weight:600;letter-spacing:.09em;text-transform:uppercase;
padding:3px 9px;border:1.5px solid;border-radius:4px;transform:rotate(-2deg);user-select:none;
}
.stamp.draft{color:var(--ink-soft);border-color:var(--line-strong);transform:none}
.stamp.generated{color:var(--amber);border-color:var(--amber)}
.stamp.approved{color:var(--green);border-color:var(--green)}
.stamp.error{color:var(--red);border-color:var(--red)}
.coverage{display:flex;align-items:center;gap:7px;width:118px}
.coverage .meter{width:70px}
.coverage span{font-family:var(--mono);font-size:10px;color:var(--ink-soft)}
.q-body{border-top:1px solid var(--line);padding:14px 16px;display:none;background:var(--subtle)}
.q-row.open .q-body{display:block}
.q-body textarea{
width:100%;min-height:130px;border:1px solid var(--line-strong);border-radius:7px;padding:11px;
font-family:var(--sans);font-size:13.5px;line-height:1.6;resize:vertical;background:var(--card);color:var(--ink);
}
.q-body textarea:focus{outline:2px solid var(--green);outline-offset:1px;border-color:transparent}
.q-actions{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap;align-items:center}
.src-note{font-family:var(--mono);font-size:10.5px;color:var(--ink-soft);margin-left:auto}
/* inputs */
input[type=text],input[type=password],select,textarea.plain{
font-family:var(--sans);font-size:13.5px;border:1px solid var(--line-strong);border-radius:7px;
padding:9px 11px;background:var(--card);color:var(--ink);width:100%;
}
input:focus,select:focus,textarea.plain:focus{outline:2px solid var(--green);outline-offset:1px;border-color:transparent}
label.field{display:block;font-family:var(--mono);font-size:10.5px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink-soft);margin-bottom:5px;font-weight:600}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.grid3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}
/* progress */
.progress-wrap{display:flex;align-items:center;gap:12px;margin-top:14px}
.progress-wrap .meter{flex:1;height:9px}
.progress-label{font-family:var(--mono);font-size:11px;color:var(--ink-soft);white-space:nowrap}
/* export cards */
.fmt-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;margin-bottom:18px}
.fmt-card.disabled{opacity:.45;cursor:not-allowed}
.qtype{
font-family:var(--mono);font-size:9.5px;font-weight:600;letter-spacing:.07em;text-transform:uppercase;
padding:2px 7px;border-radius:99px;background:var(--paper);border:1px solid var(--line-strong);color:var(--ink-soft);white-space:nowrap;
}
.qtype.compliance{color:var(--green);border-color:var(--green)}
.qtype.technical{color:var(--blue);border-color:var(--blue)}
.qtype.commercial{color:var(--amber);border-color:var(--amber)}
.gap-item{display:flex;gap:12px;align-items:flex-start;padding:11px 0;border-bottom:1px solid var(--line)}
.gap-item:last-child{border-bottom:none}
.gap-item .clause{margin-top:0}
.gap-kw{font-family:var(--mono);font-size:10.5px;color:var(--red);background:var(--red-soft);border-radius:4px;padding:1px 6px;margin:2px 4px 0 0;display:inline-block}
.map-panel{border:1px dashed var(--green);border-radius:8px;padding:14px;margin-top:14px;background:var(--green-soft)}
.map-panel h3{font-family:var(--disp);font-size:13px;font-weight:650;margin-bottom:10px}
.grid4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
@media (max-width:900px){.grid4{grid-template-columns:1fr 1fr}}
.fmt-card{
border:1.5px solid var(--line-strong);border-radius:10px;padding:18px;cursor:pointer;background:var(--card);
text-align:left;font-family:var(--sans);color:var(--ink);
}
.fmt-card:hover{border-color:var(--ink)}
.fmt-card.sel{border-color:var(--green);background:var(--green-soft)}
.fmt-card .ext{font-family:var(--mono);font-weight:600;font-size:13px;color:var(--green)}
.fmt-card b{display:block;font-family:var(--disp);font-size:15px;margin:6px 0 3px}
.fmt-card span{font-size:12px;color:var(--ink-soft)}
/* modal */
.modal-back{position:fixed;inset:0;background:rgba(31,35,31,.45);display:none;place-items:center;z-index:50;padding:20px}
.modal-back.show{display:grid}
.modal{background:var(--card);border-radius:12px;border:1px solid var(--line-strong);max-width:520px;width:100%;padding:24px;max-height:88vh;overflow:auto}
.modal h2{font-family:var(--disp);font-size:17px;font-weight:700;margin-bottom:14px}
.modal .row{margin-bottom:14px}
/* toast */
#toast{
position:fixed;bottom:22px;left:50%;transform:translateX(-50%);background:var(--ink);color:var(--paper);
font-family:var(--mono);font-size:12px;padding:10px 16px;border-radius:8px;opacity:0;pointer-events:none;
transition:opacity .2s;z-index:99;max-width:90vw;
}
#toast.show{opacity:1}
#toast.err{background:var(--red);color:var(--card)}
.empty{
text-align:center;padding:34px 16px;color:var(--ink-soft);font-size:13.5px;
border:1px dashed var(--line-strong);border-radius:10px;
}
.pill-count{font-family:var(--mono);font-size:10.5px;background:var(--paper);border:1px solid var(--line-strong);border-radius:99px;padding:2px 9px;color:var(--ink-soft)}
.flex{display:flex;align-items:center;gap:10px}
.spread{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}
.spin{display:inline-block;width:13px;height:13px;border:2px solid rgba(127,127,127,.35);border-top-color:currentColor;border-radius:50%;animation:sp .7s linear infinite}
@keyframes sp{to{transform:rotate(360deg)}}
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
@media (max-width:900px){
.shell{grid-template-columns:1fr}
.rail{position:static;height:auto;flex-direction:row;flex-wrap:wrap;align-items:center}
.rail-foot{margin:0;flex-direction:row}
.step b{font-size:12px}.step span{display:none}
.grid2,.grid3,.fmt-cards{grid-template-columns:1fr}
.main{padding:20px 16px 60px}
}
</style>
</head>
<body>
<div class="shell">
<!-- ============ RAIL ============ -->
<nav class="rail">
<div class="wordmark"><span class="seal">✓</span>Countersign</div>
<div class="tagline">RFP RESPONSE STUDIO · <span id="ver"></span></div>
<button class="step active" data-page="bucket" id="nav-bucket">
<span class="num">1</span>
<div><b>Documentation bucket</b><span>Upload the source of truth</span></div>
</button>
<button class="step" data-page="workspace" id="nav-workspace">
<span class="num">2</span>
<div><b>Response workspace</b><span>Parse the RFP, draft answers</span></div>
</button>
<button class="step" data-page="export" id="nav-export">
<span class="num">3</span>
<div><b>Export</b><span>DOCX, XLSX or CSV</span></div>
</button>
<div class="rail-foot">
<div class="provider-chip"><span class="dot" id="prov-dot"></span><span id="prov-label">Claude · built-in</span></div>
<div class="provider-chip" title="Where your workspace persists"><span class="dot" id="store-dot" style="background:var(--line-strong)"></span><span id="store-label">storage: …</span></div>
<button class="btn ghost small" id="theme-toggle">◐ Dark mode</button>
<button class="btn ghost small" id="open-settings">⚙ AI settings</button>
</div>
</nav>
<!-- ============ MAIN ============ -->
<main class="main">
<!-- ===== PAGE 1 · BUCKET ===== -->
<section class="page visible" id="page-bucket">
<div class="eyebrow">Step 1 · Source of truth</div>
<h1>Documentation bucket</h1>
<p class="lede">Drop your product docs, security policies, SOC 2 summaries, architecture overviews and past proposals — up to <b>500 source documents</b>. Countersign parses everything in your browser, indexes it for retrieval, and cites which sources ground each RFP answer.</p>
<div class="drop" id="dropzone" tabindex="0" role="button" aria-label="Upload documentation files">
<div class="big">Drop files here, or click to browse</div>
<div class="hint">Files are parsed locally — nothing is uploaded to a server. Multi-select or drop whole batches.</div>
<div class="fmt">.PDF · .DOCX · .XLSX · .CSV · .TXT · .MD — UP TO 500 SOURCES</div>
<input type="file" id="file-input" multiple accept=".pdf,.docx,.xlsx,.xls,.csv,.txt,.md" hidden>
</div>
<div class="card" style="margin-top:18px">
<div class="spread" style="margin-bottom:10px">
<h2 style="margin:0">Parsed documents <span class="pill-count" id="doc-count">0 files</span></h2>
<div class="flex" style="min-width:220px">
<span class="hint mono" id="storage-label">0 KB indexed</span>
<div class="meter" style="width:110px" id="storage-meter"><i style="width:0%"></i></div>
</div>
</div>
<div id="doc-list"><div class="empty">Nothing in the bucket yet. Everything you add here becomes retrievable context for step 2.</div></div>
</div>
<div class="card">
<h2>Self-hosting & workspace directory file</h2>
<p class="hint" style="margin-bottom:12px">
This app is a single HTML file — drop it in your web root (e.g. <span class="mono">public_html/rfp/index.html</span>) and it runs as-is.
To ship a shared knowledge base with it, export the workspace as <span class="mono">countersign-data.json</span> and place it in the <b>same directory</b>:
the app auto-loads it on first open, so your whole team starts with the same 500-source bucket. On your own hosting, work also persists in each visitor's browser storage.
To share one API key across the team instead of everyone pasting their own, deploy the bundled <span class="mono">proxy.php</span> (shared hosting) or <span class="mono">proxy.js</span> (Node) — see the README — and pick <b>Team server proxy</b> in AI settings.
</p>
<div class="q-actions">
<button class="btn small" id="ws-export">↓ Export workspace file</button>
<button class="btn small ghost" id="ws-import">↑ Import workspace file</button>
<button class="btn small ghost" id="ws-fetch">⟳ Load from site directory</button>
<input type="file" id="ws-import-input" accept=".json" hidden>
<span class="hint mono" id="ws-note"></span>
</div>
</div>
<div class="card">
<div class="spread" style="margin-bottom:6px">
<h2 style="margin:0">Answer engine <span class="pill-count" id="engine-pill">not connected</span></h2>
<div class="flex">
<button class="btn small ghost" id="engine-check">⟲ Check engine</button>
<button class="btn small" id="engine-push">⇪ Push bucket to engine</button>
</div>
</div>
<p class="hint" style="margin-bottom:8px">
Run the bundled <span class="mono">engine.js</span> on a server (see ENGINE.md) to keep the knowledge base <em>and</em> the API key server-side.
Pick <b>Countersign Engine</b> in ⚙ AI settings and generation switches to the server's retrieval — with whole-RFP batches streamed back live.
Push this bucket up so the engine indexes the same sources.
</p>
<span class="hint mono" id="engine-status">Configure in ⚙ AI settings</span>
</div>
<div class="spread">
<span class="hint">Documents persist between sessions on this device.</span>
<button class="btn green" id="to-workspace" disabled>Continue to workspace →</button>
</div>
</section>
<!-- ===== PAGE 2 · WORKSPACE ===== -->
<section class="page" id="page-workspace">
<div class="eyebrow">Step 2 · Draft & review</div>
<h1>Response workspace</h1>
<p class="lede">Load the RFP, let the model extract every question into a ledger, then generate grounded answers. Each answer cites which bucket documents informed it — edit freely, then stamp it approved.</p>
<div class="card">
<h2>RFP source</h2>
<div class="grid2">
<div>
<label class="field">Upload the RFP file</label>
<button class="btn ghost" id="rfp-upload-btn" style="width:100%;justify-content:center">Choose file (.pdf .docx .xlsx .csv .txt)</button>
<input type="file" id="rfp-file-input" accept=".pdf,.docx,.xlsx,.xls,.csv,.txt,.md" hidden>
<div class="hint mono" id="rfp-file-label" style="margin-top:6px">No file loaded</div>
</div>
<div>
<label class="field">Or paste RFP text</label>
<textarea class="plain" id="rfp-paste" rows="3" placeholder="Paste requirements or questionnaire text…"></textarea>
</div>
</div>
<div class="map-panel" id="sheet-map" style="display:none">
<h3>Spreadsheet detected — map the columns</h3>
<div class="grid4">
<div>
<label class="field">Sheet</label>
<select id="map-sheet"></select>
</div>
<div>
<label class="field">Ref column (optional)</label>
<select id="map-ref"></select>
</div>
<div>
<label class="field">Question column</label>
<select id="map-q"></select>
</div>
<div>
<label class="field">Response column (for round-trip)</label>
<select id="map-ans"></select>
</div>
</div>
<div class="q-actions" style="margin-top:12px">
<label class="flex" style="gap:7px;font-size:13px"><input type="checkbox" id="map-header" checked> First row is a header</label>
<button class="btn green small" id="map-import">Import questions from columns</button>
<span class="hint mono" id="map-preview"></span>
</div>
</div>
<div class="q-actions" style="margin-top:14px">
<button class="btn" id="extract-btn">Extract questions</button>
<button class="btn ghost" id="add-q-btn">+ Add question manually</button>
<span class="hint mono" id="rfp-chars"></span>
</div>
</div>
<div class="card">
<div class="spread" style="margin-bottom:6px">
<h2 style="margin:0">Question ledger <span class="pill-count" id="q-count">0 questions</span></h2>
<div class="flex">
<select id="tone-select" style="width:auto">
<option value="professional and precise">Tone: Professional</option>
<option value="warm, consultative and client-focused">Tone: Consultative</option>
<option value="concise and technical, for engineering evaluators">Tone: Technical</option>
<option value="formal, suitable for public-sector procurement">Tone: Formal / public sector</option>
</select>
<button class="btn green" id="generate-all">Generate all answers</button>
</div>
</div>
<div class="progress-wrap" id="gen-progress" style="display:none">
<div class="meter"><i id="gen-bar" style="width:0%"></i></div>
<span class="progress-label" id="gen-label">0 / 0</span>
</div>
<div class="ledger" id="ledger" style="margin-top:12px">
<div class="empty">No questions yet. Load an RFP above and extract, or add questions manually.</div>
</div>
</div>
<div class="card">
<div class="spread" style="margin-bottom:6px">
<h2 style="margin:0">Coverage gap report <span class="pill-count" id="gap-count">—</span></h2>
<button class="btn ghost small" id="run-gaps">Run gap analysis</button>
</div>
<p class="hint" style="margin-bottom:8px">Checks every question against the bucket locally (no AI calls) and flags the ones your documentation can't substantiate — fix these before submission.</p>
<div id="gap-list"><div class="empty">Run the analysis once questions are in the ledger.</div></div>
</div>
<div class="spread">
<button class="btn ghost" data-page="bucket">← Back to bucket</button>
<button class="btn green" data-page="export">Continue to export →</button>
</div>
</section>
<!-- ===== PAGE 3 · EXPORT ===== -->
<section class="page" id="page-export">
<div class="eyebrow">Step 3 · Deliverable</div>
<h1>Export the response pack</h1>
<p class="lede">Assemble the ledger into a submission-ready file. DOCX gives you a formatted narrative document; XLSX and CSV mirror the compliance-matrix layout most procurement teams expect.</p>
<div class="fmt-cards">
<button class="fmt-card sel" data-fmt="docx">
<span class="ext">.DOCX</span><b>Word document</b>
<span>Cover page, numbered questions as headings, answers as body text.</span>
</button>
<button class="fmt-card" data-fmt="xlsx">
<span class="ext">.XLSX</span><b>Excel workbook</b>
<span>One row per question — ref, question, response, status, sources.</span>
</button>
<button class="fmt-card" data-fmt="csv">
<span class="ext">.CSV</span><b>CSV matrix</b>
<span>Plain compliance matrix for portals that ingest flat files.</span>
</button>
<button class="fmt-card disabled" data-fmt="roundtrip" id="fmt-roundtrip">
<span class="ext">.XLSX ↩</span><b>Round-trip workbook</b>
<span id="roundtrip-hint">Writes answers back into the issuer's original spreadsheet. Import an RFP via column mapping first.</span>
</button>
</div>
<div class="card">
<h2>Options</h2>
<div class="grid2">
<div>
<label class="field">Proposal title</label>
<input type="text" id="exp-title" placeholder="e.g. Response to Acme Corp RFP 2026-014">
</div>
<div>
<label class="field">Your company name</label>
<input type="text" id="exp-company" placeholder="e.g. Northwind Software Ltd.">
</div>
</div>
<div class="flex" style="margin-top:12px;gap:18px;flex-wrap:wrap">
<label class="flex" style="gap:7px;font-size:13px"><input type="checkbox" id="exp-approved-only"> Approved answers only</label>
<label class="flex" style="gap:7px;font-size:13px"><input type="checkbox" id="exp-sources" checked> Include source references</label>
<label class="flex" style="gap:7px;font-size:13px"><input type="checkbox" id="exp-gaps"> Append coverage gap report (DOCX & XLSX)</label>
</div>
</div>
<div class="card">
<div class="spread" style="margin-bottom:10px">
<h2 style="margin:0">Preview</h2>
<span class="pill-count" id="exp-count">0 rows</span>
</div>
<div id="exp-preview" style="max-height:340px;overflow:auto"></div>
</div>
<div class="spread">
<button class="btn ghost" data-page="workspace">← Back to workspace</button>
<button class="btn green" id="download-btn">↓ Download file</button>
</div>
</section>
</main>
</div>
<!-- ============ SETTINGS MODAL ============ -->
<div class="modal-back" id="settings-modal">
<div class="modal" role="dialog" aria-label="AI settings">
<h2>AI provider</h2>
<div class="row">
<label class="field">Provider</label>
<select id="set-provider">
<option value="claude">Claude (built-in — no key needed inside Claude.ai)</option>
<option value="claude-key">Claude (your Anthropic API key — for self-hosted)</option>
<option value="gemini">Google Gemini (bring your key)</option>
<option value="openai">OpenAI-compatible / Copilot endpoint (bring your key)</option>
<option value="proxy">Team server proxy (key stays on your server)</option>
<option value="engine">Countersign Engine (server knowledge base + streaming batch)</option>
</select>
<div class="hint" id="key-warning" style="display:none;margin-top:6px;color:var(--amber)">
⚠ Keys are held in memory for this session only and sent solely to the provider. Never hard-code a key into a publicly hosted page — each user pastes their own.
</div>
</div>
<div class="row" id="key-row" style="display:none">
<label class="field" id="key-label">API key</label>
<input type="password" id="set-key" placeholder="Paste your API key" autocomplete="off">
<div class="hint" style="margin-top:5px">Stored only in this session's memory — never persisted or sent anywhere except the provider.</div>
</div>
<div class="row" id="base-row" style="display:none">
<label class="field">Base URL</label>
<input type="text" id="set-base" placeholder="https://api.openai.com/v1">
<div class="hint" style="margin-top:5px">Some enterprise/Copilot endpoints block browser calls (CORS). If requests fail, use the built-in Claude provider.</div>
</div>
<div class="row" id="model-row" style="display:none">
<label class="field">Model</label>
<input type="text" id="set-model" placeholder="e.g. gemini-2.0-flash or gpt-4o">
</div>
<div class="row">
<label class="field">Answer length targets, per question type</label>
<div class="grid2" style="gap:10px">
<div>
<label class="field" style="color:var(--green)">Compliance (yes/no)</label>
<select id="len-compliance">
<option value="50">~50 words</option>
<option value="80" selected>~80 words</option>
<option value="140">~140 words</option>
</select>
</div>
<div>
<label class="field" style="color:var(--blue)">Technical</label>
<select id="len-technical">
<option value="150">~150 words</option>
<option value="250" selected>~250 words</option>
<option value="350">~350 words</option>
</select>
</div>
<div>
<label class="field">Narrative / company</label>
<select id="len-narrative">
<option value="120">~120 words</option>
<option value="220" selected>~220 words</option>
<option value="320">~320 words</option>
</select>
</div>
<div>
<label class="field" style="color:var(--amber)">Commercial / pricing</label>
<select id="len-commercial">
<option value="80">~80 words</option>
<option value="150" selected>~150 words</option>
<option value="250">~250 words</option>
</select>
</div>
</div>
<div class="hint" style="margin-top:6px">Each question is auto-classified on import — you can reassign a type on any ledger row.</div>
</div>
<div class="q-actions">
<button class="btn" id="settings-save">Save settings</button>
<button class="btn ghost" id="settings-close">Cancel</button>
</div>
</div>
</div>
<div id="toast"></div>
<script>
/* ================================================================
Countersign — state, persistence, file parsing
================================================================ */
pdfjsLib.GlobalWorkerOptions.workerSrc =
"https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";
const APP_VERSION = "1.0.0";
const S = {
docs: [], // {id,name,type,size,chars,text}
questions: [], // {id,ref,text,answer,status,sources,coverage}
settings: { provider:"claude", key:"", base:"", model:"",
lengths: { compliance:80, technical:250, narrative:220, commercial:150 } },
exportFmt: "docx",
generating: false
};
const QTYPES = { compliance:"Compliance", technical:"Technical", narrative:"Narrative", commercial:"Commercial" };
function classify(text){
const t = text.toLowerCase().trim();
if(/\b(pric(e|ing)|cost|fees?\b|licen[cs]|subscription|discount|payment|invoice|commercial|quote)/.test(t)) return "commercial";
if(/^(do|does|is|are|can|will|has|have|must|shall)\b/.test(t) || /\b(yes\/no|confirm|compl(y|iant|iance)|certif|iso 27001|soc 2|gdpr|hipaa)/.test(t)) return "compliance";
if(/\b(architect|api\b|integrat|encrypt|security|sso\b|saml|scim|infrastructur|deploy|hosting|backup|disaster|uptime|sla\b|availab|scal(e|ab)|database|authenticat|audit log|penetration)/.test(t)) return "technical";
return "narrative";
}
const MAX_DOCS = 500; // sources allowed in the bucket
const MAX_DOC_CHARS = 220000; // per-document cap
const TOTAL_CHAR_BUDGET = 60e6; // ~60 MB of indexed text across the bucket
const CHUNK_SIZE = 1100; // retrieval chunk size (chars)
const SHARD_BUDGET = 4.2e6; // stay under 5MB per storage key; docs are sharded across keys
const $ = (id) => document.getElementById(id);
const esc = (s) => (s||"").replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
const fmtKB = (n) => n > 1e6 ? (n/1e6).toFixed(1)+" MB" : Math.max(1,Math.round(n/1024))+" KB";
const uid = () => Math.random().toString(36).slice(2,9);
function toast(msg, err=false){
const t = $("toast");
t.textContent = msg; t.className = err ? "show err" : "show";
clearTimeout(t._h); t._h = setTimeout(()=> t.className = "", 3200);
}
/* ---------- persistence: Claude cloud → browser localStorage (self-hosted) → memory ---------- */
const backend = (() => {
try{
if(window.storage && window.storage.get)
return { name: "claude", label: "Claude cloud",
set: (k,v) => window.storage.set(k,v),
get: async k => { const r = await window.storage.get(k); return r ? r.value : null; },
del: k => window.storage.delete(k) };
}catch(e){}
try{
localStorage.setItem("__cs_probe","1"); localStorage.removeItem("__cs_probe");
return { name: "local", label: "this browser",
set: async (k,v) => localStorage.setItem(k,v),
get: async k => localStorage.getItem(k),
del: async k => localStorage.removeItem(k) };
}catch(e){}
const mem = {};
return { name: "memory", label: "memory only (this tab)",
set: async (k,v) => { mem[k] = v; },
get: async k => mem[k] ?? null,
del: async k => { delete mem[k]; } };
})();
const store = {
async save(key, val){
try{ await backend.set(key, JSON.stringify(val)); }
catch(e){
console.warn("persist failed", e);
if(backend.name === "local") toast("Browser storage quota hit — use “Export workspace file” to keep your bucket", true);
}
},
async load(key){
try{ const v = await backend.get(key); return v ? JSON.parse(v) : null; }
catch(e){ return null; }
},
async del(key){ try{ await backend.del(key); }catch(e){} }
};
/* Docs are split across cs-docs-0..N keys (each < 5MB), described by cs-docs-meta. */
function serializableDoc(d){ return { id:d.id, name:d.name, type:d.type, size:d.size, chars:d.chars, text:d.text }; }
let _persistTimer = null, _lastShardCount = 0;
async function persistDocs(){
clearTimeout(_persistTimer);
_persistTimer = setTimeout(async () => {
const shards = [];
let cur = [], curSize = 2;
for(const d of S.docs){
const s = JSON.stringify(serializableDoc(d));
if(curSize + s.length > SHARD_BUDGET && cur.length){ shards.push(cur); cur = []; curSize = 2; }
cur.push(serializableDoc(d)); curSize += s.length + 1;
}
if(cur.length) shards.push(cur);
await store.save("cs-docs-meta", { shards: shards.length, count: S.docs.length, at: Date.now() });
for(let i = 0; i < shards.length; i++) await store.save("cs-docs-" + i, shards[i]);
for(let i = shards.length; i < _lastShardCount; i++) await store.del("cs-docs-" + i);
_lastShardCount = shards.length;
}, 400);
}
async function loadDocs(){
const meta = await store.load("cs-docs-meta");
if(meta && typeof meta.shards === "number"){
const out = [];
for(let i = 0; i < meta.shards; i++){
const shard = await store.load("cs-docs-" + i);
if(Array.isArray(shard)) out.push(...shard);
}
_lastShardCount = meta.shards;
return out;
}
// migrate from the old single-key format
const legacy = await store.load("cs-docs");
if(Array.isArray(legacy) && legacy.length){
setTimeout(() => { persistDocs(); store.del("cs-docs"); }, 800);
return legacy;
}
return [];
}
const persistQs = () => store.save("cs-questions", S.questions);
/* ---------- file parsing ---------- */
function extOf(name){ return name.split(".").pop().toLowerCase(); }
async function parseFile(file){
const ext = extOf(file.name);
const buf = await file.arrayBuffer();
let text = "";
if(ext === "pdf"){
const pdf = await pdfjsLib.getDocument({ data: buf }).promise;
const parts = [];
for(let p = 1; p <= pdf.numPages; p++){
const page = await pdf.getPage(p);
const tc = await page.getTextContent();
parts.push(tc.items.map(i => i.str).join(" "));
}
text = parts.join("\n\n");
} else if(ext === "docx"){
const res = await mammoth.extractRawText({ arrayBuffer: buf });
text = res.value;
} else if(ext === "xlsx" || ext === "xls" || ext === "csv"){
const wb = XLSX.read(buf, { type: "array" });
text = wb.SheetNames.map(n =>
"## Sheet: " + n + "\n" + XLSX.utils.sheet_to_csv(wb.Sheets[n])
).join("\n\n");
} else { // txt / md
text = new TextDecoder().decode(buf);
}
text = text.replace(/\u0000/g,"").replace(/[ \t]+\n/g,"\n").trim();
if(!text) throw new Error("No extractable text (scanned PDF?)");
return text.slice(0, MAX_DOC_CHARS);
}
/* ---------- retrieval: score bucket chunks against a question ---------- */
function chunksFor(doc){
if(doc._chunks) return doc._chunks;
const out = [];
for(let i = 0; i < doc.text.length; i += CHUNK_SIZE){
const t = doc.text.slice(i, i + CHUNK_SIZE + 200);
out.push({ text: t, low: t.toLowerCase() });
}
doc._chunks = out;
return out;
}
const STOP = new Set("the a an and or of to in for with on is are does do your our you we can how what which will be by as at from that this it its any all provide describe please detail such other".split(" "));
function keywords(q){
return [...new Set(q.toLowerCase().replace(/[^a-z0-9 ]/g," ").split(/\s+/)
.filter(w => w.length > 2 && !STOP.has(w)))];
}
function retrieve(question, budget = 11000){
const kws = keywords(question);
const scored = [];
for(const d of S.docs){
// cheap doc-level prescreen so a 500-source bucket doesn't scan every chunk
if(!d._low) d._low = d.text.toLowerCase();
let hit = false;
for(const k of kws){ if(d._low.includes(k)){ hit = true; break; } }
if(!hit) continue;
for(const ch of chunksFor(d)){
let score = 0;
for(const k of kws) if(ch.low.includes(k)) score += 1;
if(score > 0) scored.push({ score, doc: d.name, text: ch.text });
}
}
scored.sort((a,b) => b.score - a.score);
const picked = []; const srcs = new Set(); let used = 0;
for(const c of scored){
if(used + c.text.length > budget) continue;
picked.push(c); srcs.add(c.doc); used += c.text.length;
if(picked.length >= 12) break;
}
const maxScore = Math.max(1, kws.length);
const coverage = scored.length ? Math.min(1, (scored[0].score / maxScore) * 0.6 + Math.min(picked.length,6)/6 * 0.4) : 0;
return {
context: picked.map(c => `[Source: ${c.doc}]\n${c.text}`).join("\n\n---\n\n"),
sources: [...srcs],
coverage
};
}
/* ---------- AI providers ---------- */
function engineBase(){ return (S.settings.base || "").replace(/\/+$/, ""); }
function engineHeaders(){
const h = { "Content-Type": "application/json" };
if(S.settings.key) h["X-Team-Token"] = S.settings.key;
return h;
}
function engineMode(){ return S.settings.provider === "engine" && !!engineBase(); }
async function engineFetch(path, body){
const r = await fetch(engineBase() + path, { method: "POST", headers: engineHeaders(), body: JSON.stringify(body) });
const text = await r.text();
let data = null; try{ data = JSON.parse(text); }catch(e){}
if(!r.ok) throw new Error("Engine " + r.status + (data?.error?.message ? " — " + data.error.message : ""));
return data;
}
async function askAI(prompt){
const p = S.settings;
if(p.provider === "claude" || p.provider === "claude-key"){
const headers = { "Content-Type": "application/json" };
if(p.provider === "claude-key"){
if(!p.key) throw new Error("Add your Anthropic API key in AI settings");
headers["x-api-key"] = p.key;
headers["anthropic-version"] = "2023-06-01";
headers["anthropic-dangerous-direct-browser-access"] = "true";
}
const r = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers,
body: JSON.stringify({
model: p.provider === "claude-key" ? (p.model || "claude-sonnet-4-6") : "claude-sonnet-4-6",
max_tokens: 1000,
messages: [{ role: "user", content: prompt }]
})
});
if(!r.ok) throw new Error("Claude API " + r.status + (r.status === 401 ? " — check your API key" : ""));
const data = await r.json();
return (data.content || []).map(b => b.type === "text" ? b.text : "").join("");
}
if(p.provider === "engine"){
if(!engineBase()) throw new Error("Set the engine URL in AI settings");
const r = await fetch(engineBase() + "/proxy", {
method: "POST", headers: engineHeaders(),
body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 1000, messages: [{ role: "user", content: prompt }] })
});
const text = await r.text();
if(!r.ok){
let msg = "Engine " + r.status;
try{ msg += " — " + JSON.parse(text).error.message; }catch(e){}
throw new Error(msg);
}
const data = JSON.parse(text);
return (data.content || []).map(b => b.type === "text" ? b.text : "").join("");
}
if(p.provider === "proxy"){
const url = p.base || "proxy.php";
const headers = { "Content-Type": "application/json" };
if(p.key) headers["X-Team-Token"] = p.key; // key field doubles as the team token here
const r = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify({
model: p.model || "claude-sonnet-4-6",
max_tokens: 1000,
messages: [{ role: "user", content: prompt }]
})
});
const text = await r.text();
if(!r.ok){
let msg = "Proxy " + r.status;
try{ msg += " — " + JSON.parse(text).error.message; }catch(e){}
if(r.status === 401) msg += " (check the team token)";
throw new Error(msg);
}
const data = JSON.parse(text);
return (data.content || []).map(b => b.type === "text" ? b.text : "").join("");
}
if(p.provider === "gemini"){
if(!p.key) throw new Error("Add your Gemini API key in AI settings");
const model = p.model || "gemini-2.0-flash";
const r = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${encodeURIComponent(p.key)}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
});
if(!r.ok) throw new Error("Gemini API " + r.status);
const data = await r.json();
return data.candidates?.[0]?.content?.parts?.map(x => x.text).join("") || "";
}
// openai-compatible
if(!p.key) throw new Error("Add your API key in AI settings");
const base = (p.base || "https://api.openai.com/v1").replace(/\/$/,"");
const r = await fetch(base + "/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": "Bearer " + p.key },
body: JSON.stringify({
model: p.model || "gpt-4o-mini",
max_tokens: 1000,
messages: [{ role: "user", content: prompt }]
})
});
if(!r.ok) throw new Error("API " + r.status + " (endpoint may block browser calls)");
const data = await r.json();
return data.choices?.[0]?.message?.content || "";
}
function parseJSONish(text){
const clean = text.replace(/```json|```/g, "").trim();
const start = clean.indexOf("["), end = clean.lastIndexOf("]");
return JSON.parse(start >= 0 ? clean.slice(start, end + 1) : clean);
}
/* ================================================================
Page 1 — documentation bucket
================================================================ */
const dz = $("dropzone"), fi = $("file-input");
dz.addEventListener("click", () => fi.click());
dz.addEventListener("keydown", e => { if(e.key==="Enter"||e.key===" ") fi.click(); });
["dragover","dragenter"].forEach(ev => dz.addEventListener(ev, e => { e.preventDefault(); dz.classList.add("over"); }));
["dragleave","drop"].forEach(ev => dz.addEventListener(ev, e => { e.preventDefault(); dz.classList.remove("over"); }));
dz.addEventListener("drop", e => ingestFiles(e.dataTransfer.files));
fi.addEventListener("change", () => { ingestFiles(fi.files); fi.value = ""; });
async function ingestFiles(fileList){
const files = [...fileList];
let skippedDupes = 0, parsed = 0;
for(const f of files){
if(S.docs.length >= MAX_DOCS){
toast(`Bucket is at its ${MAX_DOCS}-source limit — remove documents to add more`, true);
break;
}
if(S.docs.some(d => d.name === f.name && d.size === f.size)){ skippedDupes++; continue; }
const row = { id: uid(), name: f.name, type: extOf(f.name), size: f.size, chars: 0, text: "", _loading: true };
S.docs.push(row); renderDocs();
try{
row.text = await parseFile(f);
row.chars = row.text.length;
const total = S.docs.reduce((a,d) => a + d.chars, 0);
if(total > TOTAL_CHAR_BUDGET){
S.docs = S.docs.filter(d => d.id !== row.id);
toast(`Bucket text budget (~${fmtKB(TOTAL_CHAR_BUDGET)}) reached — ${f.name} not added`, true);
renderDocs();
break;
}
row._loading = false;
parsed++;
}catch(err){
S.docs = S.docs.filter(d => d.id !== row.id);
toast(`Couldn't parse ${f.name}: ${err.message}`, true);
}
renderDocs();
}
if(parsed) toast(`Added ${parsed} document${parsed === 1 ? "" : "s"} to the bucket` + (skippedDupes ? ` · ${skippedDupes} duplicate${skippedDupes === 1 ? "" : "s"} skipped` : ""));
else if(skippedDupes) toast(`${skippedDupes} duplicate file${skippedDupes === 1 ? "" : "s"} skipped — already in the bucket`);
await persistDocs();
}
function renderDocs(){
const el = $("doc-list");
$("doc-count").textContent = S.docs.length + " / " + MAX_DOCS + " sources";
const total = S.docs.reduce((a,d) => a + d.chars, 0);
$("storage-label").textContent = fmtKB(total) + " indexed";
const pct = Math.min(100, Math.max(total / TOTAL_CHAR_BUDGET, S.docs.length / MAX_DOCS) * 100);
const m = $("storage-meter");
m.querySelector("i").style.width = pct + "%";
m.className = "meter" + (pct > 85 ? " bad" : pct > 60 ? " warn" : "");
$("to-workspace").disabled = S.docs.length === 0;
if(!S.docs.length){
el.innerHTML = '<div class="empty">Nothing in the bucket yet. Everything you add here becomes retrievable context for step 2.</div>';
return;
}
el.innerHTML = `<table><thead><tr>
<th>Document</th><th>Type</th><th>File size</th><th>Extracted text</th><th></th>
</tr></thead><tbody>` +
S.docs.map(d => `<tr>
<td style="font-weight:500">${esc(d.name)}</td>
<td><span class="ftype ${d.type}">${d.type.toUpperCase()}</span></td>
<td class="mono">${fmtKB(d.size)}</td>
<td class="mono">${d._loading ? "parsing…" : fmtKB(d.chars)}</td>
<td><button class="icon-btn" data-del="${d.id}" title="Remove" aria-label="Remove ${esc(d.name)}">✕</button></td>
</tr>`).join("") + "</tbody></table>";
el.querySelectorAll("[data-del]").forEach(b => b.onclick = async () => {
S.docs = S.docs.filter(d => d.id !== b.dataset.del);
renderDocs(); await persistDocs();
});
}
/* ================================================================
Page 2 — response workspace
================================================================ */
let rfpText = "";
let rfpWorkbook = null, rfpFileName = "", rfpMapping = null;
$("rfp-upload-btn").onclick = () => $("rfp-file-input").click();
$("rfp-file-input").addEventListener("change", async e => {
const f = e.target.files[0]; if(!f) return;
$("rfp-file-label").textContent = "Parsing " + f.name + "…";
try{
const ext = extOf(f.name);
if(["xlsx","xls","csv"].includes(ext)){
rfpWorkbook = XLSX.read(await f.arrayBuffer(), { type: "array", cellStyles: true });
rfpFileName = f.name;
setupSheetMap();
} else {