@balpal4495/quorum 3.7.0 → 3.8.0

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/bin/mcp/server.js CHANGED
@@ -10,6 +10,10 @@
10
10
  * GET /api/growth Memory health report
11
11
  * POST /api/proposals/:id/commit Human-gate: approve a proposal
12
12
  * DELETE /api/proposals/:id Reject / delete a proposal
13
+ * POST /api/advisor Ask a question answered from Chronicle (LLM)
14
+ * POST /api/check Instant risk triage (no LLM)
15
+ * POST /api/ingest Ingest files, git history, or URLs
16
+ * GET /api/sentinel/drift Structural drift check
13
17
  *
14
18
  * MCP also exposes resources:
15
19
  * chronicle://summary chronicle://proposals
@@ -28,6 +32,10 @@ import {
28
32
  toolCoverage,
29
33
  toolGrowth,
30
34
  toolCompass,
35
+ toolAdvisor,
36
+ toolCheck,
37
+ toolIngest,
38
+ toolSentinelDrift,
31
39
  commitProposal,
32
40
  deleteProposal,
33
41
  updateProposal,
@@ -318,6 +326,33 @@ export async function createServer({ projectRoot, chronicleDir, llm = null }) {
318
326
  return json(res, 200, result)
319
327
  }
320
328
 
329
+ // ── REST: advisor ───────────────────────────────────────────────────────
330
+ if (pathname === "/api/advisor" && req.method === "POST") {
331
+ const body = await readBody(req)
332
+ const result = await toolAdvisor({ question: body.question, projectRoot })
333
+ return json(res, 200, result)
334
+ }
335
+
336
+ // ── REST: check ─────────────────────────────────────────────────────────
337
+ if (pathname === "/api/check" && req.method === "POST") {
338
+ const body = await readBody(req)
339
+ const result = await toolCheck({ outcome: body.outcome ?? "", design: body.design ?? "", projectRoot })
340
+ return json(res, 200, result)
341
+ }
342
+
343
+ // ── REST: ingest ────────────────────────────────────────────────────────
344
+ if (pathname === "/api/ingest" && req.method === "POST") {
345
+ const body = await readBody(req)
346
+ const result = await toolIngest({ ...body, projectRoot })
347
+ return json(res, 200, result)
348
+ }
349
+
350
+ // ── REST: sentinel drift ────────────────────────────────────────────────
351
+ if (pathname === "/api/sentinel/drift" && req.method === "GET") {
352
+ const result = await toolSentinelDrift({ projectRoot })
353
+ return json(res, 200, result)
354
+ }
355
+
321
356
  // ── Web UI ──────────────────────────────────────────────────────────────
322
357
  if ((pathname === "/" || pathname === "/index.html") && req.method === "GET") {
323
358
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" })
package/bin/mcp/tools.js CHANGED
@@ -326,6 +326,163 @@ export async function toolCompass({ subcommand = "brief", goal, idea, projectRoo
326
326
  return { subcommand, data, output: data ? null : raw }
327
327
  }
328
328
 
329
+ /**
330
+ * Ingest files, git history, or a URL into .chronicle/sources/ and
331
+ * .chronicle/evidence/ as low-trust drafts (confidence 0.4).
332
+ * Returns { added, skipped, items } — no console output, no process.exit.
333
+ */
334
+ export async function toolIngest({ type = "git", paths, since = "P90D", urls, propose = false, projectRoot } = {}) {
335
+ const { promisify } = await import("util")
336
+ const { execFile } = await import("child_process")
337
+ const { createHash, randomUUID: uuid } = await import("crypto")
338
+ const execFileAsync = promisify(execFile)
339
+
340
+ const { projectRoot: root, chronicleDir } = await resolve(projectRoot)
341
+ const sourcesDir = path.join(chronicleDir, "sources")
342
+ const evidenceDir = path.join(chronicleDir, "evidence")
343
+ const proposalsDir = path.join(chronicleDir, "proposals")
344
+ await fs.mkdir(sourcesDir, { recursive: true })
345
+ await fs.mkdir(evidenceDir, { recursive: true })
346
+ if (propose) await fs.mkdir(proposalsDir, { recursive: true })
347
+
348
+ // Load existing content hashes to skip duplicates
349
+ const existingHashes = new Set()
350
+ for (const f of await fs.readdir(sourcesDir).catch(() => [])) {
351
+ if (!f.endsWith(".json")) continue
352
+ try {
353
+ const s = JSON.parse(await fs.readFile(path.join(sourcesDir, f), "utf8"))
354
+ if (s.content_hash) existingHashes.add(s.content_hash)
355
+ } catch { /* skip malformed */ }
356
+ }
357
+
358
+ async function writeRecord({ hash, kind, sourceRef, title, summary, scope }) {
359
+ const id = uuid()
360
+ const ts = new Date().toISOString()
361
+ await fs.writeFile(path.join(sourcesDir, `${id}.json`), JSON.stringify(
362
+ { id, kind, source_ref: sourceRef, content_hash: hash, ingested_at: ts, schema_version: 2 }, null, 2), "utf8")
363
+
364
+ const evidenceId = uuid()
365
+ const evidence = {
366
+ id: evidenceId, schema_version: 2,
367
+ topic: `ingest/${kind}/${title.slice(0, 40).replace(/\s+/g, "-").toLowerCase()}`,
368
+ key_insight: summary.slice(0, 200), decision: summary.slice(0, 200),
369
+ scope, affected_areas: [], status: "open", confidence: 0.4,
370
+ source_quality: "metadata-derived", needs_human_summary: true,
371
+ source_module: "ingest", evidence_cited: [],
372
+ alternatives_considered: [], rejected_reason: [],
373
+ ingested_at: ts, source_id: id,
374
+ }
375
+ await fs.writeFile(path.join(evidenceDir, `${evidenceId}.json`), JSON.stringify(evidence, null, 2), "utf8")
376
+ if (propose) {
377
+ const propId = uuid()
378
+ await fs.writeFile(path.join(proposalsDir, `${propId}.json`), JSON.stringify({ ...evidence, id: propId }, null, 2), "utf8")
379
+ }
380
+ }
381
+
382
+ let added = 0, skipped = 0
383
+ const items = []
384
+
385
+ if (type === "git") {
386
+ // Parse ISO 8601 duration PnD/PnM/PnY safely — never raw user input to shell
387
+ const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?$/.exec(since ?? "P90D")
388
+ const days = match ? (parseInt(match[1] ?? "0") * 365 + parseInt(match[2] ?? "0") * 30 + parseInt(match[3] ?? "0")) : 90
389
+ const sinceArg = `${days > 0 ? days : 90} days ago`
390
+
391
+ let stdout
392
+ try {
393
+ const res = await execFileAsync("git", ["log", `--since=${sinceArg}`, "--format=%H|%s|%ae|%ad", "--date=iso"], { cwd: root })
394
+ stdout = res.stdout.trim()
395
+ } catch { return { added: 0, skipped: 0, items: [], error: "git log failed — is this a git repository?" } }
396
+
397
+ for (const line of stdout.split("\n").filter(Boolean)) {
398
+ const [commitHash, subject = ""] = line.split("|")
399
+ if (!commitHash) continue
400
+ const fingerprint = createHash("sha256").update(commitHash).digest("hex").slice(0, 16)
401
+ if (existingHashes.has(fingerprint)) { skipped++; continue }
402
+ const short = commitHash.slice(0, 7)
403
+ await writeRecord({ hash: fingerprint, kind: "git-commit", sourceRef: commitHash, title: subject, summary: `${short}: ${subject}`, scope: ["source", "git"] })
404
+ items.push({ ref: short, summary: subject.slice(0, 80) })
405
+ added++
406
+ }
407
+ } else if (type === "url") {
408
+ const urlList = Array.isArray(urls) ? urls : (urls ? [urls] : [])
409
+ for (const u of urlList.filter(Boolean)) {
410
+ let parsed
411
+ try { parsed = new URL(u) } catch { skipped++; continue }
412
+ if (!["http:", "https:"].includes(parsed.protocol)) { skipped++; continue }
413
+ const fingerprint = createHash("sha256").update(u).digest("hex").slice(0, 16)
414
+ if (existingHashes.has(fingerprint)) { skipped++; continue }
415
+ let text = ""
416
+ try {
417
+ const res = await fetch(u, { signal: AbortSignal.timeout(15000) })
418
+ const html = await res.text()
419
+ text = html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 2000)
420
+ } catch { skipped++; continue }
421
+ const title = parsed.pathname.split("/").filter(Boolean).pop() ?? parsed.hostname
422
+ const summary = text.slice(0, 200) || u
423
+ await writeRecord({ hash: fingerprint, kind: "url", sourceRef: u, title, summary, scope: ["docs"] })
424
+ items.push({ ref: u.slice(0, 60), summary: summary.slice(0, 80) })
425
+ added++
426
+ }
427
+ } else if (type === "files") {
428
+ const TEXT_EXTS = new Set([".md", ".txt", ".js", ".mjs", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml", ".toml", ".sh", ".html", ".css", ".csv"])
429
+ const pathList = Array.isArray(paths) ? paths : (paths ? String(paths).split(",").map(p => p.trim()) : [])
430
+ for (const p of pathList.filter(Boolean)) {
431
+ const abs = path.isAbsolute(p) ? p : path.join(root, p)
432
+ if (!TEXT_EXTS.has(path.extname(abs).toLowerCase())) { skipped++; continue }
433
+ let content
434
+ try { content = await fs.readFile(abs, "utf8") } catch { skipped++; continue }
435
+ const fingerprint = createHash("sha256").update(content.slice(0, 3000)).digest("hex").slice(0, 16)
436
+ if (existingHashes.has(fingerprint)) { skipped++; continue }
437
+ const rel = path.relative(root, abs).replace(/\\/g, "/")
438
+ const lines = content.split("\n").map(l => l.trim()).filter(Boolean)
439
+ const summary = (lines.find(l => l.startsWith("#")) ?? lines[0] ?? rel).replace(/^#+\s*/, "").slice(0, 200)
440
+ await writeRecord({ hash: fingerprint, kind: "file", sourceRef: rel, title: path.basename(abs), summary, scope: ["docs"] })
441
+ items.push({ ref: rel, summary: summary.slice(0, 80) })
442
+ added++
443
+ }
444
+ }
445
+
446
+ return { added, skipped, items: items.slice(0, 30) }
447
+ }
448
+
449
+ /**
450
+ * Structural drift check — Chronicle entries whose affected_areas paths no
451
+ * longer exist as files in the codebase. LLM-free and fast.
452
+ */
453
+ export async function toolSentinelDrift({ projectRoot } = {}) {
454
+ const { projectRoot: root, chronicleDir } = await resolve(projectRoot)
455
+ const entries = await readCommitted(chronicleDir)
456
+
457
+ const flags = []
458
+ for (const entry of entries) {
459
+ if (!entry.affected_areas?.length) continue
460
+ const missingFiles = []
461
+ for (const area of entry.affected_areas) {
462
+ const abs = path.join(root, area)
463
+ const exists = await fs.access(abs).then(() => true).catch(() => false)
464
+ if (!exists) missingFiles.push(area)
465
+ }
466
+ if (missingFiles.length > 0) {
467
+ flags.push({
468
+ entryId: (entry.id ?? "").slice(0, 8),
469
+ topic: entry.topic,
470
+ decision: (entry.decision ?? entry.key_insight ?? "").slice(0, 160),
471
+ missingFiles,
472
+ confidence: entry.confidence,
473
+ status: entry.status,
474
+ })
475
+ }
476
+ }
477
+
478
+ return {
479
+ total: entries.length,
480
+ flagged: flags.length,
481
+ flags,
482
+ note: "Structural check: entries whose affected_areas paths no longer exist. For semantic drift (did the code meaning change?) run: quorum sentinel --drift from the CLI.",
483
+ }
484
+ }
485
+
329
486
  /**
330
487
  * Call once at server startup to wire the LLM provider into LLM-powered tools.
331
488
  */
package/bin/ui/app.html CHANGED
@@ -553,6 +553,173 @@
553
553
  border-radius: 0 var(--radius) var(--radius) 0;
554
554
  }
555
555
 
556
+ /* ── Advisor chat ── */
557
+ .chat-wrap {
558
+ display: flex;
559
+ flex-direction: column;
560
+ gap: 16px;
561
+ max-height: 520px;
562
+ overflow-y: auto;
563
+ padding-bottom: 4px;
564
+ margin-bottom: 14px;
565
+ }
566
+ .chat-bubble {
567
+ display: flex;
568
+ flex-direction: column;
569
+ gap: 5px;
570
+ max-width: 92%;
571
+ }
572
+ .chat-bubble--user { align-self: flex-end; }
573
+ .chat-bubble--ai { align-self: flex-start; }
574
+ .chat-label {
575
+ font-size: 11px;
576
+ font-weight: 700;
577
+ text-transform: uppercase;
578
+ letter-spacing: .06em;
579
+ color: var(--muted);
580
+ }
581
+ .chat-bubble--user .chat-label { text-align: right; }
582
+ .chat-body {
583
+ font-size: 13px;
584
+ line-height: 1.6;
585
+ padding: 10px 14px;
586
+ border-radius: var(--radius);
587
+ }
588
+ .chat-bubble--user .chat-body {
589
+ background: rgba(124,110,255,.15);
590
+ color: var(--text);
591
+ border-radius: var(--radius) var(--radius) 2px var(--radius);
592
+ }
593
+ .chat-bubble--ai .chat-body {
594
+ background: var(--surface);
595
+ border: 1px solid var(--border);
596
+ color: var(--text);
597
+ border-radius: 2px var(--radius) var(--radius) var(--radius);
598
+ }
599
+ .chat-citations {
600
+ display: flex;
601
+ flex-wrap: wrap;
602
+ gap: 4px;
603
+ margin-top: 4px;
604
+ }
605
+ .chat-citation {
606
+ font-size: 11px;
607
+ font-family: var(--mono);
608
+ padding: 2px 6px;
609
+ border-radius: 4px;
610
+ background: rgba(82,168,224,.1);
611
+ color: var(--blue);
612
+ }
613
+ .chat-confidence {
614
+ font-size: 11px;
615
+ color: var(--muted);
616
+ margin-top: 4px;
617
+ }
618
+ .chat-input-row {
619
+ display: flex;
620
+ gap: 8px;
621
+ }
622
+ .chat-input-row input {
623
+ flex: 1;
624
+ padding: 10px 14px;
625
+ background: var(--surface);
626
+ border: 1px solid var(--border);
627
+ border-radius: var(--radius);
628
+ color: var(--text);
629
+ font: inherit;
630
+ font-size: 13px;
631
+ outline: none;
632
+ transition: border-color .15s;
633
+ }
634
+ .chat-input-row input:focus { border-color: var(--accent); }
635
+
636
+ /* ── Check ── */
637
+ .risk-banner {
638
+ display: flex;
639
+ align-items: center;
640
+ gap: 12px;
641
+ padding: 14px 16px;
642
+ border-radius: var(--radius);
643
+ margin-bottom: 16px;
644
+ border: 1px solid var(--border);
645
+ }
646
+ .risk-level {
647
+ font-size: 18px;
648
+ font-weight: 800;
649
+ text-transform: uppercase;
650
+ letter-spacing: .06em;
651
+ }
652
+ .risk-critical { background: rgba(224,82,82,.12); color: var(--red); border-color: rgba(224,82,82,.3); }
653
+ .risk-high { background: rgba(224,185,82,.12); color: var(--yellow); border-color: rgba(224,185,82,.3); }
654
+ .risk-medium { background: rgba(82,168,224,.10); color: var(--blue); border-color: rgba(82,168,224,.3); }
655
+ .risk-low { background: rgba(52,201,122,.10); color: var(--green); border-color: rgba(52,201,122,.3); }
656
+ .preflight-row {
657
+ display: flex;
658
+ align-items: center;
659
+ gap: 8px;
660
+ font-size: 13px;
661
+ margin-bottom: 6px;
662
+ }
663
+ .preflight-ok { color: var(--green); }
664
+ .preflight-bad { color: var(--yellow); }
665
+
666
+ /* ── Ingest ── */
667
+ .ingest-section {
668
+ background: var(--surface);
669
+ border: 1px solid var(--border);
670
+ border-radius: var(--radius);
671
+ padding: 16px;
672
+ margin-bottom: 14px;
673
+ }
674
+ .ingest-section-title {
675
+ font-size: 13px;
676
+ font-weight: 700;
677
+ margin-bottom: 10px;
678
+ color: var(--text);
679
+ }
680
+ .ingest-result {
681
+ margin-top: 10px;
682
+ font-size: 12px;
683
+ font-family: var(--mono);
684
+ color: var(--muted);
685
+ line-height: 1.8;
686
+ }
687
+
688
+ /* ── Sentinel drift ── */
689
+ .drift-flag {
690
+ background: var(--surface);
691
+ border: 1px solid var(--border);
692
+ border-left: 3px solid var(--yellow);
693
+ border-radius: 0 var(--radius) var(--radius) 0;
694
+ padding: 12px 14px;
695
+ margin-bottom: 10px;
696
+ }
697
+ .drift-flag-title {
698
+ font-size: 13px;
699
+ font-weight: 600;
700
+ color: var(--text);
701
+ margin-bottom: 4px;
702
+ }
703
+ .drift-flag-body {
704
+ font-size: 12px;
705
+ color: var(--muted);
706
+ line-height: 1.5;
707
+ }
708
+ .drift-missing {
709
+ display: flex;
710
+ flex-wrap: wrap;
711
+ gap: 4px;
712
+ margin-top: 6px;
713
+ }
714
+ .drift-path {
715
+ font-family: var(--mono);
716
+ font-size: 11px;
717
+ padding: 2px 6px;
718
+ background: rgba(224,82,82,.1);
719
+ color: var(--red);
720
+ border-radius: 4px;
721
+ }
722
+
556
723
  /* ── Edit modal ── */
557
724
  .modal-overlay {
558
725
  display: none;
@@ -667,6 +834,14 @@
667
834
  <button onclick="showTab('coverage')">Coverage</button>
668
835
  <button onclick="showTab('growth')">Growth</button>
669
836
  <button onclick="showTab('compass')">Compass</button>
837
+ <button onclick="showTab('advisor')">Advisor</button>
838
+ <button onclick="showTab('check')">Check</button>
839
+ <button onclick="showTab('ingest')">Ingest</button>
840
+ <button onclick="showTab('sentinel')">Sentinel</button>
841
+ <button onclick="showTab('advisor')">Advisor</button>
842
+ <button onclick="showTab('check')">Check</button>
843
+ <button onclick="showTab('ingest')">Ingest</button>
844
+ <button onclick="showTab('sentinel')">Sentinel</button>
670
845
  </nav>
671
846
  </header>
672
847
 
@@ -715,6 +890,98 @@
715
890
  </div>
716
891
  <div id="compassView"><div class="empty">Select a subcommand and click Run.<small>Requires an LLM provider configured for quorum serve.</small></div></div>
717
892
  </div>
893
+
894
+ <!-- ── Advisor tab ──────────────────────────────────────────────── -->
895
+ <div id="tab-advisor" class="tab">
896
+ <h2 class="section-heading">Advisor</h2>
897
+ <p class="section-sub">Ask plain-language questions answered from Chronicle memory.</p>
898
+ <div class="chat-wrap" id="advisorChat"></div>
899
+ <div class="chat-input-row">
900
+ <input id="advisorInput" type="text" placeholder="Ask anything about your codebase…" autocomplete="off"
901
+ onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();sendAdvisorMsg()}">
902
+ <button class="btn" onclick="sendAdvisorMsg()">Ask</button>
903
+ </div>
904
+ <p style="font-size:12px;color:var(--muted);margin-top:8px">Requires an LLM provider. Answers are grounded in Chronicle entries.</p>
905
+ </div>
906
+
907
+ <!-- ── Check tab ────────────────────────────────────────────────── -->
908
+ <div id="tab-check" class="tab">
909
+ <h2 class="section-heading">Risk Check</h2>
910
+ <p class="section-sub">Instant risk triage against known sensitive patterns — no LLM required.</p>
911
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px">
912
+ <div class="field">
913
+ <label>Outcome (what changes)</label>
914
+ <textarea id="checkOutcome" rows="5" placeholder="e.g. Add JWT refresh token rotation to the auth service…"></textarea>
915
+ </div>
916
+ <div class="field">
917
+ <label>Design / approach</label>
918
+ <textarea id="checkDesign" rows="5" placeholder="e.g. Store tokens in Redis with 7-day TTL, invalidate on logout…"></textarea>
919
+ </div>
920
+ </div>
921
+ <button class="btn" onclick="runCheck()">Check risk</button>
922
+ <div id="checkResult" style="margin-top:16px"></div>
923
+ </div>
924
+
925
+ <!-- ── Ingest tab ───────────────────────────────────────────────── -->
926
+ <div id="tab-ingest" class="tab">
927
+ <h2 class="section-heading">Ingest</h2>
928
+ <p class="section-sub">Add low-trust evidence to Chronicle from git history, files, or URLs. Nothing is committed automatically — run <code style="font-family:var(--mono);font-size:12px">quorum commit --list</code> to review.</p>
929
+
930
+ <div class="ingest-section">
931
+ <div class="ingest-section-title">Git history</div>
932
+ <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
933
+ <div class="field" style="margin:0;flex:1;min-width:140px">
934
+ <label>Since (ISO 8601 duration)</label>
935
+ <input id="ingestGitSince" type="text" value="P90D" placeholder="P90D">
936
+ </div>
937
+ <div style="display:flex;align-items:center;gap:6px;padding-bottom:1px">
938
+ <input type="checkbox" id="ingestGitPropose">
939
+ <label for="ingestGitPropose" style="font-size:13px">Also stage as proposals</label>
940
+ </div>
941
+ <button class="btn" style="flex:none" onclick="runIngest('git')">Ingest commits</button>
942
+ </div>
943
+ <div class="ingest-result" id="ingestGitResult"></div>
944
+ </div>
945
+
946
+ <div class="ingest-section">
947
+ <div class="ingest-section-title">Files</div>
948
+ <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
949
+ <div class="field" style="margin:0;flex:1;min-width:200px">
950
+ <label>Paths (comma-separated, relative to project root)</label>
951
+ <input id="ingestFilePaths" type="text" placeholder="docs/RFC.md, src/lib/triage.ts">
952
+ </div>
953
+ <div style="display:flex;align-items:center;gap:6px;padding-bottom:1px">
954
+ <input type="checkbox" id="ingestFilePropose">
955
+ <label for="ingestFilePropose" style="font-size:13px">Also stage as proposals</label>
956
+ </div>
957
+ <button class="btn" style="flex:none" onclick="runIngest('files')">Ingest files</button>
958
+ </div>
959
+ <div class="ingest-result" id="ingestFileResult"></div>
960
+ </div>
961
+
962
+ <div class="ingest-section">
963
+ <div class="ingest-section-title">URL</div>
964
+ <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
965
+ <div class="field" style="margin:0;flex:1;min-width:260px">
966
+ <label>URL (http/https only)</label>
967
+ <input id="ingestUrl" type="text" placeholder="https://example.com/rfc">
968
+ </div>
969
+ <div style="display:flex;align-items:center;gap:6px;padding-bottom:1px">
970
+ <input type="checkbox" id="ingestUrlPropose">
971
+ <label for="ingestUrlPropose" style="font-size:13px">Also stage as proposals</label>
972
+ </div>
973
+ <button class="btn" style="flex:none" onclick="runIngest('url')">Ingest URL</button>
974
+ </div>
975
+ <div class="ingest-result" id="ingestUrlResult"></div>
976
+ </div>
977
+ </div>
978
+
979
+ <!-- ── Sentinel tab ─────────────────────────────────────────────── -->
980
+ <div id="tab-sentinel" class="tab">
981
+ <h2 class="section-heading">Sentinel</h2>
982
+ <p class="section-sub">Chronicle entries whose referenced files no longer exist — structural drift detection.</p>
983
+ <div id="sentinelView"><div class="loading">Loading…</div></div>
984
+ </div>
718
985
  </main>
719
986
 
720
987
  <!-- ── Edit proposal modal ───────────────────────────────────────────── -->
@@ -771,7 +1038,7 @@ window.addEventListener("DOMContentLoaded", () => {
771
1038
 
772
1039
  // ── Tab switching ──────────────────────────────────────────────────────────
773
1040
 
774
- const TAB_NAMES = ["chronicle", "proposals", "coverage", "growth", "compass"]
1041
+ const TAB_NAMES = ["chronicle", "proposals", "coverage", "growth", "compass", "advisor", "check", "ingest", "sentinel"]
775
1042
 
776
1043
  function showTab(name) {
777
1044
  document.querySelectorAll(".tab").forEach(t => t.classList.remove("active"))
@@ -780,8 +1047,9 @@ function showTab(name) {
780
1047
  })
781
1048
  document.getElementById(`tab-${name}`).classList.add("active")
782
1049
  activeTab = name
783
- if (name === "coverage" && !coverageData) loadCoverage()
784
- if (name === "growth" && !growthData) loadGrowth()
1050
+ if (name === "coverage" && !coverageData) loadCoverage()
1051
+ if (name === "growth" && !growthData) loadGrowth()
1052
+ if (name === "sentinel" && !sentinelLoaded) loadSentinel()
785
1053
  }
786
1054
 
787
1055
  // ── Toast ──────────────────────────────────────────────────────────────────
@@ -1315,6 +1583,220 @@ function renderCompass(data, subcommand) {
1315
1583
 
1316
1584
  el.innerHTML = `<div style="padding-bottom:16px">${inner}</div>`
1317
1585
  }
1586
+
1587
+ // ── Advisor ───────────────────────────────────────────────────────────────
1588
+
1589
+ let advisorHistory = [] // { role: "user"|"ai", text, citations, confidence }
1590
+
1591
+ function renderAdvisorHistory() {
1592
+ const wrap = document.getElementById("advisorChat")
1593
+ if (!advisorHistory.length) {
1594
+ wrap.innerHTML = `<div class="empty" style="margin:0">No messages yet. Ask a question above.<small>e.g. "What decisions have been made about auth?" or "What should I tackle next?"</small></div>`
1595
+ return
1596
+ }
1597
+ wrap.innerHTML = advisorHistory.map(m => {
1598
+ if (m.role === "user") {
1599
+ return `<div class="chat-bubble chat-bubble--user">
1600
+ <span class="chat-label">You</span>
1601
+ <div class="chat-body">${esc(m.text)}</div>
1602
+ </div>`
1603
+ }
1604
+ const confPct = m.confidence != null ? Math.round(m.confidence * 100) : null
1605
+ const confHtml = confPct != null ? `<div class="chat-confidence">${confPct}% confidence</div>` : ""
1606
+ const citHtml = m.citations?.length
1607
+ ? `<div class="chat-citations">${m.citations.map(c => `<span class="chat-citation">${esc(c)}</span>`).join("")}</div>`
1608
+ : ""
1609
+ const parts = []
1610
+ if (m.what_we_know) parts.push(`<strong>What we know:</strong> ${esc(m.what_we_know)}`)
1611
+ if (m.recommendation) parts.push(`<strong>Recommendation:</strong> ${esc(m.recommendation)}`)
1612
+ if (m.next_step) parts.push(`<strong>Next step:</strong> ${esc(m.next_step)}`)
1613
+ if (m.risks?.length) parts.push(`<strong>Risks:</strong> ${m.risks.map(r => esc(r)).join("; ")}`)
1614
+ return `<div class="chat-bubble chat-bubble--ai">
1615
+ <span class="chat-label">Advisor</span>
1616
+ <div class="chat-body">${parts.length ? parts.join("<br>") : esc(m.text)}</div>
1617
+ ${confHtml}${citHtml}
1618
+ </div>`
1619
+ }).join("")
1620
+ wrap.scrollTop = wrap.scrollHeight
1621
+ }
1622
+
1623
+ async function sendAdvisorMsg() {
1624
+ const input = document.getElementById("advisorInput")
1625
+ const question = input.value.trim()
1626
+ if (!question) return
1627
+ input.value = ""
1628
+ advisorHistory.push({ role: "user", text: question })
1629
+ renderAdvisorHistory()
1630
+
1631
+ // Placeholder while waiting
1632
+ advisorHistory.push({ role: "ai", text: "Thinking…", _pending: true })
1633
+ renderAdvisorHistory()
1634
+
1635
+ try {
1636
+ const res = await fetch("/api/advisor", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ question }) })
1637
+ const data = await res.json()
1638
+ // Remove placeholder
1639
+ advisorHistory = advisorHistory.filter(m => !m._pending)
1640
+
1641
+ if (data.status === "no-llm") {
1642
+ advisorHistory.push({ role: "ai", text: "No LLM provider configured. " + data.message })
1643
+ } else if (data.error) {
1644
+ advisorHistory.push({ role: "ai", text: "Error: " + data.error })
1645
+ } else {
1646
+ const citations = (data.evidence ?? []).map(e => (e.id ?? "").slice(0, 8)).filter(Boolean)
1647
+ advisorHistory.push({
1648
+ role: "ai",
1649
+ what_we_know: data.what_we_know,
1650
+ recommendation: data.recommendation,
1651
+ next_step: data.next_step,
1652
+ risks: data.risks,
1653
+ confidence: data.confidence,
1654
+ citations,
1655
+ })
1656
+ }
1657
+ } catch (err) {
1658
+ advisorHistory = advisorHistory.filter(m => !m._pending)
1659
+ advisorHistory.push({ role: "ai", text: "Request failed: " + err.message })
1660
+ }
1661
+ renderAdvisorHistory()
1662
+ }
1663
+
1664
+ // ── Check ─────────────────────────────────────────────────────────────────
1665
+
1666
+ async function runCheck() {
1667
+ const outcome = document.getElementById("checkOutcome").value.trim()
1668
+ const design = document.getElementById("checkDesign").value.trim()
1669
+ if (!outcome && !design) { toast("Enter an outcome or design first", "err"); return }
1670
+
1671
+ const el = document.getElementById("checkResult")
1672
+ el.innerHTML = `<div class="loading">Analysing…</div>`
1673
+
1674
+ try {
1675
+ const res = await fetch("/api/check", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ outcome, design }) })
1676
+ const data = await res.json()
1677
+ if (data.error) { el.innerHTML = `<div class="empty">Error: ${esc(data.error)}</div>`; return }
1678
+
1679
+ const { risk, preflight } = data
1680
+ const level = risk?.level ?? "low"
1681
+ const riskLabel = { critical: "Critical", high: "High", medium: "Medium", low: "Low" }[level] ?? level
1682
+ const reasons = (risk?.reasons ?? []).filter(r => r !== "no sensitive patterns detected")
1683
+
1684
+ let html = `<div class="risk-banner risk-${level}">
1685
+ <span class="risk-level">${riskLabel}</span>
1686
+ <span style="font-size:13px">${reasons.length ? reasons.join(" · ") : "No sensitive patterns detected"}</span>
1687
+ </div>`
1688
+
1689
+ html += `<div style="display:flex;flex-wrap:wrap;gap:16px">`
1690
+
1691
+ // Preflight flags
1692
+ html += `<div style="min-width:200px">`
1693
+ html += `<div class="cp-section-label" style="margin-bottom:8px">Preflight flags</div>`
1694
+ const sensitive = preflight?.sensitive_areas ?? []
1695
+ if (sensitive.length) {
1696
+ html += sensitive.map(a => `<div class="preflight-row preflight-bad"><span>⚠</span> ${esc(a)}</div>`).join("")
1697
+ } else {
1698
+ html += `<div class="preflight-row preflight-ok"><span>✓</span> No sensitive areas</div>`
1699
+ }
1700
+ html += `<div class="preflight-row ${preflight?.rollback_mentioned ? "preflight-ok" : "preflight-bad"}">
1701
+ <span>${preflight?.rollback_mentioned ? "✓" : "·"}</span> Rollback ${preflight?.rollback_mentioned ? "mentioned" : "not mentioned"}
1702
+ </div>`
1703
+ html += `<div class="preflight-row ${preflight?.test_strategy_mentioned ? "preflight-ok" : "preflight-bad"}">
1704
+ <span>${preflight?.test_strategy_mentioned ? "✓" : "·"}</span> Tests ${preflight?.test_strategy_mentioned ? "mentioned" : "not mentioned"}
1705
+ </div>`
1706
+ html += `</div></div>`
1707
+
1708
+ el.innerHTML = html
1709
+ } catch (err) {
1710
+ el.innerHTML = `<div class="empty">Request failed: ${esc(err.message)}</div>`
1711
+ }
1712
+ }
1713
+
1714
+ // ── Ingest ────────────────────────────────────────────────────────────────
1715
+
1716
+ async function runIngest(type) {
1717
+ let body = { type }
1718
+ let resultEl
1719
+
1720
+ if (type === "git") {
1721
+ body.since = document.getElementById("ingestGitSince").value.trim() || "P90D"
1722
+ body.propose = document.getElementById("ingestGitPropose").checked
1723
+ resultEl = document.getElementById("ingestGitResult")
1724
+ } else if (type === "files") {
1725
+ const raw = document.getElementById("ingestFilePaths").value.trim()
1726
+ if (!raw) { toast("Enter at least one file path", "err"); return }
1727
+ body.paths = raw
1728
+ body.propose = document.getElementById("ingestFilePropose").checked
1729
+ resultEl = document.getElementById("ingestFileResult")
1730
+ } else if (type === "url") {
1731
+ const u = document.getElementById("ingestUrl").value.trim()
1732
+ if (!u) { toast("Enter a URL", "err"); return }
1733
+ body.urls = u
1734
+ body.propose = document.getElementById("ingestUrlPropose").checked
1735
+ resultEl = document.getElementById("ingestUrlResult")
1736
+ }
1737
+
1738
+ resultEl.textContent = "Running…"
1739
+ try {
1740
+ const res = await fetch("/api/ingest", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
1741
+ const data = await res.json()
1742
+ if (data.error) { resultEl.textContent = "Error: " + data.error; return }
1743
+
1744
+ let out = `✓ ${data.added} added, ${data.skipped} skipped`
1745
+ if (body.propose && data.added > 0) out += ` — proposals staged, run quorum commit --list to review`
1746
+ if (data.items?.length) {
1747
+ out += "\n" + data.items.slice(0, 8).map(i => ` ${i.ref} ${i.summary}`).join("\n")
1748
+ if (data.items.length > 8) out += `\n … and ${data.items.length - 8} more`
1749
+ }
1750
+ resultEl.textContent = out
1751
+ if (data.added > 0) toast(`Ingested ${data.added} ${type} item${data.added !== 1 ? "s" : ""}`)
1752
+ } catch (err) {
1753
+ resultEl.textContent = "Request failed: " + err.message
1754
+ }
1755
+ }
1756
+
1757
+ // ── Sentinel ──────────────────────────────────────────────────────────────
1758
+
1759
+ let sentinelLoaded = false
1760
+
1761
+ async function loadSentinel() {
1762
+ sentinelLoaded = true
1763
+ const el = document.getElementById("sentinelView")
1764
+ try {
1765
+ const res = await fetch("/api/sentinel/drift")
1766
+ const data = await res.json()
1767
+ renderSentinel(data)
1768
+ } catch (err) {
1769
+ el.innerHTML = `<div class="empty">Failed to load sentinel data<small>${esc(err.message)}</small></div>`
1770
+ }
1771
+ }
1772
+
1773
+ function renderSentinel(data) {
1774
+ const el = document.getElementById("sentinelView")
1775
+ const { total = 0, flagged = 0, flags = [], note = "" } = data
1776
+
1777
+ let html = `<div style="display:flex;gap:20px;margin-bottom:18px;flex-wrap:wrap">`
1778
+ html += `<div style="text-align:center;min-width:100px"><div style="font-size:28px;font-weight:800;color:var(--text)">${total}</div><div style="font-size:12px;color:var(--muted)">Chronicle entries</div></div>`
1779
+ html += `<div style="text-align:center;min-width:100px"><div style="font-size:28px;font-weight:800;color:${flagged > 0 ? "var(--yellow)" : "var(--green)"}">${flagged}</div><div style="font-size:12px;color:var(--muted)">Structurally drifted</div></div>`
1780
+ html += `</div>`
1781
+
1782
+ if (note) html += `<p style="font-size:12px;color:var(--muted);margin-bottom:16px">${esc(note)}</p>`
1783
+
1784
+ if (!flags.length) {
1785
+ html += `<div class="empty">No drift detected — all affected_areas paths resolve to existing files.</div>`
1786
+ } else {
1787
+ for (const f of flags) {
1788
+ html += `<div class="drift-flag">
1789
+ <div class="drift-flag-title">[${esc(f.entryId)}] ${esc(f.topic)}</div>
1790
+ <div class="drift-flag-body">${esc(f.decision)}</div>
1791
+ <div class="drift-missing">
1792
+ ${f.missingFiles.map(p => `<span class="drift-path">${esc(p)}</span>`).join("")}
1793
+ </div>
1794
+ </div>`
1795
+ }
1796
+ }
1797
+
1798
+ el.innerHTML = html
1799
+ }
1318
1800
  </script>
1319
1801
  </body>
1320
1802
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@balpal4495/quorum",
3
- "version": "3.7.0",
3
+ "version": "3.8.0",
4
4
  "description": "Git-backed memory and design review for AI coding agents",
5
5
  "type": "module",
6
6
  "license": "MIT",