buildproof 0.0.0-stage → 3.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/index.html ADDED
@@ -0,0 +1,834 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <title>BuildProof</title>
7
+ <link rel="manifest" href="manifest.webmanifest">
8
+ <link rel="icon" type="image/png" sizes="32x32" href="favicon-32.png">
9
+ <link rel="apple-touch-icon" href="apple-touch-icon.png">
10
+ <meta name="apple-mobile-web-app-capable" content="yes">
11
+ <meta name="apple-mobile-web-app-title" content="BuildProof">
12
+ <meta name="apple-mobile-web-app-status-bar-style" content="default">
13
+ <meta name="theme-color" content="#FFFFFF">
14
+ <script src="html2canvas.min.js" defer onerror="var s=document.createElement('script');s.src='https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';document.head.appendChild(s);"></script>
15
+ <link rel="preconnect" href="https://fonts.googleapis.com">
16
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
17
+ <style>
18
+ :root {
19
+ --bg: #FFFFFF; --sub: #FAFAFA; --ink: #0A0A0A; --dim: #5F6368; --faint: #8A8F98; --line: #E6E6E6; --hover: #F5F7FB;
20
+ --blue: #1D4ED8; --blue-soft: #E8EEFF; --green: #12803F; --green-soft: #ECF7F0; --red: #C5221F; --red-soft: #FDF1F0; --amber: #B26A00; --amber-soft: #FFF6E6;
21
+ --ui: Inter, "Segoe UI", system-ui, -apple-system, sans-serif; --mono: "IBM Plex Mono", ui-monospace, Consolas, monospace;
22
+ --fs: 19px; --pad: 18px;
23
+ }
24
+ * { box-sizing: border-box; forced-color-adjust: none; -webkit-tap-highlight-color: transparent; }
25
+ html { -webkit-text-size-adjust: 100%; }
26
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 500 var(--fs)/1.45 var(--ui); }
27
+ button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
28
+ a { color: var(--blue); text-decoration: none; }
29
+ :focus-visible { outline: 3px solid var(--blue); outline-offset: 2px; }
30
+ .mono { font-family: var(--mono); font-size: .8em; }
31
+ .dim { color: var(--dim); }
32
+
33
+ /* ---------- shell ---------- */
34
+ .shell { min-height: 100vh; display: flex; flex-direction: column; }
35
+ .hdr { position: sticky; top: 0; z-index: 5; background: var(--bg); display: flex; align-items: center; gap: 12px; padding: calc(env(safe-area-inset-top) + 10px) var(--pad) 12px; border-bottom: 1px solid var(--line); }
36
+ .hdr img { width: 38px; height: 38px; border-radius: 9px; }
37
+ .hdr .nm { font-weight: 700; font-size: 22px; letter-spacing: -.3px; flex: 1; }
38
+ .chip { display: inline-flex; align-items: center; gap: 7px; border: 1px solid var(--line); border-radius: 999px; padding: 5px 12px; font-size: 14px; font-weight: 600; color: var(--dim); white-space: nowrap; max-width: 46vw; overflow: hidden; text-overflow: ellipsis; }
39
+ .d { width: 10px; height: 10px; border-radius: 50%; flex: none; display: inline-block; background: var(--faint); }
40
+ .d.g { background: var(--green); } .d.r { background: var(--red); } .d.a { background: var(--amber); } .d.b { background: var(--blue); box-shadow: 0 0 0 3px var(--blue-soft); }
41
+ .cam { width: 46px; height: 46px; border-radius: 12px; border: 1px solid var(--line); display: grid; place-items: center; flex: none; touch-action: manipulation; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
42
+ .cam.busy { opacity: .4; }
43
+ .main { flex: 1; display: flex; min-height: 0; }
44
+ .side { display: none; }
45
+ .list { flex: 1; min-width: 0; padding-bottom: 110px; }
46
+ .detail { display: none; flex: 1; min-width: 0; flex-direction: column; }
47
+ body.show-detail .list { display: none; }
48
+ body.show-detail .detail { display: flex; }
49
+ body.show-detail .tabs, body.show-detail .hdr { display: none; }
50
+ .dcam { display: none; } body.show-detail .dcam { display: grid; }
51
+ .tabs { position: fixed; left: 0; right: 0; bottom: 0; z-index: 6; background: #fff; border-top: 1px solid var(--line); display: flex; padding: 8px 4px calc(env(safe-area-inset-bottom) + 8px); }
52
+ .tab { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 2px; font-size: 13.5px; font-weight: 600; color: var(--faint); position: relative; }
53
+ .tab svg { width: 27px; height: 27px; } .tab.on { color: var(--ink); }
54
+ .tab .cnt { position: absolute; top: -2px; left: calc(50% + 8px); background: var(--amber); color: #fff; font-size: 12px; border-radius: 999px; min-width: 20px; height: 20px; display: grid; place-items: center; padding: 0 5px; }
55
+
56
+ /* ---------- desktop / tablet landscape ---------- */
57
+ @media (min-width: 1000px) {
58
+ :root { --fs: 18px; --pad: 24px; }
59
+ .hdr, .tabs { display: none !important; }
60
+ .shell { height: 100vh; }
61
+ .main { height: 100vh; }
62
+ .side { display: flex; flex-direction: column; width: 260px; flex: none; border-right: 1px solid var(--line); background: var(--sub); padding: 18px 12px; gap: 2px; }
63
+ .side .brand { display: flex; gap: 10px; align-items: center; padding: 0 8px 20px; font-weight: 700; font-size: 20px; }
64
+ .side .brand img { width: 32px; height: 32px; border-radius: 8px; }
65
+ .side .brand .cam { margin-left: auto; width: 38px; height: 38px; }
66
+ .nav { display: flex; gap: 12px; align-items: center; padding: 10px 12px; border-radius: 9px; font-weight: 600; color: var(--dim); text-align: left; width: 100%; }
67
+ .nav svg { width: 22px; height: 22px; } .nav:hover { background: #fff; }
68
+ .nav.on { background: #fff; color: var(--ink); box-shadow: 0 0 0 1px var(--line); }
69
+ .nav .cnt { margin-left: auto; font-size: 13px; background: #FFF1D6; color: var(--amber); border-radius: 999px; padding: 1px 9px; }
70
+ .side .foot { margin-top: auto; padding: 10px; font-size: 14px; color: var(--dim); line-height: 1.6; }
71
+ .list { flex: none; width: 480px; border-right: 1px solid var(--line); overflow-y: auto; padding-bottom: 30px; display: block !important; }
72
+ .detail { display: flex !important; overflow-y: auto; }
73
+ .wide .list { flex: 1; width: auto; border-right: 0; }
74
+ .wide .detail { display: none !important; }
75
+ .back { display: none !important; }
76
+ }
77
+
78
+ /* ---------- list pieces ---------- */
79
+ .top { display: flex; align-items: center; gap: 10px; padding: 16px var(--pad) 10px; }
80
+ .top h2 { margin: 0; font-size: 24px; letter-spacing: -.3px; flex: 1; }
81
+ .sec { padding: 18px var(--pad) 8px; font-size: 14.5px; font-weight: 600; color: var(--dim); display: flex; justify-content: space-between; text-transform: none; }
82
+ .metrics { display: flex; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
83
+ .m { flex: 1; padding: 14px 4px 12px var(--pad); border-left: 1px solid var(--line); min-width: 0; }
84
+ .m:first-child { border-left: 0; }
85
+ .m .v { font-weight: 700; font-size: 27px; line-height: 1; letter-spacing: -.5px; }
86
+ .m .k { font-size: 13.5px; font-weight: 600; color: var(--dim); margin-top: 6px; line-height: 1.25; }
87
+ .rows { border-top: 1px solid var(--line); }
88
+ .row { display: flex; gap: 12px; padding: 14px var(--pad); border-bottom: 1px solid var(--line); align-items: flex-start; width: 100%; text-align: left; }
89
+ .row:hover { background: var(--hover); }
90
+ .row.sel { background: var(--hover); box-shadow: inset 3px 0 0 var(--ink); }
91
+ .row.need { background: var(--amber-soft); }
92
+ .row .d { margin-top: 9px; }
93
+ .row .x { flex: 1; min-width: 0; }
94
+ .row .t { font-weight: 600; line-height: 1.3; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
95
+ .row .s { font-size: 15px; color: var(--dim); margin-top: 3px; }
96
+ .st { font-size: 15px; font-weight: 700; white-space: nowrap; }
97
+ .st.g { color: var(--green); } .st.r { color: var(--red); } .st.a { color: var(--amber); } .st.b { color: var(--blue); } .st.n { color: var(--dim); }
98
+ .bar { height: 5px; background: #EEF1F6; border-radius: 5px; margin-top: 10px; overflow: hidden; }
99
+ .bar i { display: block; height: 100%; background: var(--blue); border-radius: 5px; transition: width .4s ease; }
100
+ .empty { padding: 28px var(--pad); color: var(--dim); }
101
+
102
+ /* ---------- buttons / forms ---------- */
103
+ .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 54px; padding: 0 22px; border-radius: 12px; font-weight: 600; border: 1px solid #D4D4D4; background: #fff; white-space: nowrap; }
104
+ .btn.go { background: var(--ink); color: #fff; border-color: var(--ink); }
105
+ .btn.danger { color: var(--red); border-color: #F0C2BF; }
106
+ .btn.sm { min-height: 42px; padding: 0 16px; font-size: 16px; border-radius: 10px; }
107
+ .btn[disabled] { opacity: .45; pointer-events: none; }
108
+ .btn.full { width: 100%; }
109
+ .form { padding: 6px var(--pad) 20px; }
110
+ label.l { display: block; font-weight: 600; font-size: 16px; color: var(--dim); margin: 18px 0 8px; }
111
+ select, textarea, input[type=text] { width: 100%; font: 500 var(--fs)/1.4 var(--ui); padding: 14px; color: var(--ink); background: #fff; border: 1px solid #CFCFCF; border-radius: 12px; }
112
+ textarea { min-height: 130px; resize: vertical; }
113
+ .seg { display: flex; border: 1px solid var(--line); border-radius: 12px; padding: 4px; gap: 4px; background: var(--sub); }
114
+ .seg button { flex: 1; padding: 12px 8px; border-radius: 9px; font-weight: 600; font-size: 16px; color: var(--dim); line-height: 1.25; }
115
+ .seg button.on { background: #fff; color: var(--ink); box-shadow: 0 1px 2px rgba(0,0,0,.08), 0 0 0 1px var(--line); }
116
+ .hint { color: var(--dim); font-size: 15.5px; margin-top: 10px; }
117
+ .msg { margin-top: 12px; font-weight: 600; }
118
+
119
+ /* ---------- detail ---------- */
120
+ .dhead { display: flex; align-items: center; gap: 10px; padding: 14px var(--pad); border-bottom: 1px solid var(--line); position: sticky; top: 0; background: #fff; z-index: 3; }
121
+ @media (max-width: 999px) { .dhead { top: 0; padding-top: calc(env(safe-area-inset-top) + 12px); } }
122
+ .back { width: 40px; height: 40px; display: grid; place-items: center; margin-left: -10px; flex: none; }
123
+ .dhead .ttl { font-weight: 700; font-size: 21px; line-height: 1.2; }
124
+ .dhead .sub { font-size: 14.5px; color: var(--dim); }
125
+ .blk { padding: 16px var(--pad); border-bottom: 1px solid var(--line); }
126
+ .ask { font-weight: 600; font-size: 1.05em; line-height: 1.35; margin: 0; }
127
+ .err { font: 14.5px/1.55 var(--mono); color: #8A1C17; background: var(--red-soft); border: 1px solid #F5D0CD; border-radius: 10px; padding: 10px 12px; margin-top: 12px; white-space: pre-wrap; word-break: break-word; max-height: 190px; overflow: auto; }
128
+ .h3 { padding: 16px var(--pad) 6px; font-size: 14.5px; font-weight: 600; color: var(--dim); }
129
+ .chk { display: flex; align-items: center; gap: 12px; padding: 11px var(--pad); border-bottom: 1px solid var(--line); }
130
+ .chk .n { flex: 1; min-width: 0; } .chk .n small { color: var(--dim); font-size: 14.5px; }
131
+ .chk .tm { font: 14px var(--mono); color: var(--faint); }
132
+ .pill { font-size: 13.5px; font-weight: 700; border-radius: 7px; padding: 2px 8px; }
133
+ .pill.g { background: var(--green-soft); color: var(--green); } .pill.r { background: var(--red-soft); color: var(--red); } .pill.n { background: #F1F2F4; color: var(--dim); }
134
+ .file { display: flex; gap: 12px; align-items: flex-start; padding: 12px var(--pad); border-bottom: 1px solid var(--line); width: 100%; text-align: left; }
135
+ .box { width: 26px; height: 26px; border-radius: 7px; border: 2px solid var(--ink); display: grid; place-items: center; flex: none; margin-top: 1px; }
136
+ .box.on { background: var(--ink); } .box.lk { background: #F1F2F4; border-color: #F1F2F4; }
137
+ .path { font: 15px/1.4 var(--mono); word-break: break-all; }
138
+ .why { font-size: 14.5px; color: var(--dim); }
139
+ .kv { display: flex; flex-wrap: wrap; gap: 6px 18px; font-size: 15px; color: var(--dim); }
140
+ .kv b { color: var(--ink); font-weight: 600; }
141
+ .sum { display: flex; gap: 12px; align-items: center; }
142
+ .sum .ic { width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; flex: none; }
143
+ .sum .h { font-weight: 700; } .sum .p { font-size: 15px; color: var(--dim); }
144
+ .badge { display: inline-flex; align-items: center; gap: 8px; border-radius: 999px; padding: 5px 14px; font-weight: 800; font-size: 15px; letter-spacing: .5px; }
145
+ .badge.g { background: var(--green-soft); color: var(--green); border: 1px solid #BFE3CC; }
146
+ .badge.r { background: var(--red-soft); color: var(--red); border: 1px solid #F5D0CD; }
147
+ .badge.a { background: var(--amber-soft); color: var(--amber); border: 1px solid #F1D7A6; }
148
+ .badge.b { background: var(--blue-soft); color: var(--blue); border: 1px solid #C9D6FF; }
149
+ .seal { display: flex; gap: 14px; align-items: flex-start; } .seal > svg { flex: none; margin-top: 2px; }
150
+ .stepper { display: flex; align-items: flex-start; margin: 14px 0 2px; }
151
+ .sp { display: flex; flex-direction: column; align-items: center; gap: 5px; font-size: 13px; font-weight: 600; color: var(--faint); width: 62px; flex: none; }
152
+ .sp b { width: 30px; height: 30px; border-radius: 50%; display: grid; place-items: center; border: 2px solid var(--line); background: #fff; font-size: 14px; }
153
+ .sp.done b { background: var(--green); border-color: var(--green); color: #fff; } .sp.done { color: var(--ink); }
154
+ .sp.now b { border-color: var(--blue); color: var(--blue); } .sp.now { color: var(--blue); }
155
+ .sp.wait b { border-color: var(--amber); color: var(--amber); background: var(--amber-soft); } .sp.wait { color: var(--amber); }
156
+ .sp.bad b { background: var(--red); border-color: var(--red); color: #fff; } .sp.bad { color: var(--red); }
157
+ .ln { flex: 1; height: 3px; background: var(--line); margin-top: 14px; border-radius: 3px; } .ln.done { background: var(--green); }
158
+ .dock { position: sticky; bottom: 0; margin-top: auto; background: #fff; border-top: 1px solid var(--line); padding: 12px var(--pad) calc(env(safe-area-inset-bottom) + 14px); display: flex; gap: 10px; z-index: 2; }
159
+ .dock .btn { flex: 1; } .dock .btn.go { flex: 1.8; }
160
+ @media (min-width: 1000px) { .dock { justify-content: flex-end; } .dock .btn, .dock .btn.go { flex: none; min-width: 170px; } }
161
+ details { border-bottom: 1px solid var(--line); }
162
+ summary { padding: 14px var(--pad); font-weight: 600; cursor: pointer; list-style: none; display: flex; justify-content: space-between; }
163
+ summary::after { content: '+'; color: var(--dim); font-size: 22px; line-height: 1; } details[open] summary::after { content: '−'; }
164
+ pre { font: 13.5px/1.55 var(--mono); white-space: pre-wrap; word-break: break-word; background: var(--sub); border-top: 1px solid var(--line); margin: 0; padding: 12px var(--pad); max-height: 460px; overflow: auto; }
165
+ .add { color: var(--green); background: #EAF6EE; display: block; } .del { color: var(--red); background: #FCEEEE; display: block; }
166
+ .placeholder { margin: auto; text-align: center; color: var(--dim); padding: 40px; }
167
+ .placeholder svg { width: 56px; height: 56px; margin-bottom: 10px; }
168
+ .codeline { display: flex; gap: 8px; align-items: center; background: var(--sub); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; margin-top: 10px; }
169
+ .codeline code { font: 14.5px var(--mono); flex: 1; word-break: break-all; }
170
+
171
+ /* ---------- sheet / toast / camera ---------- */
172
+ .veil { position: fixed; inset: 0; background: rgba(10,10,10,.38); z-index: 40; display: flex; align-items: flex-end; justify-content: center; }
173
+ .sheet { background: #fff; width: 100%; max-width: 560px; border-radius: 20px 20px 0 0; padding: 22px var(--pad) calc(env(safe-area-inset-bottom) + 18px); max-height: 86vh; display: flex; flex-direction: column; }
174
+ @media (min-width: 1000px) { .veil { align-items: center; } .sheet { border-radius: 18px; } }
175
+ .sheet h3 { margin: 0 0 6px; font-size: 22px; }
176
+ .sheet .btns { display: flex; gap: 10px; margin-top: 18px; } .sheet .btns .btn { flex: 1; }
177
+ .picker { overflow-y: auto; border: 1px solid var(--line); border-radius: 12px; margin-top: 12px; flex: 1; min-height: 200px; }
178
+ .picker .file { padding: 12px 14px; }
179
+ .toast { position: fixed; left: 50%; bottom: calc(env(safe-area-inset-bottom) + 100px); transform: translateX(-50%); background: var(--ink); color: #fff; padding: 12px 18px; border-radius: 12px; font-size: 16px; z-index: 60; max-width: 90vw; text-align: center; }
180
+ html.inverted { filter: invert(1) hue-rotate(180deg); background: #000; }
181
+ html.inverted img { filter: invert(1) hue-rotate(180deg); }
182
+ .login { max-width: 520px; margin: 40px auto; padding: 0 var(--pad); }
183
+ @media (prefers-reduced-motion: reduce) { .bar i { transition: none; } }
184
+ </style>
185
+ </head>
186
+ <body>
187
+ <div id="toast" class="toast" role="status" hidden></div>
188
+ <div class="shell">
189
+ <header class="hdr">
190
+ <img src="icon-192.png" alt="">
191
+ <span class="nm">BuildProof</span>
192
+ <span class="chip" id="machine"><span class="d" id="dot"></span><span id="machineName">Connecting</span></span>
193
+ <button class="cam" id="cam" type="button" aria-label="Share a screenshot of this screen. Long press to invert colors."></button>
194
+ </header>
195
+ <div class="main" id="main">
196
+ <aside class="side" id="side"></aside>
197
+ <section class="list" id="list"></section>
198
+ <section class="detail" id="detail"></section>
199
+ </div>
200
+ <nav class="tabs" id="tabs"></nav>
201
+ </div>
202
+ <div id="sheetRoot"></div>
203
+
204
+ <script>
205
+ /* ================= icons ================= */
206
+ const IC = {
207
+ home: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z"/></svg>',
208
+ new: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg>',
209
+ projects: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M3 7a1 1 0 0 1 1-1h5l2 2h9a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z"/></svg>',
210
+ proofs: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/><path d="M8.5 12l2.5 2.5 4.5-5"/></svg>',
211
+ back: '<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M15 5l-7 7 7 7"/></svg>',
212
+ cam: '<svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 8h3l2-3h6l2 3h3a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/><circle cx="12" cy="14" r="4"/></svg>',
213
+ check: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="4"><path d="M5 12l5 5 9-10"/></svg>',
214
+ lock: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#5F6368" stroke-width="2.6"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>',
215
+ shield: (c, f) => `<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="${c}" stroke-width="2" stroke-linejoin="round"><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z" fill="${f}"/><path d="M8.5 12l2.5 2.5 4.5-5"/></svg>`,
216
+ shieldX: '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#C5221F" stroke-width="2" stroke-linejoin="round"><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z" fill="#FDF1F0"/><path d="M9.5 9.5l5 5M14.5 9.5l-5 5"/></svg>',
217
+ eye: '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#1D4ED8" stroke-width="2"><path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z" fill="#E8EEFF"/><circle cx="12" cy="12" r="3"/></svg>',
218
+ gear: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>',
219
+ key: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="8" cy="15" r="4"/><path d="M11 12l9-9M17 6l3 3M15 8l2 2"/></svg>',
220
+ folder: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M3 7a1 1 0 0 1 1-1h5l2 2h9a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z"/></svg>',
221
+ };
222
+
223
+ /* ================= state ================= */
224
+ const S = { claimDraft: {}, tasks: [], projects: [], certs: [], stats: null, status: null, detail: null, detailSig: '', route: 'home', id: null, newMode: 'task', scope: {}, open: new Set() };
225
+ const STATE = {
226
+ diagnosing: ['Diagnosing', 'b'], awaiting_approval: ['Approval', 'a'], executing: ['Working', 'b'], verifying: ['Verifying', 'b'],
227
+ done: ['Proven', 'g'], unproven: ['Not proven', 'a'], rolled_back: ['Rolled back', 'r'], failed: ['Not done', 'r'], stopped: ['Stopped', 'n'],
228
+ rejected: ['Rejected', 'n'], undone: ['Undone', 'n'], baselining: ['Starting guard', 'b'], watching: ['Watching', 'b'], checking: ['Checking', 'b'],
229
+ };
230
+ const RUNNING = ['diagnosing', 'executing', 'verifying', 'baselining', 'checking'];
231
+ const $ = (id) => document.getElementById(id);
232
+ const qs = new URLSearchParams(location.search);
233
+ if (qs.get('token')) { try { localStorage.setItem('bp_token', qs.get('token')); } catch {} history.replaceState(null, '', location.pathname + location.hash); }
234
+ let TOKEN = ''; try { TOKEN = localStorage.getItem('bp_token') || localStorage.getItem('mgr_token') || ''; if (TOKEN) localStorage.setItem('bp_token', TOKEN); } catch {}
235
+ const isPhone = () => !matchMedia('(min-width: 1000px)').matches;
236
+
237
+ function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
238
+ function ago(iso) {
239
+ if (!iso) return '';
240
+ const s = Math.max(0, (Date.now() - new Date(iso)) / 1000);
241
+ if (s < 60) return 'just now'; if (s < 3600) return Math.floor(s / 60) + 'm ago'; if (s < 86400) return Math.floor(s / 3600) + 'h ago';
242
+ return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
243
+ }
244
+ function secs(ms) { return ms == null ? '' : (ms / 1000).toFixed(ms < 10000 ? 1 : 0) + 's'; }
245
+ async function api(method, path, body) {
246
+ const r = await fetch(path, { method, headers: { authorization: 'Bearer ' + TOKEN, 'content-type': 'application/json' }, body: body ? JSON.stringify(body) : undefined });
247
+ if (r.status === 401) { showLogin(); throw new Error('unauthorized'); }
248
+ const j = await r.json();
249
+ if (r.status === 402 && ['needs_pro_remote', 'license_required'].includes(j.error) && S.route !== 'license') { S.block = j.error; setTimeout(() => go('license'), 0); }
250
+ return j;
251
+ }
252
+ function toast(msg) { const el = $('toast'); el.textContent = msg; el.hidden = false; clearTimeout(toast.t); toast.t = setTimeout(() => { el.hidden = true; }, 2800); }
253
+ const ERR = {
254
+ project_is_guarded: 'This project is being guarded. Finish the guard first (Accept or Rollback).',
255
+ project_busy: 'Another task is running on this project. Try again in a moment.',
256
+ changed_since_check: 'Files changed after the last check. Press Check again first.',
257
+ not_proven: 'Not proven. Fix it, or accept with warnings.', finish_guard_first: 'Finish the running guard first (Accept or Rollback).', check_first: 'Press Check first.', no_changes: 'Nothing changed yet.',
258
+ folder_not_found: 'No folder at that path.', empty_task: 'Describe the change first.',
259
+ plan_limit_projects: 'Your plan has reached its project limit. Upgrade or remove a project.', needs_pro: 'This needs the Pro plan.',
260
+ license_required: 'Your trial or license has ended. Activate a license key.', needs_pro_remote: 'Phone and tablet control needs the Pro plan.',
261
+ bad_endpoint: 'The server address must start with http:// or https://', unknown_provider: 'Unknown AI provider.',
262
+ invalid_key_format: 'That is not a BuildProof license key.', invalid_signature: 'This key is not valid.', key_expired: 'This key has expired.', no_vendor_key: 'Licensing is not set up in this copy yet.',
263
+ };
264
+ const errText = (e) => ERR[e] || ('Not done: ' + e);
265
+
266
+ /* ================= routing ================= */
267
+ function go(hash) { if (location.hash === '#' + hash) route(); else location.hash = hash; }
268
+ window.addEventListener('hashchange', route);
269
+ function route() {
270
+ const h = location.hash.replace(/^#\/?/, '') || 'home';
271
+ const [r, id] = h.split('/');
272
+ S.route = ['home', 'new', 'projects', 'proofs', 'task', 'cert', 'license', 'settings'].includes(r) ? r : 'home';
273
+ S.id = id || null;
274
+ if (S.route !== 'task' && S.route !== 'cert') { S.detail = null; S.detailSig = ''; }
275
+ render();
276
+ if (S.route === 'task' && S.id) loadDetail(true);
277
+ if (S.route === 'cert' && S.id) loadCert();
278
+ if (S.route === 'proofs') loadCerts();
279
+ if (S.route === 'license') loadLicense();
280
+ if (S.route === 'settings') loadAi();
281
+ window.scrollTo(0, 0);
282
+ }
283
+ function navTab() { return S.route === 'task' ? 'home' : S.route === 'cert' ? 'proofs' : S.route; }
284
+
285
+ /* ================= shell ================= */
286
+ function renderShell() {
287
+ const need = S.stats ? S.stats.needsYou : 0;
288
+ const items = [['home', 'Home', IC.home], ['new', 'New task', IC.new], ['projects', 'Projects', IC.projects], ['proofs', 'Proofs', IC.proofs]];
289
+ $('tabs').innerHTML = items.map(([k, label, ic]) => `<button class="tab ${navTab() === k ? 'on' : ''}" onclick="go('${k}')">${ic}${label}${k === 'home' && need ? `<span class="cnt">${need}</span>` : ''}</button>`).join('');
290
+ const st = S.status;
291
+ $('side').innerHTML = `<div class="brand"><img src="icon-192.png" alt="">BuildProof<button class="cam" type="button" data-cam aria-label="Screenshot">${IC.cam}</button></div>
292
+ ${items.map(([k, label, ic]) => `<button class="nav ${navTab() === k ? 'on' : ''}" onclick="go('${k}')">${ic}${label}${k === 'home' && need ? `<span class="cnt">${need}</span>` : ''}</button>`).join('')}
293
+ <button class="nav ${S.route === 'settings' ? 'on' : ''}" onclick="go('settings')">${IC.gear}Settings</button>
294
+ <button class="nav ${S.route === 'license' ? 'on' : ''}" onclick="go('license')">${IC.key}License${st && st.license && st.license.status !== 'active' ? `<span class="cnt">${st.license.status === 'trial' ? st.license.daysLeft + 'd' : '!'}</span>` : ''}</button>
295
+ <div class="foot">${st ? `<span class="chip"><span class="d ${st.ai.ok ? 'g' : 'r'}"></span>${st.ai.ok ? 'AI ready' : 'AI offline'}</span>
296
+ <div style="margin-top:10px">${esc(st.machine)}<br>${esc(st.aiLabel || st.ai.model || '')}<br>${S.stats ? fmtBytes(S.stats.bytesSentOff) : '0 B'} code sent off this PC<br><span class="mono">key ${esc((st.fingerprint || '').slice(0, 14))}…</span></div>` : 'Connecting…'}</div>`;
297
+ if (st) { $('dot').className = 'd ' + (st.ai.ok ? 'g' : 'r'); $('machineName').textContent = st.machine; }
298
+ wireCams();
299
+ }
300
+ function fmtBytes(n) { n = n || 0; return n < 1024 ? n + ' B' : n < 1048576 ? (n / 1024).toFixed(1) + ' KB' : (n / 1048576).toFixed(1) + ' MB'; }
301
+
302
+ function render() {
303
+ renderShell();
304
+ const detailRoute = S.route === 'task' || S.route === 'cert';
305
+ document.body.classList.toggle('show-detail', detailRoute && isPhone());
306
+ $('main').classList.toggle('wide', ['new', 'projects', 'license', 'settings'].includes(S.route));
307
+ if (S.route === 'home' || S.route === 'task') { $('list').innerHTML = homeHtml(); }
308
+ if (S.route === 'new') $('list').innerHTML = newHtml();
309
+ if (S.route === 'projects') $('list').innerHTML = projectsHtml();
310
+ if (S.route === 'proofs' || S.route === 'cert') $('list').innerHTML = proofsListHtml();
311
+ if (S.route === 'license') $('list').innerHTML = licenseHtml();
312
+ if (S.route === 'settings') $('list').innerHTML = aiHtml();
313
+ renderDetail();
314
+ }
315
+
316
+ /* ================= home ================= */
317
+ function stateOf(t) { return STATE[t.state] || [t.state, 'n']; }
318
+ function stepNo(t) { return { diagnosing: 1, awaiting_approval: 2, executing: 3, verifying: 4 }[t.state] || 5; }
319
+ function pct(t) { return t.kind === 'guard' ? (t.state === 'checking' ? 60 : 30) : { diagnosing: 18, awaiting_approval: 40, executing: 62, verifying: 84 }[t.state] || 100; }
320
+ function rowHtml(t) {
321
+ const [label, c] = stateOf(t);
322
+ let s = [esc(t.projectName)];
323
+ if (t.kind === 'guard') s.push(t.state === 'watching' ? (t.lastCheck ? `${t.lastCheck.ok ? 'proven' : t.lastCheck.files ? 'not proven' : 'no changes'} · checked ${ago(t.lastCheck.at)}` : `watching since ${ago(t.watchingSince || t.createdAt)}`) : t.state === 'done' ? 'certificate signed' : ago(t.finishedAt || t.createdAt));
324
+ else if (RUNNING.includes(t.state) && t.kind !== 'guard') s.push(`${label} ${stepNo(t)}/5`);
325
+ else if (t.state === 'awaiting_approval') s.push(`${(t.proposedScope || []).length} file${(t.proposedScope || []).length === 1 ? '' : 's'}`);
326
+ else if (t.state === 'rolled_back' && t.integrityFindings) s.push('test cheating blocked');
327
+ else if (t.state === 'done' && t.plan && ['learned', 'library'].includes(t.plan.kind)) s.push('library fix · 0 AI');
328
+ else if (t.finishedAt) s.push(ago(t.finishedAt));
329
+ else s.push(ago(t.createdAt));
330
+ const need = t.state === 'awaiting_approval';
331
+ const sel = S.route === 'task' && S.id === t.id ? ' sel' : '';
332
+ return `<button class="row${need ? ' need' : ''}${sel}" onclick="go('task/${t.id}')"><span class="d ${c}"></span><span class="x"><span class="t">${esc(t.kind === 'guard' ? 'Guard: ' + t.projectName : t.text)}</span><span class="s" style="display:block">${s.join(' · ')}</span>${RUNNING.includes(t.state) ? `<span class="bar" style="display:block"><i style="width:${pct(t)}%"></i></span>` : ''}</span><span class="st ${c}">${label}</span></button>`;
333
+ }
334
+ function homeHtml() {
335
+ const st = S.stats || { proven: 0, cheatsBlocked: 0, rolledBack: 0, bytesSentOff: 0 };
336
+ const needs = S.tasks.filter((t) => t.state === 'awaiting_approval' || (t.kind === 'guard' && ['watching', 'baselining', 'checking'].includes(t.state)));
337
+ const rest = S.tasks.filter((t) => !needs.includes(t)).slice(0, 30);
338
+ return `<div class="top"><h2>Home</h2><button class="btn sm go" onclick="go('new')">+ New task</button></div>${licenseBanner()}
339
+ <div class="sec" style="padding-top:4px"><span>Last 30 days</span></div>
340
+ <div class="metrics">
341
+ <div class="m"><div class="v" style="color:var(--green)">${st.proven}</div><div class="k">Proven</div></div>
342
+ <div class="m"><div class="v" style="color:${st.cheatsBlocked ? 'var(--red)' : 'var(--ink)'}">${st.cheatsBlocked}</div><div class="k">Cheats<br>blocked</div></div>
343
+ <div class="m"><div class="v">${st.rolledBack}</div><div class="k">Rolled<br>back</div></div>
344
+ <div class="m"><div class="v">${fmtBytes(st.bytesSentOff)}</div><div class="k">Code sent<br>off PC</div></div>
345
+ </div>
346
+ ${needs.length ? `<div class="sec"><span>Needs you</span></div><div class="rows">${needs.map(rowHtml).join('')}</div>` : ''}
347
+ <div class="sec"><span>Activity</span></div>
348
+ ${rest.length ? `<div class="rows">${rest.map(rowHtml).join('')}</div>` : `<div class="empty">${S.projects.length ? 'No tasks yet. Tap New task.' : 'Start by adding a project in Projects.'}</div>`}`;
349
+ }
350
+
351
+ function licenseBanner() {
352
+ const l = S.status && S.status.license;
353
+ if (!l || (l.status === 'active' && !l.inGrace && l.daysLeft > 7)) return '';
354
+ const txt = l.status === 'trial' ? `Trial · ${l.daysLeft} day${l.daysLeft === 1 ? '' : 's'} left · up to ${l.projects} projects`
355
+ : l.status === 'active' ? `${l.label} · renews in ${l.daysLeft} day${l.daysLeft === 1 ? '' : 's'}`
356
+ : `${l.label} ended · activate a license to keep guarding`;
357
+ return `<button class="row ${l.status === 'expired' ? '' : 'need'}" style="border-top:1px solid var(--line);${l.status === 'expired' ? 'background:var(--red-soft)' : ''}" onclick="go('license')"><span class="d ${l.status === 'expired' ? 'r' : 'a'}"></span><span class="x"><span class="t">${esc(txt)}</span></span><span class="st ${l.status === 'expired' ? 'r' : 'a'}">License</span></button>`;
358
+ }
359
+
360
+ /* ================= AI settings ================= */
361
+ const PROVIDERS = {
362
+ ollama: ['Local (Ollama)', 'Runs on this computer. Code never leaves it.', 'qwen3-coder:30b'],
363
+ openai: ['OpenAI or compatible', 'OpenAI, or any OpenAI-compatible server (LM Studio, OpenRouter...). Cloud servers receive the code.', 'model name, e.g. from your provider'],
364
+ anthropic: ['Anthropic API', 'Claude models with your own API key. Anthropic receives the code.', 'claude-sonnet-5-5'],
365
+ 'claude-code': ['Claude Code', 'Uses the Claude Code already installed here, with all its tools switched off.', 'optional model'],
366
+ };
367
+ async function loadAi() { const r = await api('GET', '/api/settings/ai'); if (r.ok) { S.ai = r; S.aiPick = S.aiPick || r.provider; if (S.route === 'settings') $('list').innerHTML = aiHtml(); } }
368
+ function aiHtml() {
369
+ const a = S.ai; if (!a) return '<div class="top"><h2>Settings</h2></div><div class="empty">Loading…</div>';
370
+ const pick = S.aiPick || a.provider; const P = PROVIDERS[pick];
371
+ const keyName = pick === 'openai' ? 'hasOpenaiKey' : pick === 'anthropic' ? 'hasAnthropicKey' : null;
372
+ return `<div class="top"><h2>Settings</h2></div>
373
+ <div class="blk"><div class="sum"><span class="ic" style="background:${a.health.ok ? 'var(--green-soft)' : 'var(--red-soft)'}"><span class="d ${a.health.ok ? 'g' : 'r'}"></span></span><div><div class="h">AI for "BuildProof fixes it": ${esc(a.label)}</div><div class="p">${a.health.ok ? 'Ready' : 'Not ready: ' + esc(a.health.reason)} · ${a.local ? 'code stays on this computer' : 'code is sent to the AI provider'}</div></div></div></div>
374
+ <div class="form" style="max-width:720px">
375
+ <label class="l">AI provider</label>
376
+ <div class="seg" style="flex-wrap:wrap">${Object.entries(PROVIDERS).map(([k, v]) => `<button class="${pick === k ? 'on' : ''}" onclick="S.aiPick='${k}';$('list').innerHTML=aiHtml()">${esc(v[0])}</button>`).join('')}</div>
377
+ <div class="hint">${esc(P[1])}</div>
378
+ <label class="l" for="aimodel">Model</label><input type="text" id="aimodel" value="${esc(pick === a.provider ? a.model : '')}" placeholder="${esc(P[2])}">
379
+ ${pick === 'openai' || pick === 'ollama' ? `<label class="l" for="aiend">Server address <span style="font-weight:500">(optional)</span></label><input type="text" id="aiend" value="${esc(pick === a.provider ? a.endpoint : '')}" placeholder="${pick === 'openai' ? 'https://api.openai.com/v1' : 'http://127.0.0.1:11434'}">` : ''}
380
+ ${keyName ? `<label class="l" for="aikey">API key ${a[keyName] ? '<span class="pill g">saved</span>' : ''}</label><input type="password" id="aikey" autocomplete="off" placeholder="${a[keyName] ? 'leave empty to keep the saved key' : 'paste your API key'}"><div class="hint">Stored only on this computer. It is never shown again.</div>` : ''}
381
+ <div style="margin-top:16px"><button class="btn go" onclick="saveAi()">Save and test</button></div><div id="aimsg" class="msg" role="status"></div>
382
+ <div class="hint" style="margin-top:22px">Guard mode does not use this - it checks the AI tool you already work with.</div>
383
+ </div>`;
384
+ }
385
+ async function saveAi() {
386
+ const body = { provider: S.aiPick || S.ai.provider, model: ($('aimodel') || {}).value || '', endpoint: ($('aiend') || {}).value || '', apiKey: ($('aikey') || {}).value || '' };
387
+ const r = await api('POST', '/api/settings/ai', body);
388
+ if (!r.ok) { $('aimsg').textContent = errText(r.error); return; }
389
+ S.ai = r; $('list').innerHTML = aiHtml(); toast(r.health.ok ? 'AI ready' : 'Saved, but not ready: ' + r.health.reason); loadStats().then(renderShell);
390
+ }
391
+
392
+ /* ================= license ================= */
393
+ async function loadLicense() { const r = await api('GET', '/api/license'); if (r.ok) { S.lic = r; if (S.route === 'license') $('list').innerHTML = licenseHtml(); } }
394
+ function licenseHtml() {
395
+ const l = S.lic;
396
+ if (!l) return '<div class="top"><h2>License</h2></div><div class="empty">Loading…</div>';
397
+ const block = S.block ? `<div class="blk" style="background:var(--red-soft)"><b style="color:var(--red)">${esc(errText(S.block))}</b></div>` : '';
398
+ const cur = l.status === 'trial' ? `Trial · ${l.daysLeft} days left · up to ${l.projects} projects · every Pro feature`
399
+ : l.status === 'active' ? `${l.label} · active until ${String(l.expires).slice(0, 10)}${l.email ? ' · ' + esc(l.email) : ''}`
400
+ : `${l.label} · ended. History, proofs and certificates stay available; new work is locked.`;
401
+ const order = ['basic', 'pro', 'team', 'enterprise'];
402
+ const plans = order.map((k) => { const p = l.plans[k]; const on = l.plan === k && l.status === 'active';
403
+ return `<div class="row" style="${on ? 'background:var(--green-soft)' : ''}"><span class="d ${on ? 'g' : ''}"></span><span class="x"><span class="t">${esc(p.label)} <span style="color:var(--dim);font-weight:500">· ${esc(p.price)}</span>${on ? ' <span class="pill g">your plan</span>' : ''}</span>
404
+ <span class="s" style="display:block">${p.projects ? `Up to ${p.projects} projects · ` : 'Unlimited projects · '}${p.features.map((f) => esc(l.featureText[f])).join(' · ')}</span></span></div>`; }).join('');
405
+ return `<div class="top"><h2>License</h2></div>${block}
406
+ <div class="blk"><div class="sum"><span class="ic" style="background:${l.status === 'expired' ? 'var(--red-soft)' : l.status === 'trial' ? 'var(--amber-soft)' : 'var(--green-soft)'}"><span class="d ${l.status === 'expired' ? 'r' : l.status === 'trial' ? 'a' : 'g'}"></span></span><div><div class="h">${esc(cur)}</div></div></div></div>
407
+ <div class="form" style="max-width:720px"><label class="l" for="lkey">License key</label><textarea id="lkey" style="min-height:90px;font-family:var(--mono);font-size:15px" placeholder="BP1.…"></textarea>
408
+ <div style="margin-top:12px"><button class="btn go" onclick="activateKey()">Activate</button></div><div id="lmsg" class="msg" role="status"></div></div>
409
+ <div class="sec"><span>Plans</span></div><div class="rows">${plans}</div>
410
+ <div class="empty" style="padding-top:14px">Every plan starts with a 14-day trial (up to 2 projects). Works offline - the key is checked on this computer.</div>`;
411
+ }
412
+ async function activateKey() {
413
+ const r = await api('POST', '/api/license', { key: $('lkey').value.trim() });
414
+ if (!r.ok) { $('lmsg').textContent = errText(r.error); $('lmsg').style.color = 'var(--red)'; return; }
415
+ S.block = null; toast(`${r.license.label} activated`); await loadStats(); await loadLicense(); renderShell();
416
+ }
417
+
418
+ /* ================= new task ================= */
419
+ function newHtml() {
420
+ const opts = S.projects.map((p) => `<option value="${p.id}">${esc(p.name)}</option>`).join('');
421
+ const m = S.newMode;
422
+ return `<div class="top"><h2>New task</h2></div>
423
+ <div class="form" style="max-width:720px">
424
+ <div class="seg"><button class="${m === 'task' ? 'on' : ''}" onclick="S.newMode='task';render()">BuildProof fixes it</button><button class="${m === 'guard' ? 'on' : ''}" onclick="S.newMode='guard';render()">Guard my AI tool</button></div>
425
+ ${S.projects.length ? `<label class="l" for="proj">Project</label><select id="proj">${opts}</select>` : `<div class="hint">No projects yet. <a href="#projects">Add a project</a> first.</div>`}
426
+ ${m === 'task' ? `
427
+ <label class="l" for="text">What should change?</label>
428
+ <textarea id="text" placeholder="Example: The total on the cart page is wrong, fix it. Naming a file helps: src/cart.js"></textarea>
429
+ <div class="hint">BuildProof diagnoses first and shows you the plan. Nothing is changed before you approve.</div>
430
+ <div style="margin-top:18px"><button class="btn go full" onclick="sendTask()">Diagnose and plan</button></div>`
431
+ : `
432
+ <div class="hint" style="font-size:17px;color:var(--ink);margin-top:18px">Keep working in Cursor, Claude Code, Copilot or any AI tool. BuildProof copies the project and records the current checks. When the AI says "done", press <b>Check</b>: it catches deleted, skipped or weakened tests, silent catches and regressions, then signs a certificate or rolls everything back.</div>
433
+ <div style="margin-top:18px"><button class="btn go full" onclick="startGuard()">Start guard</button></div>
434
+ <div class="hint">Make it automatic: <a href="#projects">Projects</a> → AI tools → Claude Code / Cursor / git. Or from a terminal:</div>
435
+ <div class="codeline"><code>buildproof check || exit 2</code></div>`}
436
+ <div id="sendMsg" class="msg" role="status"></div>
437
+ </div>`;
438
+ }
439
+ async function sendTask() {
440
+ const projectId = $('proj') && $('proj').value; const text = ($('text').value || '').trim();
441
+ if (!projectId || !text) { $('sendMsg').textContent = 'Choose a project and describe the change.'; return; }
442
+ const r = await api('POST', '/api/tasks', { projectId, text, source: isPhone() ? 'phone' : 'computer' });
443
+ if (!r.ok) { $('sendMsg').textContent = errText(r.error); return; }
444
+ await loadTasks(true); go('task/' + r.task.id);
445
+ }
446
+ async function startGuard() {
447
+ const projectId = $('proj') && $('proj').value;
448
+ if (!projectId) return;
449
+ const r = await api('POST', '/api/guards', { projectId, source: isPhone() ? 'phone' : 'computer' });
450
+ if (!r.ok) { $('sendMsg').textContent = errText(r.error); return; }
451
+ await loadTasks(true); go('task/' + r.task.id);
452
+ }
453
+
454
+ /* ================= projects ================= */
455
+ function projectsHtml() {
456
+ return `<div class="top"><h2>Projects</h2><button class="btn sm" onclick="go('settings')">AI settings</button><button class="btn sm go" onclick="openPicker('')">+ Add project</button></div>
457
+ <div class="rows">${S.projects.map((p) => `<div class="row"><span class="d ${p.verify.length ? 'g' : 'a'}"></span><span class="x"><span class="t">${esc(p.name)}</span><span class="s path" style="display:block">${esc(p.root)}</span>
458
+ <span class="s" style="display:block">${esc(p.type)} · ${p.verify.length ? 'proof: ' + esc(p.verify.join(', ')) : 'no build/test script - cannot be proven'}</span>
459
+ ${(p.notes || []).map((n) => `<span class="s" style="display:block;color:var(--amber)">${esc(n)}</span>`).join('')}
460
+ <span class="s" style="display:block">${toolsLine(p)}</span></span>
461
+ <span style="display:flex;flex-direction:column;gap:8px"><button class="btn sm" onclick="openTools('${p.id}')">AI tools</button><button class="btn sm" onclick="delProject('${p.id}', '${esc(p.name)}')">Remove</button></span></div>`).join('') || '<div class="empty">No projects yet. Tap Add project and pick the folder of a Node or web project.</div>'}</div>`;
462
+ }
463
+ const TOOL_NAMES = { claude: 'Claude Code', cursor: 'Cursor', git: 'git commits' };
464
+ function toolsLine(p) {
465
+ const on = Object.entries(p.hooks || {}).filter(([, v]) => v.connected).map(([k]) => TOOL_NAMES[k]);
466
+ return on.length ? `<span style="color:var(--green)">● Auto-guard: ${on.join(', ')}</span>` : 'Auto-guard: not connected';
467
+ }
468
+ function openTools(id, keep) {
469
+ const p = S.projects.find((x) => x.id === id); if (!p) return;
470
+ if (!keep || !window.__tl || __tl.id !== id) window.__tl = { id, sel: new Set(Object.entries(p.hooks || {}).filter(([, v]) => v.connected).map(([k]) => k)) };
471
+ const row = (k, desc) => { const h = (p.hooks || {})[k] || {}; const on = __tl.sel.has(k);
472
+ return `<button class="file" ${h.available === false ? 'disabled style="opacity:.45"' : ''} onclick="__tl.sel.has('${k}') ? __tl.sel.delete('${k}') : __tl.sel.add('${k}'); openTools('${id}', true)"><span class="box ${on ? 'on' : ''}">${on ? IC.check : ''}</span><span><span style="display:block;font-weight:600">${TOOL_NAMES[k]}${h.connected ? ' <span class="pill g">connected</span>' : ''}</span><span class="why">${h.available === false ? 'This folder is not a git repository' : desc}</span></span></button>`; };
473
+ sheet(`<h3>Guard AI tools automatically</h3><div class="dim">${esc(p.name)} · BuildProof starts a guard when you send a prompt, and checks when the AI says it is done. If it is not proven, the AI is told why and must fix it.</div>
474
+ <div class="picker" style="flex:none;min-height:0">${row('claude', 'Prompt starts the guard · Stop runs the check')}${row('cursor', 'Prompt starts the guard · Stop runs the check')}${row('git', 'A commit is blocked when the change is not proven')}</div>
475
+ <div class="btns"><button class="btn" onclick="closeSheet()">Cancel</button><button class="btn go" onclick="saveTools()">Save</button></div>`);
476
+ }
477
+ async function saveTools() {
478
+ const p = S.projects.find((x) => x.id === __tl.id);
479
+ const want = __tl.sel; const had = new Set(Object.entries(p.hooks || {}).filter(([, v]) => v.connected).map(([k]) => k));
480
+ const add = [...want].filter((k) => !had.has(k)); const del = [...had].filter((k) => !want.has(k));
481
+ let r = { ok: true };
482
+ if (add.length) r = await api('POST', `/api/projects/${p.id}/hooks`, { tools: add });
483
+ if (r.ok && del.length) r = await api('DELETE', `/api/projects/${p.id}/hooks`, { tools: del });
484
+ closeSheet();
485
+ toast(r.ok ? 'Saved' : errText(r.error || 'hooks_failed'));
486
+ await loadProjects(); render();
487
+ }
488
+ async function openPicker(p) {
489
+ const r = await api('GET', '/api/fs?path=' + encodeURIComponent(p));
490
+ if (!r.ok) { toast('Cannot open that folder'); return; }
491
+ window.__pk = { here: r.path, up: r.parent, dirs: r.dirs.map((d) => d.path) };
492
+ sheet(`<h3>Choose the project folder</h3><div class="path dim">${esc(r.path || 'This computer')}</div>
493
+ <div class="picker">${r.parent != null && r.path ? `<button class="file" onclick="openPicker(__pk.up)">${IC.back}<span>Up</span></button>` : ''}
494
+ ${r.dirs.map((d, i) => `<button class="file" onclick="openPicker(__pk.dirs[${i}])">${IC.folder}<span class="x" style="flex:1">${esc(d.name)}</span>${d.isProject ? '<span class="pill g">project</span>' : ''}</button>`).join('') || '<div class="empty">No folders here.</div>'}</div>
495
+ <div class="btns"><button class="btn" onclick="closeSheet()">Cancel</button><button class="btn go" ${r.path ? '' : 'disabled'} onclick="addProject(__pk.here)">${r.isProject ? 'Add this project' : 'Use this folder'}</button></div>`);
496
+ }
497
+ async function addProject(root) {
498
+ const r = await api('POST', '/api/projects', { root });
499
+ if (!r.ok) { toast(errText(r.error)); return; }
500
+ closeSheet(); toast('Added ' + r.project.name); await loadProjects(); render();
501
+ }
502
+ function delProject(id, name) {
503
+ confirmSheet(`Remove ${name}?`, 'It is only removed from this list. Files on disk are not touched.', 'Remove', async () => { await api('DELETE', '/api/projects/' + id); await loadProjects(); render(); });
504
+ }
505
+
506
+ /* ================= proofs ================= */
507
+ function proofsListHtml() {
508
+ return `<div class="top"><h2>Proofs</h2></div>
509
+ <div class="rows">${S.certs.map((c) => `<button class="row${S.route === 'cert' && S.id === c.id ? ' sel' : ''}" onclick="go('cert/${c.id}')"><span class="d ${c.result === 'PROVEN' ? 'g' : 'a'}"></span><span class="x"><span class="t">${esc(c.task)}</span><span class="s" style="display:block">${esc(c.project)} · ${ago(c.issuedAt)}</span></span><span class="st ${c.result === 'PROVEN' ? 'g' : 'a'}">${c.result === 'PROVEN' ? 'Proven' : 'Warnings'}</span></button>`).join('') || '<div class="empty">Signed certificates appear here when work is proven.</div>'}</div>`;
510
+ }
511
+
512
+ /* ================= detail ================= */
513
+ function placeholder() {
514
+ const what = S.route === 'proofs' ? 'Select a certificate' : 'Select a task';
515
+ return `<div class="placeholder">${IC.proofs.replace('<svg', '<svg width="56" height="56"')}<div>${what}</div></div>`;
516
+ }
517
+ function dhead(title, sub) {
518
+ return `<div class="dhead"><button class="back" onclick="history.length > 1 ? history.back() : go('home')" aria-label="Back">${IC.back}</button><div style="flex:1;min-width:0"><div class="ttl">${esc(title)}</div><div class="sub">${sub}</div></div><button class="cam dcam" type="button" data-cam aria-label="Share a screenshot of this screen. Long press to invert colors."></button></div>`;
519
+ }
520
+ function renderDetail() {
521
+ const el = $('detail');
522
+ if (S.route === 'cert') { el.innerHTML = S.cert && S.cert.id === S.id ? certHtml(S.cert) : dhead('Proof', 'Loading…'); wireCams(); return; }
523
+ if (S.route !== 'task' || !S.id) { el.innerHTML = isPhone() ? '' : placeholder(); return; }
524
+ const t = S.detail && S.detail.id === S.id ? S.detail : S.tasks.find((x) => x.id === S.id);
525
+ if (!t) { el.innerHTML = dhead('Task', 'Loading…'); return; }
526
+ el.innerHTML = t.kind === 'guard' ? guardHtml(t) : taskHtml(t);
527
+ wireCams();
528
+ for (const d of el.querySelectorAll('details[data-k]')) d.addEventListener('toggle', () => { d.open ? S.open.add(d.dataset.k) : S.open.delete(d.dataset.k); });
529
+ }
530
+ function stepper(t) {
531
+ // status of each of the 5 steps: done | now | wait | bad | '' (not reached)
532
+ const names = ['Diagnose', 'Approve', 'Fix', 'Verify', 'Proof'];
533
+ const at = (k, last) => names.map((_, i) => (i + 1 < k ? 'done' : i + 1 === k ? last : ''));
534
+ const st = {
535
+ diagnosing: at(1, 'now'), awaiting_approval: at(2, 'wait'), executing: at(3, 'now'), verifying: at(4, 'now'),
536
+ done: at(6, ''), undone: at(6, ''), rejected: at(2, 'bad'), unproven: at(5, 'bad'),
537
+ rolled_back: at(4, 'bad'), stopped: at(t.approvedAt ? 3 : 1, 'bad'), failed: at(t.approvedAt ? 3 : t.plan ? 2 : 1, 'bad'),
538
+ }[t.state] || at(1, 'now');
539
+ return `<div class="stepper">${names.map((nm, i) => {
540
+ const cls = st[i];
541
+ return `${i ? `<div class="ln ${cls === 'done' || (cls && st[i - 1] === 'done' && cls !== '') ? 'done' : ''}"></div>` : ''}<div class="sp ${cls}"><b>${cls === 'done' ? '✓' : cls === 'bad' ? '✕' : i + 1}</b>${nm}</div>`;
542
+ }).join('')}</div>`;
543
+ }
544
+ function checksHtml(base, after, steps) {
545
+ const keys = steps && steps.length ? steps : Object.keys(after || base || {});
546
+ if (!keys.length) return '<div class="chk"><span class="d a"></span><span class="n">No build or test script in this project</span></div>';
547
+ return keys.map((s) => {
548
+ const a = after && after[s]; const b = base && base[s];
549
+ const r = a || b;
550
+ const c = !r ? 'n' : r.pass ? 'g' : 'r';
551
+ const word = !r ? 'not run' : r.pass ? 'pass' : r.ran === false ? 'did not run' : 'fail';
552
+ const tests = r && r.tests ? ` <small>· ${r.tests.passed}/${r.tests.total} tests</small>` : '';
553
+ const was = a && b ? ` <small>· was ${b.pass ? 'passing' : b.ran === false ? 'not running' : 'failing'}</small>` : '';
554
+ return `<div class="chk"><span class="d ${c}"></span><span class="n">${esc(s)}${tests}${was}</span><span class="pill ${c}">${word}</span><span class="tm">${r ? secs(r.ms) : ''}</span></div>`;
555
+ }).join('');
556
+ }
557
+ function integrityHtml(integ) {
558
+ if (!integ) return '';
559
+ if (integ.clean) return `<div class="h3">Test integrity · clean · ${integ.rulesChecked.length} rules</div>
560
+ <div class="chk"><span class="d g"></span><span class="n">No tests deleted, skipped or weakened</span></div>
561
+ <div class="chk"><span class="d g"></span><span class="n">No new mocks, sleeps or silent catches</span></div>
562
+ <div class="chk"><span class="d g"></span><span class="n">No checks silenced or test scripts changed</span></div>`;
563
+ return `<div class="h3" style="color:var(--red)">Test integrity · ${integ.findings.length} problem${integ.findings.length === 1 ? '' : 's'}</div>` +
564
+ integ.findings.map((f) => `<div class="chk"><span class="d r"></span><span class="n">${esc(f.text)}<br><small class="path">${esc(f.file)}${f.detail ? ' · ' + esc(f.detail) : ''}</small></span></div>`).join('');
565
+ }
566
+ function hiddenBugsHtml(hb) {
567
+ if (!hb) return '';
568
+ if (hb.error) return `<div class="blk"><b>Hidden bug hunt</b>: not finished (${esc(hb.error)}).</div>`;
569
+ const label = { HANG: 'never finishes', CRASH: 'crashes', BAD_VALUE: 'returns a broken value', INPUT_MUTATION: 'changes the caller\'s data', ORDER: 'depends on earlier calls', RACE: 'breaks when called at the same time' };
570
+ if (!hb.findings.length) return `<div class="blk"><b>Hidden bug hunt</b>: nothing found in ${hb.stats ? hb.stats.calls : 0} extra calls.${hb.regressions.length ? ` ${hb.regressions.length} behaviour change(s) from the old code - check they are intended.` : ''}</div>`;
571
+ return `<div class="blk" style="background:var(--red-soft)"><b>Hidden bug hunt: ${hb.findings.length} possible bug(s) the tests miss</b>${hb.findings.slice(0, 8).map((f) => `<div class="codeline"><code>${esc(f.file)} ${esc(f.export)}(${esc(f.inputPreview)}) ${label[f.oracle] || f.oracle}: ${esc(f.outcome)}</code></div>`).join('')}<div>Evidence saved. Re-run one: <code>buildproof repro &lt;evidence.json&gt;</code></div></div>`;
572
+ }
573
+ function revertHtml(rc) {
574
+ if (!rc || rc.verdict === 'skipped') return '';
575
+ const c = rc.verdict === 'covered' ? 'g' : rc.verdict === 'flaky' ? 'r' : 'a';
576
+ return `<div class="h3">Revert check</div><div class="chk"><span class="d ${c}"></span><span class="n">${esc(rc.text)}</span><span class="pill ${c === 'a' ? 'n' : c}">${esc({ covered: 'covered', flaky: 'flaky', not_covered: 'not covered' }[rc.verdict] || rc.verdict)}</span></div>`;
577
+ }
578
+ function claimsHtml(list) {
579
+ if (!list || !list.length) return '';
580
+ const bad = list.filter((c) => c.truth === false).length;
581
+ return `<div class="h3" style="${bad ? 'color:var(--red)' : ''}">What the AI said${bad ? ` · ${bad} not true` : ' · checked'}</div>` + list.map((c) => `<div class="chk"><span class="d ${c.truth === false ? 'r' : c.truth ? 'g' : ''}"></span><span class="n">${c.truth === false ? '<b style="color:var(--red)">Not true:</b> ' : ''}${esc(c.text)}<br><small>${esc(c.why)}</small></span></div>`).join('');
582
+ }
583
+ function diffHtml(d) {
584
+ return esc(d).split('\n').map((l) => /^\+(?!\+\+)/.test(l) ? `<span class="add">${l}</span>` : /^-(?!--)/.test(l) ? `<span class="del">${l}</span>` : l).join('\n');
585
+ }
586
+ function moreHtml(t) {
587
+ const diffs = (t.diffs || []).map((d) => `<div class="path" style="padding:10px var(--pad) 4px">${esc(d.file)}</div><pre>${diffHtml(d.diff)}</pre>`).join('');
588
+ const log = (t.log || []).map((l) => `${l.at.slice(11, 19)} ${l.line}`).join('\n');
589
+ return `${diffs ? `<details data-k="diff-${t.id}" ${S.open.has('diff-' + t.id) ? 'open' : ''}><summary><span>Changes${t.lineStats ? ` · <span style="color:var(--green)">+${t.lineStats.plus}</span> <span style="color:var(--red)">−${t.lineStats.minus}</span>` : ''}</span></summary>${diffs}</details>` : ''}
590
+ <details data-k="log-${t.id}" ${S.open.has('log-' + t.id) ? 'open' : ''}><summary><span>Log</span></summary><pre>${esc(log)}</pre></details>`;
591
+ }
592
+ function firstError(base) {
593
+ const f = Object.entries(base || {}).find(([, r]) => !r.pass);
594
+ if (!f) return '';
595
+ const lines = String(f[1].output || '').split('\n').map((l) => l.trimEnd()).filter((l) => l && !/^>|^npm (ERR|error)|^\.\.\.$/.test(l));
596
+ const pick = lines.filter((l) => /error|expected|assert|fail|✗|×|cannot|undefined|not /i.test(l)).slice(0, 4);
597
+ return `<div class="err">✗ ${esc(f[0])}${f[1].reason ? ' · ' + esc(f[1].reason) : ''}\n${esc((pick.length ? pick : lines.slice(-4)).join('\n'))}</div>`;
598
+ }
599
+ function sourceSub(t) { return `${esc(t.projectName)} · from ${esc(t.source === 'phone' || t.source === 'mobile' ? 'phone' : t.source === 'cli' ? 'terminal' : t.source === 'computer' || t.source === 'desktop' ? 'computer' : t.source)} · ${ago(t.createdAt)}`; }
600
+
601
+ function taskHtml(t) {
602
+ const [label, c] = stateOf(t);
603
+ const plan = t.plan || {};
604
+ let h = dhead(t.state === 'awaiting_approval' ? 'Review plan' : label, sourceSub(t));
605
+ h += `<div class="blk"><p class="ask">${esc(t.text)}</p>${stepper(t)}${RUNNING.includes(t.state) ? `<div class="bar"><i style="width:${pct(t)}%"></i></div><div class="hint">${esc(t.lastLog ? t.lastLog.line : (t.log || []).slice(-1)[0]?.line || 'Starting…')}</div>` : ''}${t.state === 'awaiting_approval' && t.isFix ? firstError(t.baseline) : ''}</div>`;
606
+ let dock = '';
607
+ if (t.state === 'awaiting_approval') {
608
+ const base = t.baseline || {}; const steps = Object.keys(base); const failing = steps.filter((s) => !base[s].pass).length;
609
+ h += `<div class="blk"><div class="sum"><span class="ic" style="background:${failing ? 'var(--red-soft)' : 'var(--green-soft)'}"><span class="d ${failing ? 'r' : 'g'}"></span></span><div><div class="h">${steps.length ? `${failing} of ${steps.length} checks failing` : 'No checks in this project'}</div><div class="p">Baseline, before any change</div></div></div></div>`;
610
+ h += `<div class="blk"><div class="h" style="font-weight:700">${esc(plan.title)}</div><div class="dim" style="font-size:16.5px;margin-top:4px">${esc(plan.explain)}</div></div>`;
611
+ const files = t.proposedScope || []; const reasons = plan.reasons || {};
612
+ const chosen = S.scope[t.id] || (S.scope[t.id] = new Set(files));
613
+ h += `<div class="h3">Files it may change</div>` + (files.map((f, i) => `<button class="file" onclick="toggleScope('${t.id}', ${i})"><span class="box ${chosen.has(f) ? 'on' : ''}">${chosen.has(f) ? IC.check : ''}</span><span><span class="path" style="display:block">${esc(f)}</span><span class="why">${esc(reasons[f] || '')}</span></span></button>`).join('') || '<div class="chk dim">None</div>');
614
+ h += (plan.protectedTests || []).map((f) => `<div class="file"><span class="box lk">${IC.lock}</span><span><span class="path" style="display:block">${esc(f)}</span><span class="why">Locked · tests are never edited</span></span></div>`).join('');
615
+ h += `<div class="blk" style="border-bottom:0"><div class="kv"><span>Snapshot <b>on</b></span><span>Cheat detection <b>on</b></span><span>AI budget <b>${S.status ? S.status.budget.maxAiCallsPerTask : 3} calls</b></span><span>Plan <b>${esc({ ai: 'local AI, supervised', learned: 'library fix, no AI', library: 'library action, no AI', unknown: 'none found' }[plan.kind] || plan.kind)}</b></span></div></div>`;
616
+ dock = `<button class="btn" onclick="act('${t.id}','reject')">Reject</button><button class="btn go" ${plan.kind === 'unknown' ? 'disabled' : ''} onclick="act('${t.id}','approve')">Approve and run</button>`;
617
+ } else if (RUNNING.includes(t.state)) {
618
+ if (t.state !== 'diagnosing') dock = `<button class="btn danger" onclick="act('${t.id}','stop')">Stop and restore</button>`;
619
+ } else {
620
+ h += resultBlock(t);
621
+ if (t.after || t.baseline) h += `<div class="h3">Checks${t.state === 'done' ? ' · all passed' : ''}</div>` + checksHtml(t.baseline, t.after, t.verifySteps);
622
+ h += integrityHtml(t.integrity);
623
+ h += revertHtml(t.revertCheck);
624
+ if (t.scopeGuard && t.scopeGuard.reverted && t.scopeGuard.reverted.length) h += `<div class="blk"><div class="dim">Scope guard reverted changes outside the approved files: <span class="path">${esc(t.scopeGuard.reverted.join(', '))}</span></div></div>`;
625
+ if (t.learnedId) h += `<div class="blk"><div class="dim">Saved to the fix library. Next time this is fixed without AI.</div></div>`;
626
+ if (t.state === 'done') dock = `<button class="btn" onclick="act('${t.id}','undo')">Undo</button>${t.certId ? `<button class="btn go" onclick="go('cert/${t.certId}')">View certificate</button>` : ''}`;
627
+ if (t.state === 'unproven') dock = `<button class="btn go" onclick="act('${t.id}','undo')">Undo change</button>`;
628
+ }
629
+ h += moreHtml(t);
630
+ if (dock) h += `<div class="dock">${dock}</div>`;
631
+ return h;
632
+ }
633
+ function resultBlock(t) {
634
+ const good = t.state === 'done'; const warn = t.state === 'unproven' || (t.kind === 'guard' && t.acceptedWithWarnings);
635
+ const icon = good && !warn ? IC.shield('#12803F', '#ECF7F0') : warn ? IC.shield('#B26A00', '#FFF6E6') : IC.shieldX;
636
+ const label = good && !warn ? 'PROVEN' : warn ? (t.state === 'unproven' ? 'NOT PROVEN' : 'ACCEPTED WITH WARNINGS') : stateOf(t)[0].toUpperCase();
637
+ const cls = good && !warn ? 'g' : warn ? 'a' : ['rejected', 'stopped', 'undone'].includes(t.state) ? 'n' : 'r';
638
+ return `<div class="blk"><div class="seal">${icon}<div style="min-width:0"><span class="badge ${cls === 'n' ? 'b' : cls}">${esc(label)}</span><div class="dim" style="font-size:16px;margin-top:6px">${esc(t.resultText || '')}</div>${t.lineStats && ['done', 'unproven'].includes(t.state) ? `<div class="dim" style="font-size:15px;margin-top:2px">${(t.changedFiles || []).length || t.files || 0} file(s) · <span style="color:var(--green)">+${t.lineStats.plus}</span> <span style="color:var(--red)">−${t.lineStats.minus}</span></div>` : ''}</div></div></div>`;
639
+ }
640
+
641
+ function guardHtml(t) {
642
+ const [label] = stateOf(t);
643
+ let h = dhead(`Guard: ${t.projectName}`, sourceSub(t));
644
+ let dock = '';
645
+ if (t.state === 'baselining' || t.state === 'checking') {
646
+ h += `<div class="blk"><div class="seal">${IC.eye}<div><span class="badge b">${esc(label.toUpperCase())}</span><div class="dim" style="margin-top:6px">${t.state === 'baselining' ? 'Copying the project and running the current checks…' : 'Checking for test cheating, then running build and tests…'}</div></div></div><div class="bar"><i style="width:${pct(t)}%"></i></div><div class="hint">${esc(t.lastLog ? t.lastLog.line : '')}</div></div>`;
647
+ } else if (t.state === 'watching') {
648
+ const lc = t.lastCheck;
649
+ if (!lc) {
650
+ h += `<div class="blk"><div class="seal">${IC.eye}<div><span class="badge b">WATCHING</span><div class="dim" style="margin-top:6px">Work with your AI tool now. When it says "done", press Check.</div></div></div></div>`;
651
+ h += `<div class="h3">Baseline · when the guard started</div>` + checksHtml(t.baseline, null, t.verifySteps);
652
+ h += claimBox(t);
653
+ h += `<div class="blk"><div class="kv"><span>Full copy <b>saved</b></span><span>Cheat detection <b>on</b></span><span>Rollback <b>one tap</b></span></div><div class="codeline"><code>buildproof check || exit 2</code></div><div class="hint">Use this line as a git pre-commit or AI tool hook.</div></div>`;
654
+ dock = `<button class="btn danger" onclick="guardAct('${t.id}','rollback')">Rollback all</button><button class="btn go" onclick="guardAct('${t.id}','check')">Check</button>`;
655
+ } else {
656
+ const ok = lc.ok;
657
+ h += `<div class="blk"><div class="seal">${ok ? IC.shield('#12803F', '#ECF7F0') : lc.files ? IC.shieldX : IC.eye}<div style="min-width:0"><span class="badge ${ok ? 'g' : lc.files ? 'r' : 'b'}">${ok ? 'PROVEN' : lc.files ? 'NOT PROVEN' : 'NO CHANGES'}</span><div class="dim" style="margin-top:6px;font-size:16px">${esc(t.resultText || '')}</div><div class="dim" style="font-size:15px">${lc.files} file(s) changed · checked ${ago(lc.at)}${t.lineStats ? ` · <span style="color:var(--green)">+${t.lineStats.plus}</span> <span style="color:var(--red)">−${t.lineStats.minus}</span>` : ''}</div></div></div></div>`;
658
+ h += `<div class="h3">Checks</div>` + checksHtml(t.baseline, t.after, t.verifySteps);
659
+ if(t.proofScore) h += `<div class="blk">Proof score: <b>${t.proofScore.score}/100</b></div>`;
660
+ h += integrityHtml(t.integrity);
661
+ h += revertHtml(t.revertCheck);
662
+ h += hiddenBugsHtml(t.hiddenBugs);
663
+ h += claimsHtml(t.claims);
664
+ h += claimBox(t);
665
+ if (ok || lc.files) h += `<div class="blk" style="display:flex;gap:10px;flex-wrap:wrap">${ok ? `<button class="btn sm" onclick="guardAct('${t.id}','check')">Check again</button>` : lc.files ? `<button class="btn sm" onclick="guardAct('${t.id}','force')">Accept with warnings</button>` : ''}</div>`;
666
+ dock = ok ? `<button class="btn danger" onclick="guardAct('${t.id}','rollback')">Rollback all</button><button class="btn go" onclick="guardAct('${t.id}','accept')">Accept and sign</button>`
667
+ : `<button class="btn danger" onclick="guardAct('${t.id}','rollback')">Rollback all</button><button class="btn go" onclick="guardAct('${t.id}','check')">Check again</button>`;
668
+ }
669
+ } else {
670
+ h += resultBlock(t);
671
+ if (t.after) h += `<div class="h3">Checks</div>` + checksHtml(t.baseline, t.after, t.verifySteps);
672
+ h += integrityHtml(t.integrity);
673
+ if (t.certId) dock = `<button class="btn go" onclick="go('cert/${t.certId}')">View certificate</button>`;
674
+ }
675
+ h += moreHtml(t);
676
+ if (dock) h += `<div class="dock">${dock}</div>`;
677
+ return h;
678
+ }
679
+
680
+ function claimBox(t) {
681
+ return `<div class="blk"><label class="l" for="claim" style="margin-top:0">What did the AI say it did? <span style="font-weight:500">(optional)</span></label><textarea id="claim" oninput="S.claimDraft['${t.id}']=this.value" style="min-height:84px" placeholder="Paste the AI's last message. BuildProof checks every claim against reality.">${esc(S.claimDraft[t.id] || '')}</textarea></div>`;
682
+ }
683
+ function certHtml(c) {
684
+ const p = c.payload; const good = p.result === 'PROVEN';
685
+ let h = dhead('Proof certificate', `${esc(p.project)} · ${ago(p.issuedAt)}`);
686
+ h += `<div class="blk"><div class="seal">${good ? IC.shield('#12803F', '#ECF7F0') : IC.shield('#B26A00', '#FFF6E6')}<div style="min-width:0"><span class="badge ${good ? 'g' : 'a'}">${good ? 'PROVEN' : 'ACCEPTED WITH WARNINGS'}</span><div class="dim" style="font-size:15.5px;margin-top:6px">${new Date(p.issuedAt).toLocaleString()} · ${p.changes.length} file(s)</div></div></div><p class="ask" style="margin-top:14px">${esc(p.task.text)}</p></div>`;
687
+ h += `<div class="h3">Checks · before → after</div>` + (p.checks.map((k) => `<div class="chk"><span class="d ${k.after === 'pass' ? 'g' : 'r'}"></span><span class="n">${esc(k.step)}${k.tests ? ` <small>· ${k.tests.passed}/${k.tests.total} tests</small>` : ''} <small>· was ${esc({ pass: 'passing', fail: 'failing' }[k.before] || k.before)}</small></span><span class="pill ${k.after === 'pass' ? 'g' : 'r'}">${esc(k.after)}</span><span class="tm">${secs(k.ms)}</span></div>`).join('') || '<div class="chk dim">No checks</div>');
688
+ h += integrityHtml({ clean: p.integrity.clean, rulesChecked: p.integrity.rulesChecked, findings: p.integrity.findings.map((f) => ({ ...f, detail: '' })) });
689
+ h += revertHtml(p.revertCheck);
690
+ h += claimsHtml((p.claims || []).map((c) => ({ text: c.claim, truth: c.true, why: c.why })));
691
+ h += `<div class="h3">Changed files</div>` + p.changes.map((f) => `<div class="chk"><span class="n"><span class="path">${esc(f.file)}</span><br><small>${esc(f.kind)}${f.sha256 ? ' · sha256 ' + esc(f.sha256.slice(0, 16)) + '…' : ''}</small></span></div>`).join('');
692
+ h += `<div class="blk"><div class="kv"><span>AI <b>${p.ai.calls} call(s)</b></span><span><b>${p.ai.local ? 'ran locally' : 'remote model'}</b></span><span>Signature <b style="color:${S.certValid ? 'var(--green)' : 'var(--red)'}">${S.certValid ? 'valid' : 'INVALID'}</b></span></div><div class="mono dim" style="margin-top:10px;line-height:1.6">ed25519 · signed on ${esc(p.machine)}<br>${esc(c.fingerprint)}</div></div>`;
693
+ h += `<div class="dock"><button class="btn" onclick="openCert('${c.id}', true)">Download</button><button class="btn go" onclick="shareCert('${c.id}')">Share certificate</button></div>`;
694
+ return h;
695
+ }
696
+
697
+ /* ================= actions ================= */
698
+ function toggleScope(id, i) { const t = S.detail && S.detail.id === id ? S.detail : S.tasks.find((x) => x.id === id); const f = (t.proposedScope || [])[i]; const s = S.scope[id]; s.has(f) ? s.delete(f) : s.add(f); renderDetail(); }
699
+ async function act(id, action) {
700
+ const run = async () => {
701
+ const body = action === 'approve' ? { scope: [...(S.scope[id] || [])] } : {};
702
+ const r = await api('POST', `/api/tasks/${id}/${action}`, body);
703
+ if (!r.ok) toast(errText(r.error));
704
+ await refreshNow();
705
+ };
706
+ if (action === 'undo') return confirmSheet('Undo this change?', 'The files are restored exactly as they were before the task.', 'Undo', run);
707
+ if (action === 'stop') return confirmSheet('Stop and restore?', 'Work stops and every file is restored to the original state.', 'Stop', run);
708
+ return run();
709
+ }
710
+ async function guardAct(id, action) {
711
+ const run = async () => {
712
+ if (action === 'check') toast('Checking…');
713
+ const claim = action === 'check' && $('claim') ? $('claim').value.trim() : '';
714
+ if (claim) S.claimDraft[id] = claim;
715
+ const r = await api('POST', `/api/guards/${id}/${action === 'force' ? 'accept' : action}`, action === 'force' ? { force: true } : action === 'check' ? { claim } : {});
716
+ if (!r.ok) toast(errText(r.error));
717
+ else if (action === 'rollback') toast('Rolled back. The project is exactly as at guard start.');
718
+ else if (action === 'accept' || action === 'force') toast('Certificate signed');
719
+ await refreshNow();
720
+ };
721
+ if (action === 'rollback') return confirmSheet('Rollback everything?', 'All changes since the guard started are undone. The project returns exactly to that moment.', 'Rollback all', run, true);
722
+ if (action === 'force') return confirmSheet('Accept with warnings?', 'This is not proven. The certificate will say ACCEPTED WITH WARNINGS and list every problem.', 'Accept anyway', run, true);
723
+ return run();
724
+ }
725
+ function certUrl(id, dl) { return `/api/certs/${id}.html?token=${encodeURIComponent(TOKEN)}${dl ? '&download=1' : ''}`; }
726
+ function openCert(id, dl) { if (dl) { const a = document.createElement('a'); a.href = certUrl(id, true); a.download = `buildproof-${id}.html`; document.body.appendChild(a); a.click(); a.remove(); toast('Certificate downloaded'); } else window.open(certUrl(id), '_blank'); }
727
+ async function shareCert(id) {
728
+ try {
729
+ const html = await (await fetch(certUrl(id))).text();
730
+ const file = new File([html], `buildproof-${id}.html`, { type: 'text/html' });
731
+ if (navigator.canShare && navigator.canShare({ files: [file] })) { await navigator.share({ files: [file], title: 'BuildProof certificate' }); return; }
732
+ } catch (e) { if (e && e.name === 'AbortError') return; }
733
+ openCert(id, true);
734
+ }
735
+
736
+ /* ================= sheet ================= */
737
+ function sheet(inner) { $('sheetRoot').innerHTML = `<div class="veil" onclick="if(event.target===this)closeSheet()"><div class="sheet" role="dialog" aria-modal="true">${inner}</div></div>`; }
738
+ function closeSheet() { $('sheetRoot').innerHTML = ''; }
739
+ function confirmSheet(title, text, okLabel, fn, danger) {
740
+ window.__sheetOk = async () => { closeSheet(); await fn(); };
741
+ sheet(`<h3>${esc(title)}</h3><div class="dim">${esc(text)}</div><div class="btns"><button class="btn" onclick="closeSheet()">Cancel</button><button class="btn ${danger ? 'danger' : 'go'}" onclick="__sheetOk()">${esc(okLabel)}</button></div>`);
742
+ }
743
+
744
+ /* ================= data ================= */
745
+ let tasksSig = '';
746
+ async function loadTasks(force) {
747
+ const r = await api('GET', '/api/tasks');
748
+ const sig = JSON.stringify((r.tasks || []).map((t) => [t.id, t.state, t.updatedAt]));
749
+ if (sig === tasksSig && !force) return false;
750
+ tasksSig = sig; S.tasks = r.tasks || [];
751
+ return true;
752
+ }
753
+ async function loadProjects() { const r = await api('GET', '/api/projects'); S.projects = r.projects || []; }
754
+ async function loadStats() { const [a, b] = await Promise.all([api('GET', '/api/stats'), api('GET', '/api/status')]); S.stats = a; S.status = b; }
755
+ async function loadCerts() { const r = await api('GET', '/api/certs'); S.certs = r.certs || []; if (S.route === 'proofs' || S.route === 'cert') { $('list').innerHTML = proofsListHtml(); } }
756
+ async function loadCert() { const r = await api('GET', '/api/certs/' + S.id); if (r.ok) { S.cert = r.cert; S.certValid = r.valid; if (!S.certs.length) await loadCerts(); renderDetail(); $('list').innerHTML = proofsListHtml(); } }
757
+ async function loadDetail(force) {
758
+ const t = S.tasks.find((x) => x.id === S.id);
759
+ const sig = t ? t.updatedAt : '';
760
+ if (!force && sig && sig === S.detailSig) return;
761
+ const r = await api('GET', '/api/tasks/' + S.id);
762
+ if (r.ok) { S.detail = r.task; S.detailSig = r.task.updatedAt; renderDetail(); }
763
+ }
764
+ async function refreshNow() { await loadTasks(true); await loadStats(); render(); if (S.route === 'task') await loadDetail(true); if (S.route === 'proofs') loadCerts(); }
765
+
766
+ function showLogin() {
767
+ document.body.classList.remove('show-detail');
768
+ $('tabs').innerHTML = ''; $('side').innerHTML = ''; $('detail').innerHTML = '';
769
+ $('list').innerHTML = `<div class="login"><h2>Sign in</h2><label class="l" for="tok">Access code</label><input type="text" id="tok" autocomplete="off" spellcheck="false">
770
+ <div class="hint">On the computer open http://127.0.0.1:38700/connect and scan the code with this device.</div><div style="margin-top:16px"><button class="btn go full" onclick="saveToken()">Sign in</button></div></div>`;
771
+ }
772
+ function saveToken() { TOKEN = $('tok').value.trim(); try { localStorage.setItem('bp_token', TOKEN); } catch {} boot(); }
773
+
774
+ async function boot() {
775
+ if (!TOKEN) return showLogin();
776
+ try {
777
+ await Promise.all([loadTasks(true), loadProjects(), loadStats()]);
778
+ route();
779
+ } catch (e) { if (e.message !== 'unauthorized') { $('dot').className = 'd r'; $('machineName').textContent = 'Cannot reach the computer'; } }
780
+ }
781
+ setInterval(async () => {
782
+ if (!TOKEN || document.hidden) return;
783
+ try {
784
+ const changed = await loadTasks(false);
785
+ if (changed) {
786
+ if (['home', 'task'].includes(S.route)) $('list').innerHTML = homeHtml();
787
+ if (S.route === 'task') await loadDetail(false);
788
+ loadStats().then(renderShell).catch(() => {});
789
+ }
790
+ } catch {}
791
+ }, 2000);
792
+ setInterval(() => { if (TOKEN && !document.hidden) loadStats().then(() => { renderShell(); if (S.route === 'home') $('list').innerHTML = homeHtml(); }).catch(() => {}); }, 15000);
793
+ window.addEventListener('resize', () => { clearTimeout(window.__rz); window.__rz = setTimeout(render, 150); });
794
+
795
+ /* ================= camera: tap = screenshot + share, long press = invert colors ================= */
796
+ try { if (localStorage.getItem('bp_invert') === '1') document.documentElement.classList.add('inverted'); } catch {}
797
+ function toggleInvert() {
798
+ const on = document.documentElement.classList.toggle('inverted');
799
+ try { localStorage.setItem('bp_invert', on ? '1' : '0'); } catch {}
800
+ if (navigator.vibrate) navigator.vibrate(30);
801
+ toast(on ? 'Colors inverted' : 'Normal colors');
802
+ }
803
+ async function shareScreenshot(btn) {
804
+ if (!window.html2canvas) { toast('Screenshot tool is still loading. Try again.'); return; }
805
+ btn.classList.add('busy');
806
+ try {
807
+ const canvas = await html2canvas(document.body, {
808
+ x: window.scrollX, y: window.scrollY, width: window.innerWidth, height: window.innerHeight,
809
+ windowWidth: document.documentElement.clientWidth, scale: Math.min(window.devicePixelRatio || 1, 2),
810
+ backgroundColor: '#FFFFFF', useCORS: true, logging: false, ignoreElements: (el) => el.id === 'toast',
811
+ });
812
+ const blob = await new Promise((res) => canvas.toBlob(res, 'image/png'));
813
+ const file = new File([blob], `buildproof-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.png`, { type: 'image/png' });
814
+ if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: 'BuildProof screenshot' });
815
+ else { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = file.name; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); toast('Screenshot saved'); }
816
+ } catch (e) { if (e && e.name !== 'AbortError') toast('Screenshot failed: ' + e.message); }
817
+ finally { btn.classList.remove('busy'); }
818
+ }
819
+ function wireCam(btn) {
820
+ if (btn.__wired) return; btn.__wired = true;
821
+ if (!btn.innerHTML.trim()) btn.innerHTML = IC.cam;
822
+ let timer = null; let long = false;
823
+ btn.addEventListener('pointerdown', () => { long = false; timer = setTimeout(() => { long = true; toggleInvert(); }, 550); });
824
+ btn.addEventListener('pointerup', (e) => { clearTimeout(timer); if (long) e.preventDefault(); });
825
+ btn.addEventListener('pointerleave', () => clearTimeout(timer));
826
+ btn.addEventListener('contextmenu', (e) => e.preventDefault());
827
+ btn.addEventListener('click', (e) => { if (long) { long = false; e.preventDefault(); return; } shareScreenshot(btn); });
828
+ }
829
+ function wireCams() { wireCam($('cam')); for (const b of document.querySelectorAll('[data-cam]')) wireCam(b); }
830
+
831
+ boot();
832
+ </script>
833
+ </body>
834
+ </html>