incidentsutra 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +5 -0
  3. package/CITATION.cff +2 -2
  4. package/README.md +3 -3
  5. package/docs/EVIDENCE_MODEL.md +1 -1
  6. package/docs/STATUS.md +1 -1
  7. package/docs/THREAT_MODEL.md +1 -1
  8. package/documents/IncidentSutra-AI/01-executive-summary.html +13 -12
  9. package/documents/IncidentSutra-AI/01-executive-summary.md +4 -0
  10. package/documents/IncidentSutra-AI/02-functional-spec.html +15 -14
  11. package/documents/IncidentSutra-AI/02-functional-spec.md +4 -0
  12. package/documents/IncidentSutra-AI/03-technical-spec.html +15 -16
  13. package/documents/IncidentSutra-AI/04-architecture.html +19 -17
  14. package/documents/IncidentSutra-AI/04-architecture.md +6 -0
  15. package/documents/IncidentSutra-AI/05-user-guide.html +28 -27
  16. package/documents/IncidentSutra-AI/05-user-guide.md +4 -0
  17. package/documents/IncidentSutra-AI/06-security-privacy-legal.html +14 -13
  18. package/documents/IncidentSutra-AI/06-security-privacy-legal.md +4 -0
  19. package/documents/IncidentSutra-AI/07-independent-audit.html +17 -15
  20. package/documents/IncidentSutra-AI/07-independent-audit.md +6 -0
  21. package/documents/IncidentSutra-AI/08-agent-catalog.html +9 -10
  22. package/documents/IncidentSutra-AI/09-faq.html +7 -8
  23. package/documents/IncidentSutra-AI/10-real-world-scenarios.html +31 -0
  24. package/documents/IncidentSutra-AI/10-real-world-scenarios.md +63 -0
  25. package/documents/IncidentSutra-AI/11-visual-guide.html +28 -0
  26. package/documents/IncidentSutra-AI/11-visual-guide.md +60 -0
  27. package/documents/IncidentSutra-AI/12-glossary.html +3 -0
  28. package/documents/IncidentSutra-AI/12-glossary.md +28 -0
  29. package/documents/IncidentSutra-AI/404.html +1 -0
  30. package/documents/IncidentSutra-AI/README.html +7 -8
  31. package/documents/IncidentSutra-AI/README.md +4 -2
  32. package/documents/IncidentSutra-AI/assets/site.css +263 -0
  33. package/documents/IncidentSutra-AI/assets/site.js +135 -0
  34. package/documents/IncidentSutra-AI/evidence/audit/audit-report.html +6 -4
  35. package/documents/IncidentSutra-AI/evidence/audit/audit-report.json +3 -3
  36. package/documents/IncidentSutra-AI/evidence/audit/audit-report.md +3 -3
  37. package/documents/IncidentSutra-AI/evidence/benchmark.json +18 -18
  38. package/documents/IncidentSutra-AI/evidence/samples/incident-report.html +5 -3
  39. package/documents/IncidentSutra-AI/evidence/samples/incident-report.json +2 -2
  40. package/documents/IncidentSutra-AI/evidence/samples/incident-report.md +2 -2
  41. package/documents/IncidentSutra-AI/evidence/samples/postmortem-draft.md +1 -1
  42. package/documents/IncidentSutra-AI/evidence/scenarios/database-pool.html +47 -0
  43. package/documents/IncidentSutra-AI/evidence/scenarios/deploy-blamed.html +47 -0
  44. package/documents/IncidentSutra-AI/evidence/scenarios/night-alert-storm.html +47 -0
  45. package/documents/IncidentSutra-AI/evidence/scenarios/payment-provider.html +47 -0
  46. package/documents/IncidentSutra-AI/evidence/scenarios/thin-evidence.html +47 -0
  47. package/documents/IncidentSutra-AI/evidence/scenarios/timezone-mixup.html +47 -0
  48. package/documents/IncidentSutra-AI/evidence/test-results.json +36 -4
  49. package/documents/IncidentSutra-AI/index.html +15 -0
  50. package/documents/IncidentSutra-AI/robots.txt +3 -0
  51. package/documents/IncidentSutra-AI/sitemap.xml +26 -0
  52. package/documents/IncidentSutra-AI/test-results.html +5 -6
  53. package/documents/IncidentSutra-AI/test-results.md +10 -2
  54. package/examples/reports/demo/hypothesis-register.md +1 -1
  55. package/examples/reports/demo/incident-report.html +5 -3
  56. package/examples/reports/demo/incident-report.json +2 -2
  57. package/examples/reports/demo/incident-report.md +2 -2
  58. package/examples/reports/demo/postmortem-draft.md +1 -1
  59. package/examples/reports/demo/provenance.json +8 -8
  60. package/fixtures/scenarios/database-pool/events.jsonl +6 -0
  61. package/fixtures/scenarios/deploy-blamed/events.jsonl +6 -0
  62. package/fixtures/scenarios/night-alert-storm/events.jsonl +10 -0
  63. package/fixtures/scenarios/payment-provider/events.jsonl +6 -0
  64. package/fixtures/scenarios/thin-evidence/events.jsonl +3 -0
  65. package/fixtures/scenarios/timezone-mixup/events.jsonl +4 -0
  66. package/llms.txt +3 -0
  67. package/package.json +2 -2
  68. package/packages/reporter/index.mjs +1 -1
  69. package/packages/reporter/theme.mjs +4 -2
  70. package/scripts/build-docs.mjs +205 -51
  71. package/scripts/build-site.mjs +27 -0
  72. package/site/diagrams.mjs +68 -0
  73. package/site/extra.css +62 -0
  74. package/site/incident.css +31 -0
  75. package/site/site.css +168 -0
  76. package/site/site.js +135 -0
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schema": "incidentsutra.provenance.v1",
3
- "reportId": "inc_e95e3ae334e5f1390998",
3
+ "reportId": "inc_9f3d6ce70b16ee09374b",
4
4
  "tool": {
5
5
  "name": "incidentsutra",
6
- "version": "0.2.1",
6
+ "version": "0.2.2",
7
7
  "ruleVersion": "2026.11-r2"
8
8
  },
