contatovitorakin's picture
Upload folder using huggingface_hub
ab9f4da verified
Raw History Blame Contribute Delete
79.9 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Sidecar — Personal Coding Assistant Agent</title> <style> :root{ --bg:#0b1020; --panel:#111a2e; --panel2:#0e1626; --border:#1f2b45; --text:#dbe4f7; --muted:#8b9ac2; --accent:#59d4ff; --accent2:#a78bfa; --warn:#ffcc66; --danger:#ff8a8a; --ok:#63e6a8; --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; } *{box-sizing:border-box;} html,body{margin:0;height:100%;} body{ background:radial-gradient(1200px 600px at 15% -10%, #16223c 0%, var(--bg) 55%) fixed; color:var(--text); font-family:var(--sans); font-size:15px; line-height:1.55; } .app{display:grid; grid-template-rows:auto 1fr; height:100vh;} header{ display:flex; align-items:center; gap:14px; padding:12px 18px; border-bottom:1px solid var(--border); background:rgba(10,16,32,.72); backdrop-filter:blur(8px); } .logo{ width:34px;height:34px;border-radius:10px;flex:0 0 auto; background:linear-gradient(135deg,var(--accent),var(--accent2)); display:grid;place-items:center;color:#08111f;font-weight:800;font-size:15px; box-shadow:0 0 0 1px rgba(255,255,255,.08), 0 6px 20px rgba(89,212,255,.18); } .brand h1{margin:0;font-size:15px;letter-spacing:.2px;} .brand p{margin:0;font-size:12px;color:var(--muted);} .pulse{width:8px;height:8px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 0 rgba(99,230,168,.6);animation:p 2.4s infinite;} @keyframes p{0%{box-shadow:0 0 0 0 rgba(99,230,168,.5)}70%{box-shadow:0 0 0 9px rgba(99,230,168,0)}100%{box-shadow:0 0 0 0 rgba(99,230,168,0)}} .spacer{flex:1;} .hdr-stat{font-family:var(--mono);font-size:11px;color:var(--muted);border:1px solid var(--border);padding:3px 8px;border-radius:99px;background:var(--panel2);} main{display:grid;grid-template-columns:1fr 348px;min-height:0;} .chat{display:grid;grid-template-rows:1fr auto auto;min-height:0;border-right:1px solid var(--border);} .transcript{overflow-y:auto;padding:20px 22px 8px;scroll-behavior:smooth;} .transcript::-webkit-scrollbar,.side ::-webkit-scrollbar{width:9px} .transcript::-webkit-scrollbar-thumb,.side ::-webkit-scrollbar-thumb{background:#243250;border-radius:9px} .msg{margin:0 0 16px;display:flex;gap:10px;} .msg .av{ width:28px;height:28px;border-radius:8px;flex:0 0 auto;display:grid;place-items:center; font-size:11px;font-weight:700;font-family:var(--mono); } .msg.user .av{background:#22314f;color:#bcd0f5;} .msg.agent .av{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#08111f;} .bubble{border:1px solid var(--border);background:var(--panel);border-radius:12px;padding:12px 14px;max-width:min(760px,100%);overflow-wrap:anywhere;} .msg.user .bubble{background:#16223c;} .who{font-size:11px;color:var(--muted);margin-bottom:6px;font-family:var(--mono);letter-spacing:.4px;text-transform:uppercase;} .step{font-family:var(--mono);font-size:12px;color:var(--muted);margin:2px 0 6px 38px;display:flex;gap:8px;align-items:flex-start;} .step b{color:var(--accent);font-weight:600;} .step .tick{color:var(--accent2);} .tool{ margin:0 0 12px 38px;border:1px solid var(--border);border-radius:11px;background:var(--panel2); overflow:hidden; } .tool > summary{ cursor:pointer;list-style:none;padding:9px 12px;display:flex;gap:10px;align-items:center;font-size:13px; } .tool > summary::-webkit-details-marker{display:none} .tool .name{font-family:var(--mono);color:var(--accent);} .tool .badge{margin-left:auto;font-family:var(--mono);font-size:11px;color:var(--muted);} .tool .body{padding:0 12px 12px;border-top:1px dashed var(--border);font-size:13px;color:var(--muted);} .tool .obs{color:var(--text);margin-top:8px;} .tool .why{color:var(--muted);margin-top:6px;font-style:italic;} pre.mini{margin:8px 0 0;background:#0a1120;border:1px solid var(--border);border-radius:8px;padding:8px 10px;overflow:auto;max-height:150px;} pre.mini code{font-family:var(--mono);font-size:12px;color:#c6d4f2;white-space:pre;} .mdh{margin:14px 0 6px;font-size:14px;color:#eaf1ff;} .bubble p{margin:8px 0;} .bubble ul,.bubble ol{margin:8px 0 8px 20px;padding:0;} .bubble li{margin:3px 0;} .bubble code{font-family:var(--mono);font-size:12.5px;background:#0a1120;border:1px solid var(--border);border-radius:5px;padding:1px 5px;} .bubble blockquote{margin:8px 0;padding:6px 12px;border-left:3px solid var(--accent2);background:#0d1526;color:#c3d1ee;border-radius:0 8px 8px 0;} .cb{margin:10px 0;border:1px solid var(--border);border-radius:10px;overflow:hidden;background:#0a1120;} .cb-h{display:flex;align-items:center;gap:8px;padding:6px 10px;background:#0d1526;border-bottom:1px solid var(--border);font-family:var(--mono);font-size:11px;color:var(--muted);} .cb-h button{ margin-left:auto;background:transparent;border:1px solid var(--border);color:var(--muted); font-family:var(--mono);font-size:11px;padding:2px 8px;border-radius:99px;cursor:pointer; } .cb-h button:hover{color:var(--accent);border-color:var(--accent);} .cb pre{margin:0;padding:10px 12px;overflow:auto;max-height:420px;} .cb pre code{font-family:var(--mono);font-size:12.5px;color:#cfe0ff;white-space:pre;background:none;border:none;padding:0;} .chips{display:flex;flex-wrap:wrap;gap:8px;padding:0 22px 10px;} .chip{ font-size:12.5px;color:#cbd8f6;background:var(--panel);border:1px solid var(--border); border-radius:99px;padding:5px 11px;cursor:pointer;transition:.15s; } .chip:hover{border-color:var(--accent);color:#fff;transform:translateY(-1px);} .composer{padding:0 22px 18px;} .box{border:1px solid var(--border);background:var(--panel);border-radius:14px;padding:10px;display:flex;gap:10px;align-items:flex-end;} .box:focus-within{border-color:#2f4a75;box-shadow:0 0 0 3px rgba(89,212,255,.07);} textarea{ flex:1;resize:none;background:transparent;border:none;outline:none;color:var(--text); font-family:var(--sans);font-size:14.5px;line-height:1.5;max-height:220px;min-height:24px; } textarea::placeholder{color:#5f6f96;} .send{ background:linear-gradient(135deg,var(--accent),var(--accent2));color:#08111f;border:none; font-weight:700;font-size:13.5px;padding:9px 16px;border-radius:10px;cursor:pointer;flex:0 0 auto; } .send:disabled{opacity:.45;cursor:default;} .hint{font-size:11.5px;color:#5f6f96;margin-top:7px;font-family:var(--mono);} .typing{display:inline-flex;gap:4px;align-items:center;} .typing i{width:6px;height:6px;border-radius:50%;background:var(--accent);display:block;animation:b 1.1s infinite;} .typing i:nth-child(2){animation-delay:.15s}.typing i:nth-child(3){animation-delay:.3s} @keyframes b{0%,60%,100%{opacity:.25;transform:translateY(0)}30%{opacity:1;transform:translateY(-3px)}} .side{background:linear-gradient(180deg,#0d1526,#0b1220);overflow-y:auto;padding:16px 15px 40px;min-height:0;} .card{border:1px solid var(--border);border-radius:12px;background:var(--panel);margin-bottom:14px;overflow:hidden;} .card h2{margin:0;padding:10px 12px;font-size:12px;letter-spacing:.7px;text-transform:uppercase;color:var(--muted);border-bottom:1px solid var(--border);display:flex;gap:8px;align-items:center;} .card .in{padding:10px 12px;} .kv{display:flex;justify-content:space-between;gap:10px;font-size:12.5px;padding:3px 0;border-bottom:1px dotted #1a2540;} .kv:last-child{border-bottom:none;} .kv span:first-child{color:var(--muted);} .kv span:last-child{font-family:var(--mono);color:#dbe4f7;text-align:right;overflow-wrap:anywhere;} .toolrow{display:flex;gap:9px;align-items:flex-start;padding:6px 0;border-bottom:1px dotted #1a2540;} .toolrow:last-child{border-bottom:none;} .toolrow input{margin-top:3px;accent-color:var(--accent);} .toolrow label{cursor:pointer;} .toolrow b{font-family:var(--mono);font-size:12px;font-weight:600;color:#cfdcf9;display:block;} .toolrow small{color:var(--muted);font-size:11.5px;line-height:1.35;display:block;} .trace{max-height:230px;overflow-y:auto;font-family:var(--mono);font-size:11.5px;color:var(--muted);} .trace div{padding:3px 0;border-bottom:1px dotted #1a2540;} .trace b{color:var(--accent);font-weight:600;} .ghost{ background:transparent;border:1px solid var(--border);color:var(--muted);font-family:var(--mono); font-size:11px;padding:4px 9px;border-radius:8px;cursor:pointer;margin-top:8px; } .ghost:hover{border-color:var(--danger);color:var(--danger);} .sev-warn{color:var(--warn);} .sev-danger{color:var(--danger);} .sev-info{color:var(--muted);} .sev-ok{color:var(--ok);} @media (max-width:900px){ .app{height:auto;} main{grid-template-columns:1fr;} .chat{border-right:none;min-height:70vh;} .transcript{max-height:60vh;} .side{max-height:none;} } </style> </head> <body> <div class="app"> <header> <div class="logo">S</div> <div class="brand"> <h1>Sidecar <span class="pulse" style="display:inline-block;margin-left:4px"></span></h1> <p>Personal coding assistant agent · plans, calls tools, keeps a profile of how you code</p> </div> <div class="spacer"></div> <div class="hdr-stat" id="hdrStat">0 checks run</div> <div class="hdr-stat" id="hdrLang">lang: unknown</div> </header> <main> <section class="chat"> <div class="transcript" id="transcript"></div> <div class="chips" id="chips"></div> <div class="composer"> <div class="box"> <textarea id="input" rows="1" placeholder="Paste code, a diff, a JSON blob — or ask: review my code / write pytest tests / explain this / regex for ISO dates"></textarea> <button class="send" id="send">Send</button> </div> <div class="hint">Enter to send · Shift+Enter for newline · commands: /help /tools /memory /clear</div> </div> </section> <aside class="side"> <div class="card"> <h2>Your profile</h2> <div class="in" id="profile"></div> </div> <div class="card"> <h2>Tools</h2> <div class="in" id="toolList"></div> </div> <div class="card"> <h2>Tool trace</h2> <div class="in"><div class="trace" id="trace"></div></div> </div> </aside> </main> </div> <script> /* ============================== utils ============================== */ const BT = '\x60', FENCE = BT + BT + BT; const $ = s => document.querySelector(s); const sleep = ms => new Promise(r => setTimeout(r, ms)); const esc = s => String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); const linesOf = c => String(c).replace(/\r\n?/g,'\n').split('\n'); const indentOf = l => (l.match(/^[ \t]*/) || [''])[0].replace(/\t/g,' ').length; const clamp = (s,n) => s.length > n ? s.slice(0,n) + ' …' : s; /* ============================== markdown ============================== */ function inlineMd(s){ return s .replace(/[`]([^`]+)[`]/g, (m,p) => '<code>' + p + '</code>') .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>') .replace(/(^|[\s(])\*([^*\n]+)\*/g, '$1<em>$2</em>'); } function codeBlock(code, lang){ return '<div class="cb"><div class="cb-h"><span>' + esc(lang || 'text') + '</span><button data-copy="1">copy</button></div><pre><code>' + esc(code) + '</code></pre></div>'; } function mdToHtml(src){ const lines = String(src == null ? '' : src).split('\n'); let out = '', i = 0, list = null; const closeList = () => { if(list){ out += '</' + list + '>'; list = null; } }; while(i < lines.length){ const line = lines[i]; if(/^\s*```/.test(line)){ const lang = line.trim().slice(3).trim(); const buf = []; i++; while(i < lines.length && !/^\s*```/.test(lines[i])) buf.push(lines[i++]); i++; closeList(); out += codeBlock(buf.join('\n'), lang); continue; } const h = line.match(/^(#{1,6})\s+(.*)$/); if(h){ closeList(); const lvl = Math.min(6, h[1].length + 1); out += '<h' + lvl + ' class="mdh">' + inlineMd(esc(h[2])) + '</h' + lvl + '>'; i++; continue; } if(/^\s*>\s?/.test(line)){ closeList(); out += '<blockquote>' + inlineMd(esc(line.replace(/^\s*>\s?/,''))) + '</blockquote>'; i++; continue; } if(/^\s*[-*+]\s+/.test(line)){ if(list !== 'ul'){ closeList(); out += '<ul>'; list = 'ul'; } out += '<li>' + inlineMd(esc(line.replace(/^\s*[-*+]\s+/,''))) + '</li>'; i++; continue; } if(/^\s*\d+[.)]\s+/.test(line)){ if(list !== 'ol'){ closeList(); out += '<ol>'; list = 'ol'; } out += '<li>' + inlineMd(esc(line.replace(/^\s*\d+[.)]\s+/,''))) + '</li>'; i++; continue; } if(!line.trim()){ closeList(); i++; continue; } closeList(); const para = [line]; i++; while(i < lines.length && lines[i].trim() && !/^\s*(```|#{1,6}\s|>|[-*+]\s|\d+[.)]\s)/.test(lines[i])) para.push(lines[i++]); out += '<p>' + inlineMd(esc(para.join(' '))) + '</p>'; } closeList(); return out; } /* ============================== state ============================== */ const state = { memory: { language: null, testFramework: null, style: 'practical and concise', notes: [], turns: 0, lastSeen: null }, enabled: new Set(), trace: [], busy: false }; /* ============================== analysis helpers ============================== */ const PY = 'Python', JS = 'JavaScript', TS = 'TypeScript'; const stripStrings = line => { let out = '', i = 0, q = null; while(i < line.length){ const c = line[i]; if(q){ if(c === '\\'){ i += 2; continue; } if(c === q){ q = null; } i++; continue; } if(c === '"' || c === "'" || c === BT){ q = c; out += '""'; i++; continue; } out += c; i++; } return out; }; function stripComment(line, lang){ const s = stripStrings(line); if(lang === PY || lang === 'Shell' || lang === 'YAML'){ const i = s.indexOf('#'); return i >= 0 ? s.slice(0, i) : s; } if(lang === 'SQL'){ const i = s.indexOf('--'); return i >= 0 ? s.slice(0, i) : s; } const i = s.indexOf('//'); return i >= 0 ? s.slice(0, i) : s; } function detectLanguage(code){ const sc = {}; const add = (l,n) => sc[l] = (sc[l] || 0) + n; const s = String(code); if(/(^|\n)\s*(def|class)\s+\w+[^\n]*:\s*$/m.test(s) || /(^|\n)\s*(import|from)\s+[\w.]+/m.test(s) || /\belif\b|\bself\.|\bNone\b|\bTrue\b/.test(s)) add(PY, 3); if(/\b(const|let|var)\s+\w+\s*=/.test(s) || /=>|console\.log|===|document\.|require\(|module\.exports/.test(s)) add(JS, 3); if(/:\s*(string|number|boolean|any)\b|interface\s+\w+\s*\{|\btype\s+\w+\s*=/.test(s)) add(TS, 3); if(/\b(SELECT|INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM|CREATE\s+TABLE)\b/i.test(s)) add('SQL', 4); if(/\b(public|private|protected)\s+(static\s+)?[\w<>\[\]]+\s+\w+\s*\(|System\.out\.println/.test(s)) add('Java', 3); if(/\bfunc\s+\w+\(|:=|package\s+main|\bfmt\./.test(s)) add('Go', 3); if(/\bfn\s+\w+\(|let\s+mut\b|impl\s+\w+|use\s+std::/.test(s)) add('Rust', 3); if(/^\s*#!\/(usr\/)?bin\/(env\s+)?(ba|z)?sh/m.test(s) || /^\s*(sudo|export\s+\w+=|apt-get\s)/m.test(s)) add('Shell', 3); if(/<\/?[a-z][\w-]*(\s[^>]*)?>/i.test(s) && /<\/([a-z][\w-]*)>/i.test(s)) add('HTML', 2); if(/[.#&][\w-]+\s*\{[^}]*:[^}]+;/.test(s)) add('CSS', 3); if(/^[\s]*[{[]/.test(s)){ try{ JSON.parse(s); add('JSON', 5); }catch(e){} } if(/^\w[\w-]*:\s*$/m.test(s) && /\n\s{2,}-\s/.test(s)) add('YAML', 2); let best = 'Plain text', hi = 0; Object.keys(sc).forEach(k => { if(sc[k] > hi){ hi = sc[k]; best = k; } }); return { name: best, scores: sc }; } function splitArgs(str){ if(!str || !str.trim()) return []; let depth = 0, cur = '', out = []; for(const c of str){ if('([{'.includes(c)) depth++; if(')]}'.includes(c)) depth--; if(c === ',' && depth === 0){ out.push(cur); cur = ''; continue; } cur += c; } out.push(cur); return out.map(a => { let t = a.trim(); t = t.replace(/[:=].*$/,'').trim(); if(t.startsWith('...')) t = t.slice(3); return t.replace(/^[*&]/,'').trim(); }).filter(Boolean); } function pyBlockEnd(lines, start){ const d = indentOf(lines[start]); let i = start + 1; while(i < lines.length){ const l = lines[i]; if(!l.trim()){ i++; continue; } if(indentOf(l) <= d) return i - 1; i++; } return lines.length - 1; } function braceEnd(code, from){ const nl = code.indexOf('\n', from); const brace = code.indexOf('{', from); if(brace === -1 || (nl !== -1 && brace > nl)) return nl === -1 ? code.length - 1 : nl; let depth = 0; for(let i = brace; i < code.length; i++){ const c = code[i]; if(c === '{') depth++; else if(c === '}'){ depth--; if(!depth) return i; } } return code.length - 1; } const KEYWORDS = new Set(['if','for','while','switch','catch','function','return','else','do','with','try','foreach']); function listFunctions(code, lang){ const out = [], seen = new Set(); if(lang === PY){ const lines = linesOf(code); lines.forEach((l,i) => { const m = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)/); if(!m) return; const key = m[2] + ':' + i; if(seen.has(key)) return; seen.add(key); out.push({ name:m[2], args:splitArgs(m[3]), line:i+1, endLine:pyBlockEnd(lines,i)+1, kind:'def' }); }); return out; } const re = /(?:^|\n)(\s*)(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)|(?:^|\n)(\s*)(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?(?:function\s*)?\(([^)]*)\)\s*=>|(?:^|\n)(\s*)(?!(?:if|for|while|switch|catch|function|return|else|do)\b)(\w+)\s*\(([^)]*)\)\s*\{/g; let m; while((m = re.exec(code))){ const name = m[2] || m[5] || m[8]; if(!name || KEYWORDS.has(name)) continue; const args = splitArgs(m[3] || m[6] || m[9] || ''); const headerEnd = m.index + m[0].length; const endIdx = braceEnd(code, headerEnd); const line = code.slice(0, m.index).split('\n').length + (m[0].startsWith('\n') ? 1 : 0); const endLine = code.slice(0, endIdx).split('\n').length; const key = name + ':' + line; if(seen.has(key)) continue; seen.add(key); out.push({ name, args, line, endLine, kind:'function' }); } return out.sort((a,b) => a.line - b.line); } function fnBody(code, fn){ const lines = linesOf(code); return lines.slice(fn.line - 1, fn.endLine).join('\n'); } function decisionCount(body){ const s = stripStrings(body); const kw = (s.match(/\b(if|elif|else\s+if|for|while|case|when|catch|except)\b/g) || []).length; const logic = (s.match(/&&|\|\||\band\b|\bor\b/g) || []).length; const tern = (s.match(/\?[^=?.\s]/g) || []).length; return kw + logic + tern; } function loopNesting(body, lang){ const lines = linesOf(body); let max = 0, stack = []; for(const raw of lines){ const l = stripComment(raw, lang); if(!l.trim()) continue; const ind = indentOf(raw); const isLoop = lang === PY ? /^\s*(for|while)\b/.test(l) : /\b(for|while)\s*\(/.test(l); stack = stack.filter(s => s < ind); if(isLoop){ stack.push(ind); max = Math.max(max, stack.length); } } return max; } const bigO = n => ['O(1)', 'O(n)', 'O(n\u00b2)', 'O(n\u00b3)'][Math.min(n,3)]; /* ============================== review rules ============================== */ function findLooseEquality(line){ for(let i = 0; i < line.length - 1; i++){ const two = line.slice(i, i + 2); if(two === '==' || two === '!='){ const prev = line[i-1] || ' ', next = line[i+2] || ' '; if(prev !== '=' && prev !== '!' && prev !== '<' && prev !== '>' && next !== '=') return two; } } return null; } const REVIEW_RULES = [ { id:'loose-eq', langs:[JS,TS,'PHP','Java'], sev:'warn', msg:'Loose equality — prefer === / !== so type coercion cannot surprise you.', test:(l,lang) => ['Java','PHP'].includes(lang) ? null : findLooseEquality(l) }, { id:'var', langs:[JS,TS], sev:'info', msg:'`var` is function-scoped — use const (or let) for predictable blocks.', test:(l) => /\bvar\s+\w/.test(l) ? 'var' : null }, { id:'debug-log', langs:[JS,TS,'Python','Java','Go'], sev:'info', msg:'Debug print left in the code path — route it through a logger or delete it.', test:(l,lang) => lang === PY ? (/\bprint\(/.test(l) ? 'print' : null) : (/\bconsole\.log\(|System\.out\.println|\bfmt\.Print/.test(l) ? 'log' : null) }, { id:'eval', langs:[JS,TS], sev:'danger', msg:'eval() executes arbitrary strings — a code-injection foot-gun.', test:(l) => /\beval\s*\(/.test(l) ? 'eval' : null }, { id:'innerHTML', langs:[JS,TS], sev:'danger', msg:'Assigning innerHTML with dynamic data enables XSS — use textContent or a sanitiser.', test:(l) => /\.innerHTML\s*=/.test(l) ? 'innerHTML' : null }, { id:'off-by-one', langs:[JS,TS,'Java','Go'], sev:'danger', msg:'`<= …length` in a loop header is an off-by-one: the last iteration reads undefined.', test:(l) => /<=\s*[\w.$]+\.(length|size)\b/.test(l) ? '<= .length' : null }, { id:'empty-catch', langs:[JS,TS,'Java'], sev:'warn', msg:'Empty catch block swallows the error — log it or rethrow.', test:(l) => /catch\s*\([^)]*\)\s*\{\s*\}/.test(l) ? 'catch' : null }, { id:'bare-except', langs:[PY], sev:'warn', msg:'Bare `except:` also catches KeyboardInterrupt/SystemExit — catch a specific exception.', test:(l) => /^\s*except\s*:/.test(l) ? 'except:' : null }, { id:'mutable-default', langs:[PY], sev:'danger', msg:'Mutable default argument is shared across calls — default to None and build inside.', test:(l) => /def\s+\w+\([^)]*=\s*(\[\]|\{\})/.test(l) ? '[]/{}' : null }, { id:'is-none', langs:[PY], sev:'info', msg:'Compare with `is None` / `is not None` instead of `== None`.', test:(l) => /(==|!=)\s*None\b/.test(l) ? '== None' : null }, { id:'wildcard-import', langs:[PY], sev:'warn', msg:'Wildcard import hides where names come from — import explicitly.', test:(l) => /^\s*from\s+[\w.]+\s+import\s+\*/.test(l) ? 'import *' : null }, { id:'secrets', langs:null, sev:'danger', msg:'Hard-coded credential shaped like a secret — move it to env/config.', test:(l) => /(password|passwd|api[_-]?key|secret|token)\s*[:=]\s*["'][^"']{6,}["']/i.test(l) ? 'secret' : null }, { id:'todo', langs:null, sev:'info', msg:'TODO/FIXME marker — track it or finish it.', test:(l) => /\b(TODO|FIXME|HACK|XXX)\b/.test(l) ? 'TODO' : null }, { id:'long-line', langs:null, sev:'info', msg:'Line over 100 characters — wrap it for reviewable diffs.', test:(l) => l.length > 100 ? l.length + ' chars' : null }, { id:'mixed-indent', langs:null, sev:'warn', msg:'Line mixes tabs and spaces — pick one (tabs are ambiguous across editors).', test:(l) => /^[ ]*\t/.test(l) || /^\t* +\S/.test(l) && l.startsWith('\t') ? 'indent' : null }, { id:'trailing-ws', langs:null, sev:'info', msg:'Trailing whitespace — strip on save.', test:(l) => /\s$/.test(l) && l.trim() ? 'ws' : null } ]; function reviewCode(code, lang){ const lines = linesOf(code); const findings = []; const seenRule = {}; lines.forEach((raw, idx) => { const l = stripComment(raw, lang); if(!l.trim() && !/^\s*$/.test(raw)) return; for(const r of REVIEW_RULES){ if(r.langs && !r.langs.includes(lang)) continue; if(r.id === 'todo' && raw.indexOf(l) === -1) { /* keep raw for TODO */ } let hit = null; try { hit = r.test(r.id === 'long-line' ? raw : l, lang); } catch(e){ hit = null; } if(hit){ seenRule[r.id] = (seenRule[r.id] || 0) + 1; if(seenRule[r.id] <= 4) findings.push({ line: idx + 1, sev: r.sev, msg: r.msg, id: r.id, snippet: clamp(raw.trim(), 90) }); } } }); return findings; } /* ============================== tools ============================== */ const T = {}; T.detect_language = { blurb:'Identify the language of a snippet from syntax signals.', run: ({ code }) => { const d = detectLanguage(code); const ranked = Object.entries(d.scores).sort((a,b) => b[1] - a[1]).slice(0,3); return { summary: 'Detected ' + d.name + (ranked.length ? ' (signals: ' + ranked.map(r => r[0] + ' ' + r[1]).join(', ') + ')' : ''), md: '### Language\n**' + d.name + '**' + (ranked.length ? ' — strongest signals: ' + ranked.map(r => BT + r[0] + BT + ' (' + r[1] + ')').join(', ') : ' — no strong signals, treating as plain text.'), ctx: { lang: d.name } }; } }; T.code_stats = { blurb:'Size, structure, comments, depth, entry points.', run: ({ code, lang }) => { const lines = linesOf(code); const blank = lines.filter(l => !l.trim()).length; const isPyLike = lang === PY || lang === 'Shell' || lang === 'YAML'; const comment = lines.filter(l => { const t = l.trim(); return t && (isPyLike ? t.startsWith('#') : t.startsWith('//') || t.startsWith('/*') || t.startsWith('*') || t.startsWith('--')); }).length; const codeLines = lines.length - blank - comment; const fns = listFunctions(code, lang); const longest = lines.reduce((a,b) => (b.length > a.length ? b : a), ''); let maxDepth = 0; if(isPyLike){ lines.forEach(l => { if(l.trim()) maxDepth = Math.max(maxDepth, Math.round(indentOf(l) / 4)); }); } else { let d = 0; stripStrings(code).split('').forEach(c => { if(c === '{'){ d++; maxDepth = Math.max(maxDepth, d); } else if(c === '}') d--; }); } const joined = code.toLowerCase(); const entries = []; if(/if\s+__name__\s*==/.test(code)) entries.push('__main__ block'); if(/\bdef\s+main\b|\bstatic\s+void\s+main\b|\bfunc\s+main\b/.test(code)) entries.push('main()'); if(/app\.listen|createServer|uvicorn\.run|FastAPI\(|Flask\(/.test(code)) entries.push('HTTP server'); if(/describe\(|it\(|test\(|def\s+test_/.test(code)) entries.push('test suite'); const io = []; if(/print\(|console\.log|System\.out/.test(code)) io.push('stdout'); if(/\bopen\(|fs\.(read|write)|readFile|writeFile/.test(code)) io.push('filesystem'); if(/fetch\(|axios|requests\.|http\.get/.test(code)) io.push('network'); if(/input\(|prompt\(|readline/.test(code)) io.push('stdin'); const md = ['### Structure', '- **' + lines.length + '** lines (' + codeLines + ' code, ' + blank + ' blank, ' + comment + ' comment)', '- **' + fns.length + '** function' + (fns.length === 1 ? '' : 's') + (fns.length ? ': ' + fns.map(f => BT + f.name + BT).slice(0,10).join(', ') : ''), '- Max nesting depth: **' + maxDepth + '** · longest line: **' + longest.length + '** chars', '- Entry points: ' + (entries.length ? entries.join(', ') : 'none obvious'), '- Side effects: ' + (io.length ? io.join(', ') : 'none detected (looks pure)') ].join('\n'); return { summary: lines.length + ' lines · ' + fns.length + ' functions · depth ' + maxDepth, md, ctx:{ lang, fns } }; } }; T.review_code = { blurb:'Bugs, smells, and security issues with line numbers.', run: ({ code, lang }) => { const findings = reviewCode(code, lang); const rank = { danger:0, warn:1, info:2 }; findings.sort((a,b) => rank[a.sev] - rank[b.sev] || a.line - b.line); const bySev = { danger:0, warn:0, info:0 }; findings.forEach(f => bySev[f.sev]++); const lines = [ '### Review', bySev.danger + ' critical · ' + bySev.warn + ' warning(s) · ' + bySev.info + ' note(s)' ]; if(!findings.length) lines.push('', 'No issues matched my rule set — that is a weak signal, not a clean bill of health. The highest-value next step is tests for the untested branches.'); findings.slice(0, 14).forEach(f => { lines.push('- ' + BT + 'L' + f.line + BT + ' **' + f.sev + '** — ' + f.msg + ' ' + BT + f.snippet + BT); }); if(findings.length > 14) lines.push('- …and ' + (findings.length - 14) + ' more (mostly style).'); const worst = findings.filter(f => f.sev === 'danger').slice(0,3).map(f => 'line ' + f.line + ' (' + f.id + ')'); if(worst.length) lines.push('', '> Fix first: ' + worst.join(', ') + '.'); return { summary: bySev.danger + ' critical / ' + bySev.warn + ' warn / ' + bySev.info + ' note', md: lines.join('\n'), ctx:{ findings } }; } }; T.complexity_report = { blurb:'Cyclomatic load, loop nesting, and a Big-O guess per function.', run: ({ code, lang }) => { const fns = listFunctions(code, lang); const rows = fns.map(f => { const body = fnBody(code, f); const c = decisionCount(body); const nest = loopNesting(body, lang); const recursive = new RegExp('\\b' + f.name + '\\s*\\(').test(body.split('\n').slice(1).join('\n')); return { f, cyc: c + 1, nest, recursive, size: f.endLine - f.line + 1 }; }).sort((a,b) => b.cyc - a.cyc); const overall = rows.length ? Math.max(...rows.map(r => r.cyc)) : 1; const verdict = overall <= 4 ? 'easy to reason about' : overall <= 8 : 'moderate — worth tests around each branch'; const rating = overall <= 4 ? 'low' : overall <= 10 ? 'moderate' : 'high'; const lines = ['### Complexity', 'Worst cyclomatic complexity: **' + overall + '** (' + rating + ' — ' + (overall <= 4 ? 'easy to reason about' : overall <= 10 ? 'moderate, test each branch' : 'high, split it up') + ').']; if(rows.length){ rows.slice(0, 8).forEach(r => { lines.push('- ' + BT + r.f.name + BT + ' — cyclomatic ' + r.cyc + ', ' + r.size + ' lines, loops nested ' + r.nest + '× → ' + bigO(r.nest) + (r.recursive ? ', **recursive**' : '')); }); const worstO = Math.max(...rows.map(r => r.nest)); if(worstO >= 2) lines.push('', '> Nesting of ' + worstO + ' loops means ' + bigO(worstO) + ' work. A ' + BT + 'Map' + BT + '/set keyed on the outer value usually collapses that to ' + bigO(1) + ' → ' + bigO(1) + '.'); } else { lines.push('', 'No functions found, so I measured the file as a whole: ' + decisionCount(code) + ' decision point(s).'); } return { summary: 'worst cyclomatic ' + overall + ' (' + rating + ')', md: lines.join('\n'), ctx:{ rows } }; } }; T.explain_code = { blurb:'Plain-English walkthrough of what the code does.', run: ({ code, lang }) => { const fns = listFunctions(code, lang); const lines = linesOf(code); const low = code.toLowerCase(); const purpose = []; if(/express|flask|fastapi|app\.listen|createServer|uvicorn/.test(low)) purpose.push('an HTTP service / API layer'); if(/pandas|numpy|dataframe|\.groupby\(/.test(low)) purpose.push('data analysis over a table'); if(/select\b.*\bfrom\b/.test(low)) purpose.push('database access'); if(/describe\(|def test_|assert |expect\(/.test(low)) purpose.push('an automated test suite'); if(/argparse|click\.command|sys\.argv|process\.argv/.test(low)) purpose.push('a command-line tool'); if(/class\s+\w+/.test(code)) purpose.push('an object model (classes with behaviour)'); if(/fetch\(|axios|requests\.|http\.get/.test(low)) purpose.push('an API client'); if(/boto3|aws_|s3\.|dynamodb/.test(low)) purpose.push('AWS integration'); if(!purpose.length) purpose.push('a self-contained piece of ' + lang + ' logic'); const md = ['### What it does', 'Reading the shape of it, this looks like **' + purpose.join(' + ') + '**.', '', '- **Shape:** ' + lines.length + ' lines, ' + fns.length + ' function' + (fns.length === 1 ? '' : 's') + (fns.length ? ' — the entry point is most likely ' + BT + fns[0].name + BT + '.' : '.'), '- **Data flow:** ' + (/push\(|append\(|\.add\(/.test(code) ? 'results accumulate into a collection that grows during the loop.' : 'values are computed and returned rather than stored.'), '- **Guard clauses:** ' + (/\breturn\b|\bcontinue\b|\bthrow\b|\braise\b/.test(code) ? 'early exits handle the invalid rows/cases.' : 'no early exits — invalid input probably falls through to the end.'), '- **Error handling:** ' + (/try\b|catch\b|except\b/.test(code) ? 'errors are caught in ' + (fns.filter(f => /try|catch|except/.test(fnBody(code,f))).map(f => BT + f.name + BT).join(', ') || 'the file body') + '.' : 'none — a bad input will throw out of this code.') ]; if(fns.length){ md.push('', '#### Function by function'); fns.slice(0, 8).forEach(f => { const body = fnBody(code, f); const does = /return\s+/.test(body) ? 'computes and returns a value' : 'runs for its side effects (no return value)'; md.push('- ' + BT + f.name + '(' + f.args.join(', ') + ')' + BT + ' — ' + does + ', ' + (f.endLine - f.line + 1) + ' lines' + (/for\b|while\b/.test(body) ? ', loops over its input' : '') + '.'); }); } return { summary: purpose[0], md: md.join('\n'), ctx:{ lang } }; } }; T.refactor_suggestions = { blurb:'Concrete restructuring moves, ranked by payoff.', run: ({ code, lang }) => { const fns = listFunctions(code, lang); const suggestions = []; fns.forEach(f => { const size = f.endLine - f.line + 1; const nest = loopNesting(fnBody(code, f), lang); if(size > 40) suggestions.push('**' + f.name + '** is ' + size + ' lines — split it into a pure core plus a thin orchestrator.'); if(f.args.length > 4) suggestions.push('**' + f.name + '** takes ' + f.args.length + ' parameters — group them into an options object/dataclass.'); if(nest >= 2) suggestions.push('**' + f.name + '** nests ' + nest + ' loops (' + bigO(nest) + ') — index one collection in a Map/Set and look up instead.'); if(decisionCount(fnBody(code, f)) >= 8) suggestions.push('**' + f.name + '** branches a lot — a lookup table of handlers reads better than the if/else ladder.'); }); // duplication const norm = l => l.trim().replace(/["'`][^"'`]*["'`]/g,'str').replace(/\b\d+(\.\d+)?\b/g,'N').replace(/\s+/g,' '); const map = new Map(); linesOf(code).forEach((l,i) => { const k = norm(l); if(l.trim().length < 16 || /^[{}()\[\];,]*$/.test(l.trim())) return; if(!map.has(k)) map.set(k, []); map.get(k).push(i + 1); }); const dups = [...map.entries()].filter(([,v]) => v.length >= 3).slice(0,3); dups.forEach(([k,v]) => suggestions.push('Duplicated block at lines ' + v.join(', ') + ' — extract it: ' + BT + clamp(k, 70) + BT)); // magic numbers const nums = {}; stripStrings(stripComment(code, lang)).replace(/\b\d+(\.\d+)?\b/g, n => { if(!['0','1','2','-1','100'].includes(n)) nums[n] = (nums[n]||0)+1; return n; }); const magics = Object.entries(nums).filter(([,c]) => c >= 3).slice(0,3).map(([n]) => n); if(magics.length) suggestions.push('Repeated literals (' + magics.join(', ') + ') — name them as constants so intent is obvious.'); const depthNote = /=>\s*\{[\s\S]*=>\s*\{/.test(code) ? 'Callbacks nested inside callbacks — flatten with async/await or a small pipeline helper.' : null; if(depthNote) suggestions.push(depthNote); if(!suggestions.length) suggestions.push('Nothing structural jumps out: sizes, parameter counts and nesting all look reasonable.'); const md = ['### Refactor plan', ...suggestions.slice(0,8).map((s,i) => (i+1) + '. ' + s)].join('\n'); return { summary: suggestions.length + ' suggestion(s)', md, ctx:{} }; } }; T.generate_tests = { blurb:'Runnable test skeletons for every function, in your framework.', run: ({ code, lang }) => { const fns = listFunctions(code, lang); const memFw = state.memory.testFramework; const py = lang === PY || (!lang && false); let fw = memFw || (py ? 'pytest' : /vitest|jest|mocha/.test(code) ? 'jest' : 'jest'); if(py && !/^pytest$/.test(fw) && fw !== 'unittest') fw = 'pytest'; if(fw === 'unittest' && !py) fw = 'jest'; const header = []; let body = ''; if(py){ const mod = (code.match(/^\s*(?:def|class)\s+(\w+)/m) || [, 'module'])[1]; header.push('import pytest', 'from ' + mod.toLowerCase().replace(/_/g,'') + ' import ' + (fns.map(f => f.name).join(', ') || '*')); body = fns.map(f => { const args = f.args.length; return ['def test_' + f.name + '_happy_path():', ' # arrange', ' ' + (args ? args + ' arguments to set up' : 'no arguments — call it directly'), ' # act', ' result = ' + f.name + '(' + f.args.map(a => a + '=' + a + '_value').join(', ') + ')', ' # assert', ' assert result is not None # TODO: assert the real contract', '', 'def test_' + f.name + '_rejects_bad_input():', ' with pytest.raises((ValueError, TypeError, KeyError)):', ' ' + f.name + '(' + f.args.map(() => 'None').join(', ') + ')', ''].join('\n'); }).join('\n'); } else { const mod = '@/' + ((code.match(/(?:function|const)\s+(\w+)/) || [, 'module'])[1]).toLowerCase(); if(fw === 'vitest') header.push('import { describe, it, expect, vi } from "vitest";'); header.push('import { ' + (fns.map(f => f.name).join(', ') || 'thing') + ' } from "' + mod + '";'); body = 'describe("' + (((code.match(/(?:function|class)\s+(\w+)/) || [, 'module'])[1])) + '", () => {\n' + fns.map(f => [' it("' + f.name + ' returns the expected value for valid input", () => {', ' // arrange', ' const ' + (f.args[0] || 'input') + ' = /* build a valid fixture */ undefined;', ' // act', ' const result = ' + f.name + '(' + f.args.join(', ') + ');', ' // assert', ' expect(result).toBeDefined(); // TODO: assert the real contract', ' });', '', ' it("' + f.name + ' throws or fails safely on bad input", () => {', ' expect(() => ' + f.name + '(' + f.args.map(() => 'null').join(', ') + ')).toThrow();', ' });', ''].join('\n')).join('\n') + '});\n'; } const md = ['### Test skeleton (' + fw + ')' + (memFw ? ' — using ' + BT + fw + BT + ' because that is your remembered default' : ''), fns.length ? '' : '> I could not find named functions, so test the module through its public entry point instead.', FENCE + (py ? 'python' : 'javascript') + '\n' + header.join('\n') + '\n\n' + body + FENCE, 'Edge cases worth writing by hand: **empty / null input**, **single element**, **duplicates**, **max-size input**, and the ordering of results.'].join('\n'); return { summary: fns.length + ' test scaffold(s) · ' + fw, md, ctx:{} }; } }; T.generate_docs = { blurb:'Docstrings / JSDoc blocks inferred from signatures.', run: ({ code, lang }) => { const fns = listFunctions(code, lang); const py = lang === PY; const out = fns.slice(0, 8).map(f => { const body = fnBody(code, f); const raises = /raise\s+(\w+)/.exec(body); const ret = /return\s+(.+)/.exec(body); if(py){ return ['def ' + f.name + '(' + f.args.join(', ') + '):', ' """One-line summary of ' + f.name + '.', '', f.args.length ? ' Args:' : '', ...f.args.map(a => ' ' + a + ': describe the expected value.'), '', ' Returns:', ' ' + (ret ? 'the ' + (ret[1].trim().startsWith('[') || ret[1].trim().startsWith('{') ? 'built collection' : 'computed value') + ' (' + clamp(ret[1].trim(), 48) + ').' : 'None — this function works by side effect.'), raises ? '\n Raises:\n ' + raises[1] + ': when the input cannot be processed.' : '', ' """'].filter(Boolean).join('\n'); } return ['/**', ' * ' + f.name + ' — one-line summary.', ' *', ...f.args.map(a => ' * @param ' + a + ' - describe the expected value'), ret ? ' * @returns ' + clamp(ret[1].trim(), 60) : ' * @returns {void}', raises ? ' * @throws ' + raises[1] + ' when input is invalid' : '', ' */', f.name + '(' + f.args.join(', ') + ') {'].filter(Boolean).join('\n'); }).join('\n\n'); const md = ['### Documentation', fns.length ? 'Here are ready-to-paste blocks (I kept your original code untouched):' : 'No named functions to document — add a module-level header comment describing the entry point and the data contract.', fns.length ? FENCE + (py ? 'python' : 'javascript') + '\n' + out + '\n' + FENCE : '', 'A docstring is worth more than a comment: it states the **contract** (what a caller may pass, what they get back, what blows up).'].filter(Boolean).join('\n'); return { summary: fns.length + ' doc block(s)', md, ctx:{} }; } }; T.commit_message = { blurb:'Turn a diff into a Conventional Commit message.', run: ({ diff }) => { const lines = linesOf(diff); const files = []; let added = 0, removed = 0; lines.forEach(l => { const f = l.match(/^\+\+\+\s+b\/(.+)$/); if(f) files.push(f[1]); else if(/^\+/.test(l) && !/^\+\+\+/.test(l)) added++; else if(/^-/.test(l) && !/^---/.test(l)) removed++; }); if(!files.length){ const g = lines.map(l => (l.match(/^diff --git a\/(\S+)/) || [])[1]).filter(Boolean); files.push(...g); } const body = lines.filter(l => /^[+-]/.test(l) && !/^(\+\+\+|---)/.test(l)).join('\n').toLowerCase(); let type = 'chore'; if(/\bbug|fix|error|crash|broken|regression\b/.test(body)) type = 'fix'; else if(/\b(add|implement|introduce|new |support|feature)\b/.test(body)) type = 'feat'; else if(/\b(test|spec|assert)\b/.test(body)) type = 'test'; else if(/\b(doc|readme|comment)\b/.test(body)) type = 'docs'; else if(/\b(rename|move|extract|refactor|cleanup|clean up|simplif)\b/.test(body)) type = 'refactor'; else if(/\b(bump|version|dependenc|package|lock)\b/.test(body)) type = 'chore'; const scope = files.length ? (files[0].split('/')[0] === 'src' && files[0].split('/')[1] ? files[0].split('/')[1].replace(/\.[^.]+$/,'') : files[0].replace(/^.*\//,'').replace(/\.[^.]+$/,'')) : null; const subjectBits = []; if(/\bauth|login|token|password|session\b/.test(body)) subjectBits.push('harden authentication path'); if(/\bvalidat|sanit|check\b/.test(body)) subjectBits.push('validate input before use'); if(/\bcache|memo\b/.test(body)) subjectBits.push('cache the repeated lookup'); if(/\basync|await|promise\b/.test(body)) subjectBits.push('await the async call properly'); if(/\blog|audit|metric\b/.test(body)) subjectBits.push('record an audit entry'); const subject = (subjectBits.length ? subjectBits.slice(0,2).join(' and ') : 'update ' + (scope || 'module')); const verb = type === 'fix' ? 'fix' : type === 'feat' ? 'add' : type === 'refactor' ? 'simplify' : type === 'docs' ? 'document' : type === 'test' ? 'cover' : 'update'; const title = type + (scope ? '(' + scope + ')' : '') + ': ' + verb + ' ' + subject; const bullets = ['- ' + (added ? '+' + added + ' / ' : '') + (removed ? '-' + removed : added ? 'net add' : 'no net line change') + ' lines across ' + (files.length || 1) + ' file' + (files.length === 1 ? '' : 's') + (files.length ? ': ' + files.slice(0,4).join(', ') : '')]; if(type === 'fix') bullets.push('- Restores expected behaviour on the failing path; add a regression test with the repro input.'); if(type === 'feat') bullets.push('- New capability behind the existing interface — no caller changes required.'); if(/\bauth|password|token\b/.test(body)) bullets.push('- Security-relevant: confirm secrets stay in env/config and nothing is logged.'); const md = ['### Commit message', FENCE + 'text\n' + title + '\n\n' + bullets.join('\n') + '\n' + FENCE, 'Type inferred as **' + type + '** from the changed lines' + (scope ? ', scope **' + scope + '** from the first touched path' : '') + '.'].join('\n'); return { summary: title, md, ctx:{} }; } }; const REGEX_LIB = [ { keys:['email','mail'], name:'email', pattern:'^[^@\\s]+@[^@\\s]+\\.[^@\\s]{2,}$', note:'loose on purpose: full RFC 5322 is unreadable and rarely what you want.' }, { keys:['url','link','http'], name:'http(s) URL', pattern:'^https?:\\/\\/[^\\s/$.?#].[^\\s]*$', note:'anchored so it rejects "visit http://x now".' }, { keys:['iso','date','yyyy'], name:'ISO date (YYYY-MM-DD)', pattern:'^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$', note:'validates range per month/day position, not leap years.' }, { keys:['time','hh','clock'], name:'24h time (HH:MM)', pattern:'^([01]\\d|2[0-3]):[0-5]\\d$', note:'' }, { keys:['ip','ipv4','address'], name:'IPv4', pattern:'^((25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1?\\d?\\d)$', note:'octets capped at 255.' }, { keys:['phone','mobile','tel'], name:'phone (E.164)', pattern:'^\\+?[1-9]\\d{7,14}$', note:'digits only after an optional +.' }, { keys:['uuid','guid'], name:'UUID v4', pattern:'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', note:'version and variant nibbles pinned.' }, { keys:['color','colour','hex'], name:'hex colour', pattern:'^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$', note:'supports #rgb and #rrggbbaa.' }, { keys:['slug','kebab','url-safe'], name:'slug', pattern:'^[a-z0-9]+(?:-[a-z0-9]+)*$', note:'' }, { keys:['password','strength'], name:'password (min 8, mixed)', pattern:'^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\w\\s]).{8,}$', note:'lookaheads assert each class exists.' }, { keys:['number','int','integer','digit'], name:'integer', pattern:'^-?\\d+$', note:'' }, { keys:['float','decimal','price','money'], name:'decimal number', pattern:'^-?\\d+(\\.\\d+)?$', note:'' }, { keys:['version','semver'], name:'semver', pattern:'^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$', note:'' }, { keys:['whitespace','space','trim'], name:'collapse whitespace', pattern:'\\s+', note:'substitute with a single space to normalise.' }, { keys:['quoted','string'], name:'quoted string (single or double)', pattern:'(["\'])(?:(?!\\1)[^\\\\]|\\\\.)*\\1', note:'backreference \\1 keeps the quotes matched.' } ]; function explainRegex(p){ const table = [ [/^\\d/, 'a digit 0-9'], [/^\\w/, 'a word character (letter, digit or _)'], [/^\\s/, 'whitespace'], [/^\\D/, 'a non-digit'], [/^\\W/, 'a non-word character'], [/^\\S/, 'non-whitespace'], [/^\\./, 'any character except a newline'], [/^\\b/, 'a word boundary (zero-width)'], [/^\\\//, 'a literal forward slash'], [/^\\\\/, 'a literal backslash'] ]; const parts = []; const q = p.replace(/^\^/, 'START-OF-STRING ').replace(/\$$/, ' END-OF-STRING'); let i = 0; while(i < q.length){ const rest = q.slice(i); let hit = null; for(const [re, txt] of table){ if(re.test(rest)){ hit = { len:2, txt }; break; } } if(hit){ parts.push(hit.txt); i += hit.len; continue; } const c = q[i]; if(c === '^'){ parts.push('start of the input'); i++; continue; } if(c === '$'){ parts.push('end of the input'); i++; continue; } const cls = /^\[([^\]]*)\]/.exec(rest); if(cls){ parts.push('one character from ' + cls[1] + (cls[1].startsWith('^') ? ' (negated)' : '')); i += cls[0].length; continue; } const grp = /^\((\?:)?/.exec(rest); if(grp){ parts.push((grp[1] ? 'start of a non-capturing group' : 'start of a capture group')); i += grp[0].length; continue; } if(c === ')'){ parts.push('end of the group'); i++; continue; } const quant = /^(\{(\d+)(,(\d+)?)?\}|\*|\+|\?)/.exec(rest); if(quant){ parts.push(quant[1].replace('*','zero or more times').replace('+','one or more times').replace('?','optional').replace(/\{(\d+)\}/,'exactly $1 times').replace(/\{(\d+),\}/,'$1 or more times')); i += quant[1].length; continue; } if(c === '|'){ parts.push('OR'); i++; continue; } if(c === '.'){ parts.push('any character'); i++; continue; } if(c === ' '){ i++; continue; } parts.push('the literal "' + c + '"'); i++; } return parts.join(' → '); } T.regex_helper = { blurb:'Suggest a pattern, or explain one you paste.', run: ({ text }) => { const low = text.toLowerCase(); const candidate = (text.match(/\/(.+)\/([gimsuy]*)/) || [])[1] || (/[\\^$*+?()[\]{}|]/.test(text) && /\^|\$|\\d|\\w|\[.+\]/.test(text) ? text.trim() : null); if(candidate && /(\^|\$|\\[dws()]|\[|\]|\{|\}|\*|\+|\?)/.test(candidate)){ const md = ['### Regex explained', BT + candidate + BT, '', 'Reading left to right: **' + explainRegex(candidate) + '**.', '', 'Gotchas: check catastrophic backtracking if you used nested quantifiers like ' + BT + '(a+)+' + BT + ', and remember ' + BT + '.' + BT + ' does not match newlines unless you add the ' + BT + 's' + BT + ' flag.'].join('\n'); return { summary: 'explained a pasted pattern', md, ctx:{} }; } const hits = REGEX_LIB.filter(r => r.keys.some(k => low.includes(k))); const chosen = hits.length ? hits : REGEX_LIB.filter(r => ['email','iso','ipv4','uuid'].includes(r.name)).slice(0,2); const md = ['### Suggested pattern' + (chosen.length > 1 ? 's' : ''), ...chosen.slice(0,3).map(r => ['**' + r.name + '**', FENCE + 'regex\n' + r.pattern + '\n' + FENCE, r.note ? r.note : ''].filter(Boolean).join('\n')), 'Use a ' + BT + 'test()' + BT + ' for a boolean and a global match loop for every occurrence — do not reuse a ' + BT + '/g' + BT + ' regex across calls without resetting ' + BT + 'lastIndex' + BT + '.'].join('\n'); return { summary: chosen.length + ' pattern(s) suggested', md, ctx:{} }; } }; T.json_to_types = { blurb:'Validate JSON and emit TypeScript types / Python models.', run: ({ text }) => { const start = text.search(/[{\[]/); const raw = start >= 0 ? text.slice(start) : text; let data; try { data = JSON.parse(raw); } catch(e){ return { summary:'invalid JSON', md:'### JSON\nThat does not parse: ' + BT + e.message + BT + '\n\nCommon causes: trailing commas, single quotes, unquoted keys, or a truncated paste.' }; } const ifaces = []; const pascal = s => s.replace(/(^|[_\- ])(\w)/g, (m,p,c) => c.toUpperCase()); const seen = new Set(); function walk(obj, name){ if(Array.isArray(obj)){ if(obj.length) walk(obj[0], name); return; } if(obj === null || typeof obj !== 'object') return; if(seen.has(name)) return; seen.add(name); const fields = Object.entries(obj).map(([k,v]) => { let t; if(v === null) t = 'unknown | null'; else if(Array.isArray(v)){ const inner = v.length ? (typeof v[0] === 'object' && v[0] !== null ? pascal(k) + 'Item' : typeof v[0]) : 'unknown'; if(v.length && typeof v[0] === 'object' && v[0] !== null) walk(v[0], pascal(k) + 'Item'); t = inner + '[]'; } else if(typeof v === 'object'){ t = pascal(k); walk(v, pascal(k)); } else if(typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v)) t = 'string /* ISO date */'; else t = typeof v; return ' ' + k + ': ' + t + ';'; }); ifaces.push('interface ' + name + ' {\n' + fields.join('\n') + '\n}'); } walk(data, 'Root'); const keys = (() => { const s = new Set(); JSON.stringify(data, (k,v) => { if(k) s.add(k); return v; }); return s.size; })(); const bytes = new TextEncoder().encode(raw).length; const md = ['### JSON', '- Parsed cleanly: **' + bytes + ' bytes**, **' + keys + '** distinct keys, root is ' + (Array.isArray(data) ? 'an array of ' + data.length : 'an object') + '.', '', FENCE + 'typescript\n' + ifaces.join('\n\n') + '\n' + FENCE, 'Want the defensive version instead? Generate a validator (zod/pydantic) at runtime so bad payloads fail with a field path, not a stack trace.'].join('\n'); return { summary: ifaces.length + ' interface(s) generated', md, ctx:{} }; } }; T.sql_review = { blurb:'Sanity-check a SQL statement before it hits prod.', run: ({ text }) => { const issues = []; const up = text.toUpperCase(); if(/SELECT\s+\*/.test(up)) issues.push({ sev:'warn', msg:'`SELECT *` — name the columns so a schema change cannot silently break the caller and indexes can cover the query.' }); if(/\b(DELETE\s+FROM|UPDATE)\b/.test(up) && !/\bWHERE\b/.test(up)) issues.push({ sev:'danger', msg:'UPDATE/DELETE with no WHERE touches every row. Wrap it in a transaction and run the SELECT first.' }); if(/\bUPDATE\b/.test(up) && /\bWHERE\b/.test(up) && /\bWHERE\s+\w+\s*(=|LIKE)/.test(up) && !/\bLIMIT\b/.test(up)) issues.push({ sev:'info', msg:'Bounded by a WHERE — still verify the predicate with a COUNT(*) before committing.' }); if(/\bJOIN\b/.test(up) && !/\bON\b/.test(up)) issues.push({ sev:'danger', msg:'JOIN without ON produces a cartesian product — add the join predicate or an explicit CROSS JOIN.' }); if(/LIKE\s+'%/.test(text)) issues.push({ sev:'warn', msg:'Leading-wildcard LIKE cannot use a B-tree index. Consider a trigram or full-text index.' }); if(/\bOR\b/.test(up) && /\bWHERE\b/.test(up)) issues.push({ sev:'info', msg:'OR in a WHERE clause often defeats index usage — check the plan, or UNION two indexed queries.' }); if(/NOW\(\)|GETDATE\(\)/.test(up) && /\bBETWEEN\b/.test(up)) issues.push({ sev:'info', msg:'BETWEEN with a timestamp is inclusive on both ends; use >= start AND < next_day to avoid a one-microsecond overlap.' }); if(!/ORDER\s+BY/.test(up) && /\bLIMIT\b/.test(up)) issues.push({ sev:'warn', msg:'LIMIT without ORDER BY returns an arbitrary set of rows.' }); const tables = [...new Set((text.match(/\b(?:FROM|JOIN)\s+([\w."]+)/gi) || []).map(m => m.replace(/^(FROM|JOIN)\s+/i,'')))]; const md = ['### SQL check', '- Tables touched: ' + (tables.length ? tables.map(t => BT + t + BT).join(', ') : 'none detected') + ' · statements: ' + Math.max(1, (text.match(/;/g) || []).length), issues.length ? '' : '- No red flags from my rule set — but EXPLAIN it on real data volume before shipping.', ...issues.map(i2 => '- **' + i2.sev + '** — ' + i2.msg)].filter(Boolean).join('\n'); return { summary: issues.length + ' finding(s)', md, ctx:{} }; } }; const CATALOG = [ ['detect_language','Identify the language from syntax signals'], ['code_stats','Size, structure, comments, entry points'], ['review_code','Bugs, smells and security issues'], ['explain_code','Plain-English walkthrough'], ['complexity_report','Cyclomatic load, nesting, Big-O guess'], ['refactor_suggestions','Concrete restructuring moves'], ['generate_tests','Test skeletons in your framework'], ['generate_docs','Docstrings / JSDoc blocks'], ['commit_message','Diff → Conventional Commit message'], ['regex_helper','Suggest or explain a regex'], ['json_to_types','Validate JSON, emit TS types'], ['sql_review','Sanity-check a SQL statement'] ]; CATALOG.forEach(([n]) => state.enabled.add(n)); /* ============================== intent detection ============================== */ const INTENTS = [ { id:'review', words:['review','bug','issue','problem','wrong','error','fix','smell','lint','audit','debug','safety','security'] }, { id:'explain', words:['explain','what does','what is this','walk me','understand','how does','summar','describe','read this'] }, { id:'tests', words:['test','pytest','jest','vitest','unittest','coverage','spec','tdd'] }, { id:'docs', words:['doc','docstring','jsdoc','comment','readme','documentation','annotate'] }, { id:'refactor', words:['refactor','clean up','cleanup','simplify','optimi','improve','faster','dry','readab','tidy'] }, { id:'complexity', words:['complex','big o','big-o','bigo','cyclomatic','nest','performance','slow'] }, { id:'commit', words:['commit','diff','changelog','pull request','pr message','conventional'] }, { id:'regex', words:['regex','regexp','pattern','match','validate a','email format'] }, { id:'json', words:['json','typescript type','ts type','interface','schema','type from'] }, { id:'sql', words:['sql','query','join','select statement','database'] } ]; function detectIntents(text){ const low = ' ' + text.toLowerCase() + ' '; return INTENTS.filter(i => i.words.some(w => low.includes(w))).map(i => i.id); } function looksLikeCode(text){ const lines = linesOf(text).filter(l => l.trim()); if(lines.length < 2) return /\b(function|def|class|const|let|var|import|return|SELECT)\b|[{};]\s*$/.test(text); let score = 0; lines.forEach(l => { if(/[{};]\s*$/.test(l)) score++; if(/^\s{2,}\S/.test(l)) score++; if(/^\s*(def|class|function|const|let|var|import|from|return|if|for|while|public|private|fn|func|SELECT|INSERT|UPDATE)\b/.test(l)) score++; if(/=>|===|:=|\+=|\)\s*\{/.test(l)) score++; }); return score >= 3; } function extractCode(text){ const fences = [...text.matchAll(/```([\w+-]*)\n?([\s\S]*?)```/g)]; if(fences.length) return { lang: (fences[0][1] || '').trim(), code: fences.map(f => f[2]).join('\n'), fenced:true }; const trimmed = text.trim(); const diffish = /^(diff --git|@@ |--- a\/|\+\+\+ b\/)/m.test(trimmed); if(diffish) return { lang:'Diff', code:trimmed, fenced:false }; if(looksLikeCode(trimmed)) return { lang:'', code:trimmed, fenced:false }; return null; } function learnFromText(text){ const low = text.toLowerCase(); [['python',PY],['typescript',TS],['javascript',JS],['rust','Rust'],['golang','Go'],[' go ', 'Go'],['java ','Java'],['sql','SQL']].forEach(([k,v]) => { if(low.includes(k)) state.memory.language = v; }); [['pytest','pytest'],['unittest','unittest'],['jest','jest'],['vitest','vitest'],['mocha','mocha'],['rspec','rspec'],['gotest','go test'],['go test','go test']].forEach(([k,v]) => { if(low.includes(k)) state.memory.testFramework = v; }); if(/i (use|prefer|like) ([a-z0-9 +.#-]{2,30})/.test(low)){ const note = low.match(/i (use|prefer|like) ([a-z0-9 +.#-]{2,30})/)[2].trim(); if(note && !state.memory.notes.some(n => n.text === note)) state.memory.notes.push({ text: note, kind:'preference' }); } } /* ============================== planner ============================== */ function buildPlan(text, codeInfo){ const intents = detectIntents(text); const wants = k => intents.includes(k); const calls = []; const add = (name, args, why) => { if(state.enabled.has(name)) calls.push({ name, args, why }); }; const has = k => intents.length ? wants(k) : false; if(codeInfo){ const lang = codeInfo.lang || detectLanguage(codeInfo.code).name; const isDiff = /^(diff --git|@@ |--- |\+\+\+ )/m.test(codeInfo.code) && /^[+-]/m.test(codeInfo.code); if((wants('commit') || isDiff) ){ add('commit_message', { diff: codeInfo.code }, 'Input is diff-shaped, so I can read intent straight from the +/- lines.'); } else { add('code_stats', { code: codeInfo.code, lang }, 'Measure the file before making claims about it.'); const specific = ['review','explain','tests','docs','refactor','complexity'].some(wants); if(!specific){ add('review_code', { code: codeInfo.code, lang }, 'Default play: look for real defects first.'); add('explain_code', { code: codeInfo.code, lang }, 'Then explain what it does in plain English.'); } if(wants('review')) add('review_code', { code: codeInfo.code, lang }, 'You asked for a review, so I run the defect scan with line numbers.'); if(wants('refactor')){ add('refactor_suggestions', { code: codeInfo.code, lang }, 'Restructuring moves ranked by payoff.'); add('complexity_report', { code: codeInfo.code, lang }, 'Nesting and cyclomatic load tell me where splitting pays off.'); } if(wants('complexity') && !wants('refactor')) add('complexity_report', { code: codeInfo.code, lang }, 'Quantify the branching and nesting you are worried about.'); if(wants('explain')) add('explain_code', { code: codeInfo.code, lang }, 'Turn the structure into a readable walkthrough.'); if(wants('tests')) add('generate_tests', { code: codeInfo.code, lang }, 'Scaffold tests around the extracted signatures.'); if(wants('docs')) add('generate_docs', { code: codeInfo.code, lang }, 'Infer docs from signature + return statements.'); } } else { if(wants('regex')) add('regex_helper', { text }, 'Pattern request — check the library or explain what you pasted.'); if(wants('json')) add('json_to_types', { text }, 'Parse the payload, then derive types from real data.'); if(wants('sql')) add('sql_review', { text }, 'Check the statement against a short list of production foot-guns.'); if(wants('commit')) add('commit_message', { diff: text }, 'Turn the pasted diff into a commit message.'); } return { calls, intents, lang: codeInfo ? (codeInfo.lang || detectLanguage(codeInfo.code).name) : null }; } /* ============================== UI ============================== */ const transcript = $('#transcript'); function scroll(){ transcript.scrollTop = transcript.scrollHeight; } function addUser(text){ const el = document.createElement('div'); el.className = 'msg user'; el.innerHTML = '<div class="av">you</div><div class="bubble"><div class="who">you</div>' + mdToHtml(text) + '</div>'; transcript.appendChild(el); scroll(); } function addStep(text, tick){ const el = document.createElement('div'); el.className = 'step'; el.innerHTML = '<span class="tick">' + (tick === false ? '\u25c7' : '\u25c6') + '</span><span>' + esc(text) + '</span>'; transcript.appendChild(el); scroll(); } function addToolCard(call){ const el = document.createElement('details'); el.className = 'tool'; const args = call.args.code || call.args.diff || call.args.text || ''; el.innerHTML = '<summary><span class="name">' + call.name + '</span><span class="tick" style="color:var(--ok)">\u2714</span>' + '<span class="badge">' + call.ms + ' ms</span></summary>' + '<div class="body"><div class="obs">' + esc(call.obs.summary || '') + '</div>' + '<div class="why">' + esc(call.why) + '</div>' + (args ? '<pre class="mini"><code>' + esc(clamp(String(args), 900)) + '</code></pre>' : '') + '</div>'; transcript.appendChild(el); scroll(); } function addAgent(md){ const el = document.createElement('div'); el.className = 'msg agent'; el.innerHTML = '<div class="av">S</div><div class="bubble"><div class="who">sidecar</div>' + mdToHtml(md) + '</div>'; transcript.appendChild(el); scroll(); } function addTyping(){ const el = document.createElement('div'); el.className = 'msg agent'; el.id = 'typing'; el.innerHTML = '<div class="av">S</div><div class="bubble"><span class="typing"><i></i><i></i><i></i></span> planning…</div>'; transcript.appendChild(el); scroll(); } function killTyping(){ const t = $('#typing'); if(t) t.remove(); } transcript.addEventListener('click', e => { const btn = e.target.closest('[data-copy]'); if(!btn) return; const code = btn.closest('.cb').querySelector('code').textContent; const done = () => { btn.textContent = 'copied'; setTimeout(() => btn.textContent = 'copy', 1400); }; if(navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(code).then(done).catch(done); else done(); }); /* sidebar */ function renderProfile(){ const m = state.memory; $('#profile').innerHTML = kv('Preferred language', m.language || 'not learned yet') + kv('Test framework', m.testFramework || 'not learned yet') + kv('Answer style', m.style) + kv('Turns', m.turns) + kv('Last code seen', m.lastSeen || '—') + (m.notes.length ? '<div style="margin-top:8px;font-size:12.5px;color:var(--muted)">Notes</div>' + m.notes.slice(-5).map(n => '<div class="kv"><span>' + esc(n.kind) + '</span><span>' + esc(n.text) + '</span></div>').join('') : '') + '<button class="ghost" id="resetMem">reset memory</button>'; const b = $('#resetMem'); if(b) b.onclick = () => { state.memory = { language:null, testFramework:null, style:'practical and concise', notes:[], turns:0, lastSeen:null }; renderProfile(); renderHdr(); }; renderHdr(); } const kv = (k,v) => '<div class="kv"><span>' + esc(k) + '</span><span>' + esc(v) + '</span></div>'; function renderHdr(){ $('#hdrLang').textContent = 'lang: ' + (state.memory.language || 'unknown'); } function renderTools(){ $('#toolList').innerHTML = CATALOG.map(([n, d]) => '<div class="toolrow"><input type="checkbox" id="t_' + n + '" ' + (state.enabled.has(n) ? 'checked' : '') + '>' + '<label for="t_' + n + '"><b>' + n + '</b><small>' + esc(d) + '</small></label></div>').join(''); CATALOG.forEach(([n]) => { const box = $('#t_' + n); box.onchange = () => { box.checked ? state.enabled.add(n) : state.enabled.delete(n); }; }); } function logTrace(entry){ state.trace.unshift(entry); state.trace = state.trace.slice(0, 40); $('#trace').innerHTML = state.trace.map(t => '<div>' + esc(t) + '</div>').join('') || '<div>no calls yet</div>'; $('#hdrStat').textContent = state.trace.length + ' check' + (state.trace.length === 1 ? '' : 's') + ' run'; } /* ============================== agent loop ============================== */ async function runAgent(text){ state.busy = true; $('#send').disabled = true; const t0 = performance.now(); const memOp = text.match(/^\/?remember[:\s]+(.+)$/i); const codeInfo = extractCode(text); learnFromText(text); addStep('Intake — ' + (codeInfo ? (codeInfo.code.split('\n').length + ' lines of ' + (codeInfo.lang || detectLanguage(codeInfo.code).name) + ' detected') : 'no code payload, reading it as a request')); await sleep(220); if(memOp){ state.memory.notes.push({ text: memOp[1].trim(), kind:'remembered' }); renderProfile(); addStep('Memory — stored "' + clamp(memOp[1].trim(), 60) + '" in your profile'); await sleep(180); killTyping(); addAgent('### Noted\nI will keep **' + memOp[1].trim() + '** in mind for the rest of this session. It shows up in the profile panel — clear it any time with ' + BT + '/memory' + BT + '.'); state.busy = false; $('#send').disabled = false; $('#input').focus(); return; } const plan = buildPlan(text, codeInfo); if(plan.lang && plan.lang !== 'Plain text') state.memory.language = plan.lang; if(codeInfo) state.memory.lastSeen = (plan.lang || 'text'); if(plan.calls.length){ addStep('Plan — ' + plan.calls.length + ' tool call' + (plan.calls.length === 1 ? '' : 's') + ': ' + plan.calls.map(c => c.name).join(' → ')); await sleep(240); } else { addStep('Plan — no tool needed, answering from the request itself'); await sleep(200); } const results = []; for(const call of plan.calls){ const tool = T[call.name]; if(!tool) continue; addTyping(); const start = performance.now(); await sleep(150 + Math.random() * 220); let obs; try { obs = tool.run(call.args) || {}; } catch(err){ obs = { summary:'tool error: ' + err.message, md:'### ' + call.name + '\nTool failed: ' + BT + err.message + BT }; } call.ms = Math.max(1, Math.round(performance.now() - start)); call.obs = obs; if(obs.ctx){ if(obs.ctx.lang && obs.ctx.lang !== 'Plain text' && call.name === 'detect_language') state.memory.language = obs.ctx.lang; } killTyping(); addToolCard(call); logTrace(new Date().toLocaleTimeString() + ' ' + call.name + ' → ' + call.ms + 'ms'); results.push({ call, obs }); } if(results.length) { await sleep(160); addStep('Synthesise — merging ' + results.length + ' observation' + (results.length === 1 ? '' : 's') + ' into one report'); await sleep(200); } const md = composeAnswer(text, codeInfo, plan, results); addAgent(md); state.memory.turns++; renderProfile(); const total = Math.round(performance.now() - t0); logTrace(new Date().toLocaleTimeString() + ' turn complete → ' + total + 'ms total'); state.busy = false; $('#send').disabled = false; $('#input').focus(); } function composeAnswer(text, codeInfo, plan, results){ if(!results.length){ const m = state.memory; const lines = ['### What I can do right now', 'Paste a snippet, a diff, a JSON payload or a SQL statement — or ask for one of these:', '', '- **Review** my code for bugs and security issues', '- **Explain** what this file does', '- **Write tests** for these functions', '- **Document** these functions', '- **Refactor** suggestions / complexity analysis', '- Turn this **diff** into a commit message', '- Build me a **regex** for ISO dates / emails', '- Convert this **JSON** into TypeScript types', '- Check this **SQL** before I run it', '', m.language ? '> I will keep assuming ' + BT + m.language + BT + ' unless the code says otherwise.' : '> Tell me things like "I use pytest" or "I prefer TypeScript" and I will remember them for this session.']; return lines.join('\n'); } const lang = plan.lang && plan.lang !== 'Plain text' ? plan.lang : 'text'; const head = '### Report\n' + results.length + ' check(s) run' + (codeInfo ? ' against **' + lang + '**, ' + codeInfo.code.split('\n').length + ' lines' : '') + '.'; const body = results.map(r => r.obs.md).filter(Boolean).join('\n\n'); const tips = []; if(state.memory.testFramework && results.some(r => r.call.name === 'generate_tests')) tips.push('tests scaffolded for ' + BT + state.memory.testFramework + BT + ' from your profile'); if(results.some(r => r.call.name === 'review_code')){ const danger = (results.find(r => r.call.name === 'review_code').obs.ctx.findings || []).filter(f => f.sev === 'danger').length; tips.push(danger ? danger + ' critical item(s) to fix before anything else' : 'no critical defects surfaced'); } if(results.some(r => r.call.name === 'complexity_report')) tips.push('complexity report gives the split points'); const closing = tips.length ? '\n\n---\n\n**Next:** ' + tips.join(' · ') + '.' : '\n\n---\n\n**Next:** paste the failing test or the input that breaks it and I will trace that path specifically.'; return head + '\n\n' + body + closing; } /* ============================== commands & wiring ============================== */ const HELP = ['### Commands', '- ' + BT + '/help' + BT + ' — this list', '- ' + BT + '/tools' + BT + ' — show the tool catalog', '- ' + BT + '/memory' + BT + ' — what I have learned about you', '- ' + BT + '/clear' + BT + ' — wipe the transcript', '- ' + BT + 'remember: I use pytest' + BT + ' — store a preference', '', 'Anything else is treated as a coding request; paste code in a fenced block when you can so the language detection is exact.'].join('\n'); const CHIPS = [ ['Review this JavaScript for bugs', SAMPLE_JS()], ['Explain this Python function', SAMPLE_PY()], ['Generate tests for this Python code', SAMPLE_PY()], ['Write documentation for this JS', SAMPLE_DOC()], ['Turn this diff into a commit message', SAMPLE_DIFF()], ['Refactor suggestions for nested loops', SAMPLE_NEST()], ['I need a regex to validate ISO dates', 'I need a regex to validate ISO dates like 2026-09-19.'], ['Convert this JSON to TypeScript types', SAMPLE_JSON()], ['Check this SQL before I run it', 'I need a SQL check on this:\n\nSELECT * FROM users JOIN orders WHERE created_at BETWEEN NOW() - 7 AND NOW() LIMIT 50;'], ['remember: I use pytest', 'remember: I use pytest and I prefer TypeScript'] ]; function SAMPLE_JS(){ return 'Review this code:\n\n' + FENCE + 'javascript\nconst users = [];\n\nfunction addUser(name, role) {\n if (name == null) {\n return;\n }\n var user = { name: name, role: role, active: true };\n if (role == "admin") {\n user.permissions = ["read", "write", "delete"];\n }\n users.push(user);\n console.log("added", name);\n}\n\nfunction findUser(name) {\n for (let i = 0; i <= users.length; i++) {\n if (users[i].name == name) {\n return users[i];\n }\n }\n}\n\nfunction processUsers(list) {\n for (let i = 0; i < list.length; i++) {\n for (let j = 0; j < list.length; j++) {\n if (list[i].role == list[j].role) {\n if (list[i].name != list[j].name) {\n list[i].teammate = list[j].name;\n }\n }\n }\n }\n return list;\n}\n\n// TODO: handle roles without permissions\n' + FENCE; } function SAMPLE_PY(){ return FENCE + 'python\ndef parse_records(rows, opts={}):\n result = []\n for r in rows:\n try:\n if r["age"] == None:\n continue\n result.append({"name": r["name"], "age": int(r["age"])})\n except:\n print("bad row", r)\n return result\n' + FENCE; } function SAMPLE_DOC(){ return 'Write docs for this:\n\n' + FENCE + 'javascript\nexport async function syncInvoices(clientId, since, dryRun = false) {\n const rows = await db.invoices.where({ clientId, since });\n if (!rows.length) return { synced: 0 };\n const payload = rows.map(toApiShape);\n if (dryRun) return { synced: 0, preview: payload };\n return await api.post("/sync", payload);\n}\n' + FENCE; } function SAMPLE_DIFF(){ return 'Turn this diff into a commit message:\n\n' + FENCE + 'diff\ndiff --git a/src/auth.js b/src/auth.js\n--- a/src/auth.js\n+++ b/src/auth.js\n@@ -10,6 +10,8 @@ export async function login(user, input) {\n- if (user.password == input) {\n+ if (await bcrypt.compare(input, user.hash)) {\n+ auditLog("login", user.id);\n return issueToken(user);\n }\n+ throw new AuthError("bad credentials");\n' + FENCE; } function SAMPLE_NEST(){ return 'Can you refactor this? It feels slow:\n\n' + FENCE + 'javascript\nfunction pairUp(list) {\n const out = [];\n for (let i = 0; i < list.length; i++) {\n for (let j = 0; j < list.length; j++) {\n if (list[i].team === list[j].team && list[i].id !== list[j].id) {\n out.push([list[i].id, list[j].id]);\n }\n }\n }\n return out;\n}\n' + FENCE; } function SAMPLE_JSON(){ return 'Convert this JSON to TypeScript types:\n\n' + FENCE + 'json\n{\n "id": "inv_1042",\n "amount": 249.5,\n "currency": "AUD",\n "createdAt": "2026-09-19T05:49:00Z",\n "customer": { "name": "Ada", "email": "ada@example.com", "vip": true },\n "lineItems": [ { "sku": "PLAN-PRO", "qty": 2, "unit": 99.75 } ],\n "notes": null\n}\n' + FENCE; } function renderChips(){ $('#chips').innerHTML = CHIPS.map(([label], i) => '<button class="chip" data-i="' + i + '">' + esc(label) + '</button>').join(''); $('#chips').querySelectorAll('.chip').forEach(b => b.onclick = () => { const [, payload] = CHIPS[+b.dataset.i]; $('#input').value = payload; autoGrow(); send(); }); } function autoGrow(){ const ta = $('#input'); ta.style.height = 'auto'; ta.style.height = Math.min(220, ta.scrollHeight) + 'px'; } function send(){ if(state.busy) return; const text = $('#input').value.trim(); if(!text) return; $('#input').value = ''; autoGrow(); if(text === '/clear'){ transcript.innerHTML = ''; return; } addUser(text); if(text === '/help'){ addAgent(HELP); return; } if(text === '/tools'){ addAgent('### Tools\n' + CATALOG.map(([n,d]) => '- ' + BT + n + BT + ' — ' + d).join('\n')); return; } if(text === '/memory'){ const m = state.memory; addAgent('### Memory\n' + ['- language: ' + BT + (m.language || 'unknown') + BT, '- test framework: ' + BT + (m.testFramework || 'unknown') + BT, '- turns: ' + m.turns, ...m.notes.map(n => '- ' + n.kind + ': ' + n.text)].join('\n')); return; } runAgent(text); } $('#send').onclick = send; $('#input').addEventListener('keydown', e => { if(e.key === 'Enter' && !e.shiftKey){ e.preventDefault(); send(); } }); $('#input').addEventListener('input', autoGrow); /* boot */ renderTools(); renderProfile(); $('#trace').innerHTML = '<div>no calls yet</div>'; addAgent('### Hey — I am Sidecar, your coding assistant agent.\n' + 'I do not guess from vibes: I **plan**, call the tools that fit your request, read the observations, then hand you one report.\n\n' + 'Try a chip below, or paste code in a ' + BT + '```' + BT + ' block and tell me what you want done with it. ' + 'If you tell me things like "I use pytest", I keep them in your profile and use them later — say ' + BT + '/memory' + BT + ' to see what I know.'); </script> </body> </html> <script data-huggingchat-badge="script"> (function () { try { if (document.querySelector("[data-huggingchat-badge]:not(script)")) return; var host = document.createElement("div"); host.setAttribute("data-huggingchat-badge", ""); var styles = [["all","initial"],["position","fixed"],["right","12px"],["bottom","12px"],["z-index","2147483647"],["display","block"],["visibility","visible"],["opacity","1"],["pointer-events","auto"],["width","auto"],["height","auto"],["margin","0"],["padding","0"],["max-width","none"],["max-height","none"],["transform","none"],["filter","none"],["clip-path","none"],["color-scheme","light"]]; for (var i = 0; i < styles.length; i++) { host.style.setProperty(styles[i][0], styles[i][1], "important"); } host.attachShadow({ mode: "closed" }).innerHTML = "<style>\n:host { all: initial; }\na {\n display: flex;\n align-items: center;\n gap: 5px;\n box-sizing: border-box;\n height: 26px;\n padding: 0 9px 0 7px;\n border-radius: 999px;\n border: 1px solid rgba(0, 0, 0, 0.07);\n background: rgba(255, 255, 255, 0.92);\n -webkit-backdrop-filter: saturate(180%) blur(8px);\n backdrop-filter: saturate(180%) blur(8px);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 6px 16px rgba(0, 0, 0, 0.06);\n color: #111827;\n font: 500 11px/1 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n text-decoration: none;\n white-space: nowrap;\n opacity: 0.72;\n transition: opacity 0.15s ease, transform 0.15s ease;\n}\na:hover, a:focus-visible { opacity: 1; transform: translateY(-1px); }\nsvg { width: 14px; height: 14px; flex: none; }\n@media print { a { display: none; } }\n<\/style><a href=\"https://huggingface.co/chat\" target=\"_blank\" rel=\"noopener noreferrer nofollow\"><svg viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\"><path d=\"M16.0006 25.9992C13.8266 25.999 11.7118 25.2901 9.97686 23.9799C8.2419 22.6698 6.98127 20.8298 6.38599 18.7388C5.79071 16.6478 5.89323 14.4198 6.678 12.3923C7.46278 10.3648 8.88705 8.64837 10.735 7.50308C12.5829 6.35779 14.7538 5.84606 16.9187 6.04544C19.0837 6.24481 21.1246 7.14442 22.7323 8.60795C24.34 10.0715 25.4268 12.0192 25.8281 14.1559C26.2293 16.2926 25.9232 18.5019 24.9561 20.449C24.7703 20.8042 24.7223 21.2155 24.8211 21.604L25.4211 23.8316C25.4803 24.0518 25.4805 24.2837 25.4216 24.5039C25.3627 24.7242 25.2468 24.925 25.0856 25.0862C24.9244 25.2474 24.7235 25.3633 24.5033 25.4222C24.283 25.4811 24.0512 25.4809 23.831 25.4217L21.6034 24.8217C21.2172 24.7248 20.809 24.7729 20.4558 24.9567C19.0683 25.6467 17.5457 26.0068 16.0006 26.0068V25.9992Z\" fill=\"currentColor\"/><path d=\"M9.62598 16.0013C9.62598 15.3799 10.1294 14.8765 10.7508 14.8765C11.3721 14.8765 11.8756 15.3799 11.8756 16.0013C11.8756 17.0953 12.3102 18.1448 13.0838 18.9184C13.8574 19.692 14.9069 20.1266 16.001 20.1267C17.095 20.1267 18.1445 19.692 18.9181 18.9184C19.6918 18.1448 20.1264 17.0953 20.1264 16.0013C20.1264 15.3799 20.6299 14.8765 21.2512 14.8765C21.8725 14.8765 22.3759 15.3799 22.3759 16.0013C22.3759 17.6921 21.7046 19.3137 20.509 20.5093C19.3134 21.7049 17.6918 22.3762 16.001 22.3762C14.3102 22.3762 12.6885 21.7049 11.4929 20.5093C10.2974 19.3137 9.62598 17.6921 9.62598 16.0013Z\" fill=\"#fff\"/><\/svg><span>Made with HuggingChat<\/span><\/a>"; function attach() { var parent = document.body || document.documentElement; if (parent && host.parentNode !== parent) parent.appendChild(host); } attach(); // Artifacts that rewrite document.body wholesale would drop the badge. if (document.body && typeof MutationObserver === "function") { new MutationObserver(attach).observe(document.body, { childList: true }); } else { document.addEventListener("DOMContentLoaded", attach); } } catch (e) {} })(); </script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Sidecar — Personal Coding Assistant Agent</title>
<style>
:root{
--bg:#0b1020; --panel:#111a2e; --panel2:#0e1626; --border:#1f2b45;
--text:#dbe4f7; --muted:#8b9ac2; --accent:#59d4ff; --accent2:#a78bfa;
--warn:#ffcc66; --danger:#ff8a8a; --ok:#63e6a8;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
*{box-sizing:border-box;}
html,body{margin:0;height:100%;}
body{
background:radial-gradient(1200px 600px at 15% -10%, #16223c 0%, var(--bg) 55%) fixed;
color:var(--text); font-family:var(--sans); font-size:15px; line-height:1.55;
}
.app{display:grid; grid-template-rows:auto 1fr; height:100vh;}
header{
display:flex; align-items:center; gap:14px; padding:12px 18px;
border-bottom:1px solid var(--border); background:rgba(10,16,32,.72); backdrop-filter:blur(8px);
}
.logo{
width:34px;height:34px;border-radius:10px;flex:0 0 auto;
background:linear-gradient(135deg,var(--accent),var(--accent2));
display:grid;place-items:center;color:#08111f;font-weight:800;font-size:15px;
box-shadow:0 0 0 1px rgba(255,255,255,.08), 0 6px 20px rgba(89,212,255,.18);
}
.brand h1{margin:0;font-size:15px;letter-spacing:.2px;}
.brand p{margin:0;font-size:12px;color:var(--muted);}
.pulse{width:8px;height:8px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 0 rgba(99,230,168,.6);animation:p 2.4s infinite;}
@keyframes p{0%{box-shadow:0 0 0 0 rgba(99,230,168,.5)}70%{box-shadow:0 0 0 9px rgba(99,230,168,0)}100%{box-shadow:0 0 0 0 rgba(99,230,168,0)}}
.spacer{flex:1;}
.hdr-stat{font-family:var(--mono);font-size:11px;color:var(--muted);border:1px solid var(--border);padding:3px 8px;border-radius:99px;background:var(--panel2);}
main{display:grid;grid-template-columns:1fr 348px;min-height:0;}
.chat{display:grid;grid-template-rows:1fr auto auto;min-height:0;border-right:1px solid var(--border);}
.transcript{overflow-y:auto;padding:20px 22px 8px;scroll-behavior:smooth;}
.transcript::-webkit-scrollbar,.side ::-webkit-scrollbar{width:9px}
.transcript::-webkit-scrollbar-thumb,.side ::-webkit-scrollbar-thumb{background:#243250;border-radius:9px}
.msg{margin:0 0 16px;display:flex;gap:10px;}
.msg .av{
width:28px;height:28px;border-radius:8px;flex:0 0 auto;display:grid;place-items:center;
font-size:11px;font-weight:700;font-family:var(--mono);
}
.msg.user .av{background:#22314f;color:#bcd0f5;}
.msg.agent .av{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#08111f;}
.bubble{border:1px solid var(--border);background:var(--panel);border-radius:12px;padding:12px 14px;max-width:min(760px,100%);overflow-wrap:anywhere;}
.msg.user .bubble{background:#16223c;}
.who{font-size:11px;color:var(--muted);margin-bottom:6px;font-family:var(--mono);letter-spacing:.4px;text-transform:uppercase;}
.step{font-family:var(--mono);font-size:12px;color:var(--muted);margin:2px 0 6px 38px;display:flex;gap:8px;align-items:flex-start;}
.step b{color:var(--accent);font-weight:600;}
.step .tick{color:var(--accent2);}
.tool{
margin:0 0 12px 38px;border:1px solid var(--border);border-radius:11px;background:var(--panel2);
overflow:hidden;
}
.tool > summary{
cursor:pointer;list-style:none;padding:9px 12px;display:flex;gap:10px;align-items:center;font-size:13px;
}
.tool > summary::-webkit-details-marker{display:none}
.tool .name{font-family:var(--mono);color:var(--accent);}
.tool .badge{margin-left:auto;font-family:var(--mono);font-size:11px;color:var(--muted);}
.tool .body{padding:0 12px 12px;border-top:1px dashed var(--border);font-size:13px;color:var(--muted);}
.tool .obs{color:var(--text);margin-top:8px;}
.tool .why{color:var(--muted);margin-top:6px;font-style:italic;}
pre.mini{margin:8px 0 0;background:#0a1120;border:1px solid var(--border);border-radius:8px;padding:8px 10px;overflow:auto;max-height:150px;}
pre.mini code{font-family:var(--mono);font-size:12px;color:#c6d4f2;white-space:pre;}
.mdh{margin:14px 0 6px;font-size:14px;color:#eaf1ff;}
.bubble p{margin:8px 0;}
.bubble ul,.bubble ol{margin:8px 0 8px 20px;padding:0;}
.bubble li{margin:3px 0;}
.bubble code{font-family:var(--mono);font-size:12.5px;background:#0a1120;border:1px solid var(--border);border-radius:5px;padding:1px 5px;}
.bubble blockquote{margin:8px 0;padding:6px 12px;border-left:3px solid var(--accent2);background:#0d1526;color:#c3d1ee;border-radius:0 8px 8px 0;}
.cb{margin:10px 0;border:1px solid var(--border);border-radius:10px;overflow:hidden;background:#0a1120;}
.cb-h{display:flex;align-items:center;gap:8px;padding:6px 10px;background:#0d1526;border-bottom:1px solid var(--border);font-family:var(--mono);font-size:11px;color:var(--muted);}
.cb-h button{
margin-left:auto;background:transparent;border:1px solid var(--border);color:var(--muted);
font-family:var(--mono);font-size:11px;padding:2px 8px;border-radius:99px;cursor:pointer;
}
.cb-h button:hover{color:var(--accent);border-color:var(--accent);}
.cb pre{margin:0;padding:10px 12px;overflow:auto;max-height:420px;}
.cb pre code{font-family:var(--mono);font-size:12.5px;color:#cfe0ff;white-space:pre;background:none;border:none;padding:0;}
.chips{display:flex;flex-wrap:wrap;gap:8px;padding:0 22px 10px;}
.chip{
font-size:12.5px;color:#cbd8f6;background:var(--panel);border:1px solid var(--border);
border-radius:99px;padding:5px 11px;cursor:pointer;transition:.15s;
}
.chip:hover{border-color:var(--accent);color:#fff;transform:translateY(-1px);}
.composer{padding:0 22px 18px;}
.box{border:1px solid var(--border);background:var(--panel);border-radius:14px;padding:10px;display:flex;gap:10px;align-items:flex-end;}
.box:focus-within{border-color:#2f4a75;box-shadow:0 0 0 3px rgba(89,212,255,.07);}
textarea{
flex:1;resize:none;background:transparent;border:none;outline:none;color:var(--text);
font-family:var(--sans);font-size:14.5px;line-height:1.5;max-height:220px;min-height:24px;
}
textarea::placeholder{color:#5f6f96;}
.send{