9
9
  "inputs": [
@@ -23,18 +23,18 @@
23
23
  "outputs": [
24
24
  {
25
25
  "file": "incident-report.json",
26
- "sha256": "da6c4848e7a99873432c41dabe3ed5f7d353aa239ab8676e7f905db1398d592b",
26
+ "sha256": "feb850200e919a832b686f00586f109a2decb42da41c4eb5e6144974adfbaad6",
27
27
  "bytes": 37801
28
28
  },
29
29
  {
30
30
  "file": "incident-report.md",
31
- "sha256": "4cb790ca632545a2fa1ad4009fa7a83703a305951dc8d7a7dd6b8b4831acba7b",
31
+ "sha256": "76a0c55c5705830d03ff0b59163ab804b2894402422e92584688b44a7331513b",
32
32
  "bytes": 9337
33
33
  },
34
34
  {
35
35
  "file": "incident-report.html",
36
- "sha256": "73fa92824b5020eb5ba7e3e7fac13f8931ffc12a20b672727c873271a912c5b1",
37
- "bytes": 21903
36
+ "sha256": "e14721eb60ba59fb3c73e9e745c0d9b224db26087512766036b6e67c53667d14",
37
+ "bytes": 22289
38
38
  },
39
39
  {
40
40
  "file": "normalized-events.jsonl",
@@ -48,12 +48,12 @@
48
48
  },
49
49
  {
50
50
  "file": "hypothesis-register.md",
51
- "sha256": "17a70822ae60d96daf18c32b6b51dfc37b89bf90a3c2705467735bbead3ee417",
51
+ "sha256": "e26bf4a99ffa3d73072abf6453c36cec557975d3078478d0d9ff8bf5918d59a5",
52
52
  "bytes": 3181
53
53
  },
54
54
  {
55
55
  "file": "postmortem-draft.md",
56
- "sha256": "024c870ea99996289ce57fc830b04a879b3928b502d177a0a1fc78ada8242f7a",
56
+ "sha256": "d25f5c40d336d22cc641938d075c61fa5eb1927eb359876694bfb351e3c6e613",
57
57
  "bytes": 3039
58
58
  }
59
59
  ],
@@ -0,0 +1,6 @@
1
+ {"timestamp":"2026-11-13T07:30:00Z","type":"deploy","service":"accounts","message":"accounts release 1.18","deploymentId":"accounts-1.18"}
2
+ {"timestamp":"2026-11-13T08:05:00Z","type":"metric","service":"accounts","message":"database connections","attributes":{"db_connections":40}}
3
+ {"timestamp":"2026-11-13T08:14:00Z","type":"error","service":"accounts","severity":"error","message":"postgres connection pool exhausted"}
4
+ {"timestamp":"2026-11-13T08:15:00Z","type":"metric","service":"accounts","message":"database connections","attributes":{"db_connections":200}}
5
+ {"timestamp":"2026-11-13T08:16:00Z","type":"alert","service":"accounts","severity":"critical","message":"login failures rising"}
6
+ {"timestamp":"2026-11-13T08:17:00Z","type":"log","service":"accounts","severity":"warning","message":"slow query on sessions table, lock wait"}
@@ -0,0 +1,6 @@
1
+ {"timestamp":"2026-11-10T09:55:00Z","type":"metric","service":"orders","message":"error rate baseline","attributes":{"error_rate_pct":0.2}}
2
+ {"timestamp":"2026-11-10T10:02:00Z","type":"error","service":"orders","severity":"error","message":"order creation failed: null customer reference"}
3
+ {"timestamp":"2026-11-10T10:06:00Z","type":"deploy","service":"orders","message":"orders release 4.2.0 rolled out","deploymentId":"orders-4.2.0"}
4
+ {"timestamp":"2026-11-10T10:08:00Z","type":"error","service":"orders","severity":"error","message":"order creation failed: null customer reference"}
5
+ {"timestamp":"2026-11-10T10:09:00Z","type":"alert","service":"orders","severity":"critical","message":"orders error rate above threshold"}
6
+ {"timestamp":"2026-11-10T10:10:00Z","type":"metric","service":"orders","message":"error rate now","attributes":{"error_rate_pct":6.4}}
@@ -0,0 +1,10 @@
1
+ {"timestamp":"2026-11-14T21:30:00Z","type":"metric","service":"media","message":"memory use","attributes":{"memory_pct":61}}
2
+ {"timestamp":"2026-11-14T21:41:00Z","type":"error","service":"media","severity":"error","message":"worker killed: out of memory while resizing upload from meera@example.com"}
3
+ {"timestamp":"2026-11-14T21:41:20Z","type":"alert","service":"media","severity":"critical","message":"pod restart 1"}
4
+ {"timestamp":"2026-11-14T21:41:50Z","type":"alert","service":"media","severity":"critical","message":"pod restart 2"}
5
+ {"timestamp":"2026-11-14T21:42:10Z","type":"alert","service":"media","severity":"critical","message":"pod restart 3"}
6
+ {"timestamp":"2026-11-14T21:42:40Z","type":"alert","service":"media","severity":"critical","message":"queue depth backlog growing"}
7
+ {"timestamp":"2026-11-14T21:43:05Z","type":"alert","service":"media","severity":"critical","message":"pod restart 4"}
8
+ {"timestamp":"2026-11-14T21:43:30Z","type":"alert","service":"media","severity":"critical","message":"upload success rate low"}
9
+ {"timestamp":"2026-11-14T21:44:00Z","type":"log","service":"media","severity":"warning","message":"retrying with authorization: Bearer demo-not-a-real-token-123456"}
10
+ {"timestamp":"2026-11-14T21:45:00Z","type":"metric","service":"media","message":"memory use","attributes":{"memory_pct":98}}
@@ -0,0 +1,6 @@
1
+ {"timestamp":"2026-11-12T14:00:00Z","type":"log","service":"payments","severity":"warning","message":"external payment provider latency rising, upstream timeout","traceId":"t-100"}
2
+ {"timestamp":"2026-11-12T14:01:00Z","type":"deploy","service":"search","message":"search ranking release 9.1","deploymentId":"search-9.1"}
3
+ {"timestamp":"2026-11-12T14:03:00Z","type":"error","service":"checkout","severity":"error","message":"payment gateway timeout after 30s","traceId":"t-101"}
4
+ {"timestamp":"2026-11-12T14:04:00Z","type":"alert","service":"checkout","severity":"critical","message":"checkout failures above threshold"}
5
+ {"timestamp":"2026-11-12T14:05:00Z","type":"metric","service":"checkout","message":"checkout latency","attributes":{"p95_ms":30200}}
6
+ {"timestamp":"2026-11-12T14:06:00Z","type":"error","service":"checkout","severity":"error","message":"payment gateway timeout after 30s","traceId":"t-102"}
@@ -0,0 +1,3 @@
1
+ {"timestamp":"2026-11-15T12:10:00+01:00","type":"incident","service":"portal","severity":"warning","message":"support: customer reports blank page"}
2
+ {"timestamp":"2026-11-15T12:25:00+01:00","type":"incident","service":"portal","severity":"warning","message":"support: second customer reports blank page"}
3
+ {"timestamp":"yesterday afternoon","type":"log","service":"portal","message":"someone saw errors"}
@@ -0,0 +1,4 @@
1
+ {"timestamp":"2026-11-11T01:15:00+05:30","type":"deploy","service":"checkout","message":"checkout release 2.7.0 started by CI","deploymentId":"checkout-2.7.0"}
2
+ {"timestamp":"2026-11-10T19:49:00Z","type":"error","service":"checkout","severity":"error","message":"cart total calculation failed"}
3
+ {"timestamp":"2026-11-10T19:51:00Z","type":"alert","service":"checkout","severity":"critical","message":"checkout success rate dropped"}
4
+ {"timestamp":"2026-11-10T19:55:00Z","type":"error","service":"checkout","severity":"error","message":"cart total calculation failed"}
package/llms.txt CHANGED
@@ -17,6 +17,9 @@ It never confirms a root cause, never executes anything against production, and
17
17
  - [Agent catalogue](documents/IncidentSutra-AI/08-agent-catalog.md)
18
18
  - [FAQ](documents/IncidentSutra-AI/09-faq.md)
19
19
  - [Observed test results](documents/IncidentSutra-AI/test-results.md)
20
+ - [Real-world scenarios](documents/IncidentSutra-AI/10-real-world-scenarios.md): six runnable samples
21
+ - [Visual guide](documents/IncidentSutra-AI/11-visual-guide.md)
22
+ - [Glossary](documents/IncidentSutra-AI/12-glossary.md)
20
23
 
21
24
  ## Quick start
22
25
  - `npx incidentsutra analyze --input <dir> --out report`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "incidentsutra",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "IncidentSutra AI: offline, read-only incident evidence CLI. Builds auditable UTC timelines and competing hypotheses from logs, metrics and deployments, with MD/HTML/JSON reports, an automated audit and 20 portable agent skills for Claude Code, Cursor, Codex, Gemini CLI and Copilot.",
5
5
  "keywords": ["incident-response", "sre", "postmortem", "observability", "root-cause-analysis", "timeline", "opentelemetry", "on-call", "blameless", "agent-skills", "claude-code", "cursor", "codex", "gemini-cli", "copilot", "ai-agents", "offline", "privacy", "cli"],
6
6
  "license": "Apache-2.0",
@@ -13,7 +13,7 @@
13
13
  "exports": {".": "./packages/core/analyze.mjs", "./ingest": "./packages/core/ingest.mjs", "./cli": "./packages/cli/index.mjs"},
14
14
  "bin": {"incidentsutra": "packages/cli/index.mjs"},
15
15
  "engines": {"node": ">=20"},
16
- "files": ["packages", "skills", "agents", "schemas", "policies", "rules", "workflows", "adapters", "templates", "fixtures", "examples", "docs", "documents/IncidentSutra-AI", ".claude-plugin", "scripts", "compatibility-matrix.json", "LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md", "CONTRIBUTING.md", "CODE_OF_CONDUCT.md", "SUPPORT.md", "SECURITY.md", "CHANGELOG.md", "CITATION.cff", "llms.txt", "README.md", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "GOVERNANCE.md", "ROADMAP.md"],
16
+ "files": ["packages", "skills", "agents", "schemas", "policies", "rules", "workflows", "adapters", "templates", "fixtures", "examples", "docs", "documents/IncidentSutra-AI", ".claude-plugin", "scripts", "site", "compatibility-matrix.json", "LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md", "CONTRIBUTING.md", "CODE_OF_CONDUCT.md", "SUPPORT.md", "SECURITY.md", "CHANGELOG.md", "CITATION.cff", "llms.txt", "README.md", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "GOVERNANCE.md", "ROADMAP.md"],
17
17
  "scripts": {
18
18
  "test": "node --test",
19
19
  "doctor": "node packages/cli/index.mjs doctor",
@@ -2,7 +2,7 @@ import {escapeHtml as h, mdCell, page} from './theme.mjs';
2
2
 
3
3
  const list = a => (a && a.length ? a.join(', ') : 'none');
4
4
 
5
- function svgTimeline(report) {
5
+ export function svgTimeline(report) {
6
6
  const ev = report.timeline;
7
7
  if (ev.length < 2) return '';
8
8
  const t0 = Date.parse(ev[0].timestamp), t1 = Date.parse(ev.at(-1).timestamp), span = Math.max(1, t1 - t0);
@@ -5,7 +5,9 @@ export const CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:
5
5
 
6
6
  export const CSS = `
7
7
  :root{--bg:#f5f7fa;--card:#fff;--fg:#14202e;--mut:#506072;--bd:#dbe3ec;--ac:#0b5c7a;--ok:#0f7a4d;--warn:#9a5b00;--bad:#b3261e;--info:#2b4fa3;--chip:#eaf0f6;--code:#eef2f6}
8
- @media(prefers-color-scheme:dark){:root{--bg:#0d141c;--card:#141e29;--fg:#e6edf5;--mut:#9db0c4;--bd:#243445;--ac:#6cc4e6;--ok:#52d39b;--warn:#f0b24a;--bad:#ff8a80;--info:#8fb0ff;--chip:#1c2a39;--code:#1a2735}}
8
+ :root:has(#theme-dark:checked){color-scheme:dark;--bg:#0d141c;--card:#141e29;--fg:#e6edf5;--mut:#9db0c4;--bd:#243445;--ac:#6cc4e6;--ok:#52d39b;--warn:#f0b24a;--bad:#ff8a80;--info:#8fb0ff;--chip:#1c2a39;--code:#1a2735}
9
+ .theme-toggle{display:inline-flex;gap:.45rem;align-items:center;float:right;margin:0 0 10px;padding:6px 12px;border:1px solid var(--bd);border-radius:999px;background:var(--card);font-size:.85rem;cursor:pointer;min-height:40px}
10
+ .theme-toggle+*{clear:both}@media print{.theme-toggle{display:none}}
9
11
  *{box-sizing:border-box}html{scroll-behavior:smooth}
10
12
  body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.6 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
11
13
  a{color:var(--ac)}code{background:var(--code);padding:.1em .35em;border-radius:5px;font:.85em ui-monospace,Consolas,monospace;overflow-wrap:anywhere}
@@ -37,5 +39,5 @@ footer{color:var(--mut);font-size:.82rem;margin-top:24px}
37
39
  `;
38
40
 
39
41
  export function page({title, description, body}) {
40
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><meta http-equiv="Content-Security-Policy" content="${CSP}"><meta name="description" content="${escapeHtml(description)}"><title>${escapeHtml(title)}</title><style>${CSS}</style></head><body><div class="wrap">${body}</div></body></html>\n`;
42
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><meta http-equiv="Content-Security-Policy" content="${CSP}"><meta name="description" content="${escapeHtml(description)}"><title>${escapeHtml(title)}</title><style>${CSS}</style></head><body><div class="wrap"><label class="theme-toggle"><input type="checkbox" id="theme-dark"> Dark theme</label>${body}</div></body></html>\n`;
41
43
  }
@@ -1,72 +1,226 @@
1
- // Dependency-free Markdown -> HTML builder for documents/IncidentSutra-AI. `--check` fails if HTML is stale.
1
+ #!/usr/bin/env node
2
+ // Builds the documentation website into documents/IncidentSutra-AI from its Markdown. Dependency-free.
3
+ // Light theme by default; dark by toggle. Numbers come from evidence/, scenario results from real analysis runs.
4
+ // Directives (HTML comments, invisible on GitHub): <!-- svg:name --> <!-- flow:name --> <!-- chart:name --> <!-- scenario:folder -->
5
+ // `--check` fails when committed output differs from what the sources would produce.
2
6
  import fs from 'node:fs';
3
7
  import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {DIAGRAMS, FLOWS, NARROW} from '../site/diagrams.mjs';
10
+ import {loadEvents} from '../packages/core/ingest.mjs';
11
+ import {analyzeIncident, toHTML} from '../packages/core/analyze.mjs';
12
+ import {SECRET_CORPUS, KNOWN_REDACTION_GAPS} from '../packages/core/audit.mjs';
13
+ import {svgTimeline} from '../packages/reporter/index.mjs';
5
14
 
6
15
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
- const dir = path.join(root, 'documents/IncidentSutra-AI');
16
+ const DIR = path.join(root, 'documents/IncidentSutra-AI');
8
17
  const check = process.argv.includes('--check');
9
- const esc = s => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
10
- const safeHref = h => (/^(https?:|mailto:|#|[\w./-]+\.(md|html|json)(#[\w-]*)?$)/i.test(h) ? h.replace(/\.md(#|$)/, '.html$1') : '#');
11
- const inline = s => esc(s)
12
- .replace(/`([^`]+)`/g, '<code>$1</code>')
13
- .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
14
- .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, h) => `<a href="${esc(safeHref(h.replace(/&amp;/g, '&')))}">${t}</a>`);
15
- const slug = s => s.toLowerCase().replace(/<[^>]+>/g, '').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '');
18
+ const GH = 'https://github.com/shahvatsalofficial/IncidentSutra-AI';
19
+ const SITE = 'https://shahvatsalofficial.github.io/IncidentSutra-AI';
20
+ const NPM = 'https://www.npmjs.com/package/incidentsutra';
21
+ const read = f => fs.readFileSync(path.join(root, f), 'utf8').replace(/\r\n/g, '\n');
22
+ const json = f => JSON.parse(read(f));
23
+ const V = json('package.json').version;
24
+ const tests = json('documents/IncidentSutra-AI/evidence/test-results.json');
25
+ const audit = json('documents/IncidentSutra-AI/evidence/audit/audit-report.json');
26
+ const bench = json('documents/IncidentSutra-AI/evidence/benchmark.json');
27
+ const skills = json('agents/manifest.json').agents.length;
28
+ const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
29
+ const headingId = t => t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
16
30
 
17
- export function mdToHtml(md) {
18
- const out = [], toc = [];
19
- const lines = md.replace(/\r\n/g, '\n').split('\n');
20
- let i = 0;
31
+ const GROUPS = [
32
+ ['Start here', ['01-executive-summary', '11-visual-guide', '05-user-guide', '10-real-world-scenarios']],
33
+ ['Reference', ['02-functional-spec', '03-technical-spec', '08-agent-catalog', '12-glossary']],
34
+ ['Design and trust', ['04-architecture', '06-security-privacy-legal', '07-independent-audit', 'test-results']],
35
+ ['Help', ['09-faq', 'README']]
36
+ ];
37
+ const ORDER = GROUPS.flatMap(g => g[1]);
38
+ const SCENARIOS = [
39
+ ['deploy-blamed', '"It was the deploy!"', 'The errors started before the release did.', 'k-bad'],
40
+ ['timezone-mixup', 'The time zone trap', 'Two clocks make a cause look like an effect.', 'k-warn'],
41
+ ['payment-provider', 'Provider slow, search shipped', 'The innocent release is about to be rolled back.', 'k-info'],
42
+ ['database-pool', 'The connection pool', 'A metric moves from 40 to 200 connections.', 'k-info'],
43
+ ['night-alert-storm', '3 a.m. alert storm', 'One storm, one first signal, secrets masked.', 'k-bad'],
44
+ ['thin-evidence', 'Almost no evidence', 'The tool refuses to guess and says what is missing.', 'k-warn']
45
+ ];
46
+
47
+ const ICONS = {
48
+ search: '<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>',
49
+ sun: '<circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M1 12h2M21 12h2M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4"/>',
50
+ moon: '<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>',
51
+ menu: '<path d="M3 6h18M3 12h18M3 18h18"/>',
52
+ copy: '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>',
53
+ arrow: '<path d="M5 12h14M12 5l7 7-7 7"/>',
54
+ code: '<path d="M16 18l6-6-6-6M8 6l-6 6 6 6"/>',
55
+ shield: '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>',
56
+ lock: '<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',
57
+ file: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/>',
58
+ eye: '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>',
59
+ layers: '<path d="M12 2l10 5-10 5L2 7z"/><path d="M2 17l10 5 10-5M2 12l10 5 10-5"/>',
60
+ clock: '<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>',
61
+ check: '<path d="M20 6L9 17l-5-5"/>'
62
+ };
63
+ const sprite = `<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>${Object.entries(ICONS).map(([k, v]) => `<symbol id="i-${k}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${v}</symbol>`).join('')}</defs></svg>`;
64
+ const ic = (n, s = 20) => `<svg class="ic" width="${s}" height="${s}" aria-hidden="true"><use href="#i-${n}"/></svg>`;
65
+
66
+ // ---------- Markdown ----------
67
+ const href = u => {
68
+ if (/^(https?:|mailto:|#)/i.test(u)) return u;
69
+ if (!/^[\w./-]+(#[\w-]*)?$/.test(u) || u.startsWith('/')) return '#';
70
+ if (u.startsWith('../')) return `${GH}/blob/main/${u.replace(/^(\.\.\/)+/, '')}`;
71
+ return u.replace(/^([\w-]+)\.md(#|$)/, '$1.html$2');
72
+ };
73
+ function inline(s) {
74
+ const codes = [];
75
+ s = s.replace(/`([^`]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
76
+ s = esc(s)
77
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, u) => { const h = href(u.replace(/&amp;/g, '&')); return `<a href="${esc(h)}"${/^https?:/.test(h) ? ' rel="noopener"' : ''}>${t}</a>`; })
78
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/(^|[\s(])_([^_]+)_(?=[\s.,;:)]|$)/g, '$1<em>$2</em>');
79
+ return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${esc(codes[i])}</code>`);
80
+ }
81
+ function mdToHtml(md, directive) {
82
+ const lines = md.split('\n'), out = [], toc = [], para = [];
83
+ let i = 0, firstQuote = true;
84
+ const flush = () => { if (para.length) { out.push(`<p>${inline(para.join(' '))}</p>`); para.length = 0; } };
21
85
  while (i < lines.length) {
22
86
  const l = lines[i];
23
- if (/^```/.test(l)) {
24
- const buf = []; i++;
25
- while (i < lines.length && !/^```/.test(lines[i])) buf.push(lines[i++]);
26
- i++; out.push(`<pre><code>${esc(buf.join('\n'))}</code></pre>`); continue;
27
- }
87
+ if (/^\s*$/.test(l)) { flush(); i++; continue; }
88
+ const fence = l.match(/^```(\w*)/);
89
+ if (fence) { flush(); const buf = []; i++; while (i < lines.length && !/^```/.test(lines[i])) buf.push(lines[i++]); i++; out.push(`<pre class="code" data-lang="${esc(fence[1])}"><code>${esc(buf.join('\n'))}</code><button class="copy" type="button">Copy</button></pre>`); continue; }
90
+ const dir = l.match(/^<!--\s*(svg|flow|chart|scenario):([\w-]+)\s*-->$/);
91
+ if (dir) { flush(); out.push(directive(dir[1], dir[2])); i++; continue; }
28
92
  const h = l.match(/^(#{1,4})\s+(.*)$/);
29
- if (h) { const n = h[1].length, id = slug(h[2]); if (n >= 2 && n <= 3) toc.push([n, id, h[2].replace(/`/g, '')]); out.push(`<h${n} id="${id}">${inline(h[2])}</h${n}>`); i++; continue; }
93
+ if (h) {
94
+ flush(); const id = headingId(h[2]), n = h[1].length;
95
+ if (n === 2 || n === 3) toc.push({level: n, text: h[2].replace(/`/g, ''), id});
96
+ out.push(n === 1 ? `<h1>${inline(h[2])}</h1>` : `<h${n} id="${id}">${inline(h[2])}<a class="anchor" href="#${id}" aria-label="Link to this section">#</a></h${n}>`); i++; continue;
97
+ }
98
+ if (/^---+\s*$/.test(l)) { flush(); out.push('<hr>'); i++; continue; }
99
+ if (/^>\s?/.test(l)) {
100
+ flush(); const buf = []; while (i < lines.length && /^>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^>\s?/, ''));
101
+ out.push(`<blockquote class="${firstQuote ? 'lead-q' : 'callout-note'}">${inline(buf.join(' '))}</blockquote>`); firstQuote = false; continue;
102
+ }
30
103
  if (/^\|.*\|\s*$/.test(l) && /^\|[\s:|-]+\|\s*$/.test(lines[i + 1] ?? '')) {
31
- const cells = r => r.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
104
+ flush(); const cells = r => r.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'));
32
105
  const head = cells(l); i += 2; const rows = [];
33
106
  while (i < lines.length && /^\|.*\|\s*$/.test(lines[i])) rows.push(cells(lines[i++]));
34
- out.push(`<div class="tw"><table><thead><tr>${head.map(c => `<th>${inline(c)}</th>`).join('')}</tr></thead><tbody>${rows.map(r => `<tr>${r.map(c => `<td>${inline(c)}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`); continue;
107
+ out.push(`<div class="table-wrap"><table><thead><tr>${head.map(c => `<th scope="col">${inline(c)}</th>`).join('')}</tr></thead><tbody>${rows.map(r => `<tr>${r.map(c => `<td>${inline(c)}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`); continue;
35
108
  }
36
- if (/^\s*[-*]\s+/.test(l) || /^\s*\d+\.\s+/.test(l)) {
37
- const ord = /^\s*\d+\./.test(l), items = [];
38
- while (i < lines.length && (/^\s*[-*]\s+/.test(lines[i]) || /^\s*\d+\.\s+/.test(lines[i]))) items.push(lines[i++].replace(/^\s*(?:[-*]|\d+\.)\s+/, ''));
39
- out.push(`<${ord ? 'ol' : 'ul'}>${items.map(x => `<li>${inline(x)}</li>`).join('')}</${ord ? 'ol' : 'ul'}>`); continue;
109
+ const li = l.match(/^(\s*)([-*]|\d+\.)\s+(.*)$/);
110
+ if (li) {
111
+ flush(); const tag = /\d/.test(li[2]) ? 'ol' : 'ul', items = [];
112
+ while (i < lines.length) { const m = lines[i].match(/^(\s*)([-*]|\d+\.)\s+(.*)$/); if (m) { items.push(m[3]); i++; } else if (/^\s{2,}\S/.test(lines[i]) && items.length) { items[items.length - 1] += ' ' + lines[i].trim(); i++; } else break; }
113
+ out.push(`<${tag}>${items.map(x => `<li>${inline(x)}</li>`).join('')}</${tag}>`); continue;
40
114
  }
41
- if (/^>\s?/.test(l)) { const buf = []; while (i < lines.length && /^>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^>\s?/, '')); out.push(`<blockquote>${inline(buf.join(' '))}</blockquote>`); continue; }
42
- if (/^---+\s*$/.test(l)) { out.push('<hr>'); i++; continue; }
43
- if (!l.trim()) { i++; continue; }
44
- const buf = [];
45
- while (i < lines.length && lines[i].trim() && !/^(#{1,4}\s|```|\||\s*[-*]\s|\s*\d+\.\s|>|---+\s*$)/.test(lines[i])) buf.push(lines[i++]);
46
- out.push(`<p>${inline(buf.join(' '))}</p>`);
115
+ para.push(l.trim()); i++;
47
116
  }
48
- return { html: out.join('\n'), toc };
117
+ flush();
118
+ return {html: out.join('\n'), toc};
49
119
  }
50
120
 
51
- const CSS = `:root{--bg:#f6f8fb;--fg:#0f172a;--mut:#475569;--card:#fff;--bd:#d9e1ec;--ac:#3538cd;--code:#eef2f7}@media(prefers-color-scheme:dark){:root{--bg:#0b1220;--fg:#e6edf7;--mut:#9fb0c7;--card:#121b2e;--bd:#25324a;--ac:#a4bcfd;--code:#1a2540}}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.7 system-ui,-apple-system,Segoe UI,sans-serif}a{color:var(--ac)}.layout{display:grid;grid-template-columns:260px minmax(0,1fr);max-width:1240px;margin:0 auto}nav{position:sticky;top:0;align-self:start;height:100vh;overflow:auto;padding:24px 16px;border-right:1px solid var(--bd)}nav b{display:block;margin-bottom:8px}nav a{display:block;padding:4px 8px;border-radius:6px;text-decoration:none;color:var(--mut);font-size:.92rem}nav a[aria-current]{background:var(--card);color:var(--fg);font-weight:600}nav .sub a{padding-left:20px;font-size:.84rem}main{padding:32px 28px 80px;min-width:0}h1{font-size:2rem;line-height:1.2}h2{margin-top:2.2em;border-bottom:1px solid var(--bd);padding-bottom:.25em}h3{margin-top:1.6em}code{background:var(--code);padding:.1em .35em;border-radius:5px;font:.88em ui-monospace,Consolas,monospace}pre{background:var(--code);padding:14px;border-radius:10px;overflow:auto}pre code{background:none;padding:0}.tw{overflow-x:auto}table{border-collapse:collapse;width:100%;background:var(--card);font-size:.92rem}th,td{border:1px solid var(--bd);padding:8px 10px;text-align:left;vertical-align:top}th{background:var(--code)}blockquote{margin:1em 0;padding:8px 16px;border-left:4px solid var(--ac);background:var(--card);border-radius:0 8px 8px 0}footer{color:var(--mut);font-size:.85rem;margin-top:48px}:focus-visible{outline:3px solid var(--ac);outline-offset:2px}.skip{position:absolute;left:-999px}.skip:focus{left:8px;top:8px;background:var(--card);padding:6px}@media(max-width:820px){.layout{display:block}nav{position:static;height:auto;border-right:0;border-bottom:1px solid var(--bd)}main{padding:20px 16px 60px}}@media print{nav{display:none}.layout{display:block}}`;
121
+ // ---------- charts and scenarios ----------
122
+ const bars = rows => { const max = Math.max(1, ...rows.map(r => r[1])); return `<div class="bars">${rows.map(([l, v, c = '', label]) => `<div class="bar"><span class="lab">${esc(l)}</span><div class="trk"><div class="fill ${c}" style="width:${v ? Math.max(3, Math.round(100 * v / max)) : 0}%"></div></div><span class="val">${esc(label ?? v)}</span></div>`).join('')}</div>`; };
123
+ const chart = (title, body, note = '') => `<figure class="chart"><h4>${esc(title)}</h4>${body}${note ? `<p class="note">${esc(note)}</p>` : ''}</figure>`;
124
+ const stack = (parts, label) => `<div class="stack" role="img" aria-label="${esc(label)}">${parts.map(([v, c]) => `<i style="width:${v}%;background:var(${c})"></i>`).join('')}</div>`;
125
+ const legend = items => `<p class="legend">${items.map(([c, t]) => `<span><b style="background:var(${c})"></b>${esc(t)}</span>`).join('')}</p>`;
126
+ const CHARTS = {
127
+ tests: () => chart(`Automated tests: ${tests.pass} of ${tests.total} pass`, stack([[100 * tests.pass / tests.total, '--ok'], [100 * tests.skipped / tests.total, '--warn'], [100 * tests.fail / tests.total, '--bad']], `${tests.pass} passed, ${tests.skipped} skipped, ${tests.fail} failed`) + legend([['--ok', `${tests.pass} passed`], ['--warn', `${tests.skipped} skipped`], ['--bad', `${tests.fail} failed`]]), `Recorded with Node ${tests.environment.node} on ${tests.environment.platform}. ${tests.skippedReason}`),
128
+ audit: () => { const areas = {}; for (const c of audit.checks) { areas[c.area] ??= [0, 0]; areas[c.area][1]++; if (c.status === 'pass') areas[c.area][0]++; } return chart(`Self-audit: ${audit.counts.pass} of ${audit.counts.total} checks pass, ${audit.counts.skipped} skipped, ${audit.counts.fail} failed`, bars(Object.entries(areas).map(([a, [p, t]]) => [a, t, p === t ? 'ok' : 'warn', `${p}/${t}`])), `${audit.nature}. Verdict ${audit.verdict}. Bar length is the number of checks in the area.`); },
129
+ redaction: () => chart(`Masking corpus: ${SECRET_CORPUS.length} synthetic secret classes`, `<div class="chips">${SECRET_CORPUS.map(([n]) => `<span>${esc(n)}</span>`).join('')}</div><h4 style="margin-top:1rem">Not covered</h4><div class="chips">${KNOWN_REDACTION_GAPS.map(n => `<span>${esc(n)}</span>`).join('')}</div>`, 'Best effort only. This is not data-loss prevention. Sanitize exports before analysis.'),
130
+ benchmark: () => chart(`Synthetic benchmark: ${bench.casesPassed} of ${bench.cases} cases, ${bench.expectationsPassed} of ${bench.expectations} expectations`, `<div class="chips">${bench.results.map(r => `<span title="${esc(r.title)}">${r.pass ? '✓' : '✗'} ${esc(r.family)}</span>`).join('')}</div>`, bench.labelProvenance)
131
+ };
52
132
 
53
- export function build() {
54
- const mds = fs.readdirSync(dir).filter(f => f.endsWith('.md')).sort((a, b) => (a === 'README.md' ? -1 : b === 'README.md' ? 1 : a.localeCompare(b)));
55
- const titles = Object.fromEntries(mds.map(f => [f, (fs.readFileSync(path.join(dir, f), 'utf8').match(/^#\s+(.*)$/m) ?? [, f])[1].replace(/`/g, '')]));
56
- const stale = [];
57
- for (const f of mds) {
58
- const { html, toc } = mdToHtml(fs.readFileSync(path.join(dir, f), 'utf8'));
59
- const nav = mds.map(m => `<a href="${m.replace(/\.md$/, '.html')}"${m === f ? ' aria-current="page"' : ''}>${esc(titles[m])}</a>` + (m === f ? `<div class="sub">${toc.filter(t => t[0] === 2).map(t => `<a href="#${t[1]}">${esc(t[2])}</a>`).join('')}</div>` : '')).join('');
60
- const page = `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>${esc(titles[f])} · IncidentSutra AI</title><meta name="description" content="IncidentSutra AI documentation: evidence-first, offline, read-only incident investigation."><style>${CSS}</style></head><body><a class="skip" href="#content">Skip to content</a><div class="layout"><nav aria-label="Documentation"><b>IncidentSutra AI</b>${nav}<p><a href="https://github.com/shahvatsalofficial/IncidentSutra-AI">GitHub</a> · <a href="https://www.npmjs.com/package/incidentsutra">npm</a></p></nav><main id="content">${html}<footer>Apache-2.0 · Created by Vatsal Shah · Generated from <code>${esc(f)}</code>. Advisory only; this documentation makes no root-cause or production-safety claim.</footer></main></div></body></html>\n`;
61
- const target = path.join(dir, f.replace(/\.md$/, '.html'));
62
- if (check) { if (!fs.existsSync(target) || fs.readFileSync(target, 'utf8') !== page) stale.push(path.basename(target)); }
63
- else fs.writeFileSync(target, page);
64
- }
65
- return { count: mds.length, stale };
133
+ const outputs = new Map();
134
+ const scn = {};
135
+ for (const [name] of SCENARIOS) {
136
+ const data = await loadEvents(path.join(root, 'fixtures/scenarios', name));
137
+ scn[name] = analyzeIncident(data, {synthetic: true});
138
+ outputs.set(`evidence/scenarios/${name}.html`, toHTML(scn[name]));
66
139
  }
140
+ function scenario(name) {
141
+ const r = scn[name]; if (!r) throw new Error('Unknown scenario ' + name);
142
+ const hyps = r.hypotheses.map(x => `<div class="hcard"><b>${esc(x.title)}</b><p class="chips"><span>${esc(x.family)}</span><span>supports ${x.supportingEventIds.length}</span><span class="${x.contradictingEventIds.length ? 'against' : ''}">against ${x.contradictingEventIds.length}</span><span>unconfirmed</span></p>${x.contradictions.map(c => `<p class="why">${esc(c.note)}</p>`).join('')}</div>`).join('');
143
+ const extra = [r.alertStorms.map(a => `Alert storm: ${a.count} signals`).join(', '), r.privacy.redactions ? `${r.privacy.redactions} values masked` : '', r.ingestionErrors.length ? `${r.ingestionErrors.length} record rejected: ${r.ingestionErrors[0].error}` : '', ...r.metricSeries.map(m => `${m.name}: ${m.first.value} to ${m.last.value}`)].filter(Boolean);
144
+ return `<div class="scnbox"><div class="mock-cards four"><div><b>${r.summary.count}</b><span>events</span></div><div><b>${r.hypotheses.length}</b><span>hypotheses</span></div><div><b>${r.contradictions.length}</b><span>contradictions</span></div><div><b>${r.gaps.length}</b><span>gaps</span></div></div><ol class="vtl">${r.timeline.map(t => `<li class="${/deploy|release|rollout|rollback/.test(t.type) ? 'change' : /error|alert|critical|incident/.test(t.type + ' ' + t.severity) ? 'issue' : ''}"><time datetime="${t.timestamp}">${t.timestamp.slice(11, 19)} UTC</time><em>${esc(t.service)} ${esc(t.type)}</em>${esc(t.description)}</li>`).join('')}</ol><div class="dia-scroll tl">${svgTimeline(r)}</div><p class="legend"><span>◆ change</span><span>● error or alert</span><span>■ other</span></p>${extra.length ? `<div class="chips">${extra.map(x => `<span>${esc(x)}</span>`).join('')}</div>` : ''}<h4>What the report offers</h4><div class="hgrid">${hyps}</div>${r.gaps.length ? `<h4>Still unknown</h4><ul>${r.gaps.map(g => `<li>${esc(g.message)}</li>`).join('')}</ul>` : ''}<p><a class="btn" href="evidence/scenarios/${name}.html">Open the full report ${ic('arrow', 18)}</a></p></div>`;
145
+ }
146
+ const steps = (list, cls) => `<ol class="flow ${cls}">${list.map(([t, d, c]) => `<li class="${c || ''}"><b>${inline(t)}</b><span>${inline(d)}</span></li>`).join('')}</ol>`;
147
+ const diagram = name => `<figure class="dia"><div class="dia-wide">${DIAGRAMS[name]()}</div>${steps(NARROW[name], 'dia-narrow')}</figure>`;
148
+ const directive = (kind, name) => {
149
+ if (kind === 'scenario') return scenario(name);
150
+ if (kind === 'svg') { if (!DIAGRAMS[name]) throw new Error('Unknown diagram ' + name); return diagram(name); }
151
+ if (kind === 'chart') { if (!CHARTS[name]) throw new Error('Unknown chart ' + name); return CHARTS[name](); }
152
+ const f = FLOWS[name]; if (!f) throw new Error('Unknown flow ' + name);
153
+ return `<ol class="flow${f.row ? ' row' : ''}" style="--n:${f.steps.length > 5 ? 3 : f.steps.length}">${f.steps.map(([t, d, c]) => `<li class="${c || ''}"><b>${inline(t)}</b><span>${inline(d)}</span></li>`).join('')}</ol>`;
154
+ };
155
+
156
+ // ---------- shell ----------
157
+ const favicon = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%234338ca'/%3E%3Cpath d='M5 17h5l3-8 5 15 3-7h6' fill='none' stroke='white' stroke-width='2.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E";
158
+ const logo = '<span class="logo" aria-hidden="true"><svg width="22" height="22" viewBox="0 0 32 32"><path d="M4 17h6l3-9 6 16 3-7h6" fill="none" stroke="#fff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg></span><span class="brand-name">Incident<b>Sutra</b> AI</span>';
159
+ const themeInit = "try{var t=localStorage.getItem('incidentsutra-theme');document.documentElement.setAttribute('data-theme',t==='dark'?'dark':'light')}catch(e){document.documentElement.setAttribute('data-theme','light')}";
160
+ const head = ({title, desc, canon, extra = ''}) => `<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title><meta name="description" content="${esc(desc)}"><meta name="keywords" content="incident response, SRE, on-call, postmortem, root cause analysis, incident timeline, OpenTelemetry, agent skills, Claude Code, Cursor, Codex, Gemini CLI, Copilot"><meta name="color-scheme" content="light dark"><meta name="theme-color" content="#4338ca"><meta name="author" content="Vatsal Shah"><link rel="canonical" href="${canon}"><meta property="og:title" content="${esc(title)}"><meta property="og:description" content="${esc(desc)}"><meta property="og:type" content="website"><meta property="og:site_name" content="IncidentSutra AI"><meta property="og:url" content="${canon}"><meta name="twitter:card" content="summary"><link rel="icon" href="${favicon}"><script>${themeInit}</script><link rel="stylesheet" href="assets/site.css">${extra}</head>`;
161
+ const NAV = [['05-user-guide', 'Guide'], ['10-real-world-scenarios', 'Scenarios'], ['11-visual-guide', 'Visuals'], ['04-architecture', 'Architecture'], ['07-independent-audit', 'Proof']];
162
+ const topbar = (home, cur) => `<header class="topbar"><div class="topbar-in"><button class="icon-btn menu-btn" type="button" aria-label="Open navigation menu" aria-expanded="false" aria-controls="sidebar">${ic('menu')}</button><a class="brand" href="${home ? '#top' : 'index.html'}">${logo}<span class="ver">v${V}</span></a><nav class="topnav" aria-label="Primary">${NAV.map(([s, t]) => `<a href="${s}.html"${cur === s ? ' aria-current="page"' : ''}>${t}</a>`).join('')}</nav><div class="search" role="search">${ic('search', 18)}<label class="sr" for="q">Search the documentation</label><input id="q" type="search" placeholder="Search docs" autocomplete="off" role="combobox" aria-expanded="false" aria-controls="results"><kbd aria-hidden="true">/</kbd><ul id="results" role="listbox" hidden></ul></div><a class="icon-btn gh" href="${GH}" rel="noopener" aria-label="IncidentSutra AI on GitHub">${ic('code')}</a><button class="icon-btn theme-btn" type="button" aria-pressed="false" aria-label="Switch to dark theme"><svg class="ic i-sun" width="20" height="20" aria-hidden="true"><use href="#i-sun"/></svg><svg class="ic i-moon" width="20" height="20" aria-hidden="true"><use href="#i-moon"/></svg></button></div></header>`;
163
+ const col = (title, links) => `<div><p class="foot-title">${title}</p><ul>${links.map(([u, t]) => `<li><a href="${u}"${/^http/.test(u) ? ' rel="noopener"' : ''}>${t}</a></li>`).join('')}</ul></div>`;
164
+ const footer = () => `<footer class="site-foot"><div class="foot-in"><div class="foot-brand"><a class="brand" href="index.html">${logo}</a><p>Observe precisely. Reason cautiously. Recover responsibly.</p><p class="fine">Created by Vatsal Shah. Apache-2.0.</p></div>${col('Start', [['01-executive-summary.html', 'Overview'], ['05-user-guide.html', 'User guide'], ['10-real-world-scenarios.html', 'Scenarios']])}${col('Reference', [['02-functional-spec.html', 'Functional spec'], ['03-technical-spec.html', 'Technical spec'], ['12-glossary.html', 'Glossary']])}${col('Trust', [['06-security-privacy-legal.html', 'Security and legal'], ['07-independent-audit.html', 'Audit'], ['test-results.html', 'Test results']])}${col('Project', [[GH, 'GitHub'], [NPM, 'npm'], [`${GH}/blob/main/CHANGELOG.md`, 'Changelog']])}</div><p class="legal">IncidentSutra AI ${V}. Advisory output for people: it does not determine root cause and is not legal, compliance or security certification. The audit is a self-audit. Product names belong to their owners; no endorsement is implied.</p></footer>`;
165
+
166
+ const pages = ORDER.map(slug => {
167
+ const raw = read(`documents/IncidentSutra-AI/${slug}.md`);
168
+ return {slug, raw, title: (raw.match(/^#\s+(.+)$/m) || [, slug])[1].replace(/`/g, ''), summary: (raw.match(/^>\s+(.+)$/m) || [, ''])[1].replace(/[*`]/g, '')};
169
+ });
170
+ const unknown = fs.readdirSync(DIR).filter(f => f.endsWith('.md') && !ORDER.includes(f.slice(0, -3)));
171
+ if (unknown.length) throw new Error(`Markdown files missing from GROUPS: ${unknown.join(', ')}`);
172
+ const plain = md => md.replace(/```[\s\S]*?```/g, ' ').replace(/<!--[\s\S]*?-->/g, ' ').replace(/[`*#>|_\[\]()]/g, ' ').replace(/\s+/g, ' ').trim();
173
+ const index = pages.map(p => ({t: p.title, u: `${p.slug}.html`, x: plain(p.raw).slice(0, 2500)}));
174
+ const tail = () => `<script>window.__DOCS_INDEX__=${JSON.stringify(index).replace(/</g, '\\u003c')}</script><script src="assets/site.js" defer></script></body></html>\n`;
175
+ const side = cur => `<aside class="sidebar" id="sidebar" aria-label="Documentation"><a class="nav-home" href="index.html">Home</a>${GROUPS.map(([g, slugs]) => `<div class="nav-group"><p class="nav-title">${g}</p><ol>${slugs.map(s => `<li><a href="${s}.html"${s === cur ? ' aria-current="page"' : ''}>${esc(s === 'README' ? 'Documentation map' : pages.find(x => x.slug === s).title)}</a></li>`).join('')}</ol></div>`).join('')}</aside><div class="scrim" hidden></div>`;
176
+
177
+ pages.forEach((p, n) => {
178
+ const {html, toc} = mdToHtml(p.raw, directive);
179
+ const prev = pages[n - 1], next = pages[n + 1];
180
+ const tocUl = `<ul>${toc.map(t => `<li class="l${t.level}"><a href="#${t.id}">${esc(t.text)}</a></li>`).join('')}</ul>`;
181
+ const tocM = `<details class="toc-m"><summary>On this page</summary>${tocUl}</details>`;
182
+ const body = html.replace('</blockquote>', () => '</blockquote>' + tocM).replace(/^<h1>/, `<p class="eyebrow">${esc(GROUPS.find(g => g[1].includes(p.slug))[0])}</p><h1>`);
183
+ outputs.set(`${p.slug}.html`, `${head({title: `${p.title} · IncidentSutra AI`, desc: p.summary || `${p.title} for IncidentSutra AI, the offline incident evidence CLI.`, canon: `${SITE}/${p.slug}.html`})}<body><a class="skip" href="#content">Skip to content</a>${sprite}${topbar(false, p.slug)}<div class="layout">${side(p.slug)}<main class="content" id="content" tabindex="-1"><article class="prose">${body}<p class="edit"><a href="${GH}/blob/main/documents/IncidentSutra-AI/${p.slug}.md" rel="noopener">View this page source on GitHub</a></p><nav class="pager" aria-label="Pagination">${prev ? `<a class="prev" href="${prev.slug}.html"><span>Previous</span><b>${esc(prev.title)}</b></a>` : '<span></span>'}${next ? `<a class="next" href="${next.slug}.html"><span>Next</span><b>${esc(next.title)}</b></a>` : '<span></span>'}</nav></article></main><nav class="toc" aria-label="On this page"><h2>On this page</h2>${tocUl}</nav></div>${footer()}${tail()}`);
184
+ });
185
+
186
+ // ---------- home ----------
187
+ const demo = scn['deploy-blamed'];
188
+ const mock = `<div class="mock" role="img" aria-label="Sample report: errors began before the release, so the report lists counter-evidence"><div class="mock-bar"><i></i><i></i><i></i><span>incident-report.html</span></div><div class="mock-in"><div class="mock-head"><b>orders: errors rising</b><span class="pill warn">HUMAN REVIEW</span></div><div class="mock-cards"><div><b>${demo.summary.count}</b><span>observed</span></div><div><b>${demo.hypotheses.length}</b><span>hypotheses</span></div><div><b>${demo.contradictions.length}</b><span>against</span></div></div><ul class="mock-list"><li><span class="pill bad">10:02</span> first error: before the release</li><li><span class="pill ok">10:06</span> release 4.2.0 rolled out</li><li><span class="pill warn">verdict</span> cause unconfirmed; pre-existing defect also possible</li></ul></div></div>`;
189
+ const feats = [['clock', 'An auditable timeline', 'Strict time zones, nanoseconds kept, every line traced to a file, record and SHA-256.'], ['layers', 'Competing explanations', 'Change, dependency, saturation, datastore, latent defect and unknown, side by side.'], ['eye', 'Counter-evidence first', 'Errors that started before a release are shown against it, not hidden.'], ['file', 'Reports people can read', 'Single-file HTML, Markdown, JSON and a blameless postmortem draft.'], ['lock', 'Stays on your machine', 'No network, no API key, no telemetry, no dependencies, nothing executed.'], ['shield', 'Checks itself', `${audit.counts.total} automated checks, written as HTML, Markdown and JSON.`]];
190
+ const faqs = [['Does it find the root cause?', 'No. It lists explanations you can disprove, with evidence for and against. Every one stays unconfirmed.'], ['Does it need an API key or internet?', 'No. It uses only Node.js built-ins.'], ['Can it change production?', 'There is no code path for it: no network client and no process execution in product code.'], ['Is my data safe?', 'It never leaves your machine unless you share it. Masking is best effort, so sanitize exports first.'], ['Is the audit a certification?', 'No. It is a self-audit that anyone can rerun.'], ['Can I use it commercially?', 'Yes, under Apache-2.0, provided as is.']];
191
+ const INSTALL = 'npx incidentsutra doctor';
192
+ const install = (cls = '') => `<div class="install ${cls}"><span class="prompt" aria-hidden="true">$</span><code>${INSTALL}</code><button class="copy-inline" type="button" aria-label="Copy command">${ic('copy', 16)}<span>Copy</span></button></div>`;
193
+ const sec = (alt, kicker, title, sub, body) => `<section class="sec${alt ? ' alt' : ''}"><div class="wrap"><p class="kicker">${kicker}</p><h2>${title}</h2>${sub ? `<p class="sub">${sub}</p>` : ''}${body}</div></section>`;
194
+ const homeDesc = 'Offline, read-only incident investigation CLI: auditable UTC timelines, competing root-cause hypotheses with counter-evidence, blameless postmortems, HTML, Markdown and JSON reports, and 20 agent skills.';
195
+ const LD = JSON.stringify({'@context': 'https://schema.org', '@type': 'SoftwareApplication', name: 'IncidentSutra AI', applicationCategory: 'DeveloperApplication', operatingSystem: 'Windows, macOS, Linux (Node.js 20+)', softwareVersion: V, license: 'https://www.apache.org/licenses/LICENSE-2.0', author: {'@type': 'Person', name: 'Vatsal Shah', url: 'https://github.com/shahvatsalofficial'}, url: SITE + '/', codeRepository: GH, description: homeDesc, offers: {'@type': 'Offer', price: '0', priceCurrency: 'USD'}});
196
+ outputs.set('index.html', `${head({title: 'IncidentSutra AI · Offline incident evidence and root-cause reasoning CLI', desc: homeDesc, canon: `${SITE}/`, extra: `<script type="application/ld+json">${LD}</script>`})}<body class="home-page" id="top"><a class="skip" href="#main">Skip to content</a>${sprite}${topbar(true, '')}<main id="main">
197
+ <section class="hero"><div class="wrap hero-grid"><div><p class="badge"><span class="dot"></span>v${V} · Apache-2.0 · zero dependencies</p><h1>Find what <span class="grad">really happened</span>, not the first guess.</h1><p class="lead">IncidentSutra AI turns exported logs, alerts, metrics and deployments into an auditable timeline, several competing explanations with the evidence against each, and a blameless postmortem draft. Offline. Read-only. Honest about what it does not know.</p><div class="cta"><a class="btn primary" href="05-user-guide.html">Get started ${ic('arrow', 18)}</a><a class="btn" href="10-real-world-scenarios.html">See real scenarios</a></div>${install()}<ul class="facts"><li>Node 20+</li><li>No API key</li><li>No network</li><li>HTML · MD · JSON</li></ul></div><div class="hero-art">${mock}</div></div></section>
198
+ <section class="statband" aria-label="Key facts"><div class="wrap"><ul><li><b>${tests.pass}</b><span>tests passing</span></li><li><b>${audit.counts.pass}/${audit.counts.total}</b><span>audit checks pass</span></li><li><b>${bench.casesPassed}</b><span>synthetic cases</span></li><li><b>${skills}</b><span>agent skills</span></li><li><b>0</b><span>dependencies</span></li></ul></div></section>
199
+ ${sec(false, 'The problem', 'The first story of an outage is easy to believe', 'A recent deploy, mixed time zones and missing data all push a team toward one explanation. IncidentSutra keeps the alternatives and the gaps visible.', `<div class="feat-grid">${feats.map(([i, t, d]) => `<div class="feat"><div class="feat-ic">${ic(i, 22)}</div><h3>${t}</h3><p>${d}</p></div>`).join('')}</div>`)}
200
+ ${sec(true, 'How it works', 'From exported files to a human decision', 'Six steps. Only the last one decides anything, and it is yours.', `${diagram('pipeline')}${directive('flow', 'oncall')}`)}
201
+ ${sec(false, 'Honest by design', 'Four kinds of statement, never blurred', 'Observed facts, inferred hypotheses, unknown data and checks that were not run are different things in the report.', `${diagram('evidence')}`)}
202
+ ${sec(true, 'Real-world scenarios', 'Six situations you will recognise', 'Each runs on a committed sample file, so the timeline and hypotheses you see are real tool output.', `<div class="scn-grid">${SCENARIOS.map(([n, t, d, k], i) => `<a class="scard ${k}" href="10-real-world-scenarios.html#${headingId(`Scenario ${i + 1}: ` + [...read('documents/IncidentSutra-AI/10-real-world-scenarios.md').matchAll(/^## Scenario \d+: (.+)$/gm)][i][1])}"><span class="snum">${i + 1}</span><h3>${esc(t)}</h3><p>${esc(d)}</p><span class="more">Read the scenario ${ic('arrow', 16)}</span></a>`).join('')}</div>`)}
203
+ ${sec(false, 'The classic trap', 'Why time zones change the story', 'One offset decides which event came first.', `${diagram('timezone')}`)}
204
+ ${sec(true, 'Proof, with limits', 'Measured, then shown', 'Numbers below are read from committed evidence files that anyone can regenerate.', `${CHARTS.tests()}${CHARTS.audit()}<div class="cta"><a class="btn" href="07-independent-audit.html">Read the audit ${ic('arrow', 18)}</a><a class="btn ghost" href="evidence/samples/incident-report.html">Open a sample report</a></div>`)}
205
+ ${sec(false, 'Compare', 'What it is, and is not', '', `<div class="table-wrap"><table><thead><tr><th scope="col">Question</th><th scope="col">IncidentSutra AI</th><th scope="col">Not this</th></tr></thead><tbody><tr><td>Root cause</td><td>Several unconfirmed hypotheses</td><td>An automatic verdict</td></tr><tr><td>Data</td><td>Files you export and sanitize</td><td>A telemetry platform or live connector</td></tr><tr><td>Actions</td><td>Proposes read-only checks</td><td>Restarts, rollbacks or paging</td></tr><tr><td>Privacy</td><td>Local, best-effort masking</td><td>Data-loss prevention</td></tr><tr><td>Assurance</td><td>Reproducible self-audit</td><td>A certification</td></tr></tbody></table></div>`)}
206
+ ${sec(true, 'Agent skills', `${skills} roles for your AI coding tool`, 'Install project-locally for Claude Code, Cursor, Codex, Gemini CLI or Copilot. Copying is tested; native activation per tool is not.', `${diagram('agents')}<pre class="code"><code>npx incidentsutra skills install --host claude --project .</code><button class="copy" type="button">Copy</button></pre>`)}
207
+ ${sec(false, 'Who uses it', 'For the people in the room', '', '<div class="who"><div><b>On-call engineers</b><span>A timeline before the war room argues.</span></div><div><b>Incident commanders</b><span>See what is known, unknown and not run.</span></div><div><b>Support escalation</b><span>Turn reports into evidence with IDs.</span></div><div><b>Postmortem authors</b><span>Start from facts and stay blameless.</span></div></div>')}
208
+ ${sec(true, 'Documentation', 'Everything, in order', '', `<div class="dgrid">${GROUPS.map(([g, slugs]) => `<div class="dgroup"><h3>${g}</h3><p>${slugs.length} pages</p><ul>${slugs.map(s => `<li><a href="${s}.html">${esc(s === 'README' ? 'Documentation map' : pages.find(x => x.slug === s).title)}</a></li>`).join('')}</ul></div>`).join('')}</div>`)}
209
+ <section class="sec"><div class="wrap narrow"><p class="kicker center">FAQ</p><h2 class="center">Quick answers</h2>${faqs.map(([q, a]) => `<details class="qa"><summary>${esc(q)}</summary><p>${esc(a)}</p></details>`).join('')}</div></section>
210
+ <section class="cta-band"><div class="wrap"><h2>Bring evidence to your next incident</h2><p>Free, offline and open source.</p>${install('on-dark')}<div class="cta center"><a class="btn light" href="${GH}" rel="noopener">View on GitHub</a><a class="btn outline" href="05-user-guide.html">Read the guide</a></div></div></section></main>${footer()}${tail()}`);
211
+
212
+ outputs.set('404.html', `${head({title: 'Page not found · IncidentSutra AI', desc: 'Page not found', canon: `${SITE}/404.html`, extra: '<base href="/IncidentSutra-AI/">'})}<body>${sprite}<main class="wrap narrow center" style="padding:5rem 0"><h1>Page not found</h1><p class="lead">This page is unknown. We will not guess where it went.</p><p class="cta center"><a class="btn primary" href="index.html">Back to the home page</a></p></main><script src="assets/site.js" defer></script></body></html>\n`);
213
+ outputs.set('assets/site.css', ['site.css', 'extra.css', 'incident.css'].map(f => read(`site/${f}`)).join('\n'));
214
+ outputs.set('assets/site.js', read('site/site.js'));
215
+ const urls = ['', ...pages.map(p => p.slug + '.html'), ...SCENARIOS.map(([n]) => `evidence/scenarios/${n}.html`), 'evidence/samples/incident-report.html', 'evidence/audit/audit-report.html'];
216
+ outputs.set('sitemap.xml', `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.map(u => ` <url><loc>${SITE}/${u}</loc></url>`).join('\n')}\n</urlset>\n`);
217
+ outputs.set('robots.txt', `User-agent: *\nAllow: /\nSitemap: ${SITE}/sitemap.xml\n`);
67
218
 
68
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
69
- const { count, stale } = build();
70
- if (stale.length) { console.error('Stale docs HTML (run npm run build:docs): ' + stale.join(', ')); process.exit(1); }
71
- console.log(`${check ? 'checked' : 'built'} ${count} documents`);
219
+ const stale = [];
220
+ for (const [rel, content] of outputs) {
221
+ const f = path.join(DIR, rel);
222
+ if (check) { if (!fs.existsSync(f) || fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n') !== content.replace(/\r\n/g, '\n')) stale.push(rel); }
223
+ else { fs.mkdirSync(path.dirname(f), {recursive: true}); fs.writeFileSync(f, content); }
72
224
  }
225
+ if (stale.length) { console.error('Stale site output (run npm run build:docs): ' + stale.join(', ')); process.exit(1); }
226
+ console.log(`${check ? 'checked' : 'built'} ${pages.length} pages, home, ${SCENARIOS.length} scenario reports`);
@@ -0,0 +1,27 @@
1
+ // Copies the built documentation website to _site/ for GitHub Pages, plus redirects for the former /docs/ URLs.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+
6
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
+ const src = path.join(root, 'documents/IncidentSutra-AI'), out = path.join(root, '_site');
8
+
9
+ fs.rmSync(out, {recursive: true, force: true});
10
+ fs.cpSync(src, out, {recursive: true});
11
+ fs.writeFileSync(path.join(out, '.nojekyll'), '');
12
+ fs.copyFileSync(path.join(root, 'llms.txt'), path.join(out, 'llms.txt'));
13
+
14
+ let redirects = 0;
15
+ (function walk(dir) {
16
+ for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
17
+ const f = path.join(dir, e.name);
18
+ if (e.isDirectory()) { walk(f); continue; }
19
+ if (!e.name.endsWith('.html') || e.name === '404.html') continue;
20
+ const rel = path.relative(src, f).replaceAll('\\', '/'), old = path.join(out, 'docs', rel);
21
+ const target = '../'.repeat(rel.split('/').length) + rel;
22
+ fs.mkdirSync(path.dirname(old), {recursive: true});
23
+ fs.writeFileSync(old, `<!doctype html><meta charset="utf-8"><title>Moved</title><meta http-equiv="refresh" content="0;url=${target}"><link rel="canonical" href="${target}"><a href="${target}">This page moved</a>\n`);
24
+ redirects++;
25
+ }
26
+ })(src);
27
+ console.log(`site built in _site/ with ${redirects} redirects`);