chimericmesh 0.2.2__py3-none-any.whl

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 (147) hide show
  1. chimericmesh/__init__.py +3 -0
  2. chimericmesh/__main__.py +119 -0
  3. chimericmesh/agent/__init__.py +21 -0
  4. chimericmesh/agent/codesearch.py +131 -0
  5. chimericmesh/agent/digest.py +131 -0
  6. chimericmesh/agent/errors.py +38 -0
  7. chimericmesh/agent/feed.py +47 -0
  8. chimericmesh/agent/limits.py +98 -0
  9. chimericmesh/agent/ports.py +32 -0
  10. chimericmesh/agent/routes.py +92 -0
  11. chimericmesh/agent/service.py +116 -0
  12. chimericmesh/agent/snippet.py +135 -0
  13. chimericmesh/agent/verify.py +215 -0
  14. chimericmesh/agent/watch.py +156 -0
  15. chimericmesh/api.py +626 -0
  16. chimericmesh/approvals/__init__.py +25 -0
  17. chimericmesh/approvals/errors.py +72 -0
  18. chimericmesh/approvals/format.py +76 -0
  19. chimericmesh/approvals/irc.py +54 -0
  20. chimericmesh/approvals/ledger.py +149 -0
  21. chimericmesh/approvals/limits.py +87 -0
  22. chimericmesh/approvals/manager.py +935 -0
  23. chimericmesh/approvals/matching.py +107 -0
  24. chimericmesh/approvals/models.py +251 -0
  25. chimericmesh/approvals/ports.py +36 -0
  26. chimericmesh/approvals/routes.py +220 -0
  27. chimericmesh/approvals/rulebook.py +337 -0
  28. chimericmesh/approvals/schema.py +64 -0
  29. chimericmesh/approvals/scope.py +104 -0
  30. chimericmesh/approvals/validate.py +215 -0
  31. chimericmesh/catalog/demo_apps.json +41 -0
  32. chimericmesh/catalog/legacy_apps.json +612 -0
  33. chimericmesh/commands.py +223 -0
  34. chimericmesh/connectors/__init__.py +1 -0
  35. chimericmesh/connectors/config.py +55 -0
  36. chimericmesh/connectors/framing.py +132 -0
  37. chimericmesh/connectors/limiter.py +42 -0
  38. chimericmesh/connectors/manager.py +252 -0
  39. chimericmesh/connectors/offsets.py +157 -0
  40. chimericmesh/connectors/schema.py +31 -0
  41. chimericmesh/connectors/submit.py +26 -0
  42. chimericmesh/connectors/syslog_tcp.py +141 -0
  43. chimericmesh/connectors/tailer.py +236 -0
  44. chimericmesh/connectors/tailread.py +288 -0
  45. chimericmesh/demo/__init__.py +1 -0
  46. chimericmesh/demo/agent.py +32 -0
  47. chimericmesh/demo/apps/__init__.py +1 -0
  48. chimericmesh/demo/apps/__main__.py +83 -0
  49. chimericmesh/demo/apps/common.py +163 -0
  50. chimericmesh/demo/apps/mail_bridge.py +48 -0
  51. chimericmesh/demo/apps/orders_api.py +31 -0
  52. chimericmesh/demo/apps/spooler.py +28 -0
  53. chimericmesh/demo/config.py +38 -0
  54. chimericmesh/demo/engine.py +68 -0
  55. chimericmesh/demo/env.py +46 -0
  56. chimericmesh/demo/hub.py +172 -0
  57. chimericmesh/demo/launcher.py +165 -0
  58. chimericmesh/demo/ports.py +44 -0
  59. chimericmesh/demo/routes.py +81 -0
  60. chimericmesh/demo/samples.py +32 -0
  61. chimericmesh/demo/scenario.py +95 -0
  62. chimericmesh/demo/supervisor.py +267 -0
  63. chimericmesh/demo/watch.py +46 -0
  64. chimericmesh/diagnostics.py +253 -0
  65. chimericmesh/discovery/__init__.py +17 -0
  66. chimericmesh/discovery/accept.py +131 -0
  67. chimericmesh/discovery/catalog.py +313 -0
  68. chimericmesh/discovery/collect.py +131 -0
  69. chimericmesh/discovery/dismissals.py +46 -0
  70. chimericmesh/discovery/engine.py +41 -0
  71. chimericmesh/discovery/errors.py +34 -0
  72. chimericmesh/discovery/expand.py +151 -0
  73. chimericmesh/discovery/manager.py +220 -0
  74. chimericmesh/discovery/match.py +177 -0
  75. chimericmesh/discovery/models.py +174 -0
  76. chimericmesh/discovery/parse.py +166 -0
  77. chimericmesh/discovery/probe.py +69 -0
  78. chimericmesh/discovery/routes.py +129 -0
  79. chimericmesh/discovery/runner.py +147 -0
  80. chimericmesh/discovery/schema.py +25 -0
  81. chimericmesh/discovery/text.py +53 -0
  82. chimericmesh/events.py +74 -0
  83. chimericmesh/fsperms.py +72 -0
  84. chimericmesh/hub.py +757 -0
  85. chimericmesh/listeners.py +162 -0
  86. chimericmesh/mcp_server.py +199 -0
  87. chimericmesh/mute/__init__.py +10 -0
  88. chimericmesh/mute/models.py +14 -0
  89. chimericmesh/mute/mutelist.py +51 -0
  90. chimericmesh/mute/routes.py +49 -0
  91. chimericmesh/mute/schema.py +29 -0
  92. chimericmesh/mute/store.py +94 -0
  93. chimericmesh/notify.py +47 -0
  94. chimericmesh/parsers/__init__.py +12 -0
  95. chimericmesh/parsers/formats.py +23 -0
  96. chimericmesh/parsers/irc.py +91 -0
  97. chimericmesh/parsers/logctx.py +143 -0
  98. chimericmesh/parsers/ncsa.py +57 -0
  99. chimericmesh/parsers/plain.py +17 -0
  100. chimericmesh/parsers/syslog.py +82 -0
  101. chimericmesh/parsers/syslogtext.py +62 -0
  102. chimericmesh/parsers/telnet.py +56 -0
  103. chimericmesh/parsers/w3c.py +58 -0
  104. chimericmesh/parsers/xferlog.py +31 -0
  105. chimericmesh/replay.py +108 -0
  106. chimericmesh/replay_irc.py +202 -0
  107. chimericmesh/services/__init__.py +39 -0
  108. chimericmesh/services/access.py +224 -0
  109. chimericmesh/services/asgi.py +107 -0
  110. chimericmesh/services/deps.py +42 -0
  111. chimericmesh/services/errors.py +49 -0
  112. chimericmesh/services/limiter.py +130 -0
  113. chimericmesh/services/models.py +160 -0
  114. chimericmesh/services/paths.py +139 -0
  115. chimericmesh/services/registry.py +638 -0
  116. chimericmesh/services/routes.py +161 -0
  117. chimericmesh/services/schema.py +48 -0
  118. chimericmesh/services/status.py +239 -0
  119. chimericmesh/services/tagging.py +63 -0
  120. chimericmesh/services/token.py +129 -0
  121. chimericmesh/services/validate.py +184 -0
  122. chimericmesh/store/__init__.py +43 -0
  123. chimericmesh/store/audit.py +89 -0
  124. chimericmesh/store/config.py +88 -0
  125. chimericmesh/store/connection.py +98 -0
  126. chimericmesh/store/errors.py +65 -0
  127. chimericmesh/store/events.py +430 -0
  128. chimericmesh/store/incidents.py +292 -0
  129. chimericmesh/store/migrations.py +109 -0
  130. chimericmesh/store/models.py +49 -0
  131. chimericmesh/store/ports.py +61 -0
  132. chimericmesh/store/proposals.py +215 -0
  133. chimericmesh/store/schema.py +102 -0
  134. chimericmesh/store/store.py +173 -0
  135. chimericmesh/store/tx.py +143 -0
  136. chimericmesh/store/writer.py +315 -0
  137. chimericmesh/web/__init__.py +1 -0
  138. chimericmesh/web/feed.py +212 -0
  139. chimericmesh/web/index.html +3775 -0
  140. chimericmesh/web/sse.py +74 -0
  141. chimericmesh/web/stream.py +64 -0
  142. chimericmesh-0.2.2.dist-info/METADATA +537 -0
  143. chimericmesh-0.2.2.dist-info/RECORD +147 -0
  144. chimericmesh-0.2.2.dist-info/WHEEL +5 -0
  145. chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
  146. chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
  147. chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3775 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <link rel="icon" href="data:,">
7
+ <title>ChimericMesh · The Crypt of Legacy Protocols</title>
8
+ <style>
9
+ :root {
10
+ --bg: #0b0a10; --panel: #13111c; --line: #2a2640; --ink: #d9d4ee; --dim: #9791b5;
11
+ --ghost: #7CFFB2; --ember: #ff8a3d; --blood: #ff4d6d; --amber: #ffd166; --violet: #a98cff;
12
+ --mono: ui-monospace, "Cascadia Code", Consolas, monospace;
13
+ }
14
+ * { box-sizing: border-box; }
15
+ body {
16
+ margin: 0; background: radial-gradient(1200px 600px at 70% -10%, #1d1433 0%, var(--bg) 60%);
17
+ color: var(--ink); font: 15px/1.5 var(--mono); min-height: 100vh;
18
+ }
19
+ body::after { /* faint CRT scanlines */
20
+ content: ""; position: fixed; inset: 0; pointer-events: none;
21
+ background: repeating-linear-gradient(to bottom, transparent 0 2px, rgba(0,0,0,.18) 2px 3px);
22
+ }
23
+ header { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; justify-content: space-between;
24
+ padding: 24px clamp(16px, 4vw, 48px); border-bottom: 1px solid var(--line); }
25
+ h1 { margin: 0; font-size: 1.4rem; letter-spacing: .08em; }
26
+ h1 span { color: var(--ghost); text-shadow: 0 0 12px rgba(124,255,178,.55); }
27
+ .logo { margin: 0; font-size: 1.4rem; font-weight: 700; letter-spacing: .08em; white-space: nowrap; } /* the app header and Home share it */
28
+ .logo span { color: var(--ghost); text-shadow: 0 0 12px rgba(124,255,178,.55); }
29
+ .tag { color: var(--dim); font-size: .85rem; }
30
+ button { font: inherit; color: var(--bg); background: var(--ember); border: 0; padding: 10px 16px;
31
+ border-radius: 4px; cursor: pointer; font-weight: 700; }
32
+ button:hover { background: #ffa05f; }
33
+ button:disabled { opacity: .55; cursor: not-allowed; }
34
+ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible, summary:focus-visible, [tabindex]:focus-visible {
35
+ outline: 3px solid var(--ghost); outline-offset: 2px; }
36
+ button.ghost { background: transparent; color: var(--ghost); border: 1px solid var(--ghost); padding: 6px 10px; }
37
+ button.ghost:hover { background: rgba(124,255,178,.12); }
38
+ button.warn { color: var(--blood); border-color: var(--blood); }
39
+ button.warn:hover { background: rgba(255,77,109,.12); }
40
+ button.small { padding: 3px 8px; font-size: .8rem; }
41
+ main { display: flex; flex-direction: column; gap: 24px; padding: 24px clamp(16px, 4vw, 48px) 64px; }
42
+ .grid { display: grid; gap: 24px; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); align-items: start; }
43
+ .col { display: flex; flex-direction: column; gap: 24px; min-width: 0; }
44
+ #termPanel { display: flex; flex-direction: column; }
45
+ @media (max-width: 960px) {
46
+ .grid { display: flex; flex-direction: column; align-items: stretch; }
47
+ .col { display: contents; }
48
+ #termPanel { order: 1; }
49
+ #incPanel { order: 2; } #propPanel { order: 3; } #evPanel { order: 4; }
50
+ .col.left.has-pending #propPanel { order: 0; }
51
+ }
52
+ section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 20px; min-width: 0; }
53
+ h2 { margin: 0 0 14px; font-size: .9rem; letter-spacing: .14em; text-transform: uppercase; color: var(--violet); }
54
+ .stats { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
55
+ .stat b { display: block; font-size: 2rem; color: var(--ghost); }
56
+ .stat span { color: var(--dim); font-size: .8rem; letter-spacing: .1em; text-transform: uppercase; }
57
+ .incident { border-left: 3px solid var(--amber); padding: 12px 14px; margin-bottom: 12px; background: #0f0d17; border-radius: 0 6px 6px 0; }
58
+ .incident.sev-0, .incident.sev-1, .incident.sev-2, .incident.sev-3 { border-color: var(--blood); }
59
+ .incident.resolved { border-color: var(--ghost); opacity: .7; }
60
+ .incident h3 { margin: 0 0 4px; font-size: 1rem; }
61
+ .meta { color: var(--dim); font-size: .8rem; }
62
+ .sample { margin: 8px 0; padding: 8px; background: #08070d; color: var(--amber); overflow-wrap: anywhere; border-radius: 4px; }
63
+ ol { margin: 6px 0 10px 18px; padding: 0; }
64
+ .src { display: inline-block; padding: 0 6px; margin-right: 4px; border: 1px solid var(--line); border-radius: 3px; font-size: .75rem; color: var(--ghost); }
65
+ .log { max-height: 520px; overflow: auto; }
66
+ #liveBox.log { max-height: 260px; }
67
+ .skip { position: absolute; left: -9999px; top: 8px; }
68
+ .skip:focus { left: 8px; z-index: 20; padding: 8px 12px; background: var(--panel); color: var(--ghost); border: 1px solid var(--ghost); border-radius: 4px; }
69
+ .decide { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; padding: 12px 20px;
70
+ background: #2a1d08; border: 1px solid var(--amber); border-radius: 8px; color: var(--amber); }
71
+ .decide span { min-width: 0; overflow-wrap: anywhere; }
72
+ button.quiet { color: var(--dim); border-color: var(--line); }
73
+ .col.left.has-pending #propPanel { order: -1; }
74
+ .lock-note { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; }
75
+ .row { display: grid; grid-template-columns: 62px 70px 1fr; gap: 10px; padding: 4px 0; border-bottom: 1px dashed #221f33; font-size: .85rem; }
76
+ .row .m { overflow-wrap: anywhere; }
77
+ .row .t { white-space: nowrap; }
78
+ .sev-err, .sev-crit, .sev-alert, .sev-emerg { color: var(--blood); }
79
+ .sev-warning { color: var(--amber); }
80
+ .empty { color: var(--dim); font-style: italic; }
81
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
82
+ form.send, form.propose { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
83
+ form.send input[type=text] { flex: 1 1 12ch; min-width: 0; }
84
+ form.propose { margin-top: 10px; }
85
+ #evPanel, #incPanel, #propPanel, #termPanel { min-width: 0; }
86
+ input, select { font: inherit; background: #08070d; color: var(--ink); border: 1px solid var(--line); border-radius: 4px; padding: 8px; }
87
+ input[type=text] { flex: 1; min-width: 0; }
88
+ .sr { position: absolute; left: -9999px; }
89
+ .hidden, [hidden] { display: none !important; }
90
+ [data-view] { display: flex; flex-direction: column; gap: 24px; min-width: 0; }
91
+ nav { display: flex; gap: 8px; flex-wrap: wrap; }
92
+ nav button[aria-current="page"] { background: rgba(124,255,178,.18); }
93
+ nav .count { display: inline-block; min-width: 1.4em; padding: 0 6px; margin-left: 4px; border: 1px solid var(--amber); border-radius: 10px; color: var(--amber); font-size: .75rem; text-align: center; }
94
+ nav .count[hidden] { display: none; }
95
+ .meta.warnline { color: var(--amber); }
96
+ button.tag { font-size: .75rem; }
97
+ .hdr-right { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
98
+ #status { max-width: 40ch; overflow-wrap: anywhere; }
99
+ .banner { margin: 0; padding: 10px clamp(16px, 4vw, 48px); background: #2a1d08; color: var(--amber); border-bottom: 1px solid var(--amber); }
100
+ #selftest { white-space: pre-wrap; overflow-wrap: anywhere; color: var(--ghost); }
101
+ form.unlock { padding: 12px clamp(16px, 4vw, 48px); border-bottom: 1px solid var(--line); background: var(--panel); }
102
+ form.unlock .meta { overflow-wrap: anywhere; }
103
+ form.unlock .prompt { flex-wrap: wrap; }
104
+ form.unlock .prompt input { flex: 1 1 14ch; min-width: 0; }
105
+ dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0; }
106
+ dl.facts dt { color: var(--dim); }
107
+ dl.facts dd { margin: 0; overflow-wrap: anywhere; }
108
+ .svc-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr)); margin-top: 14px; }
109
+ .svc-card { border: 1px solid var(--line); border-radius: 6px; padding: 12px; background: #0f0d17; min-width: 0; overflow-wrap: anywhere; }
110
+ .svc-card h3 { margin: 0; font-size: 1rem; }
111
+ .svc-card .top { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; justify-content: space-between; }
112
+ .svc-card ul { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 4px; }
113
+ #svcCrumb, #svcCrumb:visited { color: var(--ghost); font-size: .85rem; display: inline-block; margin-bottom: 6px; }
114
+ .svc-title { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
115
+ .svc-title h2 { margin: 0; }
116
+ .svc-card .facts-line { display: flex; flex-wrap: wrap; gap: 2px 12px; }
117
+ .svc-card .facts-line span { white-space: nowrap; }
118
+ .svc-card .err { color: var(--blood); font-size: .8rem; }
119
+ .pill.st-active { color: var(--ghost); }
120
+ .pill.st-idle { color: var(--amber); }
121
+ .pill.st-never, .pill.st-unknown { color: var(--dim); }
122
+ .pill.muted { color: var(--amber); }
123
+ .mute-confirm { flex-basis: 100%; display: grid; gap: 8px; }
124
+ .mute-confirm .meta { margin: 0; }
125
+ form.svc-form { display: grid; gap: 10px; margin-top: 14px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; }
126
+ form.svc-form h3, form.svc-form h4 { margin: 0; }
127
+ .field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
128
+ .field label { color: var(--dim); font-size: .85rem; }
129
+ fieldset { border: 1px solid var(--line); border-radius: 4px; display: flex; flex-wrap: wrap; gap: 12px; }
130
+ .table-wrap { overflow-x: auto; }
131
+ table.rules { border-collapse: collapse; width: 100%; font-size: .85rem; }
132
+ table.rules th, table.rules td { text-align: left; padding: 6px 8px; border-bottom: 1px dashed #221f33; vertical-align: top; overflow-wrap: anywhere; min-width: 10ch; }
133
+ table.rules th { color: var(--dim); font-weight: 400; }
134
+ table.audit td:nth-child(1), table.audit td:nth-child(3) { white-space: nowrap; }
135
+ .row.live { grid-template-columns: 70px 70px minmax(0, 1fr); }
136
+ .row.live .cell { min-width: 0; }
137
+ .row.live .m { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
138
+ .row.live.open .m { white-space: normal; overflow-wrap: anywhere; }
139
+ .row.live.sys { color: var(--amber); }
140
+ .live-ctl { align-items: flex-end; margin-bottom: 8px; }
141
+ .live-ctl button, .live-ctl .field.inline { min-height: 40px; }
142
+ .live-ctl select, .live-ctl input[type=text] { box-sizing: border-box; flex: none; height: 40px; }
143
+ .live-ctl .field.inline { flex-direction: row; align-items: center; gap: 8px; }
144
+ .cand { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; border-top: 1px dashed var(--line); padding-top: 8px; }
145
+ table.sources { border-collapse: collapse; width: 100%; }
146
+ table.sources td { padding: 4px; vertical-align: bottom; }
147
+ details.perm { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px 20px; }
148
+ details.perm summary { cursor: pointer; color: var(--violet); font-weight: 700; }
149
+ details.perm pre { white-space: pre-wrap; max-height: 360px; overflow: auto; }
150
+
151
+ /* guide */
152
+ .guide-head { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; }
153
+ .guide-head h2 { margin: 0; }
154
+ .bar { height: 6px; background: #08070d; border: 1px solid var(--line); border-radius: 3px; margin: 10px 0 14px; overflow: hidden; }
155
+ .bar > i { display: block; height: 100%; background: var(--ghost); }
156
+ .steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); }
157
+ .step { display: flex; gap: 10px; padding: 10px; border: 1px solid var(--line); border-radius: 6px; background: #0f0d17; }
158
+ .step .n { flex: none; width: 26px; height: 26px; border-radius: 50%; border: 1px solid var(--dim); display: grid; place-items: center; font-size: .8rem; color: var(--dim); }
159
+ .step .t { font-weight: 700; }
160
+ .step.done { opacity: .7; }
161
+ .step.done .n { border-color: var(--ghost); color: var(--ghost); }
162
+ .step.next { border-color: var(--ember); box-shadow: 0 0 0 1px var(--ember); }
163
+ .step.next .n { border-color: var(--ember); color: var(--ember); }
164
+ .step button { margin-top: 8px; }
165
+ #guideStatus { min-height: 1.2em; margin-top: 10px; }
166
+
167
+ /* terminal */
168
+ .term-log { flex: 1; min-height: 220px; max-height: 360px; overflow: auto; background: #08070d; border: 1px solid var(--line); border-radius: 4px; padding: 8px; font-size: .85rem; }
169
+ .tline { overflow-wrap: anywhere; white-space: pre-wrap; padding: 1px 0; }
170
+ .tline .ts { color: var(--dim); margin-right: 8px; }
171
+ .tline.bot { color: var(--ghost); }
172
+ .tline.bot .who { font-weight: 700; margin-right: 6px; }
173
+ .tline.user { color: var(--amber); }
174
+ .tline.user .who { margin-right: 6px; }
175
+ .tline.system { color: var(--dim); font-style: italic; }
176
+ .term-wrap { position: relative; display: flex; flex-direction: column; min-height: 0; }
177
+ #newMsgs { position: absolute; right: 12px; bottom: 10px; padding: 4px 10px; font-size: .8rem; }
178
+ .prompt { display: flex; gap: 8px; align-items: center; margin-top: 10px; }
179
+ .prompt .glyph { color: var(--ghost); font-weight: 700; }
180
+ .chips { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 10px; align-items: center; }
181
+ .chips .spacer { flex: 1; }
182
+
183
+ /* proposals */
184
+ .prop { border: 1px solid var(--line); border-radius: 6px; padding: 10px 12px; margin-bottom: 10px; background: #0f0d17; }
185
+ .prop .top { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
186
+ .prop .act { margin: 6px 0; overflow-wrap: anywhere; }
187
+ .pill { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: .75rem; border: 1px solid currentColor; }
188
+ .pill.pending { color: var(--amber); }
189
+ .pill.approved { color: var(--ghost); }
190
+ .pill.denied { color: var(--blood); }
191
+ .pill.done { color: var(--violet); }
192
+ .pill.auto { color: var(--violet); font-weight: 700; }
193
+ form.rule-form { display: grid; gap: 10px; margin-top: 10px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; }
194
+ form.rule-form .grid-n { display: grid; gap: 10px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 150px), 1fr)); }
195
+ form.rule-form input[type=number] { width: 100%; }
196
+ .pill.unknown { color: var(--dim); }
197
+
198
+ #toast { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); z-index: 10; background: #2a0f18; color: #ffd6de;
199
+ border: 1px solid var(--blood); border-radius: 6px; padding: 8px 14px; max-width: 90vw; }
200
+ #toast:empty { display: none; }
201
+ .scan { height: 6px; max-width: min(420px, 100%); overflow: hidden; border-radius: 3px; background: var(--line); margin: 8px 0; }
202
+ .scan[hidden] { display: none; }
203
+ footer#hubVersion { padding: 0 clamp(16px, 4vw, 48px) 24px; }
204
+ .scan-bar { width: 35%; height: 100%; border-radius: 3px; background: var(--amber); }
205
+ @media (prefers-reduced-motion: no-preference) { .pulse { animation: pulse 2.4s ease-in-out infinite; } .scan-bar { animation: sweep 1.4s ease-in-out infinite; } @keyframes tourpulse { 50% { outline-offset: 7px; } } .tour-target { animation: tourpulse 1.6s ease-in-out 3; } }
206
+ @media (max-width: 480px) {
207
+ header { padding: 16px; gap: 10px; }
208
+ main { padding: 16px 12px 48px; gap: 16px; }
209
+ section { padding: 14px; }
210
+ .hdr-right { width: 100%; }
211
+ #status { max-width: 100%; }
212
+ nav button { padding: 8px 10px; }
213
+ .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
214
+ .row.live { grid-template-columns: 56px 56px minmax(0, 1fr); gap: 6px; }
215
+ form.svc-form, form.rule-form { padding: 10px; }
216
+ dl.facts { grid-template-columns: 1fr; }
217
+ button { min-height: 40px; }
218
+ .mute-btn { min-height: 44px; min-width: 44px; }
219
+ .actions { gap: 10px; }
220
+ }
221
+ /* Rules and Audit rows become small cards on phones, so Pause and Revoke stay reachable (UX-07). */
222
+ @media (max-width: 640px) {
223
+ table.rules thead { display: none; }
224
+ table.rules, table.rules tbody { display: block; }
225
+ table.rules tr { display: block; margin-bottom: 10px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; background: #0f0d17; }
226
+ table.rules td { display: grid; grid-template-columns: 11ch minmax(0, 1fr); gap: 8px; min-width: 0; padding: 3px 0; border-bottom: 0; overflow-wrap: break-word; }
227
+ table.rules td::before { content: attr(data-label); color: var(--dim); }
228
+ table.audit td:nth-child(1), table.audit td:nth-child(3) { white-space: normal; }
229
+ table.rules td:empty { display: none; }
230
+ }
231
+ @keyframes pulse { 50% { text-shadow: 0 0 22px rgba(255,138,61,.9); } }
232
+ @keyframes sweep { from { transform: translateX(-100%); } to { transform: translateX(286%); } }
233
+
234
+ /* ==== Home (demo-mode task 16) ==== */
235
+ .sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
236
+ .vh { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } /* read by screen readers, not shown */
237
+ .ghost-mini { width: 26px; height: 29px; flex: none; color: var(--ghost); }
238
+ .ghost-mid { width: 44px; height: 50px; flex: none; color: var(--ghost); }
239
+ .ghost-big { width: 84px; height: 94px; color: var(--ghost); }
240
+ body[data-route="home"] > header, body[data-route="home"] > form.unlock, body[data-route="home"] > #pausedBanner, body[data-route="home"] > footer#hubVersion { display: none; }
241
+ body[data-route="home"] main { padding: 0; gap: 0; }
242
+ .demo-banner { position: sticky; top: 0; z-index: 30; display: flex; flex-wrap: wrap; gap: 10px 16px; align-items: center; justify-content: space-between;
243
+ padding: 10px clamp(16px, 4vw, 48px); background: #2a1d08; color: var(--amber); border-bottom: 1px solid var(--amber); }
244
+ .demo-copy { display: grid; gap: 2px; min-width: 0; flex: 1 1 28ch; }
245
+ .demo-banner strong { display: flex; align-items: center; gap: 8px; font-size: .85rem; letter-spacing: .14em; text-transform: uppercase; }
246
+ .demo-banner span { overflow-wrap: anywhere; }
247
+ .demo-hint { color: var(--ink); }
248
+ .demo-banner button { min-height: 44px; }
249
+ #view-home { gap: 0; --gut: clamp(16px, 4vw, 48px); }
250
+ :where(.hm) section { background: transparent; border: 0; border-radius: 0; }
251
+ .hm-wrap { width: min(1160px, 100% - 2 * var(--gut)); margin-inline: auto; }
252
+ .hm h1 { margin: 14px 0 18px; font-size: clamp(1.85rem, 4.6vw, 3.6rem); line-height: 1.1; letter-spacing: -.02em; font-weight: 800; overflow-wrap: anywhere; }
253
+ .hm h2 { margin: 10px 0 0; font-size: clamp(1.5rem, 3.2vw, 2.4rem); line-height: 1.15; letter-spacing: -.01em; text-transform: none; color: var(--ink); overflow-wrap: anywhere; }
254
+ .hm h3 { margin: 0 0 8px; font-size: 1.05rem; color: var(--ink); }
255
+ :where(.hm) p { margin: 0; }
256
+ .hm button { min-height: 44px; padding: 12px 20px; font-size: 1rem; border-radius: 6px; }
257
+ .hm button.small { padding: 8px 14px; font-size: .9rem; }
258
+ .hm button[data-busy="yes"] { opacity: .65; cursor: progress; }
259
+ .hm code { color: var(--ghost); }
260
+ .hm-eyebrow { margin: 0; color: var(--violet); font-size: .8rem; letter-spacing: .14em; text-transform: uppercase; }
261
+ .hm-line { margin-top: 14px; max-width: 62ch; color: var(--dim); }
262
+ .hm-top { position: sticky; top: 0; z-index: 12; background: rgba(11,10,16,.9); backdrop-filter: blur(8px); border-bottom: 1px solid var(--line); }
263
+ body[data-demo="on"] .hm-top { position: static; }
264
+ .hm-top-in { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 64px; }
265
+ .hm-brand { font-size: 1.25rem; }
266
+ .hm-links { display: flex; align-items: center; gap: 8px; }
267
+ .hm-notice { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 16px; padding: 4px 4px 4px 14px; border: 1px solid var(--ghost); border-radius: 6px; color: var(--ghost); background: rgba(124,255,178,.08); }
268
+ .hm-notice[hidden] { display: none; }
269
+ .hm-notice p { min-width: 0; overflow-wrap: anywhere; }
270
+ .hm button.hm-x { flex: none; min-width: 44px; padding: 4px 10px; border-color: transparent; font-size: 1.3rem; line-height: 1; }
271
+ .hm-hero { padding: clamp(40px, 7vw, 96px) 0 clamp(56px, 8vw, 112px);
272
+ background: radial-gradient(700px 380px at 84% 8%, rgba(124,255,178,.10), transparent 70%), radial-gradient(560px 320px at 6% 0%, rgba(255,138,61,.10), transparent 70%); }
273
+ .hm-hero-grid { display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); gap: clamp(32px, 5vw, 72px); align-items: center; }
274
+ .hm-hero-copy { min-width: 0; }
275
+ .hm-lead { max-width: 54ch; font-size: clamp(1rem, 1.5vw, 1.15rem); }
276
+ .hm-cta { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 28px; }
277
+ .hm-status { margin-top: 12px; min-height: 1.5em; color: var(--amber); overflow-wrap: anywhere; }
278
+ .hm-guide { display: flex; gap: 14px; align-items: center; margin-top: 24px; padding: 14px 16px; max-width: 56ch; border: 1px dashed var(--line); border-radius: 10px; background: rgba(19,17,28,.7); }
279
+ .hm-guide b { color: var(--ember); }
280
+ .hm-frame { min-width: 0; border: 1px solid var(--line); border-radius: 12px; background: #0f0d17; overflow: hidden; box-shadow: 0 0 0 1px rgba(124,255,178,.06), 0 24px 60px rgba(0,0,0,.45); }
281
+ .fr-bar { display: flex; align-items: center; gap: 6px; padding: 10px 14px; border-bottom: 1px solid var(--line); background: #13111c; }
282
+ .fr-bar i { width: 10px; height: 10px; border-radius: 50%; background: var(--line); }
283
+ .fr-title { margin-left: 8px; color: var(--dim); font-size: .8rem; letter-spacing: .1em; text-transform: uppercase; }
284
+ .fr-live { margin-left: auto; display: flex; align-items: center; gap: 6px; color: var(--ghost); font-size: .8rem; }
285
+ .fr-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ghost); }
286
+ .fr-body { display: grid; gap: 14px; padding: 16px; }
287
+ .fr-inc { padding: 12px 14px; border-left: 3px solid var(--blood); border-radius: 0 6px 6px 0; background: #13111c; }
288
+ .fr-row { display: flex; align-items: center; gap: 10px; }
289
+ .fr-sev { padding: 0 8px; border: 1px solid var(--blood); border-radius: 10px; color: var(--blood); font-size: .75rem; }
290
+ .fr-sample { margin: 10px 0; padding: 8px; border-radius: 4px; background: #08070d; color: var(--amber); font-size: .85rem; overflow-wrap: anywhere; }
291
+ .fr-meta { color: var(--dim); font-size: .8rem; }
292
+ .fr-prop { padding: 12px 14px; border: 1px solid var(--amber); border-radius: 6px; background: #2a1d08; }
293
+ .fr-prop .fr-meta { color: var(--amber); }
294
+ .fr-act { margin: 6px 0 12px; color: var(--ink); overflow-wrap: anywhere; }
295
+ .fr-btns { display: flex; gap: 8px; }
296
+ .fr-b { padding: 6px 14px; border-radius: 4px; font-size: .85rem; font-weight: 700; }
297
+ .fr-ok { background: var(--ember); color: var(--bg); }
298
+ .fr-no { border: 1px solid var(--blood); color: var(--blood); }
299
+ .fr-log { display: grid; gap: 4px; padding: 10px 12px; border-radius: 6px; background: #08070d; color: var(--dim); font-size: .78rem; overflow-wrap: anywhere; }
300
+ .fr-log span { color: var(--ghost); margin-right: 8px; }
301
+ .hm-sec { padding: clamp(56px, 9vw, 112px) 0; border-top: 1px solid var(--line); }
302
+ .hm-flow { display: grid; grid-template-columns: minmax(0, 1fr) 64px minmax(0, 1fr) 64px minmax(0, 1fr); align-items: center; margin: 40px 0 48px; }
303
+ .fl-col { display: grid; gap: 12px; min-width: 0; }
304
+ .fl-node { display: grid; gap: 2px; min-width: 0; padding: 14px 16px; border: 1px solid var(--line); border-radius: 8px; background: #0f0d17; overflow-wrap: anywhere; }
305
+ .fl-node span { color: var(--dim); font-size: .82rem; }
306
+ .fl-hub { justify-items: center; text-align: center; padding: 22px 16px; border-color: var(--ghost); box-shadow: 0 0 40px rgba(124,255,178,.08); }
307
+ .fl-you { border-color: var(--amber); }
308
+ .fl-link { position: relative; height: 2px; background: linear-gradient(90deg, var(--line), var(--ghost)); }
309
+ .fl-link i { position: absolute; top: -3px; left: calc(50% - 4px); width: 8px; height: 8px; border-radius: 50%; background: var(--ghost); }
310
+ .hm-steps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 28px; margin: 0; padding: 0; list-style: none; }
311
+ .hm-steps li { padding-top: 16px; border-top: 2px solid var(--line); min-width: 0; }
312
+ .hm-steps li:hover { border-top-color: var(--ghost); }
313
+ .st-n { display: block; margin-bottom: 8px; color: var(--ember); font-size: .85rem; letter-spacing: .1em; }
314
+ .hm-steps p { color: var(--dim); }
315
+ .hm-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 170px), 1fr)); gap: 24px; margin: 32px 0 0; }
316
+ .hm-stat { min-width: 0; padding-top: 14px; border-top: 2px solid var(--ghost); }
317
+ .hm-stat dt { color: var(--dim); font-size: .8rem; letter-spacing: .1em; text-transform: uppercase; }
318
+ .hm-stat dd { margin: 6px 0 0; color: var(--ghost); font-size: clamp(1.9rem, 5.4vw, 3.4rem); font-weight: 800; line-height: 1.1; overflow-wrap: anywhere; }
319
+ .hm-install { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; margin-top: 32px; }
320
+ .hm-card { min-width: 0; padding: 20px; border: 1px solid var(--line); border-radius: 10px; background: #0f0d17; }
321
+ .hm-wide { grid-column: 1 / -1; }
322
+ .hm-cmd { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-top: 12px; padding: 8px 8px 8px 12px; border: 1px solid var(--line); border-radius: 6px; background: #08070d; }
323
+ .hm-cmd code, .hm-cmd pre { flex: 1 1 18ch; min-width: 0; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: .88rem; color: var(--ghost); }
324
+ .hm-close { text-align: center; }
325
+ .hm-close .hm-line { margin-inline: auto; }
326
+ .hm-close .hm-cta { justify-content: center; }
327
+ .hm-foot { padding: 24px 0 40px; border-top: 1px solid var(--line); color: var(--dim); font-size: .85rem; }
328
+ .hm-foot .hm-wrap { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px; }
329
+ @media (max-width: 860px) {
330
+ .hm-hero-grid { grid-template-columns: minmax(0, 1fr); }
331
+ .hm-flow { grid-template-columns: minmax(0, 1fr); gap: 0; }
332
+ .fl-link { width: 2px; height: 44px; justify-self: center; background: linear-gradient(180deg, var(--line), var(--ghost)); }
333
+ .fl-link i { top: calc(50% - 4px); left: -3px; }
334
+ .hm-steps, .hm-install { grid-template-columns: minmax(0, 1fr); }
335
+ }
336
+ @media (max-width: 640px) { .hm-opt { display: none; } .demo-banner { position: static; } } /* a tall sticky banner would eat a phone screen */
337
+ @media (max-width: 480px) {
338
+ .hm-cta button { flex: 1 1 100%; }
339
+ .hm-guide { padding: 12px; }
340
+ .hm-card { padding: 14px; }
341
+ .hm-sec { padding: 48px 0; }
342
+ }
343
+ @media (prefers-reduced-motion: no-preference) {
344
+ @keyframes rise { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
345
+ @keyframes travel { from { left: 0; opacity: 0; } 15% { opacity: 1; } to { left: calc(100% - 8px); opacity: 1; } }
346
+ @keyframes travel-down { from { top: 0; opacity: 0; } 15% { opacity: 1; } to { top: calc(100% - 8px); opacity: 1; } }
347
+ @keyframes bob { 50% { transform: translateY(-5px); } }
348
+ @keyframes blink { 50% { opacity: .25; } }
349
+ .hm-hero-copy > * { animation-name: rise; animation-duration: .6s; animation-timing-function: ease-out; animation-fill-mode: backwards; }
350
+ .hm-hero-copy > :nth-child(2) { animation-delay: .06s; }
351
+ .hm-hero-copy > :nth-child(3) { animation-delay: .12s; }
352
+ .hm-hero-copy > :nth-child(4) { animation-delay: .18s; }
353
+ .hm-hero-copy > :nth-child(n+5) { animation-delay: .24s; }
354
+ .hm-frame { animation-name: rise; animation-duration: .7s; animation-delay: .2s; animation-timing-function: ease-out; animation-fill-mode: backwards; }
355
+ .fl-link i { animation-name: travel; animation-duration: 2.2s; animation-iteration-count: 2; animation-timing-function: linear; }
356
+ .hm-guide .ghost-mid, .ghost-big { animation-name: bob; animation-duration: 1.6s; animation-iteration-count: 3; animation-timing-function: ease-in-out; }
357
+ .fr-dot { animation-name: blink; animation-duration: 1.4s; animation-iteration-count: 3; }
358
+ .hm button, .demo-banner button { transition-property: transform, background-color; transition-duration: .12s; }
359
+ .hm button:hover:not([data-busy="yes"]), .demo-banner button:hover { transform: translateY(-1px); }
360
+ .hm button:active:not([data-busy="yes"]), .demo-banner button:active { transform: translateY(1px); }
361
+ .hm-steps li { transition-property: border-color, transform; transition-duration: .2s; }
362
+ .hm-steps li:hover { transform: translateY(-2px); }
363
+ @media (max-width: 860px) { .fl-link i { animation-name: travel-down; } }
364
+ }
365
+ #tour { position: fixed; right: 16px; bottom: 16px; z-index: 40; box-sizing: border-box; width: 360px; max-width: calc(100vw - 16px); max-height: 60vh; overflow: auto;
366
+ display: grid; gap: 8px; padding: 14px 16px; background: var(--panel); border: 1px solid var(--violet); border-radius: 8px; box-shadow: 0 8px 30px #000a; }
367
+ #tour h2 { margin: 0; color: var(--ghost); font-size: .95rem; letter-spacing: .06em; }
368
+ #tour p { margin: 0; overflow-wrap: anywhere; }
369
+ .tour-head { display: flex; align-items: center; gap: 8px; }
370
+ .tour-count { color: var(--dim); font-size: .8rem; }
371
+ .tour-actions { display: flex; flex-wrap: wrap; gap: 8px; }
372
+ #tour button { min-height: 44px; min-width: 44px; }
373
+ body.tour-open { padding-bottom: 240px; }
374
+ body.tour-open #guide { display: none; }
375
+ .tour-target { outline: 3px solid var(--amber); outline-offset: 3px; }
376
+ body.tour-open .tour-target { scroll-margin-top: 16px; scroll-margin-bottom: 260px; } /* scroll clear of the fixed panel */
377
+ @media (max-width: 640px) { #tour { left: 8px; right: 8px; bottom: 8px; width: auto; max-width: none; max-height: 52vh; } body.tour-open { padding-bottom: 300px; } body.tour-open .tour-target { scroll-margin-bottom: 340px; } }
378
+ </style>
379
+ </head>
380
+ <body data-route="home">
381
+ <svg class="sprite" aria-hidden="true" focusable="false"><symbol id="ghost" viewBox="0 0 64 72"><path fill="currentColor" d="M8 66V30C8 15 19 4 32 4s24 11 24 26v36l-8-7-8 7-8-7-8 7-8-7z"/><ellipse cx="24" cy="31" rx="4" ry="6" fill="#0b0a10"/><path d="M37 32q4-6 8 0" fill="none" stroke="#0b0a10" stroke-width="3" stroke-linecap="round"/><path d="M22 45q10 9 20 0" fill="none" stroke="#0b0a10" stroke-width="3" stroke-linecap="round"/></symbol></svg>
382
+ <a class="skip" id="skip" href="#main">Skip to content</a>
383
+ <div id="demoBanner" class="demo-banner" role="region" aria-label="Demo mode" hidden>
384
+ <div class="demo-copy">
385
+ <strong><svg class="ghost-mini" aria-hidden="true" focusable="false"><use href="#ghost"/></svg>Demo mode</strong>
386
+ <span>Three sample apps on this computer. All of it is thrown away when you exit.</span>
387
+ <span id="demoHint" class="demo-hint" aria-live="polite"></span>
388
+ </div>
389
+ <button type="button" id="tourShow" class="ghost" hidden>Show tour</button>
390
+ <button type="button" id="demoExit" data-tour="exit-demo">Exit demo</button>
391
+ </div><!-- /demoBanner -->
392
+ <header>
393
+ <div>
394
+ <h1 class="logo"><span>CHIMERIC</span>MESH <span class="pulse" aria-hidden="true">☠</span></h1>
395
+ <div class="tag">Syslog · IRC · Telnet, stitched to AI agents through MCP</div>
396
+ </div>
397
+ <nav aria-label="Views">
398
+ <button class="ghost" type="button" data-nav="home" data-tour="nav-home">Home</button>
399
+ <button class="ghost" type="button" data-nav="overview" data-tour="nav-overview">Overview</button>
400
+ <button class="ghost" type="button" data-nav="services" data-tour="nav-services">Services <span class="count" hidden></span></button>
401
+ <button class="ghost" type="button" data-nav="discovery" data-tour="nav-discovery">Discovery</button>
402
+ <button class="ghost" type="button" data-nav="rules" data-tour="nav-rules">Rules <span class="count" hidden></span></button>
403
+ </nav>
404
+ <div class="hdr-right">
405
+ <div id="status" class="meta" role="status" aria-live="polite"></div>
406
+ <span id="lockText" class="meta"></span>
407
+ <button class="ghost small" type="button" id="unlockBtn" aria-controls="tokenForm" aria-expanded="false">Unlock to approve</button>
408
+ <button class="ghost small" type="button" id="lockBtn" hidden>Lock</button>
409
+ <button id="storm" class="ghost small" type="button">Summon a failure storm</button>
410
+ </div>
411
+ </header>
412
+ <form class="unlock hidden" id="tokenForm" autocomplete="off" aria-label="Unlock">
413
+ <div class="meta" id="tokenNote"></div>
414
+ <div class="meta" id="tokenFile"></div>
415
+ <div class="prompt">
416
+ <label class="sr" for="tokenInput">Admin token</label>
417
+ <input type="password" id="tokenInput" maxlength="256" autocomplete="off" spellcheck="false" aria-label="Admin token" placeholder="admin token">
418
+ <button type="submit">Save</button>
419
+ <button class="ghost" type="button" id="tokenCancel">Cancel</button>
420
+ </div>
421
+ </form>
422
+ <div id="pausedBanner" class="banner" role="status" hidden></div>
423
+ <main id="main" tabindex="-1">
424
+ <div id="view-home" data-view="home" class="hm">
425
+ <div class="hm-top"><div class="hm-wrap hm-top-in">
426
+ <p class="hm-brand logo"><span>CHIMERIC</span>MESH <span class="pulse" aria-hidden="true">☠</span></p>
427
+ <nav aria-label="Home sections" class="hm-links">
428
+ <button class="ghost hm-opt" type="button" data-scroll="how-h">How it works</button>
429
+ <button class="ghost hm-opt" type="button" data-scroll="install-h">Install</button>
430
+ <button class="ghost" type="button" data-go="overview">Open app</button>
431
+ </nav>
432
+ </div></div>
433
+ <div id="homeNote" class="hm-notice hm-wrap" hidden><p id="homeNoteText" role="status"></p><button class="ghost small hm-x" type="button" id="homeNoteClose" aria-label="Dismiss">×</button></div>
434
+ <div class="hm-hero"><div class="hm-wrap hm-hero-grid">
435
+ <div class="hm-hero-copy">
436
+ <p class="hm-eyebrow">Syslog, IRC and Telnet, for AI agents</p>
437
+ <h1>Let your AI agent read the <span>logs</span> your old servers still send.</h1>
438
+ <p class="hm-lead">ChimericMesh listens on Syslog, IRC and Telnet, groups the errors into incidents, and gives your agent the context over MCP to propose a fix. You approve every change.</p>
439
+ <div class="hm-cta">
440
+ <button type="button" id="homeDemo" data-demo-btn>Try the demo</button>
441
+ <button class="ghost" type="button" data-go="discovery">Connect my apps</button>
442
+ </div>
443
+ <p id="homeDemoStatus" class="hm-status" role="status" aria-live="polite"></p>
444
+ <button class="ghost small" type="button" id="homeDemoStop" hidden>Stop the demo</button>
445
+ <div class="hm-guide">
446
+ <svg class="ghost-mid" aria-hidden="true" focusable="false"><use href="#ghost"/></svg>
447
+ <p>Not sure where to start? Tap <b>Try the demo</b>. I haunt three sample apps for you, and none of it touches your data.</p>
448
+ </div>
449
+ </div>
450
+ <div class="hm-frame" role="img" aria-label="Sketch of the app. An incident from the orders-api sample app shows its error line and likely cause. Below it, the agent's proposed fix waits for Approve or Deny.">
451
+ <div class="fr-bar"><i></i><i></i><i></i><span class="fr-title">Haunted incidents</span><span class="fr-live"><b class="fr-dot"></b>live</span></div>
452
+ <div class="fr-body">
453
+ <div class="fr-inc">
454
+ <div class="fr-row"><span class="fr-sev">err</span><strong>orders-api</strong></div>
455
+ <p class="fr-sample">db pool exhausted: timed out waiting for connection to 10.0.4.12:5432</p>
456
+ <p class="fr-meta">Likely cause: database or network. Still repeating.</p>
457
+ </div>
458
+ <div class="fr-prop">
459
+ <p class="fr-meta">Agent proposal, waiting for you</p>
460
+ <p class="fr-act">Add a retry with backoff to the caller</p>
461
+ <div class="fr-btns"><span class="fr-b fr-ok">Approve</span><span class="fr-b fr-no">Deny</span></div>
462
+ </div>
463
+ <div class="fr-log">
464
+ <p><span>spooler</span> no space left on device /var/spool/print</p>
465
+ <p><span>mail-bridge</span> connection refused to smtp relay 10.0.0.25:25</p>
466
+ </div>
467
+ </div>
468
+ </div><!-- /hm-frame -->
469
+ </div></div>
470
+ <section class="hm-sec" aria-labelledby="how-h"><div class="hm-wrap">
471
+ <p class="hm-eyebrow">How it works</p>
472
+ <h2 id="how-h" tabindex="-1">From log line to fix in three steps</h2>
473
+ <div class="hm-flow" role="img" aria-label="Diagram. Syslog, IRC and Telnet lines flow into the ChimericMesh hub. The hub hands incidents to your AI agent over MCP. You approve or deny the fix.">
474
+ <div class="fl-col">
475
+ <div class="fl-node"><b>Syslog</b><span>UDP and TCP, port 5514 by default</span></div>
476
+ <div class="fl-node"><b>IRC</b><span>channel lines, port 6667</span></div>
477
+ <div class="fl-node"><b>Telnet</b><span>session text, port 2323</span></div>
478
+ </div>
479
+ <div class="fl-link"><i></i></div>
480
+ <div class="fl-col">
481
+ <div class="fl-node fl-hub"><svg class="ghost-mid" aria-hidden="true" focusable="false"><use href="#ghost"/></svg><b>ChimericMesh hub</b><span>groups errors into incidents</span></div>
482
+ </div>
483
+ <div class="fl-link"><i></i></div>
484
+ <div class="fl-col">
485
+ <div class="fl-node"><b>Your AI agent</b><span>reads and proposes over MCP</span></div>
486
+ <div class="fl-node fl-you"><b>You</b><span>approve or deny</span></div>
487
+ </div>
488
+ </div>
489
+ <ol class="hm-steps">
490
+ <li><span class="st-n">01</span><h3>Listen</h3><p>Point your old servers at the hub. It reads Syslog over UDP and TCP, IRC channels, Telnet sessions and log files.</p></li>
491
+ <li><span class="st-n">02</span><h3>Group</h3><p>Repeated errors become one incident, with a likely cause and a hint about where in your code to look.</p></li>
492
+ <li><span class="st-n">03</span><h3>Approve</h3><p>Your agent proposes a fix over MCP. Nothing runs until you approve it here or on IRC.</p></li>
493
+ </ol>
494
+ </div></section>
495
+ <section class="hm-sec" aria-labelledby="home-live-h"><div class="hm-wrap">
496
+ <p class="hm-eyebrow">Live from this hub</p>
497
+ <h2 id="home-live-h" tabindex="-1">What this hub has seen</h2>
498
+ <dl id="homeStrip" class="hm-stats"></dl>
499
+ <p id="homeStripNote" class="hm-line"></p>
500
+ </div></section>
501
+ <section class="hm-sec" aria-labelledby="install-h"><div class="hm-wrap">
502
+ <p class="hm-eyebrow">Install</p>
503
+ <h2 id="install-h" tabindex="-1">Install in one command</h2>
504
+ <p class="hm-line">Python 3.11 or newer. Then run <code>chimericmesh</code> and open port 8000 on this computer.</p>
505
+ <div class="hm-install">
506
+ <div class="hm-card">
507
+ <h3>From GitHub</h3>
508
+ <div class="hm-cmd"><code data-cmd="pipx-git"></code><button class="ghost small" type="button" data-copy="pipx-git" aria-label="Copy the pipx command for GitHub">Copy</button></div>
509
+ <div class="hm-cmd"><code data-cmd="uvx-git"></code><button class="ghost small" type="button" data-copy="uvx-git" aria-label="Copy the uvx command for GitHub">Copy</button></div>
510
+ </div>
511
+ <div class="hm-card">
512
+ <h3>From PyPI</h3>
513
+ <div class="hm-cmd"><code data-cmd="pipx-pypi"></code><button class="ghost small" type="button" data-copy="pipx-pypi" aria-label="Copy the pipx command for PyPI">Copy</button></div>
514
+ <div class="hm-cmd"><code data-cmd="uvx-pypi"></code><button class="ghost small" type="button" data-copy="uvx-pypi" aria-label="Copy the uvx command for PyPI">Copy</button></div>
515
+ </div>
516
+ <div class="hm-card hm-wide">
517
+ <h3>Use it from Kiro</h3>
518
+ <p class="hm-line">Add this to your MCP settings, and Kiro can read and propose.</p>
519
+ <div class="hm-cmd hm-mcp"><pre id="homeMcp"></pre><button class="ghost small" type="button" id="copyMcp" aria-label="Copy the Kiro MCP settings">Copy</button></div>
520
+ </div>
521
+ </div>
522
+ <p id="homeCopyMsg" class="vh" role="status" aria-live="polite"></p>
523
+ </div></section>
524
+ <section class="hm-sec hm-close" aria-labelledby="close-h"><div class="hm-wrap">
525
+ <svg class="ghost-big" aria-hidden="true" focusable="false"><use href="#ghost"/></svg>
526
+ <h2 id="close-h" tabindex="-1">Try the sample apps first</h2>
527
+ <p class="hm-line">Three small apps fail on purpose, on this computer only. Watch the hub find them, then approve a fix. Leave when you like. Everything is thrown away.</p>
528
+ <div class="hm-cta">
529
+ <button type="button" id="homeDemo2" data-demo-btn>Try the demo</button>
530
+ <button class="ghost" type="button" data-go="overview">Open app</button>
531
+ </div>
532
+ <p id="homeDemoStatus2" class="hm-status"></p>
533
+ </div></section>
534
+ <footer class="hm-foot"><div class="hm-wrap"><span id="homeVersion"></span><span>Runs on this computer by default.</span></div></footer>
535
+ </div><!-- /view-home -->
536
+ <div id="view-overview" data-view="overview" hidden>
537
+ <section class="stats" aria-label="Statistics" id="stats"></section>
538
+
539
+ <div id="decideStrip" class="decide" role="status" hidden>
540
+ <span id="decideText"></span>
541
+ <button type="button" id="decideReview">Review</button>
542
+ </div>
543
+
544
+ <section id="guide" aria-labelledby="guide-h" class="hidden">
545
+ <div class="guide-head">
546
+ <h2 id="guide-h">Getting started</h2>
547
+ <span class="meta" id="guideProgress"></span>
548
+ <button class="ghost small" id="guideToggle" type="button">Hide guide</button>
549
+ </div>
550
+ <div class="bar" id="guideBar" role="progressbar" aria-label="Workflow progress" aria-valuemin="0" aria-valuemax="6" aria-valuenow="0"><i id="guideFill" style="width:0%"></i></div>
551
+ <ol class="steps" id="guideSteps"></ol>
552
+ <div class="meta" id="guideStatus" role="status" aria-live="polite"></div>
553
+ <div class="meta" id="guideLockHint"></div>
554
+ </section>
555
+
556
+ <div class="grid">
557
+ <div class="col left">
558
+ <section id="incPanel" aria-labelledby="inc-h" tabindex="-1" data-tour="incidents">
559
+ <h2 id="inc-h">Haunted incidents</h2>
560
+ <div id="incidents" aria-live="polite"></div>
561
+ </section>
562
+ <section id="propPanel" aria-labelledby="prop-h" tabindex="-1" data-tour="proposals">
563
+ <h2 id="prop-h">Proposals</h2>
564
+ <div class="meta" id="propNote"></div>
565
+ <div id="proposals"></div>
566
+ </section>
567
+ </div>
568
+ <div class="col right">
569
+ <section id="termPanel" aria-labelledby="term-h">
570
+ <h2 id="term-h">ChimericBot terminal</h2>
571
+ <div class="term-wrap">
572
+ <div class="term-log" id="transcript" role="log" aria-live="polite" aria-label="ChimericBot transcript"><div class="tline system" id="termHint">ChimericBot is listening from the shadows. Try !help.</div></div>
573
+ <button class="ghost small hidden" id="newMsgs" type="button">New messages ↓</button>
574
+ </div>
575
+ <form class="prompt" id="termForm" autocomplete="off">
576
+ <span class="glyph" aria-hidden="true">›</span>
577
+ <label class="sr" for="termInput">Terminal command</label>
578
+ <input type="text" id="termInput" maxlength="200" autocomplete="off" spellcheck="false" aria-label="Terminal command" placeholder="type !help">
579
+ <button type="submit">Send</button>
580
+ </form>
581
+ <div class="chips" id="chips">
582
+ <button class="ghost small" type="button" data-cmd="!help">!help</button>
583
+ <button class="ghost small" type="button" data-cmd="!status">!status</button>
584
+ <button class="ghost small" type="button" data-cmd="!incidents">!incidents</button>
585
+ <button class="ghost small" type="button" data-cmd="!proposals">!proposals</button>
586
+ <span class="spacer"></span>
587
+ <button class="ghost small" type="button" id="termClear">Clear</button>
588
+ </div>
589
+ <div class="meta" id="termStatus" role="status" aria-live="polite"></div>
590
+ <div class="meta" id="identity" style="margin-top:8px"></div>
591
+ <div class="meta">Press / to focus, Tab to complete, ↑↓ for history.</div>
592
+ </section>
593
+ <section id="evPanel" aria-labelledby="ev-h">
594
+ <h2 id="ev-h">Séance log</h2>
595
+ <div class="log" id="events"></div>
596
+ <form class="send" id="sendForm">
597
+ <label class="sr" for="source">Protocol</label>
598
+ <select id="source"><option>syslog</option><option>irc</option><option>telnet</option></select>
599
+ <label class="sr" for="line">Log line</label>
600
+ <input type="text" id="line" placeholder="e.g. kernel: Out of memory: Kill process 4412" maxlength="500" required>
601
+ <button type="submit">Send</button>
602
+ </form>
603
+ </section>
604
+ </div>
605
+ </div>
606
+ </div>
607
+ <div id="view-services" data-view="services" hidden>
608
+ <section aria-labelledby="svc-h">
609
+ <div class="guide-head">
610
+ <h2 id="svc-h">Services</h2>
611
+ <button class="ghost small" type="button" id="svcAdd">Add service</button>
612
+ </div>
613
+ <div id="svcFormBox"></div>
614
+ <div id="svcList" class="svc-grid"></div>
615
+ </section>
616
+ </div>
617
+ <div id="view-service" data-view="service" hidden>
618
+ <section id="svcDetail" aria-labelledby="svcName">
619
+ <a href="#/services" id="svcCrumb">All services</a>
620
+ <div class="svc-title"><h2 id="svcName">Service</h2><span id="svcPill" class="pill" hidden></span><span id="svcMuted" class="pill muted" hidden></span></div>
621
+ <dl class="facts">
622
+ <dt>Id</dt><dd id="svcId"></dd>
623
+ <dt>State</dt><dd id="svcState"></dd>
624
+ <dt>Last seen</dt><dd id="svcSeen"></dd>
625
+ <dt>Errors per minute</dt><dd id="svcRate"></dd>
626
+ <dt>Open incidents</dt><dd id="svcOpen"></dd>
627
+ </dl>
628
+ <p id="svcHint" class="meta" role="status" hidden></p>
629
+ <p><button class="ghost small" type="button" id="svcHintEdit" hidden>Edit this service</button></p>
630
+ <p id="svcDropped" class="meta" hidden></p>
631
+ <div id="svcMute" class="actions" data-tour="mute"></div>
632
+ </section>
633
+ <div data-slot="proposals">
634
+ <section aria-labelledby="svcProp-h">
635
+ <h2 id="svcProp-h">Proposals</h2>
636
+ <div class="meta" id="svcPropNote"></div>
637
+ <div id="svcProposals"></div>
638
+ </section>
639
+ </div>
640
+ <div data-slot="incidents">
641
+ <section aria-labelledby="svcInc-h">
642
+ <h2 id="svcInc-h">Incidents</h2>
643
+ <div id="svcIncidents" aria-live="polite"></div>
644
+ </section>
645
+ </div>
646
+ <div data-slot="live-log">
647
+ <section id="liveLog" aria-labelledby="live-h">
648
+ <h2 id="live-h">Live log</h2>
649
+ <div class="actions live-ctl">
650
+ <button class="ghost small" type="button" id="livePause">Pause</button>
651
+ <div class="field"><label for="liveSev">Minimum severity</label>
652
+ <select id="liveSev">
653
+ <option value="7">all severities</option>
654
+ <option value="6">info or worse</option>
655
+ <option value="5">notice or worse</option>
656
+ <option value="4">warning or worse</option>
657
+ <option value="3">err or worse</option>
658
+ <option value="2">crit or worse</option>
659
+ <option value="1">alert or worse</option>
660
+ <option value="0">emerg only</option>
661
+ </select></div>
662
+ <div class="field"><label for="liveText">Filter text</label>
663
+ <input type="text" id="liveText" maxlength="100" autocomplete="off" spellcheck="false"></div>
664
+ <div class="field inline"><label for="liveAuto">Auto-scroll</label>
665
+ <input type="checkbox" id="liveAuto" checked></div>
666
+ </div>
667
+ <div class="meta" id="liveStatus" role="status" aria-live="polite"></div>
668
+ <div class="log" id="liveBox" role="log" aria-label="Live log rows"></div>
669
+ </section>
670
+ </div>
671
+ <div data-slot="permissions">
672
+ <details id="permPanel" class="perm">
673
+ <summary>Kiro permissions (optional, for hands-off edits)</summary>
674
+ <p>ChimericMesh never writes this file; paste it yourself.</p>
675
+ <p class="meta">The text has two sections: prompt mode (Kiro asks before each change) and autonomous mode.</p>
676
+ <div class="actions"><button class="ghost small" type="button" id="permCopy">Copy</button><span id="permCopyMsg" class="vh" role="status" aria-live="polite"></span></div>
677
+ <pre id="permText" class="sample"></pre>
678
+ <div class="meta" id="permMsg" role="status" aria-live="polite"></div>
679
+ </details>
680
+ </div>
681
+ <section id="svcGone" hidden>
682
+ <p>This service is gone (or never existed). Back to services.</p>
683
+ <button class="ghost" type="button" id="svcBack">Back to services</button>
684
+ </section>
685
+ </div><!-- /view-service -->
686
+ <div id="view-discovery" data-view="discovery" hidden>
687
+ <section aria-labelledby="disc-h">
688
+ <div class="guide-head">
689
+ <h2 id="disc-h">Discovery</h2>
690
+ <span id="discDismissSlot"></span>
691
+ </div>
692
+ <p class="meta" id="discExplainer"></p>
693
+ <div class="meta" id="discLockHint"></div>
694
+ <div class="actions" id="discScanSlot"></div>
695
+ <div id="discScan" class="scan" hidden><div class="scan-bar" aria-hidden="true"></div></div>
696
+ <div class="meta" id="discStatus" role="status" aria-live="polite"></div>
697
+ <div class="meta" id="discLimited"></div>
698
+ <div class="actions" id="discEmptySlot"></div>
699
+ <div id="discList" class="svc-grid"></div>
700
+ </section>
701
+ </div>
702
+ <div id="view-rules" data-view="rules" hidden>
703
+ <section aria-labelledby="rules-h">
704
+ <div class="guide-head">
705
+ <h2 id="rules-h">Approval rules</h2>
706
+ <span class="actions" id="rulesTools"></span>
707
+ </div>
708
+ <p class="meta" id="rulesLegend">Paused rules can be resumed. Revoked rules are gone.</p>
709
+ <div class="meta" id="rulesMsg" role="status" aria-live="polite"></div>
710
+ <div id="ruleFormBox"></div>
711
+ <div class="table-wrap">
712
+ <table class="rules" aria-label="Approval rules">
713
+ <thead><tr>
714
+ <th scope="col">Id</th><th scope="col">Service</th><th scope="col">Matches</th><th scope="col">Severity floor</th>
715
+ <th scope="col">Expires</th><th scope="col">Limits</th><th scope="col">Uses (hour / total)</th>
716
+ <th scope="col">Status</th><th scope="col">Source proposal</th><th scope="col">Actions</th>
717
+ </tr></thead>
718
+ <tbody id="rulesBody"></tbody>
719
+ </table>
720
+ </div>
721
+ </section>
722
+ <section aria-labelledby="audit-h">
723
+ <h2 id="audit-h">Audit trail</h2>
724
+ <div class="actions live-ctl">
725
+ <div class="field"><label for="auditSvc">Service</label>
726
+ <select id="auditSvc"><option value="">all services</option></select></div>
727
+ <div class="field"><label for="auditRule">Rule id</label>
728
+ <input type="text" id="auditRule" maxlength="100" autocomplete="off" spellcheck="false"></div>
729
+ </div>
730
+ <div class="meta" id="auditMsg" role="status" aria-live="polite"></div>
731
+ <div class="table-wrap">
732
+ <table class="rules audit" aria-label="Audit trail">
733
+ <thead><tr>
734
+ <th scope="col">Time</th><th scope="col">Actor</th><th scope="col">Action</th><th scope="col">Subject</th><th scope="col">Detail</th>
735
+ </tr></thead>
736
+ <tbody id="auditBody"></tbody>
737
+ </table>
738
+ </div>
739
+ <div class="actions"><button class="ghost small" type="button" id="auditMore" hidden>Load more</button></div>
740
+ </section>
741
+ </div>
742
+ <pre id="selftest" hidden></pre>
743
+ </main>
744
+ <footer id="hubVersion" class="meta"></footer>
745
+ <aside id="tour" aria-label="Demo tour" role="region" hidden>
746
+ <div class="tour-head"><svg class="ghost-mini" aria-hidden="true" focusable="false"><use href="#ghost"/></svg><h2 id="tourTitle" tabindex="-1"></h2></div>
747
+ <div id="tourLive" aria-live="polite" aria-atomic="true">
748
+ <div id="tourCount" class="tour-count"></div>
749
+ <p id="tourBody"></p>
750
+ </div>
751
+ <div class="tour-actions">
752
+ <button type="button" id="tourBack" class="ghost">Back</button>
753
+ <button type="button" id="tourNext">Next</button>
754
+ <button type="button" id="tourSkip" class="ghost">Skip tour</button>
755
+ </div>
756
+ </aside>
757
+ <div id="toast" role="status" aria-live="polite"></div>
758
+ <script>
759
+ /* ==== PURE ==== */
760
+ /* PURE:begin */
761
+ // Pure functions: no browser global, no request, no storage, no clock. Self-tested by #selftest.
762
+ const SEV_NAMES = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug'];
763
+ const SCHED_SLACK_MS = 100; // a 1 s tick can land a few ms early
764
+ function sevName(n) { const i = Number(n); return Number.isInteger(i) && i >= 0 && i <= 7 ? SEV_NAMES[i] : 'unknown'; }
765
+ function capText(s, n) { const t = s === null || s === undefined ? '' : String(s); return t.length <= n ? t : `${t.slice(0, n)}…`; }
766
+ function relTime(ts, now) {
767
+ if (ts === null || ts === undefined) return 'never';
768
+ const d = now - ts;
769
+ if (!(d >= 5)) return 'just now';
770
+ if (d < 60) return `${Math.floor(d)} s ago`;
771
+ if (d < 3600) return `${Math.floor(d / 60)} min ago`;
772
+ if (d < 86400) return `${Math.floor(d / 3600)} h ago`;
773
+ return `${Math.floor(d / 86400)} d ago`;
774
+ }
775
+ function countdown(ts, now) {
776
+ const d = ts - now;
777
+ if (!(d > 0)) return 'expired';
778
+ if (d >= 86400) return `${Math.floor(d / 86400)} d ${Math.floor((d % 86400) / 3600)} h`;
779
+ if (d >= 3600) return `${Math.floor(d / 3600)} h ${Math.floor((d % 3600) / 60)} min`;
780
+ return `${Math.max(1, Math.floor(d / 60))} min`;
781
+ }
782
+ const STATE_LABELS = {
783
+ service: { active: 'active', idle: 'idle', never_seen: 'never seen' },
784
+ source: { running: 'running', missing: 'missing', unreadable: 'unreadable', error: 'error', stopped: 'stopped', unknown: 'unknown' },
785
+ rule: { active: 'active', suspended: 'suspended', revoked: 'revoked', expired: 'expired' },
786
+ proposal: { pending: 'pending', approved: 'approved', denied: 'denied', done: 'done', withdrawn: 'withdrawn' },
787
+ };
788
+ function stateLabel(kind, value) {
789
+ const table = STATE_LABELS[kind] || {};
790
+ return Object.prototype.hasOwnProperty.call(table, value) ? table[value] : 'unknown';
791
+ }
792
+ function nextBackoff(n) { const k = Number.isInteger(n) && n > 0 ? n : 0; return Math.min(30, 2 ** Math.min(k, 5)); }
793
+ function errorText(status, body) {
794
+ const detail = body && typeof body === 'object' ? body.detail : undefined;
795
+ let text = '';
796
+ if (typeof detail === 'string' && detail) text = detail;
797
+ else if (Array.isArray(detail) && detail.length) {
798
+ text = detail.map((d) => {
799
+ const loc = Array.isArray(d && d.loc) ? d.loc.filter((p) => p !== 'body' && p !== 'query' && p !== 'path').join('.') : '';
800
+ const msg = d && typeof d.msg === 'string' ? d.msg : 'invalid';
801
+ return loc ? `${loc}: ${msg}` : msg;
802
+ }).join('; ');
803
+ }
804
+ if (!text) return `HTTP ${status}`;
805
+ const field = body && typeof body.field === 'string' && body.field ? body.field : '';
806
+ return field ? `${field}: ${text}` : text;
807
+ }
808
+ function parseRoute(hash) {
809
+ const h = String(hash || '');
810
+ const m = /^#\/services\/([^/?#]+)$/.exec(h);
811
+ if (m) {
812
+ let id = '';
813
+ try { id = decodeURIComponent(m[1]); } catch (e) { id = ''; }
814
+ return /^[a-z0-9][a-z0-9-]{0,39}$/.test(id) ? { view: 'service', id } : { view: 'services' };
815
+ }
816
+ if (h === '#/services') return { view: 'services' };
817
+ if (h === '#/discovery') return { view: 'discovery' };
818
+ if (h === '#/rules') return { view: 'rules' };
819
+ if (h === '#/overview') return { view: 'overview' };
820
+ return { view: 'home' }; // '', '#/', '#/home' and anything unknown: Home on every visit, no stored flag
821
+ }
822
+ function dueTasks(tasks, now, view, visible) {
823
+ if (!visible) return [];
824
+ return tasks.filter((t) => (t.view === '*' || t.view === view) && now - t.last + SCHED_SLACK_MS >= t.every).map((t) => t.id);
825
+ }
826
+ function rowMatches(ev, minSev, text) {
827
+ const sev = Number(ev && ev.severity);
828
+ if (Number.isFinite(minSev) && !(sev <= minSev)) return false;
829
+ const t = String(text === null || text === undefined ? '' : text).toLowerCase();
830
+ if (!t) return true;
831
+ return `${ev.host || ''} ${ev.app || ''} ${ev.message || ''}`.toLowerCase().includes(t);
832
+ }
833
+ function approvalText(p) {
834
+ const a = p && p.approval;
835
+ if (!a || typeof a !== 'object') return '';
836
+ if (a.by === 'user') return `approved by ${p.decided_by || 'a user'}`;
837
+ if (a.by === 'rule') {
838
+ const st = a.rule_status_now;
839
+ const known = st === 'active' || st === 'suspended' || st === 'revoked' || st === 'expired';
840
+ return `auto-approved by rule ${a.rule_id} (${known ? `rule ${st}` : 'rule status unknown'})`;
841
+ }
842
+ return '';
843
+ }
844
+ // Rule form helpers (7.3, 8.2). Numbers come from the hub's bounds when it sent them, else from the fallbacks.
845
+ function canMakeRule(p) {
846
+ const a = p && p.approval;
847
+ return Boolean(a && a.by === 'user' && (p.status === 'approved' || (p.status === 'done' && p.verification_result === 'passed')));
848
+ }
849
+ function boundOf(bounds, key, fallback) {
850
+ const b = bounds && typeof bounds === 'object' ? bounds[key] : null;
851
+ const src = b && typeof b === 'object' ? b : {};
852
+ const num = (v, d) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
853
+ return { min: num(src.min, fallback.min), max: num(src.max, fallback.max), default: num(src.default, fallback.default) };
854
+ }
855
+ function clampInt(v, lo, hi) {
856
+ const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
857
+ if (typeof n !== 'number' || !Number.isFinite(n)) return null;
858
+ return Math.min(hi, Math.max(lo, Math.round(n)));
859
+ }
860
+ function sevFloorText(n) {
861
+ const i = Number(n);
862
+ return Number.isInteger(i) && i >= 0 && i <= 7 ? `${sevName(i)} (${i}) or more urgent` : 'unknown';
863
+ }
864
+ // The hub takes an absolute expires_at; the form shows days. Computed from the hub's own default (7 days),
865
+ // never from the browser clock; n is clamped to 1..29 so the 30 day cap cannot be passed.
866
+ function expiryFromDays(serverExpiryDefault, n) {
867
+ if (typeof serverExpiryDefault !== 'number' || !Number.isFinite(serverExpiryDefault)) return null;
868
+ if (typeof n !== 'number' || !Number.isInteger(n)) return null;
869
+ return serverExpiryDefault + (Math.min(29, Math.max(1, n)) - 7) * 86400;
870
+ }
871
+ // The fields of a rule form that differ from the hub's defaults (the proposal route takes only these).
872
+ function ruleOverrides(defaults, v) {
873
+ const out = {};
874
+ for (const k of ['most_urgent_severity', 'max_per_hour', 'max_per_incident', 'max_files', 'max_lines']) {
875
+ if (v[k] !== null && v[k] !== undefined && v[k] !== defaults[k]) out[k] = v[k];
876
+ }
877
+ const when = expiryFromDays(defaults.expires_at, v.days);
878
+ if (v.days !== 7 && when !== null) out.expires_at = when;
879
+ if (typeof v.note === 'string' && v.note !== (defaults.note || '')) out.note = v.note;
880
+ return out;
881
+ }
882
+ // Union by id, newest first; the arrays it is given are never changed.
883
+ function mergeAudit(existing, incoming) {
884
+ const byId = new Map();
885
+ for (const r of existing || []) byId.set(r.id, r);
886
+ for (const r of incoming || []) byId.set(r.id, r);
887
+ return Array.from(byId.values()).sort((a, b) => b.id - a.id);
888
+ }
889
+ // The text of the decide strip (UX-01): how many fixes wait and, for the newest, what it does. '' when none waits.
890
+ function decideText(pending) {
891
+ const list = Array.isArray(pending) ? pending : [];
892
+ if (!list.length) return '';
893
+ const newest = list.reduce((a, b) => ((b.created || 0) >= (a.created || 0) ? b : a));
894
+ const what = capText(newest.action, 80);
895
+ return list.length === 1 ? `A fix is waiting for you: ${what}` : `${list.length} fixes are waiting for you. Newest: ${what}`;
896
+ }
897
+ // The confirmation text of a finished action (UX-03, UX-17). The id is shown as text only.
898
+ function actionToast(kind, id) {
899
+ const i = capText(id, 40);
900
+ if (kind === 'approve') return `Approved ${i}. The agent will apply it; this card turns "done" when it reports back.`;
901
+ if (kind === 'deny') return `Denied ${i}. The agent will not run it.`;
902
+ if (kind === 'withdraw') return `Withdrew ${i}. Nothing will run.`;
903
+ if (kind === 'resolve') return `Laid ${i} to rest. If the errors return, it can reopen.`;
904
+ if (kind === 'unconfirmed') return `Could not confirm that ${i} was laid to rest. The terminal shows what the hub said.`;
905
+ if (kind === 'storm') return 'A failure storm is on its way. Incidents appear in a few seconds.';
906
+ return '';
907
+ }
908
+ // What to tell the user when a request failed; status 0 means the hub did not answer (UX-23).
909
+ function friendlyError(status) {
910
+ if (!Number.isInteger(status) || status <= 0) return 'The mesh went quiet. Check that the hub is running, then try again.';
911
+ return `The mesh turned that away (status ${status}). Try again or check the hub log.`;
912
+ }
913
+ const TOKEN_REJECTED_TEXT = 'That token was not accepted. The ghost wants the exact line from the token file.';
914
+ // The result of the check made when the user saves a token: ok only when the hub accepted it (UX-04).
915
+ function unlockOutcome(status) {
916
+ if (status === 200) return { ok: true, text: 'Unlocked' };
917
+ if (status === 401) return { ok: false, text: TOKEN_REJECTED_TEXT };
918
+ return { ok: false, text: friendlyError(status) };
919
+ }
920
+ // F2: the header says "Unlocked" in one place, #lockText. The status line says nothing on success.
921
+ function headerLockText(hasToken, ls) { return hasToken ? 'Unlocked' : (ls && ls.locked ? 'Locked: view only' : ''); }
922
+ function unlockStatusText(out, kept) { return !out || out.ok ? (kept ? '' : 'token kept for this tab only') : out.text; }
923
+ // What a finished proposal says about the loop (UX-18): the pill text, a warning, and whether the incident can be laid to rest.
924
+ function closeLoop(p, inc) {
925
+ const done = Boolean(p) && p.status === 'done';
926
+ const passed = done && p.verification_result === 'passed';
927
+ const failed = done && p.verification_result === 'failed';
928
+ return {
929
+ pill: passed ? 'done, tests passed' : '',
930
+ warn: failed ? 'Tests failed. Deny it and ask the agent for another fix.' : '',
931
+ rest: passed && !(inc && inc.resolved),
932
+ };
933
+ }
934
+ // The line on an incident card about its newest live proposal (pending, approved or done); '' when none.
935
+ function fixLine(proposals, incidentId) {
936
+ const live = (Array.isArray(proposals) ? proposals : []).filter((p) => String(p.incident_id) === String(incidentId) && ['pending', 'approved', 'done'].includes(p.status));
937
+ if (!live.length) return '';
938
+ const p = live.reduce((a, b) => ((b.created || 0) >= (a.created || 0) ? b : a));
939
+ return `fix #${capText(p.id, 20)} ${stateLabel('proposal', p.status)}`;
940
+ }
941
+ // How many pending proposals belong to one service.
942
+ function pendingFor(proposals, serviceId) {
943
+ return (Array.isArray(proposals) ? proposals : []).filter((p) => p.status === 'pending' && p.service_id === serviceId).length;
944
+ }
945
+ // The counters on the Services and Rules tabs: visible text and the accessible name for each.
946
+ function navBadges(incidents, proposals, rules, paused) {
947
+ const n = (Array.isArray(incidents) ? incidents : []).filter((i) => !i.resolved && i.service_id).length
948
+ + (Array.isArray(proposals) ? proposals : []).filter((p) => p.status === 'pending').length;
949
+ const susp = (Array.isArray(rules) ? rules : []).filter((r) => r.status === 'suspended').length;
950
+ const services = n > 0 ? { text: String(n), label: `Services, ${n} waiting` } : { text: '', label: 'Services' };
951
+ let r = { text: '', label: 'Rules' };
952
+ if (paused) r = { text: 'paused', label: 'Rules, auto-approval paused' };
953
+ else if (susp > 0) r = { text: String(susp), label: `Rules, ${susp} paused` };
954
+ return { services, rules: r };
955
+ }
956
+ function isNewer(id, lastId) { return typeof id === 'number' && Number.isFinite(id) && id > lastId; }
957
+ function lockState(uiConfig, hasToken) {
958
+ const flag = uiConfig ? uiConfig.enforce_access : null;
959
+ if (flag === true) return { locked: !hasToken, mode: 'enforced' };
960
+ if (flag === false) return { locked: false, mode: 'off' };
961
+ return { locked: false, mode: 'unknown' };
962
+ }
963
+ function afterAuthFailure(status, hadToken, retryAfter) {
964
+ if (status === 401) return hadToken ? { clearToken: true, text: 'token rejected' } : { clearToken: false, text: 'unlock first' };
965
+ if (status === 403) return { clearToken: false, text: 'blocked by the hub: open this page at the address the hub printed' };
966
+ if (status === 429) return { clearToken: false, text: Number(retryAfter) > 0 ? `too many requests, try again in ${Math.floor(Number(retryAfter))} s` : 'too many requests, try again later' };
967
+ return { clearToken: false, text: '' };
968
+ }
969
+ // Routes that need the admin token (method, path pattern). Taken from the route tables of the services,
970
+ // discovery and auto-approval designs; POST /api/terminal is conditional (only !approve and !deny check it).
971
+ const PRIVILEGED = [
972
+ ['POST', '^/api/services$'],
973
+ ['PATCH', '^/api/services/[^/]+$'],
974
+ ['DELETE', '^/api/services/[^/]+$'],
975
+ ['POST', '^/api/services/[^/]+/log-sources$'],
976
+ ['PATCH', '^/api/services/[^/]+/log-sources/[^/]+$'],
977
+ ['DELETE', '^/api/services/[^/]+/log-sources/[^/]+$'],
978
+ ['PUT', '^/api/services/[^/]+/mute$'],
979
+ ['POST', '^/api/discovery/scan$'],
980
+ ['GET', '^/api/discovery/scans/[^/]+$'],
981
+ ['POST', '^/api/discovery/suggestions/[^/]+/accept$'],
982
+ ['POST', '^/api/discovery/suggestions/[^/]+/dismiss$'],
983
+ ['GET', '^/api/discovery/dismissals$'],
984
+ ['DELETE', '^/api/discovery/dismissals$'],
985
+ ['POST', '^/api/rules$'],
986
+ ['PATCH', '^/api/rules/[^/]+$'],
987
+ ['POST', '^/api/rules/[^/]+/enable$'],
988
+ ['POST', '^/api/rules/resume$'],
989
+ ['POST', '^/api/proposals/[^/]+/rule$'],
990
+ ['POST', '^/api/proposals/[^/]+/decide$'],
991
+ ['POST', '^/api/terminal$'],
992
+ ];
993
+ // Sent when a token is stored, harmless when the route is open (agent-loop owns the route).
994
+ const SEND_IF_PRESENT = [['GET', '^/api/services/[^/]+/permissions-snippet$']];
995
+ function matchesTable(table, method, path) {
996
+ const p = String(path).split('?')[0];
997
+ return table.some(([m, rx]) => m === method && new RegExp(rx).test(p));
998
+ }
999
+ function needsToken(method, path) { return matchesTable(PRIVILEGED, method, path); }
1000
+ function sendsTokenIfPresent(method, path) { return needsToken(method, path) || matchesTable(SEND_IF_PRESENT, method, path); }
1001
+ // Lock registry: true needs the token (disabled while locked), false is a reduce action (always enabled),
1002
+ // 'conditional' is never disabled and sends the token when one is stored.
1003
+ const ACTIONS = {
1004
+ 'svc-save': true, 'svc-source-edit': true, 'svc-mute': true, 'scan-start': true, 'suggestion-accept': true,
1005
+ 'suggestion-dismiss': true, 'dismissals-clear': true, 'proposal-approve': true, 'proposal-deny': true,
1006
+ 'rule-create': true, 'rule-edit': true, 'rule-enable': true, 'rules-resume': true, 'rule-from-proposal': true,
1007
+ 'rules-pause-all': false, 'rule-pause': false, 'rule-revoke': false, 'proposal-withdraw': false,
1008
+ 'terminal-send': 'conditional',
1009
+ };
1010
+ function actionNeedsToken(id) { return Object.prototype.hasOwnProperty.call(ACTIONS, id) && ACTIONS[id] === true; }
1011
+ function tokenShapeOk(s) { return typeof s === 'string' && /^[\x21-\x7e]{1,200}$/.test(s); }
1012
+ // Used when GET /api/ui-config fails: the access mode is unknown, nothing is locked (the hub decides).
1013
+ const UI_FALLBACK = {
1014
+ enforce_access: null, token_file: null,
1015
+ formats: ['syslog-text', 'ncsa', 'w3c', 'xferlog', 'plain'],
1016
+ protocols: ['syslog-udp', 'syslog-tcp', 'telnet', 'irc', 'file'],
1017
+ };
1018
+ // Open incidents first, then the error rate (highest first), the built-in card last on a tie, then the name.
1019
+ function sortServices(list) {
1020
+ const key = (s) => [Number(s.open_incidents) > 0 ? 0 : 1, -(Number(s.error_rate) || 0), s.builtin ? 1 : 0];
1021
+ return list.slice().sort((a, b) => {
1022
+ const x = key(a), y = key(b);
1023
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return x[i] - y[i];
1024
+ const na = String(a.name), nb = String(b.name);
1025
+ return na < nb ? -1 : na > nb ? 1 : 0;
1026
+ });
1027
+ }
1028
+ // A service id suggested from a name: lower case letters and digits joined by single hyphens, at most 40 characters.
1029
+ // Empty when nothing usable is left or the result is the reserved id.
1030
+ function slugify(name) {
1031
+ const s = String(name === null || name === undefined ? '' : name).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
1032
+ return s === 'unassigned' ? '' : s;
1033
+ }
1034
+ // The App names value suggested from a service name. A plain one-word name is kept as typed (apps log as 'proxy-worker', 'nginx.exe').
1035
+ // Anything else (spaces, brackets, commas) could never be a syslog app name, so it becomes the slug. '' when nothing usable is left.
1036
+ function defaultAppNames(name) {
1037
+ const t = String(name === null || name === undefined ? '' : name).trim();
1038
+ return /^[A-Za-z0-9._-]+$/.test(t) ? t.slice(0, 64) : slugify(t);
1039
+ }
1040
+ // Which form field the never-matched hint button should focus. '' (no button) unless the service never matched and can be edited.
1041
+ function hintEditField(s) {
1042
+ if (!s || s.state !== 'never_seen' || s.builtin) return '';
1043
+ return Array.isArray(s.app_names) && s.app_names.length ? 'svcFName' : 'svcFApps';
1044
+ }
1045
+ // Audit display: the raw values stay in the data and in tooltips; the table shows plain words.
1046
+ function actorText(a) {
1047
+ const s = String(a === null || a === undefined ? '' : a);
1048
+ if (s.startsWith('rest:')) return 'API';
1049
+ if (s.startsWith('client:')) return 'browser';
1050
+ return s;
1051
+ }
1052
+ function actionText(a) { return String(a === null || a === undefined ? '' : a).replace(/_/g, ' '); }
1053
+ function subjectText(x) {
1054
+ const s = String(x === null || x === undefined ? '' : x);
1055
+ if (!/^[A-Z]+ \/api\//.test(s)) return s;
1056
+ return s.includes('/decide') ? 'a decision request' : 'an API request';
1057
+ }
1058
+ function splitList(text) { return String(text === null || text === undefined ? '' : text).split(',').map((x) => x.trim()).filter((x) => x); }
1059
+ // The create body: code_folder only when given (the server treats a missing key as "none").
1060
+ function serviceCreateBody(form) {
1061
+ const body = { id: form.id, name: form.name, hosts: form.hosts, app_names: form.app_names, protocols: form.protocols };
1062
+ if (form.code_folder) body.code_folder = form.code_folder;
1063
+ return body;
1064
+ }
1065
+ // The PATCH body: changed fields only; a cleared code folder is sent as null (services maps it to "clear").
1066
+ function servicePatch(original, form) {
1067
+ const out = {};
1068
+ if (form.name !== original.name) out.name = form.name;
1069
+ for (const k of ['hosts', 'app_names', 'protocols']) {
1070
+ if (JSON.stringify(form[k]) !== JSON.stringify(original[k] || [])) out[k] = form[k];
1071
+ }
1072
+ const was = original.code_folder || '';
1073
+ if (form.code_folder !== was) out.code_folder = form.code_folder === '' ? null : form.code_folder;
1074
+ return out;
1075
+ }
1076
+ // Log-source operations for the form. The path of a source cannot change, so a new path is remove + add.
1077
+ function diffSources(oldList, newList) {
1078
+ const old = new Map((oldList || []).map((s) => [s.id, s]));
1079
+ const add = [], update = [], remove = [], kept = new Set();
1080
+ (newList || []).forEach((row, index) => {
1081
+ const prev = row.id ? old.get(row.id) : undefined;
1082
+ if (prev && prev.path === row.path) {
1083
+ kept.add(row.id);
1084
+ const patch = {};
1085
+ if (row.format !== prev.format) patch.format = row.format;
1086
+ if (Boolean(row.enabled) !== Boolean(prev.enabled)) patch.enabled = Boolean(row.enabled);
1087
+ if (Object.keys(patch).length) update.push({ id: row.id, patch });
1088
+ } else if (row.path) add.push({ index, path: row.path, format: row.format, enabled: Boolean(row.enabled) });
1089
+ });
1090
+ for (const s of oldList || []) if (!kept.has(s.id)) remove.push(s.id);
1091
+ return { add, update, remove };
1092
+ }
1093
+ // Discovery accept body: exactly id, name, log_paths, plus code_folder and app_names only when non-empty.
1094
+ function buildAcceptBody(form) {
1095
+ const body = {
1096
+ id: form.id, name: form.name,
1097
+ log_paths: (form.rows || []).filter((r) => r.checked && !r.watched_by).map((r) => ({ path: r.path, format: r.format })),
1098
+ };
1099
+ const cf = String(form.code_folder || '').trim();
1100
+ if (cf) body.code_folder = cf;
1101
+ const apps = Array.isArray(form.app_names) ? form.app_names.filter((a) => a) : [];
1102
+ if (apps.length) body.app_names = apps;
1103
+ return body;
1104
+ }
1105
+ // The header storm button text: the same action as guide step 1, so it is a quiet ghost button, and says "Another" once an incident exists (UX-13).
1106
+ function stormLabel(count) { return Number.isInteger(count) && count > 0 ? 'Another storm' : 'Summon a failure storm'; }
1107
+ // The line under the guide while locked: step 5 (decide) needs the admin token (UX-12). '' when nothing to say.
1108
+ function guideLockText(w, locked) { return locked && w && !w.complete ? 'Step 5 needs the admin token. Unlock first.' : ''; }
1109
+ // F3: why a service page shows nothing. '' unless the service never matched an event (D13: no retroactive tagging).
1110
+ function serviceMatchHint(s) {
1111
+ if (!s || s.state !== 'never_seen') return '';
1112
+ const has = (v) => Array.isArray(v) && v.length > 0;
1113
+ if (!has(s.hosts) && !has(s.app_names) && !has(s.log_sources)) {
1114
+ return 'No app name, host or log file is set, so no event can reach this service. Edit it and add the app name your program logs as.';
1115
+ }
1116
+ return 'No event has matched yet. Events that arrived before this service existed stay under Unassigned.';
1117
+ }
1118
+ // The footer line with the hub version, so a stale hub is visible. '' when the hub sends none.
1119
+ function versionText(cfg) { return cfg && typeof cfg.version === 'string' && cfg.version ? `ChimericMesh ${cfg.version}` : ''; }
1120
+ // F4: the Discovery waiting text and the empty result. Counts come from the hub; without them nothing is invented.
1121
+ const KNOWN_APPS_COUNT = 15; // the entries of catalog/legacy_apps.json (a test keeps the two equal)
1122
+ function scanStateText(state) {
1123
+ const t = { starting: 'Starting scan...', running: 'Scanning this machine...', stalled: 'The scan is taking too long. Check again.', expired: 'The scan expired. Run it again.' };
1124
+ return Object.prototype.hasOwnProperty.call(t, state) ? t[state] : '';
1125
+ }
1126
+ function emptyScanText(sc) {
1127
+ const n = (v) => Number.isInteger(v) && v >= 0;
1128
+ const tail = `Nothing matched the ${KNOWN_APPS_COUNT} known apps. A Python script or a custom daemon is not one of them.`;
1129
+ if (!sc || !n(sc.processes_seen) || !n(sc.listeners_seen)) return tail;
1130
+ const p = sc.processes_seen, l = sc.listeners_seen;
1131
+ const why = sc.limited && typeof sc.reason === 'string' && sc.reason ? ` The scan was limited (${sc.reason.slice(0, 120)}), so it may have missed apps.` : '';
1132
+ return `Looked at ${p} ${p === 1 ? 'process' : 'processes'} and ${l} listening ${l === 1 ? 'port' : 'ports'}. ${tail}${why}`;
1133
+ }
1134
+ // Mute (demo-mode R3.9). Mute needs the admin token and is disabled while locked; Unmute never needs it.
1135
+ function muteLabel(muted, locked) {
1136
+ const on = Boolean(muted);
1137
+ const off = !on && Boolean(locked);
1138
+ return { text: on ? 'Unmute' : 'Mute', pressed: on, disabled: off, title: off ? 'unlock first' : '' };
1139
+ }
1140
+ function muteAriaLabel(muted, name) { return `${muted ? 'Unmute' : 'Mute'} ${capText(name, 60)}`; }
1141
+ function droppedText(n) {
1142
+ if (!Number.isInteger(n) || n <= 0) return '';
1143
+ return `${n} ${n === 1 ? 'event' : 'events'} dropped since the hub started`;
1144
+ }
1145
+ function mutePillText(s) { return s && s.muted === true ? 'Muted' : ''; }
1146
+ function mutedIdsOf(m) { return m && Array.isArray(m.muted) ? m.muted.map((x) => (x ? x.service_id : null)).filter((x) => typeof x === 'string') : []; }
1147
+ // An open incident of a muted service stays listed and says so; one with no service belongs to Unassigned.
1148
+ function mutedIncidentTag(incident, mutedIds) {
1149
+ if (!incident || !Array.isArray(mutedIds)) return '';
1150
+ return mutedIds.includes(incident.service_id ? String(incident.service_id) : 'unassigned') ? 'muted' : '';
1151
+ }
1152
+ const MUTE_UNASSIGNED_TEXT = 'Every event that matches no service will be dropped: not stored, not counted, no incident. Mute Unassigned?';
1153
+ function muteToast(kind, name) {
1154
+ const n = capText(name, 40);
1155
+ if (kind === 'mute') return `Muted ${n}. Its events are dropped until you unmute it.`;
1156
+ if (kind === 'unmute') return `Unmuted ${n}. Its events count again from now.`;
1157
+ return '';
1158
+ }
1159
+ /* PURE:end */
1160
+
1161
+ /* HOME:begin */
1162
+ // Pure helpers of the Home view and the "Try the demo" flow. They sit outside the PURE block because the in-page
1163
+ // self-test is capped at 200 lines; tests/unit/test_dashboard_home.py runs them through node. Same rules as PURE:
1164
+ // no browser global, no request, no storage, no clock (the caller passes `now`).
1165
+ const DEMO_POLL_MS = 500;
1166
+ const DEMO_TIMEOUT_MS = 20000;
1167
+ const COPY_RESET_MS = 2000; // a Copy button says Copied or Copy failed for this long, then Copy again
1168
+ const NOTICE_HIDE_MS = 8000; // the Home notice hides itself after this long, unless the pointer or the focus is on it
1169
+ // The page holds no literal address, so the "no external origin" test stays strict: schemes are joined here.
1170
+ const SCHEME_HTTP = 'http' + '://';
1171
+ const GIT_PREFIX = 'git+' + 'https' + '://github.com/HarshitDhaduk/chimericmesh';
1172
+ const HOME_INSTALL = [
1173
+ { id: 'pipx-git', cmd: `pipx install ${GIT_PREFIX}` },
1174
+ { id: 'uvx-git', cmd: `uvx --from ${GIT_PREFIX} chimericmesh` },
1175
+ { id: 'pipx-pypi', cmd: 'pipx install chimericmesh' },
1176
+ { id: 'uvx-pypi', cmd: 'uvx chimericmesh' },
1177
+ ];
1178
+ const HOME_MCP = JSON.stringify({ mcpServers: { chimericmesh: { command: 'chimericmesh', args: ['mcp'], env: { CHIMERICMESH_URL: `${SCHEME_HTTP}127.0.0.1:8000` } } } }, null, 2).replace(/\[\s+"mcp"\s+\]/, '["mcp"]');
1179
+ const HOME_COPY = {
1180
+ starting: 'Starting the sample apps...',
1181
+ ready: 'The demo is ready. Opening it...',
1182
+ timeout: 'The demo took more than 20 seconds to start. Nothing on your machine was changed.',
1183
+ closed: 'Demo closed. Your data was not touched.',
1184
+ copied: 'Copied to the clipboard.',
1185
+ copyManual: 'Copy failed. The text is selected: press Ctrl+C to copy it.',
1186
+ stripEmpty: 'Nothing has arrived yet. Point a Syslog sender at this hub, or try the demo.',
1187
+ stripQuiet: 'Quiet right now. The ghost is watching.',
1188
+ hintWait: 'Waiting for the sample apps to fail. The first incident shows up in about 20 seconds.',
1189
+ hintReview: 'A fix is waiting. On Overview, tap Review, read it, then approve or deny.',
1190
+ hintOpen: 'Open an incident to read its diagnosis, then approve or deny the proposed fix.',
1191
+ running: 'A demo is still running on this computer.',
1192
+ exiting: 'Closing the demo...',
1193
+ };
1194
+ // A Copy button's own label after a try (ok or not), and the sentence the hidden live region says.
1195
+ function copyFeedback(ok) { return ok ? { label: 'Copied', say: HOME_COPY.copied } : { label: 'Copy failed', say: HOME_COPY.copyManual }; }
1196
+ function countOf(v) { const n = Number(v); return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0; }
1197
+ function groupDigits(n) { return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ','); }
1198
+ // prev {state, since}, status: the hub's answer {state, reason?} or null. Success beats the clock; 20 s ends a wait.
1199
+ function demoStartState(prev, status, now) {
1200
+ const st = status && typeof status === 'object' && typeof status.state === 'string' ? status.state : '';
1201
+ if (st === 'running') return { state: 'ready', text: HOME_COPY.ready, retry: false };
1202
+ if (st === 'failed') {
1203
+ const why = typeof status.reason === 'string' ? capText(status.reason.trim(), 200).replace(/[.\s]+$/, '') : '';
1204
+ return { state: 'failed', text: `The demo could not start${why ? `: ${why}` : ''}. Nothing on your machine was changed.`, retry: true };
1205
+ }
1206
+ if (!prev || prev.state !== 'starting') return { state: 'idle', text: '', retry: false };
1207
+ if (!(now - prev.since < DEMO_TIMEOUT_MS)) return { state: 'failed', text: HOME_COPY.timeout, retry: true };
1208
+ return { state: 'starting', text: HOME_COPY.starting, retry: false };
1209
+ }
1210
+ function demoFailReason(status, body) {
1211
+ const b = body && typeof body === 'object' ? body : {};
1212
+ if (typeof b.reason === 'string' && b.reason.trim()) return b.reason.trim();
1213
+ if (status === 0) return 'the hub did not answer';
1214
+ if (status === 429 && typeof b.detail === 'string') return `${b.detail}. Try again in a moment.`;
1215
+ return errorText(status, body);
1216
+ }
1217
+ // The origin of a loopback http address (127.0.0.1, localhost or [::1], port 1 to 65535, no credentials), else ''.
1218
+ function loopbackOrigin(url) {
1219
+ if (typeof url !== 'string' || url.length > 200) return '';
1220
+ const m = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]{1,5}))?(\/[^\s\x00-\x1f\x7f]*)?$/.exec(url);
1221
+ if (!m) return '';
1222
+ const port = m[2] === undefined ? null : Number(m[2]);
1223
+ if (port !== null && !(port >= 1 && port <= 65535)) return '';
1224
+ return `${SCHEME_HTTP}${m[1]}${port === null ? '' : `:${port}`}`;
1225
+ }
1226
+ function validateReturnUrl(url) { return loopbackOrigin(url) ? url : '/'; }
1227
+ function demoTarget(url) { const o = loopbackOrigin(url); return o ? `${o}/#/overview` : ''; }
1228
+ function returnTarget(url) { const o = loopbackOrigin(url); return `${o}/#/home?closed`; }
1229
+ function homeClosedFlag(hash) { return hash === '#/home?closed'; }
1230
+ function homeStripItems(stats, services) {
1231
+ const s = stats && typeof stats === 'object' ? stats : {};
1232
+ const count = Array.isArray(services) ? services.filter((x) => x && !x.builtin).length : 0;
1233
+ return [
1234
+ { label: 'Events seen', value: groupDigits(countOf(s.total_events)) },
1235
+ { label: 'Open incidents', value: groupDigits(countOf(s.open_incidents)) },
1236
+ { label: 'Services', value: groupDigits(count) },
1237
+ ];
1238
+ }
1239
+ function homeStripNote(stats) {
1240
+ const s = stats && typeof stats === 'object' ? stats : {};
1241
+ const open = countOf(s.open_incidents);
1242
+ if (countOf(s.total_events) === 0) return HOME_COPY.stripEmpty;
1243
+ if (open > 0) return `${open} open incident${open === 1 ? '' : 's'} ${open === 1 ? 'is' : 'are'} waiting. Tap Open app to read ${open === 1 ? 'it' : 'them'}.`;
1244
+ return HOME_COPY.stripQuiet;
1245
+ }
1246
+ // The one line of the demo banner: always names the next tap.
1247
+ function demoHint(incidents, pending) {
1248
+ if (countOf(pending) > 0) return HOME_COPY.hintReview;
1249
+ return countOf(incidents) > 0 ? HOME_COPY.hintOpen : HOME_COPY.hintWait;
1250
+ }
1251
+ /* HOME:end */
1252
+
1253
+ /* TOUR:begin */
1254
+ // Pure helpers of the guided tour (demo mode only). Outside the PURE block because of the 200-line self-test cap;
1255
+ // tests/unit/test_dashboard_tour.py runs them through node. Same rules as PURE: no browser global, no storage, no clock.
1256
+ // `view` is the view the user is on when the step's target is on screen; reaching the next step's view advances the tour.
1257
+ const TOUR_STEPS = [
1258
+ { id: 'overview', view: 'overview', target: 'nav-overview', title: 'Welcome to the haunting', body: 'Three sample apps are failing on purpose. Their incidents land here on Overview in about 20 seconds. Press Next when one shows up.' },
1259
+ { id: 'incident', view: 'overview', target: 'incidents', title: 'Read their last words', body: 'Each card holds a hypothesis from the ghost. Press Find in code for the code hint, then Explain to ask ChimericBot in the terminal.' },
1260
+ { id: 'services', view: 'services', target: 'nav-services', title: 'Visit the haunted houses', body: 'Click Services and open Unassigned. Its live log is the ghosts talking. The sample apps get pages of their own once Discovery finds them.' },
1261
+ { id: 'discovery', view: 'discovery', target: 'nav-discovery', title: 'Let the ghost sniff them out', body: 'Click Discovery and run a scan. Accept the three sample apps it finds. They only join this throwaway demo.' },
1262
+ { id: 'proposal', view: 'overview', target: 'proposals', title: 'Judge the fix', body: 'Click Overview. The demo agent left a fix under Proposals. Read it, then press Approve or Deny. Nothing outside this demo changes.' },
1263
+ { id: 'mute', view: 'service', target: 'mute', title: 'Hush the noisy one', body: 'Click Services, open the noisiest app and press Mute. Its events stop counting and the dropped counter rises. Unmute brings the screams back.' },
1264
+ { id: 'exit', view: 'rules', target: 'exit-demo', title: 'Seal the crypt', body: 'Click Rules to see when a fix may approve itself. Then press Exit demo: the ghosts are swept away and your real data was never touched.' },
1265
+ ];
1266
+ const TOUR_LAST = TOUR_STEPS.length - 1;
1267
+ function tourState(s) {
1268
+ const o = s && typeof s === 'object' && !Array.isArray(s) ? s : {};
1269
+ const n = Number.isInteger(o.step) ? o.step : 0;
1270
+ return { step: Math.min(TOUR_LAST, Math.max(0, n)), open: o.open === true };
1271
+ }
1272
+ // state {step, open}, action {type: next | back | skip | show | route, view?}. Always returns a new, valid state.
1273
+ function tourReduce(state, action) {
1274
+ const s = tourState(state);
1275
+ const type = action && typeof action === 'object' ? action.type : '';
1276
+ if (type === 'show') return { step: s.step, open: true };
1277
+ if (type === 'skip') return { step: s.step, open: false };
1278
+ if (!s.open) return s;
1279
+ if (type === 'next') return { step: Math.min(TOUR_LAST, s.step + 1), open: true };
1280
+ if (type === 'back') return { step: Math.max(0, s.step - 1), open: true };
1281
+ if (type === 'route' && typeof action.view === 'string') {
1282
+ const after = TOUR_STEPS[s.step + 1];
1283
+ if (after && after.view === action.view && TOUR_STEPS[s.step].view !== action.view) return { step: s.step + 1, open: true };
1284
+ }
1285
+ return s;
1286
+ }
1287
+ // The data-tour values to outline on `view`: the step's target, plus the nav button of the step's view when the
1288
+ // user is elsewhere (an app page counts as Services for the nav).
1289
+ function tourTargets(index, view) {
1290
+ const step = TOUR_STEPS[Number.isInteger(index) ? Math.min(TOUR_LAST, Math.max(0, index)) : 0];
1291
+ const out = [step.target];
1292
+ const nav = `nav-${step.view === 'service' ? 'services' : step.view}`;
1293
+ if (view !== step.view && !out.includes(nav)) out.push(nav);
1294
+ return out;
1295
+ }
1296
+ // Steps whose action needs the admin token (scan, approve, mute). The demo hub runs without access enforcement,
1297
+ // so this only shows on a hub that enforces it.
1298
+ const TOUR_LOCKED = ['discovery', 'proposal', 'mute'];
1299
+ function tourLockNote(id, locked) {
1300
+ return locked === true && TOUR_LOCKED.includes(id) ? 'This step is locked. Press Unlock to approve in the header first.' : '';
1301
+ }
1302
+ function tourLabels(state) {
1303
+ const s = tourState(state);
1304
+ const last = s.step === TOUR_LAST;
1305
+ return { counter: `Step ${s.step + 1} of ${TOUR_STEPS.length}`, next: last ? 'Exit demo' : 'Next', backDisabled: s.step === 0, last };
1306
+ }
1307
+ // Only the step and the open flag are saved, never anything else.
1308
+ function tourSerialize(state) { const s = tourState(state); return JSON.stringify({ step: s.step, open: s.open }); }
1309
+ function tourParse(raw) {
1310
+ const fresh = { step: 0, open: true };
1311
+ if (typeof raw !== 'string' || raw.length > 100) return fresh;
1312
+ let v = null;
1313
+ try { v = JSON.parse(raw); } catch (e) { return fresh; }
1314
+ if (!v || typeof v !== 'object' || Array.isArray(v) || !Number.isInteger(v.step) || v.step < 0 || v.step > TOUR_LAST || typeof v.open !== 'boolean') return fresh;
1315
+ return { step: v.step, open: v.open };
1316
+ }
1317
+ /* TOUR:end */
1318
+
1319
+ /* ==== SELFTEST ==== */
1320
+ const SELFTEST_CASES = [
1321
+ { name: 'sevName', args: [3], expect: 'err' },
1322
+ { name: 'sevName', args: [8], expect: 'unknown' },
1323
+ { name: 'capText', args: ['abc', 3], expect: 'abc' },
1324
+ { name: 'capText', args: ['abcd', 3], expect: 'abc…' },
1325
+ { name: 'capText', args: [null, 5], expect: '' },
1326
+ { name: 'relTime', args: [null, 100], expect: 'never' },
1327
+ { name: 'relTime', args: [100, 100], expect: 'just now' },
1328
+ { name: 'stateLabel', args: ['source', 'stopped'], expect: 'stopped' },
1329
+ { name: 'countdown', args: [100, 100], expect: 'expired' },
1330
+ { name: 'countdown', args: [90, 100], expect: 'expired' },
1331
+ { name: 'countdown', args: [2800, 100], expect: '45 min' },
1332
+ { name: 'countdown', args: [100 + 20, 100], expect: '1 min' },
1333
+ { name: 'countdown', args: [100 + 3900, 100], expect: '1 h 5 min' },
1334
+ { name: 'countdown', args: [100 + 183600, 100], expect: '2 d 3 h' },
1335
+ { name: 'stateLabel', args: ['service', 'never_seen'], expect: 'never seen' },
1336
+ { name: 'stateLabel', args: ['service', 'active'], expect: 'active' },
1337
+ { name: 'stateLabel', args: ['service', 'idle'], expect: 'idle' },
1338
+ { name: 'stateLabel', args: ['source', 'running'], expect: 'running' },
1339
+ { name: 'stateLabel', args: ['source', 'missing'], expect: 'missing' },
1340
+ { name: 'stateLabel', args: ['source', 'unreadable'], expect: 'unreadable' },
1341
+ { name: 'stateLabel', args: ['source', 'error'], expect: 'error' },
1342
+ { name: 'hintEditField', args: [{ state: 'never_seen', app_names: [] }], expect: 'svcFApps' },
1343
+ { name: 'stateLabel', args: ['rule', 'suspended'], expect: 'suspended' },
1344
+ { name: 'stateLabel', args: ['proposal', 'pending'], expect: 'pending' },
1345
+ { name: 'nextBackoff', args: [0], expect: 1 },
1346
+ { name: 'nextBackoff', args: [1], expect: 2 },
1347
+ { name: 'nextBackoff', args: [2], expect: 4 },
1348
+ { name: 'nextBackoff', args: [3], expect: 8 },
1349
+ { name: 'nextBackoff', args: [4], expect: 16 },
1350
+ { name: 'nextBackoff', args: [5], expect: 30 },
1351
+ { name: 'nextBackoff', args: [6], expect: 30 },
1352
+ { name: 'nextBackoff', args: [7], expect: 30 },
1353
+ { name: 'nextBackoff', args: [8], expect: 30 },
1354
+ { name: 'stormLabel', args: [0], expect: 'Summon a failure storm' },
1355
+ { name: 'scanStateText', args: ['running'], expect: 'Scanning this machine...' },
1356
+ { name: 'emptyScanText', args: [{ processes_seen: 1, listeners_seen: 2 }], expect: 'Looked at 1 process and 2 listening ports. Nothing matched the 15 known apps. A Python script or a custom daemon is not one of them.' },
1357
+ { name: 'headerLockText', args: [true, null], expect: 'Unlocked' },
1358
+ { name: 'unlockStatusText', args: [{ ok: true }, true], expect: '' },
1359
+ { name: 'serviceMatchHint', args: [{ state: 'active' }], expect: '' },
1360
+ { name: 'versionText', args: [{ version: '1.2.3' }], expect: 'ChimericMesh 1.2.3' },
1361
+ { name: 'stormLabel', args: [2], expect: 'Another storm' },
1362
+ { name: 'guideLockText', args: [{ complete: false }, true], expect: 'Step 5 needs the admin token. Unlock first.' },
1363
+ { name: 'errorText', args: [422, { detail: 'bad path', field: 'log_paths' }], expect: 'log_paths: bad path' },
1364
+ { name: 'errorText', args: [400, { detail: 'nope' }], expect: 'nope' },
1365
+ { name: 'errorText', args: [422, { detail: [{ loc: ['body', 'name'], msg: 'required' }, { loc: [], msg: 'bad' }] }], expect: 'name: required; bad' },
1366
+ { name: 'errorText', args: [500, null], expect: 'HTTP 500' },
1367
+ { name: 'errorText', args: [404, { detail: { a: 1 } }], expect: 'HTTP 404' },
1368
+ { name: 'errorText', args: [503, {}], expect: 'HTTP 503' },
1369
+ { name: 'parseRoute', args: [''], expect: { view: 'home' } },
1370
+ { name: 'parseRoute', args: ['#/'], expect: { view: 'home' } },
1371
+ { name: 'parseRoute', args: ['#/services'], expect: { view: 'services' } },
1372
+ { name: 'parseRoute', args: ['#/services/web'], expect: { view: 'service', id: 'web' } },
1373
+ { name: 'parseRoute', args: ['#/services/Bad_Id'], expect: { view: 'services' } },
1374
+ { name: 'parseRoute', args: ['#/services/web/x'], expect: { view: 'home' } },
1375
+ { name: 'parseRoute', args: ['#/discovery'], expect: { view: 'discovery' } },
1376
+ { name: 'parseRoute', args: ['#/rules'], expect: { view: 'rules' } },
1377
+ { name: 'dueTasks', args: [[{ id: 'a', every: 3000, last: 0, view: 'overview' }, { id: 'b', every: 1000, last: 0, view: '*' }, { id: 'c', every: 1000, last: 0, view: 'services' }], 3000, 'overview', true], expect: ['a', 'b'] },
1378
+ { name: 'dueTasks', args: [[{ id: 'a', every: 3000, last: 0, view: 'overview' }], 3000, 'overview', false], expect: [] },
1379
+ { name: 'dueTasks', args: [[{ id: 'a', every: 3000, last: 0, view: 'overview' }, { id: 'c', every: 1000, last: 0, view: 'services' }], 1000, 'services', true], expect: ['c'] },
1380
+ { name: 'dueTasks', args: [[{ id: 'b', every: 5000, last: 0, view: '*' }], 5000, 'services', true], expect: ['b'] },
1381
+ { name: 'dueTasks', args: [[{ id: 'b', every: 5000, last: 0, view: '*' }], 5000, 'overview', true], expect: ['b'] },
1382
+ { name: 'dueTasks', args: [[{ id: 'a', every: 3000, last: 1000, view: 'overview' }], 2500, 'overview', true], expect: [] },
1383
+ { name: 'rowMatches', args: [{ severity: 3, message: 'Disk full' }, 7, ''], expect: true },
1384
+ { name: 'rowMatches', args: [{ severity: 5, message: 'x' }, 3, ''], expect: false },
1385
+ { name: 'rowMatches', args: [{ severity: 3, message: 'Disk full' }, 7, 'DISK'], expect: true },
1386
+ { name: 'rowMatches', args: [{ severity: 3, host: 'web', message: 'ok' }, 7, 'zzz'], expect: false },
1387
+ { name: 'rowMatches', args: [{ severity: 4, host: 'db01', app: 'pg', message: 'x' }, 4, 'pg'], expect: true },
1388
+ { name: 'approvalText', args: [null], expect: '' },
1389
+ { name: 'approvalText', args: [{ approval: null }], expect: '' },
1390
+ { name: 'approvalText', args: [{ decided_by: 'alice', approval: { by: 'user' } }], expect: 'approved by alice' },
1391
+ { name: 'approvalText', args: [{ approval: { by: 'rule', rule_id: 'r1', rule_status_now: 'active' } }], expect: 'auto-approved by rule r1 (rule active)' },
1392
+ { name: 'approvalText', args: [{ approval: { by: 'rule', rule_id: 'r1', rule_status_now: 'suspended' } }], expect: 'auto-approved by rule r1 (rule suspended)' },
1393
+ { name: 'approvalText', args: [{ approval: { by: 'rule', rule_id: 'r2', rule_status_now: 'revoked' } }], expect: 'auto-approved by rule r2 (rule revoked)' },
1394
+ { name: 'approvalText', args: [{ approval: { by: 'rule', rule_id: 'r2', rule_status_now: 'expired' } }], expect: 'auto-approved by rule r2 (rule expired)' },
1395
+ { name: 'approvalText', args: [{ approval: { by: 'rule', rule_id: 'r3', rule_status_now: null } }], expect: 'auto-approved by rule r3 (rule status unknown)' },
1396
+ { name: 'canMakeRule', args: [{ status: 'approved', approval: { by: 'user' } }], expect: true },
1397
+ { name: 'canMakeRule', args: [{ status: 'done', verification_result: 'passed', approval: { by: 'user' } }], expect: true },
1398
+ { name: 'canMakeRule', args: [{ status: 'done', verification_result: 'failed', approval: { by: 'user' } }], expect: false },
1399
+ { name: 'canMakeRule', args: [{ status: 'approved', approval: { by: 'rule' } }], expect: false },
1400
+ { name: 'canMakeRule', args: [{ status: 'pending', approval: null }], expect: false },
1401
+ { name: 'canMakeRule', args: [{ status: 'approved' }], expect: false },
1402
+ { name: 'boundOf', args: [{ max_files: { min: 1, max: 9, default: 2 } }, 'max_files', { min: 1, max: 20, default: 5 }], expect: { min: 1, max: 9, default: 2 } },
1403
+ { name: 'boundOf', args: [{}, 'max_files', { min: 1, max: 20, default: 5 }], expect: { min: 1, max: 20, default: 5 } },
1404
+ { name: 'boundOf', args: [null, 'x', { min: 1, max: 2, default: 1 }], expect: { min: 1, max: 2, default: 1 } },
1405
+ { name: 'clampInt', args: ['5', 1, 10], expect: 5 },
1406
+ { name: 'clampInt', args: [0, 1, 10], expect: 1 },
1407
+ { name: 'clampInt', args: [99, 1, 10], expect: 10 },
1408
+ { name: 'clampInt', args: ['x', 1, 10], expect: null },
1409
+ { name: 'clampInt', args: ['', 1, 10], expect: null },
1410
+ { name: 'sevFloorText', args: [3], expect: 'err (3) or more urgent' },
1411
+ { name: 'sevFloorText', args: [4], expect: 'warning (4) or more urgent' },
1412
+ { name: 'sevFloorText', args: [9], expect: 'unknown' },
1413
+ { name: 'expiryFromDays', args: [1000000, 1], expect: 481600 },
1414
+ { name: 'expiryFromDays', args: [1000000, 7], expect: 1000000 },
1415
+ { name: 'expiryFromDays', args: [1000000, 29], expect: 2900800 },
1416
+ { name: 'expiryFromDays', args: [1000000, 30], expect: 2900800 },
1417
+ { name: 'expiryFromDays', args: [1000000, 0], expect: 481600 },
1418
+ { name: 'expiryFromDays', args: [1000000, NaN], expect: null },
1419
+ { name: 'expiryFromDays', args: [1000000, 2.5], expect: null },
1420
+ { name: 'ruleOverrides', args: [{ most_urgent_severity: 3, max_per_hour: 3, max_per_incident: 1, max_files: 5, max_lines: 100, expires_at: 1000000, note: '' }, { most_urgent_severity: 3, max_per_hour: 3, max_per_incident: 1, max_files: 5, max_lines: 100, days: 7, note: '' }], expect: {} },
1421
+ { name: 'ruleOverrides', args: [{ most_urgent_severity: 3, max_per_hour: 3, max_lines: 100, expires_at: 1000000 }, { most_urgent_severity: 3, max_per_hour: 3, max_lines: 50, days: 7 }], expect: { max_lines: 50 } },
1422
+ { name: 'ruleOverrides', args: [{ max_files: 5, expires_at: 1000000 }, { max_files: 5, days: 10 }], expect: { expires_at: 1259200 } },
1423
+ { name: 'ruleOverrides', args: [{ max_files: 5, expires_at: 1000000, note: 'a' }, { max_files: null, days: 7, note: 'b' }], expect: { note: 'b' } },
1424
+ { name: 'mergeAudit', args: [[{ id: 2 }, { id: 1 }], [{ id: 3 }]], expect: [{ id: 3 }, { id: 2 }, { id: 1 }] },
1425
+ { name: 'mergeAudit', args: [[{ id: 2, a: 'old' }], [{ id: 2, a: 'new' }]], expect: [{ id: 2, a: 'new' }] },
1426
+ { name: 'mergeAudit', args: [[{ id: 5 }, { id: 4 }, { id: 3 }], [{ id: 6 }, { id: 5 }]], expect: [{ id: 6 }, { id: 5 }, { id: 4 }, { id: 3 }] },
1427
+ { name: 'mergeAudit', args: [[{ id: 1 }, { id: 3 }], [{ id: 2 }]], expect: [{ id: 3 }, { id: 2 }, { id: 1 }] },
1428
+ { name: 'mergeAudit', args: [null, [{ id: 1 }]], expect: [{ id: 1 }] },
1429
+ { name: 'decideText', args: [[]], expect: '' },
1430
+ { name: 'decideText', args: [[{ action: 'Add bounded backoff to upstream.py', created: 5 }]], expect: 'A fix is waiting for you: Add bounded backoff to upstream.py' },
1431
+ { name: 'decideText', args: [[{ action: 'old', created: 1 }, { action: 'new', created: 9 }]], expect: '2 fixes are waiting for you. Newest: new' },
1432
+ { name: 'decideText', args: [[{ action: 'x'.repeat(90), created: 1 }]], expect: `A fix is waiting for you: ${'x'.repeat(80)}…` },
1433
+ { name: 'isNewer', args: [5, 4], expect: true },
1434
+ { name: 'isNewer', args: [4, 4], expect: false },
1435
+ { name: 'isNewer', args: [3, 4], expect: false },
1436
+ { name: 'isNewer', args: ['9', 4], expect: false },
1437
+ { name: 'lockState', args: [{ enforce_access: true }, false], expect: { locked: true, mode: 'enforced' } },
1438
+ { name: 'lockState', args: [{ enforce_access: true }, true], expect: { locked: false, mode: 'enforced' } },
1439
+ { name: 'lockState', args: [{ enforce_access: false }, false], expect: { locked: false, mode: 'off' } },
1440
+ { name: 'lockState', args: [{ enforce_access: null }, false], expect: { locked: false, mode: 'unknown' } },
1441
+ { name: 'lockState', args: [null, false], expect: { locked: false, mode: 'unknown' } },
1442
+ { name: 'afterAuthFailure', args: [401, true], expect: { clearToken: true, text: 'token rejected' } },
1443
+ { name: 'afterAuthFailure', args: [401, false], expect: { clearToken: false, text: 'unlock first' } },
1444
+ { name: 'afterAuthFailure', args: [403, true], expect: { clearToken: false, text: 'blocked by the hub: open this page at the address the hub printed' } },
1445
+ { name: 'afterAuthFailure', args: [429, false, 7], expect: { clearToken: false, text: 'too many requests, try again in 7 s' } },
1446
+ { name: 'afterAuthFailure', args: [429, false], expect: { clearToken: false, text: 'too many requests, try again later' } },
1447
+ { name: 'afterAuthFailure', args: [500, false], expect: { clearToken: false, text: '' } },
1448
+ { name: 'matchesTable', args: [[['GET', '^/a$']], 'GET', '/a?x=1'], expect: true },
1449
+ { name: 'matchesTable', args: [[['GET', '^/a$']], 'POST', '/a'], expect: false },
1450
+ { name: 'needsToken', args: ['POST', '/api/services'], expect: true },
1451
+ { name: 'needsToken', args: ['GET', '/api/services'], expect: false },
1452
+ { name: 'needsToken', args: ['GET', '/api/discovery/scans/s1'], expect: true },
1453
+ { name: 'needsToken', args: ['POST', '/api/rules/resume'], expect: true },
1454
+ { name: 'needsToken', args: ['POST', '/api/rules/pause'], expect: false },
1455
+ { name: 'needsToken', args: ['POST', '/api/rules/r1/revoke'], expect: false },
1456
+ { name: 'sendsTokenIfPresent', args: ['GET', '/api/services/web/permissions-snippet'], expect: true },
1457
+ { name: 'sendsTokenIfPresent', args: ['GET', '/api/services/web'], expect: false },
1458
+ { name: 'actionNeedsToken', args: ['svc-save'], expect: true },
1459
+ { name: 'actionNeedsToken', args: ['rule-revoke'], expect: false },
1460
+ { name: 'actionNeedsToken', args: ['terminal-send'], expect: false },
1461
+ { name: 'actionNeedsToken', args: ['constructor'], expect: false },
1462
+ { name: 'tokenShapeOk', args: ['abc-123'], expect: true },
1463
+ { name: 'tokenShapeOk', args: ['a b'], expect: false },
1464
+ { name: 'tokenShapeOk', args: [''], expect: false },
1465
+ { name: 'tokenShapeOk', args: ['x'.repeat(201)], expect: false },
1466
+ { name: 'sortServices', args: [[{ name: 'b', open_incidents: 0, error_rate: 1 }, { name: 'a', open_incidents: 2, error_rate: 0 }]], expect: [{ name: 'a', open_incidents: 2, error_rate: 0 }, { name: 'b', open_incidents: 0, error_rate: 1 }] },
1467
+ { name: 'sortServices', args: [[{ name: 'b', open_incidents: 0, error_rate: 1 }, { name: 'c', open_incidents: 0, error_rate: 5 }]], expect: [{ name: 'c', open_incidents: 0, error_rate: 5 }, { name: 'b', open_incidents: 0, error_rate: 1 }] },
1468
+ { name: 'sortServices', args: [[{ name: 'Unassigned', builtin: true, open_incidents: 0, error_rate: 0 }, { name: 'z', open_incidents: 0, error_rate: 0 }]], expect: [{ name: 'z', open_incidents: 0, error_rate: 0 }, { name: 'Unassigned', builtin: true, open_incidents: 0, error_rate: 0 }] },
1469
+ { name: 'sortServices', args: [[{ name: 'b', open_incidents: 0, error_rate: 0 }, { name: 'a', open_incidents: 0, error_rate: 0 }]], expect: [{ name: 'a', open_incidents: 0, error_rate: 0 }, { name: 'b', open_incidents: 0, error_rate: 0 }] },
1470
+ { name: 'splitList', args: [' a, ,b ,'], expect: ['a', 'b'] },
1471
+ { name: 'splitList', args: [null], expect: [] },
1472
+ { name: 'serviceCreateBody', args: [{ id: 'web', name: 'Web', hosts: ['h'], app_names: [], protocols: ['file'], code_folder: '' }], expect: { id: 'web', name: 'Web', hosts: ['h'], app_names: [], protocols: ['file'] } },
1473
+ { name: 'serviceCreateBody', args: [{ id: 'web', name: 'Web', hosts: [], app_names: [], protocols: [], code_folder: 'C:/src' }], expect: { id: 'web', name: 'Web', hosts: [], app_names: [], protocols: [], code_folder: 'C:/src' } },
1474
+ { name: 'servicePatch', args: [{ name: 'a', hosts: ['h'], app_names: [], protocols: [], code_folder: '/c' }, { name: 'a', hosts: ['h'], app_names: [], protocols: [], code_folder: '' }], expect: { code_folder: null } },
1475
+ { name: 'servicePatch', args: [{ name: 'a', hosts: ['h'], app_names: [], protocols: [], code_folder: null }, { name: 'b', hosts: ['h', 'i'], app_names: [], protocols: [], code_folder: '' }], expect: { name: 'b', hosts: ['h', 'i'] } },
1476
+ { name: 'servicePatch', args: [{ name: 'a', hosts: [], app_names: [], protocols: [], code_folder: null }, { name: 'a', hosts: [], app_names: [], protocols: [], code_folder: '' }], expect: {} },
1477
+ { name: 'diffSources', args: [[], [{ id: '', path: '/l', format: 'ncsa', enabled: true }]], expect: { add: [{ index: 0, path: '/l', format: 'ncsa', enabled: true }], update: [], remove: [] } },
1478
+ { name: 'diffSources', args: [[{ id: 's1', path: '/l', format: 'ncsa', enabled: true }], [{ id: 's1', path: '/l', format: 'w3c', enabled: false }]], expect: { add: [], update: [{ id: 's1', patch: { format: 'w3c', enabled: false } }], remove: [] } },
1479
+ { name: 'diffSources', args: [[{ id: 's1', path: '/l', format: 'ncsa', enabled: true }], []], expect: { add: [], update: [], remove: ['s1'] } },
1480
+ { name: 'diffSources', args: [[{ id: 's1', path: '/l', format: 'ncsa', enabled: true }], [{ id: 's1', path: '/l', format: 'ncsa', enabled: true }]], expect: { add: [], update: [], remove: [] } },
1481
+ { name: 'diffSources', args: [[{ id: 's1', path: '/l', format: 'ncsa', enabled: true }], [{ id: 's1', path: '/m', format: 'ncsa', enabled: true }]], expect: { add: [{ index: 0, path: '/m', format: 'ncsa', enabled: true }], update: [], remove: ['s1'] } },
1482
+ { name: 'buildAcceptBody', args: [{ id: 'a', name: 'A', code_folder: ' ', app_names: [], rows: [{ checked: true, path: '/x', format: 'ncsa', watched_by: null }, { checked: false, path: '/y', format: 'w3c' }] }], expect: { id: 'a', name: 'A', log_paths: [{ path: '/x', format: 'ncsa' }] } },
1483
+ { name: 'buildAcceptBody', args: [{ id: 'a', name: 'A', code_folder: '/src', app_names: ['p'], rows: [{ checked: true, path: '/x', format: 'ncsa', watched_by: 'web' }] }], expect: { id: 'a', name: 'A', log_paths: [], code_folder: '/src', app_names: ['p'] } },
1484
+ { name: 'buildAcceptBody', args: [{ id: 'a', name: 'A', code_folder: '', app_names: [], rows: [{ checked: false, path: '/x', format: 'ncsa' }] }], expect: { id: 'a', name: 'A', log_paths: [] } },
1485
+ { name: 'buildAcceptBody', args: [{ id: 'a', name: 'A', rows: [{ checked: true, path: '/x', format: 'ncsa', watched_by: null }, { checked: true, path: '/y', format: 'w3c' }] }], expect: { id: 'a', name: 'A', log_paths: [{ path: '/x', format: 'ncsa' }, { path: '/y', format: 'w3c' }] } },
1486
+ { name: 'actionToast', args: ['approve', 'p4'], expect: 'Approved p4. The agent will apply it; this card turns "done" when it reports back.' },
1487
+ { name: 'actionToast', args: ['deny', 'p4'], expect: 'Denied p4. The agent will not run it.' },
1488
+ { name: 'actionToast', args: ['withdraw', 'p4'], expect: 'Withdrew p4. Nothing will run.' },
1489
+ { name: 'actionToast', args: ['resolve', '2f9159b0aa'], expect: 'Laid 2f9159b0aa to rest. If the errors return, it can reopen.' },
1490
+ { name: 'friendlyError', args: [0], expect: 'The mesh went quiet. Check that the hub is running, then try again.' },
1491
+ { name: 'friendlyError', args: [500], expect: 'The mesh turned that away (status 500). Try again or check the hub log.' },
1492
+ { name: 'unlockOutcome', args: [200], expect: { ok: true, text: 'Unlocked' } },
1493
+ { name: 'unlockOutcome', args: [401], expect: { ok: false, text: 'That token was not accepted. The ghost wants the exact line from the token file.' } },
1494
+ { name: 'unlockOutcome', args: [0], expect: { ok: false, text: 'The mesh went quiet. Check that the hub is running, then try again.' } },
1495
+ { name: 'closeLoop', args: [{ status: 'done', verification_result: 'passed' }, { resolved: false }], expect: { pill: 'done, tests passed', warn: '', rest: true } },
1496
+ { name: 'closeLoop', args: [{ status: 'done', verification_result: 'passed' }, { resolved: true }], expect: { pill: 'done, tests passed', warn: '', rest: false } },
1497
+ { name: 'closeLoop', args: [{ status: 'done', verification_result: 'failed' }, null], expect: { pill: '', warn: 'Tests failed. Deny it and ask the agent for another fix.', rest: false } },
1498
+ { name: 'closeLoop', args: [{ status: 'approved', verification_result: 'passed' }, null], expect: { pill: '', warn: '', rest: false } },
1499
+ { name: 'fixLine', args: [[{ id: 'p4', incident_id: 'a', status: 'approved', created: 2 }, { id: 'p3', incident_id: 'a', status: 'denied', created: 3 }], 'a'], expect: 'fix #p4 approved' },
1500
+ { name: 'fixLine', args: [[{ id: 'p3', incident_id: 'a', status: 'withdrawn', created: 3 }], 'a'], expect: '' },
1501
+ { name: 'fixLine', args: [null, 'a'], expect: '' },
1502
+ { name: 'pendingFor', args: [[{ status: 'pending', service_id: 'x' }, { status: 'pending', service_id: 'y' }, { status: 'done', service_id: 'x' }], 'x'], expect: 1 },
1503
+ { name: 'pendingFor', args: [null, 'x'], expect: 0 },
1504
+ { name: 'slugify', args: ['Web Proxy (prod)'], expect: 'web-proxy-prod' },
1505
+ { name: 'actorText', args: ['rest:127.0.0.1'], expect: 'API' },
1506
+ { name: 'defaultAppNames', args: ['Web Proxy (prod)'], expect: 'web-proxy-prod' },
1507
+ { name: 'actionText', args: ['proposal_withdrawn'], expect: 'proposal withdrawn' },
1508
+ { name: 'subjectText', args: ['POST /api/proposals/{pid}/decide'], expect: 'a decision request' },
1509
+ { name: 'navBadges', args: [[{ service_id: 'x' }, { service_id: null }, { service_id: 'x', resolved: true }], [{ status: 'pending' }], [], false], expect: { services: { text: '2', label: 'Services, 2 waiting' }, rules: { text: '', label: 'Rules' } } },
1510
+ { name: 'navBadges', args: [[], [], [{ status: 'suspended' }, { status: 'active' }], false], expect: { services: { text: '', label: 'Services' }, rules: { text: '1', label: 'Rules, 1 paused' } } },
1511
+ { name: 'navBadges', args: [null, null, null, true], expect: { services: { text: '', label: 'Services' }, rules: { text: 'paused', label: 'Rules, auto-approval paused' } } },
1512
+ { name: 'muteLabel', args: [false, true], expect: { text: 'Mute', pressed: false, disabled: true, title: 'unlock first' } },
1513
+ { name: 'muteAriaLabel', args: [false, 'orders-api'], expect: 'Mute orders-api' },
1514
+ { name: 'droppedText', args: [1234], expect: '1234 events dropped since the hub started' },
1515
+ { name: 'mutePillText', args: [{ muted: true }], expect: 'Muted' },
1516
+ { name: 'mutedIdsOf', args: [{ muted: [{ service_id: 'a' }, {}] }], expect: ['a'] },
1517
+ { name: 'mutedIncidentTag', args: [{ service_id: null }, ['unassigned']], expect: 'muted' },
1518
+ { name: 'muteToast', args: ['unmute', 'web'], expect: 'Unmuted web. Its events count again from now.' },
1519
+ ];
1520
+ function runSelfTest() {
1521
+ const fns = { sevName, capText, relTime, countdown, stateLabel, nextBackoff, errorText, parseRoute, dueTasks, isNewer, lockState, afterAuthFailure,
1522
+ matchesTable, needsToken, sendsTokenIfPresent, actionNeedsToken, tokenShapeOk, sortServices,
1523
+ actorText, actionText, subjectText, splitList, serviceCreateBody, servicePatch, diffSources, buildAcceptBody, rowMatches, approvalText, canMakeRule, boundOf, clampInt, sevFloorText, expiryFromDays, ruleOverrides, mergeAudit, decideText, actionToast, friendlyError, unlockOutcome, closeLoop, fixLine, pendingFor, navBadges, serviceMatchHint, versionText, headerLockText, unlockStatusText, scanStateText, emptyScanText, stormLabel, guideLockText, slugify, defaultAppNames, hintEditField, muteLabel, muteAriaLabel, droppedText, mutePillText, mutedIdsOf, mutedIncidentTag, muteToast };
1524
+ const failures = [];
1525
+ for (const c of SELFTEST_CASES) {
1526
+ let got;
1527
+ try { got = fns[c.name](...c.args); } catch (e) { got = `threw: ${e.message}`; }
1528
+ if (JSON.stringify(got) !== JSON.stringify(c.expect)) failures.push(`${c.name}(${JSON.stringify(c.args)}) gave ${JSON.stringify(got)}, expected ${JSON.stringify(c.expect)}`);
1529
+ }
1530
+ const box = document.getElementById('selftest');
1531
+ box.hidden = false;
1532
+ box.textContent = failures.length ? `SELFTEST FAIL (${failures.length} of ${SELFTEST_CASES.length})\n${failures.join('\n')}` : `SELFTEST PASS (${SELFTEST_CASES.length} cases)`;
1533
+ return failures.length === 0;
1534
+ }
1535
+
1536
+ /* ==== DOM helpers ==== */
1537
+ const $ = (id) => document.getElementById(id);
1538
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; };
1539
+ // A visible label bound to its input (R8.1).
1540
+ function field(labelText, input) {
1541
+ const wrap = el('div', 'field');
1542
+ const lab = el('label', '', labelText);
1543
+ lab.htmlFor = input.id;
1544
+ wrap.append(lab, input);
1545
+ return wrap;
1546
+ }
1547
+ function setStatus(text) { $('status').textContent = text || ''; }
1548
+ let toastTimer = null;
1549
+ function toast(msg) {
1550
+ const t = $('toast'); t.textContent = msg;
1551
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => { t.textContent = ''; }, 5000);
1552
+ }
1553
+ function unreachable() { toast(friendlyError(0)); }
1554
+ const here = window.location; // the page's own address; only its hash is read (routes) or set (navigation)
1555
+
1556
+ // A button for a registered action: locked (disabled, title "unlock first") only for a token action while
1557
+ // access control is on and no token is stored. Reduce actions and the terminal are never locked here.
1558
+ function lockButton(b) {
1559
+ const locked = Boolean(STATE.lock && STATE.lock.locked) && actionNeedsToken(b.dataset.action);
1560
+ if (locked) { b.disabled = true; b.title = 'unlock first'; }
1561
+ else if (b.title === 'unlock first') { b.disabled = false; b.title = ''; }
1562
+ }
1563
+ function actionButton(id, label, handler, cls, aria) {
1564
+ if (!Object.prototype.hasOwnProperty.call(ACTIONS, id)) throw new Error(`unknown action ${id}`);
1565
+ if (typeof label !== 'string' || !label.trim()) throw new Error(`action ${id} needs a visible name`);
1566
+ const b = el('button', cls === undefined ? 'ghost small' : cls, label);
1567
+ b.type = 'button';
1568
+ if (aria) b.setAttribute('aria-label', aria);
1569
+ b.dataset.action = id;
1570
+ b.onclick = handler;
1571
+ lockButton(b);
1572
+ return b;
1573
+ }
1574
+
1575
+ /* ==== API ==== */
1576
+ // The admin token is kept for this tab only (sessionStorage, or memory when storage is off), read only by
1577
+ // authHeaders, sent only on the PRIVILEGED routes, and never shown, logged, put in a URL or in localStorage.
1578
+ const TOKEN_KEY = 'cm.token';
1579
+ const TOKEN_PROMPT_TEXT = 'Protected actions (approve, deny, add or edit a service, scan, rules) need the admin token. Paste the contents of the token file. Open that file, copy its single line, paste it here.';
1580
+ let memToken = null;
1581
+ function storedToken() {
1582
+ try { const t = sessionStorage.getItem(TOKEN_KEY); if (t) return t; } catch (e) { /* storage unavailable */ }
1583
+ return memToken;
1584
+ }
1585
+ function saveToken(value) {
1586
+ memToken = null;
1587
+ try { sessionStorage.setItem(TOKEN_KEY, value); return true; } catch (e) { memToken = value; return false; }
1588
+ }
1589
+ function clearToken() {
1590
+ memToken = null;
1591
+ try { sessionStorage.removeItem(TOKEN_KEY); } catch (e) { /* storage unavailable */ }
1592
+ }
1593
+ function authHeaders(method, path) {
1594
+ const token = storedToken();
1595
+ if (!token || !(needsToken(method, path) || sendsTokenIfPresent(method, path))) return {};
1596
+ return { 'X-Admin-Token': token };
1597
+ }
1598
+ class ApiError extends Error {
1599
+ constructor(status, body, retryAfter) { super(String(status)); this.status = status; this.body = body; this.retryAfter = retryAfter; }
1600
+ }
1601
+ async function errorFromResponse(r) {
1602
+ let body = null;
1603
+ try { body = await r.json(); } catch (e) { body = null; }
1604
+ return new ApiError(r.status, body, r.headers.get('Retry-After'));
1605
+ }
1606
+ // 401, 403 and 429 from the hub: clear a rejected token, say why in the status line, re-apply the lock.
1607
+ function handle401(path, status, retryAfter) {
1608
+ const out = afterAuthFailure(status === undefined ? 401 : status, Boolean(storedToken()), retryAfter);
1609
+ if (out.clearToken) { clearToken(); toast(TOKEN_REJECTED_TEXT); }
1610
+ if (out.text) setStatus(out.text);
1611
+ applyLock();
1612
+ if (out.clearToken) openUnlock(TOKEN_REJECTED_TEXT);
1613
+ return out.text;
1614
+ }
1615
+ // `as` is 'json' (default) or 'text' (the permissions snippet is plain text).
1616
+ const DEMO_INTENT_PATH = /^\/api\/demo\/(start|stop|exit)$/;
1617
+ async function request(method, path, body, as) {
1618
+ if (typeof path !== 'string' || !(path === '/' || path.startsWith('/api/'))) throw new ApiError(0, { detail: 'bad path' }, null);
1619
+ const headers = Object.assign({}, authHeaders(method, path));
1620
+ if (method === 'POST' && DEMO_INTENT_PATH.test(path)) headers['X-Chimericmesh-Intent'] = 'demo'; // the demo routes refuse a request without it
1621
+ const opts = { method, headers };
1622
+ if (body !== undefined) { headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }
1623
+ let r;
1624
+ try { r = await fetch(path, opts); } catch (e) { throw new ApiError(0, { detail: 'Could not reach the mesh' }, null); }
1625
+ const dateHeader = r.headers.get('Date'); // the hub's clock, for rule expiry (never the browser's)
1626
+ const stamp = dateHeader ? Date.parse(dateHeader) : NaN;
1627
+ if (Number.isFinite(stamp)) STATE.serverDate = Math.floor(stamp / 1000);
1628
+ if (!r.ok) {
1629
+ const err = await errorFromResponse(r);
1630
+ if (r.status === 401 || r.status === 403 || r.status === 429) err.authText = handle401(path, r.status, err.retryAfter);
1631
+ throw err;
1632
+ }
1633
+ if (r.status === 204) return null;
1634
+ if (as === 'text') { try { return await r.text(); } catch (e) { return ''; } }
1635
+ try { return await r.json(); } catch (e) { return null; }
1636
+ }
1637
+ // The Overview's short names for request(): a read and a JSON post. Errors are ApiError (message = status).
1638
+ const api = (path) => request('GET', path);
1639
+ const post = (path, body) => request('POST', path, body || {});
1640
+
1641
+ /* ==== STATE ==== */
1642
+ const COMMANDS = ['!help', '!status', '!incidents', '!explain', '!proposals', '!resolve', '!approve', '!deny'];
1643
+ const STATE = { route: { view: 'overview' }, uiConfig: UI_FALLBACK, lock: lockState(UI_FALLBACK, false), incidents: [], proposals: [], workflow: null, chatCursor: 0, history: [], histIdx: 0, flash: new Map(), navInc: [], navProp: [], mutedIds: [], muteConfirm: null,
1644
+ demo: false, tour: { step: 0, open: false }, demoStart: { state: 'idle', since: 0 }, demoRunning: null }; // tour: {step, open}, see the tour code
1645
+ const state = STATE;
1646
+ const SEV = SEV_NAMES;
1647
+ const firstOpen = () => state.incidents.find((i) => !i.resolved);
1648
+
1649
+ /* ==== SCHEDULER ==== */
1650
+ // One 1 s timer runs the tasks whose period has elapsed, only for a visible tab and the active view
1651
+ // (a task with view '*' runs on every view). A 2.5 s task therefore runs every 3 s in practice.
1652
+ const SCHED = [
1653
+ { id: 'overview-refresh', every: 2500, last: 0, view: 'overview', run: () => refresh() },
1654
+ { id: 'overview-chat', every: 1000, last: 0, view: 'overview', run: () => fetchChat() },
1655
+ { id: 'home-live', every: 3000, last: 0, view: 'home', run: () => loadHome() },
1656
+ { id: 'services-list', every: 5000, last: 0, view: 'services', run: () => loadServices() },
1657
+ { id: 'service-detail', every: 5000, last: 0, view: 'service', run: () => loadServiceDetail() },
1658
+ { id: 'service-lists', every: 5000, last: 0, view: 'service', run: () => loadServiceLists() },
1659
+ { id: 'approvals-status', every: 5000, last: 0, view: '*', run: () => loadApprovalStatus() },
1660
+ { id: 'nav-counts', every: 5000, last: 0, view: '*', run: () => loadNavData() },
1661
+ { id: 'rules-list', every: 5000, last: 0, view: 'rules', run: () => loadRules() },
1662
+ { id: 'audit-list', every: 5000, last: 0, view: 'rules', run: () => refreshAudit() },
1663
+ { id: 'scan-poll', every: 1000, last: 0, view: 'discovery', run: () => (scanRunning() ? pollScan() : null) },
1664
+ { id: 'tour-mark', every: 1000, last: 0, view: '*', run: () => tourMark() },
1665
+ ];
1666
+ function tick() {
1667
+ const now = Date.now();
1668
+ const due = dueTasks(SCHED.map((t) => ({ id: t.id, every: t.every, last: t.last, view: t.view })), now, STATE.route.view, document.visibilityState === 'visible');
1669
+ for (const t of SCHED) {
1670
+ if (!due.includes(t.id)) continue;
1671
+ t.last = now;
1672
+ try { Promise.resolve(t.run()).catch(() => { /* the next tick retries */ }); } catch (e) { /* the next tick retries */ }
1673
+ }
1674
+ }
1675
+ function startScheduler() {
1676
+ const now = Date.now();
1677
+ for (const t of SCHED) t.last = now;
1678
+ setInterval(tick, 1000);
1679
+ }
1680
+
1681
+ /* ==== VIEWS ==== */
1682
+ /* ---------- stats ---------- */
1683
+ function renderStats(s) {
1684
+ const box = $('stats'); box.replaceChildren();
1685
+ const n = (v) => Number(v || 0).toLocaleString();
1686
+ const by = s.total_by_source || {};
1687
+ const items = [['Events seen', n(s.total_events)], ['Events / sec', Number(s.events_per_second || 0).toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })],
1688
+ ['Incidents', n(s.incidents)], ['Open', n(s.open_incidents)],
1689
+ ['Syslog', n(by.syslog)], ['IRC', n(by.irc)], ['Telnet', n(by.telnet)]];
1690
+ for (const [label, val] of items) { const d = el('div', 'stat'); d.append(el('b', '', val), el('span', '', label)); box.append(d); }
1691
+ }
1692
+
1693
+ /* ---------- incidents ---------- */
1694
+ let lastIncKey = null;
1695
+ function openPropose(i, card, actions, btn) {
1696
+ if (card.querySelector('form.propose')) { card.querySelector('form.propose input').focus(); return; }
1697
+ const f = el('form', 'propose');
1698
+ const lab = el('label', 'sr', 'Proposed action'); lab.htmlFor = `pa-${i.id}`;
1699
+ const inp = el('input'); inp.type = 'text'; inp.id = `pa-${i.id}`; inp.maxLength = 200; inp.autocomplete = 'off';
1700
+ inp.value = String((i.remediation && i.remediation[0]) || '').slice(0, 200);
1701
+ const ok = el('button', '', 'Submit'); ok.type = 'submit';
1702
+ const cancel = el('button', 'ghost', 'Cancel'); cancel.type = 'button';
1703
+ const msg = el('div', 'meta');
1704
+ cancel.onclick = () => { f.remove(); msg.remove(); btn.focus(); };
1705
+ f.onsubmit = async (ev) => {
1706
+ ev.preventDefault();
1707
+ const action = inp.value.trim();
1708
+ if (!action) { msg.textContent = 'Describe the action first.'; return; }
1709
+ ok.disabled = true;
1710
+ try {
1711
+ await post('/api/proposals', { incident_id: i.id, action: action.slice(0, 200) });
1712
+ f.remove(); msg.remove(); btn.focus();
1713
+ await Promise.allSettled([loadProposals(), fetchChat(), loadWorkflow(), STATE.route.view === 'service' ? loadServiceLists() : null]);
1714
+ } catch (err) {
1715
+ msg.textContent = err.message === '404' ? 'Incident no longer exists (404).' : friendlyError(err.status);
1716
+ ok.disabled = false;
1717
+ }
1718
+ };
1719
+ f.append(lab, inp, ok, cancel);
1720
+ actions.after(f); f.after(msg);
1721
+ inp.focus(); inp.select();
1722
+ }
1723
+
1724
+ // The action row of an incident card, shared by the Overview and the service page. noService leaves out the
1725
+ // "service: x" button (the service page already is that service).
1726
+ function appendIncidentActions(d, i, noService) {
1727
+ const hint = el('div', 'meta'); d.append(hint);
1728
+ const actions = el('div', 'actions');
1729
+ const mk = (label, act, fn) => { const b = el('button', 'ghost', label); b.type = 'button'; b.dataset.act = act; b.onclick = fn; actions.append(b); return b; };
1730
+ mk('Explain', 'explain', () => { runCommand(`!explain ${i.id}`); $('termInput').focus(); });
1731
+ mk('Find in code', 'code', async () => {
1732
+ try { const h = await api(`/api/incidents/${i.id}/code`); hint.textContent = h.length ? h.map((x) => `${x.file}:${x.line}`).join(' ') : 'No matching source found.'; }
1733
+ catch (e) { hint.textContent = 'Could not look up code.'; }
1734
+ });
1735
+ if (!i.resolved) {
1736
+ const pb = mk('Propose a fix', 'propose', () => openPropose(i, d, actions, pb));
1737
+ mk('Lay to rest', 'resolve', () => resolveIncident(i.id));
1738
+ }
1739
+ if (i.service_id && !noService) {
1740
+ const t = mk(`service: ${i.service_id}`, 'service', () => { here.hash = `#/services/${encodeURIComponent(i.service_id)}`; });
1741
+ t.classList.add('tag');
1742
+ t.setAttribute('aria-label', `Open service ${i.service_id}`);
1743
+ }
1744
+ d.append(actions);
1745
+ }
1746
+ function renderIncidents(list, force) {
1747
+ $('storm').textContent = stormLabel(list.length);
1748
+ if (document.querySelector('form.propose')) return; // never wipe a form being typed in
1749
+ const fixes = list.map((i) => fixLine(state.proposals, i.id));
1750
+ const key = JSON.stringify([list, fixes, STATE.mutedIds]);
1751
+ if (!force && key === lastIncKey) return;
1752
+ lastIncKey = key;
1753
+ const box = $('incidents'); box.replaceChildren();
1754
+ if (!list.length) { box.append(el('p', 'empty', 'The crypt is quiet. Summon a failure storm or send a log line.')); return; }
1755
+ for (const i of list) {
1756
+ const d = el('article', `incident sev-${i.severity}${i.resolved ? ' resolved' : ''}`);
1757
+ d.dataset.id = String(i.id);
1758
+ d.append(el('h3', '', `${i.category.toUpperCase()} on ${i.host} ×${i.count}`));
1759
+ const meta = el('div', 'meta'); for (const s of i.sources) meta.append(el('span', 'src', s));
1760
+ meta.append(`${SEV[i.severity]} · id ${i.id}${i.resolved ? ' · resolved' : ''}`);
1761
+ const mutedTag = mutedIncidentTag(i, STATE.mutedIds);
1762
+ if (mutedTag) meta.append(' ', el('span', 'pill muted', mutedTag));
1763
+ d.append(meta);
1764
+ d.append(el('div', 'sample', i.sample), el('p', '', i.hypothesis));
1765
+ const ol = el('ol'); i.remediation.forEach((s) => ol.append(el('li', '', s))); d.append(ol);
1766
+ const fixText = fixLine(state.proposals, i.id);
1767
+ if (fixText) d.append(el('div', 'meta fixline', fixText));
1768
+ appendIncidentActions(d, i, false);
1769
+ box.append(d);
1770
+ }
1771
+ }
1772
+
1773
+ /* ---------- events ---------- */
1774
+ function renderEvents(list) {
1775
+ const box = $('events'); box.replaceChildren();
1776
+ if (!list.length) { box.append(el('p', 'empty', 'No whispers yet.')); return; }
1777
+ for (const e of list) {
1778
+ const r = el('div', 'row');
1779
+ r.append(el('span', 'meta t', fmtTime(e.ts)), el('span', `sev-${e.severity_name}`, `${e.source}`), el('span', 'm', `${e.host}: ${e.message}`));
1780
+ box.append(r);
1781
+ }
1782
+ }
1783
+
1784
+ /* ---------- proposals ---------- */
1785
+ let lastPropKey = null;
1786
+ // The hint under the Proposals heading: Approve and Deny need the token while the page is locked.
1787
+ function renderLockNote(box, locked, text) {
1788
+ box.replaceChildren();
1789
+ if (!locked) return;
1790
+ const wrap = el('span', 'lock-note');
1791
+ wrap.append(el('span', '', text));
1792
+ const b = el('button', 'ghost small', 'Unlock');
1793
+ b.type = 'button';
1794
+ b.onclick = () => openUnlock();
1795
+ wrap.append(b);
1796
+ box.append(wrap);
1797
+ }
1798
+ function updatePropNote() {
1799
+ const locked = Boolean(STATE.lock && STATE.lock.locked);
1800
+ const text = 'Approve and Deny are locked: unlock first with the admin token. Withdraw works without it.';
1801
+ renderLockNote($('propNote'), locked, text);
1802
+ renderLockNote($('svcPropNote'), locked, text);
1803
+ }
1804
+ // The strip above the guide that says a decision is waiting, and the class that lifts the proposals above the incidents (UX-01).
1805
+ function renderDecideStrip() {
1806
+ const pending = state.proposals.filter((p) => p.status === 'pending');
1807
+ const text = decideText(pending);
1808
+ $('decideStrip').hidden = !text;
1809
+ $('decideText').textContent = text;
1810
+ document.querySelector('.col.left').classList.toggle('has-pending', pending.length > 0);
1811
+ }
1812
+ $('decideReview').onclick = () => scrollFocus($('propPanel'));
1813
+ $('skip').onclick = (ev) => { ev.preventDefault(); $('main').focus(); };
1814
+ // The one proposal renderer: used by the Overview panel and by the service detail. Every string is text.
1815
+ function renderProposalCard(p, incidentText, noteId) {
1816
+ const d = el('div', 'prop');
1817
+ const top = el('div', 'top');
1818
+ const st = ['pending', 'approved', 'denied', 'done'].includes(p.status) ? p.status : 'unknown';
1819
+ const loop = closeLoop(p, findIncident(p.incident_id));
1820
+ const label = loop.pill || (p.status === 'approved' ? 'approved - waiting for agent' : stateLabel('proposal', p.status));
1821
+ top.append(el('span', `pill ${st}`, label), el('span', 'meta', `#${p.id} · ${incidentText}`));
1822
+ if (p.approval && p.approval.by === 'rule') top.append(el('span', 'pill auto', 'AUTO-APPROVED'));
1823
+ d.append(top, el('div', 'act', p.action));
1824
+ const files = Array.isArray(p.files) ? p.files : [];
1825
+ if (files.length) d.append(el('div', 'meta', `files: ${files.slice(0, 5).join(', ')}${files.length > 5 ? ` +${files.length - 5} more` : ''}`));
1826
+ if (p.verification) d.append(el('div', 'meta', `verification: ${p.verification}`));
1827
+ const how = approvalText(p);
1828
+ if (how) d.append(el('div', 'meta', how));
1829
+ const extra = [];
1830
+ if (p.decided_by && !how) extra.push(`decided by ${p.decided_by}`);
1831
+ if (p.estimated_lines) extra.push(`about ${p.estimated_lines} lines`);
1832
+ if (p.files_changed !== null && p.files_changed !== undefined) extra.push(`${p.files_changed} files changed`);
1833
+ if (p.lines_changed !== null && p.lines_changed !== undefined) extra.push(`${p.lines_changed} lines changed`);
1834
+ if (p.verification_result) extra.push(`verification ${p.verification_result}`);
1835
+ if (p.result_note) extra.push(p.result_note);
1836
+ if (extra.length) d.append(el('div', 'meta', extra.join(' · ')));
1837
+ const msg = el('div', 'meta');
1838
+ msg.setAttribute('role', 'status');
1839
+ msg.dataset.flash = String(p.id);
1840
+ if (STATE.flash.has(String(p.id))) msg.textContent = STATE.flash.get(String(p.id));
1841
+ if (p.status === 'pending') {
1842
+ const a = el('div', 'actions');
1843
+ const approve = actionButton('proposal-approve', 'Approve', () => decideProposal(p, true, msg), 'small', `Approve proposal ${p.id}`);
1844
+ const deny = actionButton('proposal-deny', 'Deny', () => decideProposal(p, false, msg), 'ghost small warn', `Deny proposal ${p.id}`);
1845
+ if (noteId) { approve.setAttribute('aria-describedby', noteId); deny.setAttribute('aria-describedby', noteId); }
1846
+ a.append(approve, deny,
1847
+ actionButton('proposal-withdraw', 'Withdraw', () => withdrawProposal(p, msg), 'ghost small quiet', `Withdraw proposal ${p.id}`));
1848
+ d.append(a);
1849
+ }
1850
+ if (loop.warn) d.append(el('div', 'meta warnline', loop.warn));
1851
+ if (loop.rest) {
1852
+ const a = el('div', 'actions');
1853
+ const rest = el('button', 'small', 'Lay incident to rest');
1854
+ rest.type = 'button';
1855
+ rest.dataset.act = 'rest-incident';
1856
+ rest.setAttribute('aria-label', `Lay incident ${p.incident_id} to rest`);
1857
+ rest.onclick = async () => { rest.disabled = true; if (!(await resolveIncident(p.incident_id))) rest.disabled = false; };
1858
+ a.append(rest);
1859
+ d.append(a);
1860
+ }
1861
+ if (canMakeRule(p)) {
1862
+ const more = el('div', 'actions');
1863
+ const b = el('button', 'ghost small', 'Always approve fixes like this');
1864
+ b.type = 'button';
1865
+ b.onclick = () => openRuleFromProposal(p, d, msg);
1866
+ more.append(b);
1867
+ d.append(more);
1868
+ }
1869
+ d.append(msg);
1870
+ return d;
1871
+ }
1872
+ // The result line of a card survives the re-render that follows a decision: it is kept by proposal id for 8 s (UX-03).
1873
+ function flashMessage(id, text, msg) {
1874
+ const key = String(id);
1875
+ msg.textContent = text;
1876
+ STATE.flash.set(key, text);
1877
+ setTimeout(() => {
1878
+ STATE.flash.delete(key);
1879
+ document.querySelectorAll('[data-flash]').forEach((n) => { if (n.dataset.flash === key) n.textContent = ''; });
1880
+ }, 8000);
1881
+ }
1882
+ async function refreshProposalViews() {
1883
+ await Promise.allSettled([loadProposals(), STATE.route.view === 'service' ? loadServiceLists() : null, loadWorkflow()]);
1884
+ }
1885
+ // Approve or deny through the REST route with the token (R6.3); the result or the server's text is shown in the card.
1886
+ async function decideProposal(p, approve, msg) {
1887
+ msg.textContent = approve ? 'Approving...' : 'Denying...';
1888
+ try { await request('POST', `/api/proposals/${encodeURIComponent(p.id)}/decide`, { approve, by: 'dashboard' }); }
1889
+ catch (e) {
1890
+ msg.textContent = e.authText || errorText(e.status, e.body);
1891
+ if (!e.authText) toast(friendlyError(e.status));
1892
+ return;
1893
+ }
1894
+ flashMessage(p.id, approve ? 'Approved.' : 'Denied.', msg);
1895
+ setStatus(`Proposal ${p.id} ${approve ? 'approved' : 'denied'}`);
1896
+ toast(actionToast(approve ? 'approve' : 'deny', p.id));
1897
+ await refreshProposalViews();
1898
+ }
1899
+ // Withdraw needs no token (a reduce action).
1900
+ async function withdrawProposal(p, msg) {
1901
+ msg.textContent = 'Withdrawing...';
1902
+ try { await request('POST', `/api/proposals/${encodeURIComponent(p.id)}/withdraw`); }
1903
+ catch (e) {
1904
+ msg.textContent = e.authText || errorText(e.status, e.body);
1905
+ if (!e.authText) toast(friendlyError(e.status));
1906
+ return;
1907
+ }
1908
+ flashMessage(p.id, 'Withdrawn.', msg);
1909
+ setStatus(`Proposal ${p.id} withdrawn`);
1910
+ toast(actionToast('withdraw', p.id));
1911
+ await refreshProposalViews();
1912
+ }
1913
+ function renderProposals(force) {
1914
+ renderDecideStrip();
1915
+ renderIncidents(state.incidents); // the fix line of an incident card follows the proposals
1916
+ setNavData(state.incidents, state.proposals);
1917
+ const list = state.proposals.slice().sort((a, b) => (b.created || 0) - (a.created || 0)).slice(0, 20);
1918
+ const key = JSON.stringify([list, state.incidents.map((i) => [i.id, i.category, i.host, i.resolved])]);
1919
+ if (!force && key === lastPropKey) return;
1920
+ lastPropKey = key;
1921
+ updatePropNote();
1922
+ const box = $('proposals'); box.replaceChildren();
1923
+ if (!list.length) { box.append(el('p', 'empty', 'No proposals yet. Nobody has haunted a fix into being. Ask your agent to look at an incident, or press "Propose a fix" on a card.')); return; }
1924
+ for (const p of list) {
1925
+ const inc = state.incidents.find((i) => String(i.id) === String(p.incident_id));
1926
+ box.append(renderProposalCard(p, inc ? `${inc.category} on ${inc.host}` : `incident ${p.incident_id}`, 'propNote'));
1927
+ }
1928
+ }
1929
+
1930
+ /* ---------- workflow guide ---------- */
1931
+ const PREF_KEY = 'cm.guide.pref';
1932
+ const getPref = () => { try { return localStorage.getItem(PREF_KEY); } catch (e) { return null; } };
1933
+ const setPref = (v) => { try { localStorage.setItem(PREF_KEY, v); } catch (e) { /* ignore */ } };
1934
+ let lastGuideKey = null;
1935
+ function guideCollapsed(w) { const p = getPref(); return p === 'hide' || (w.complete && p !== 'show'); }
1936
+ function guideStatus(msg) { $('guideStatus').textContent = msg || ''; }
1937
+
1938
+ function renderGuide() {
1939
+ const w = state.workflow, sec = $('guide');
1940
+ if (!w || !Array.isArray(w.steps)) { sec.classList.add('hidden'); return; }
1941
+ sec.classList.remove('hidden');
1942
+ const collapsed = guideCollapsed(w);
1943
+ const key = JSON.stringify([w, collapsed]);
1944
+ if (key === lastGuideKey) return;
1945
+ lastGuideKey = key;
1946
+ const done = w.steps.filter((s) => s.done).length, total = w.steps.length;
1947
+ $('guideProgress').textContent = `${done} / ${total} done`;
1948
+ const bar = $('guideBar'); bar.setAttribute('aria-valuenow', String(done)); bar.setAttribute('aria-valuemax', String(total));
1949
+ $('guideFill').style.width = `${total ? Math.round(done * 100 / total) : 0}%`;
1950
+ $('guideToggle').textContent = collapsed ? 'Show guide' : 'Hide guide';
1951
+ $('guideToggle').setAttribute('aria-expanded', String(!collapsed));
1952
+ const ol = $('guideSteps'); ol.replaceChildren();
1953
+ $('guideBar').classList.toggle('hidden', collapsed);
1954
+ $('guideStatus').classList.toggle('hidden', collapsed);
1955
+ if (collapsed) {
1956
+ ol.classList.add('hidden');
1957
+ if (w.complete) $('guideProgress').textContent = 'Workflow complete - the crypt is yours';
1958
+ return;
1959
+ }
1960
+ ol.classList.remove('hidden');
1961
+ w.steps.forEach((s, idx) => {
1962
+ const li = el('li', `step${s.done ? ' done' : ''}${w.next === s.key ? ' next' : ''}`);
1963
+ li.append(el('span', 'n', s.done ? '✓' : String(idx + 1)));
1964
+ const body = el('div');
1965
+ body.append(el('div', 't', s.title), el('div', 'meta', s.hint));
1966
+ if (!s.done && w.next === s.key) {
1967
+ const b = el('button', '', 'Do it'); b.type = 'button'; b.onclick = () => doIt(s.key); body.append(b);
1968
+ }
1969
+ li.append(body); ol.append(li);
1970
+ });
1971
+ }
1972
+ $('guideToggle').onclick = () => { const w = state.workflow; if (!w) return; setPref(guideCollapsed(w) ? 'show' : 'hide'); renderGuide(); };
1973
+
1974
+ function scrollFocus(node) { node.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'center' }); try { node.focus({ preventScroll: true }); } catch (e) { node.focus(); } }
1975
+ async function storm() {
1976
+ try { await post('/api/demo/storm'); toast(actionToast('storm')); } catch (e) { toast(friendlyError(e.status)); }
1977
+ refresh();
1978
+ }
1979
+ async function doIt(key) {
1980
+ guideStatus('');
1981
+ if (key === 'traffic') { await storm(); }
1982
+ else if (key === 'incidents') {
1983
+ if (!state.incidents.length) { guideStatus('Waiting for 3 similar errors...'); await storm(); }
1984
+ else scrollFocus($('incPanel'));
1985
+ } else if (key === 'ask') {
1986
+ $('termInput').focus();
1987
+ await runCommand('!incidents');
1988
+ const o = firstOpen(); if (o) await runCommand(`!explain ${o.id}`);
1989
+ } else if (key === 'propose') {
1990
+ const o = firstOpen();
1991
+ if (!o) { guideStatus('No open incident to propose a fix for yet.'); return; }
1992
+ renderIncidents(state.incidents, true);
1993
+ const card = document.querySelector(`.incident[data-id="${CSS.escape(String(o.id))}"]`);
1994
+ const btn = card && card.querySelector('button[data-act="propose"]');
1995
+ if (btn) { scrollFocus(card); btn.click(); }
1996
+ } else if (key === 'decide') {
1997
+ await runCommand('!proposals'); scrollFocus($('propPanel'));
1998
+ } else if (key === 'resolve') {
1999
+ const o = firstOpen();
2000
+ if (!o) { guideStatus('No open incident left to lay to rest.'); return; }
2001
+ const card = document.querySelector(`.incident[data-id="${CSS.escape(String(o.id))}"]`);
2002
+ const btn = card && card.querySelector('button[data-act="resolve"]');
2003
+ if (btn) { card.scrollIntoView({ block: 'center' }); btn.focus(); }
2004
+ }
2005
+ }
2006
+
2007
+ /* ---------- terminal ---------- */
2008
+ const tlog = $('transcript');
2009
+ const nearBottom = () => tlog.scrollHeight - tlog.scrollTop - tlog.clientHeight <= 40;
2010
+ function fmtTime(ts) { return new Date(ts * 1000).toLocaleTimeString([], { hour12: false }); }
2011
+ function appendMessages(msgs) {
2012
+ if (!msgs.length) return;
2013
+ const hint = $('termHint'); if (hint) hint.remove(); // the placeholder is not a message
2014
+ const stick = nearBottom();
2015
+ for (const m of msgs) {
2016
+ const kind = ['bot', 'user', 'system'].includes(m.kind) ? m.kind : 'system';
2017
+ const line = el('div', `tline ${kind}`);
2018
+ line.append(el('span', 'ts', fmtTime(m.ts)));
2019
+ if (kind === 'bot') line.append(el('span', 'who', 'ChimericBot'));
2020
+ if (kind === 'user') line.append(el('span', 'who', `${m.sender} >`));
2021
+ line.append(document.createTextNode(String(m.text)));
2022
+ tlog.append(line);
2023
+ }
2024
+ while (tlog.childElementCount > 300) tlog.firstElementChild.remove();
2025
+ if (stick) { tlog.scrollTop = tlog.scrollHeight; $('newMsgs').classList.add('hidden'); }
2026
+ else $('newMsgs').classList.remove('hidden');
2027
+ }
2028
+ $('newMsgs').onclick = () => { tlog.scrollTop = tlog.scrollHeight; $('newMsgs').classList.add('hidden'); $('termInput').focus(); };
2029
+ tlog.addEventListener('scroll', () => { if (nearBottom()) $('newMsgs').classList.add('hidden'); });
2030
+
2031
+ let chatBusy = false;
2032
+ async function fetchChat() {
2033
+ if (chatBusy) return;
2034
+ chatBusy = true;
2035
+ try {
2036
+ for (let round = 0; round < 5; round++) {
2037
+ const d = await api(`/api/chat?after=${state.chatCursor}&limit=200`);
2038
+ const msgs = Array.isArray(d.messages) ? d.messages : [];
2039
+ if (typeof d.last_id === 'number' && d.last_id < state.chatCursor) {
2040
+ state.chatCursor = 0; tlog.replaceChildren(); continue; // server restarted
2041
+ }
2042
+ appendMessages(msgs);
2043
+ for (const m of msgs) if (m.id > state.chatCursor) state.chatCursor = m.id;
2044
+ if (msgs.length < 200) break;
2045
+ }
2046
+ } catch (e) { /* tolerate; next poll retries */ }
2047
+ finally { chatBusy = false; }
2048
+ }
2049
+
2050
+ async function runCommand(text) {
2051
+ text = String(text).trim().slice(0, 200);
2052
+ if (!text) return;
2053
+ if (state.history[state.history.length - 1] !== text) state.history.push(text);
2054
+ if (state.history.length > 50) state.history.shift();
2055
+ state.histIdx = state.history.length;
2056
+ $('termStatus').textContent = '';
2057
+ try { await request('POST', '/api/terminal', { text }); }
2058
+ catch (e) {
2059
+ // Only !approve and !deny need the token on this route (R6.5); request() already cleared a rejected token.
2060
+ if (e.status === 401 && /^!(approve|deny)\b/.test(text)) { $('termStatus').textContent = 'unlock first'; openUnlock(e.authText === 'token rejected' ? TOKEN_REJECTED_TEXT : undefined); }
2061
+ else if (!e.authText) unreachable();
2062
+ return false;
2063
+ }
2064
+ await Promise.allSettled([fetchChat(), loadProposals(), loadIncidents(), loadWorkflow()]);
2065
+ return true;
2066
+ }
2067
+ // Lay an incident to rest through the terminal command the incident card has always used (needs no token), then say so.
2068
+ async function resolveIncident(id) {
2069
+ const sid = String(id);
2070
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(sid)) { toast(actionToast('unconfirmed', sid)); return false; }
2071
+ if (!(await runCommand(`!resolve ${sid} via dashboard`))) return false;
2072
+ const inc = state.incidents.find((i) => String(i.id) === sid);
2073
+ toast(actionToast(inc && inc.resolved ? 'resolve' : 'unconfirmed', sid));
2074
+ if (STATE.serviceDetail) STATE.serviceDetail.propKey = null;
2075
+ if (STATE.route.view === 'service') { await loadNavData(); await loadServiceLists(); }
2076
+ return Boolean(inc && inc.resolved);
2077
+ }
2078
+
2079
+
2080
+ const termInput = $('termInput');
2081
+ $('termForm').onsubmit = (ev) => { ev.preventDefault(); const t = termInput.value; termInput.value = ''; runCommand(t); };
2082
+ document.querySelectorAll('#chips [data-cmd]').forEach((b) => { b.onclick = () => runCommand(b.dataset.cmd); });
2083
+ $('termClear').onclick = () => { tlog.replaceChildren(); $('newMsgs').classList.add('hidden'); };
2084
+
2085
+ function commonPrefix(arr) { let p = arr[0]; for (const s of arr) while (!s.startsWith(p)) p = p.slice(0, -1); return p; }
2086
+ function complete() {
2087
+ const v = termInput.value;
2088
+ const sp = v.indexOf(' ');
2089
+ let head = '', pool, prefix;
2090
+ if (sp < 0) { pool = COMMANDS; prefix = v; }
2091
+ else {
2092
+ const cmd = v.slice(0, sp); head = v.slice(0, sp + 1); prefix = v.slice(sp + 1);
2093
+ if (cmd === '!explain' || cmd === '!resolve') pool = state.incidents.map((i) => String(i.id));
2094
+ else if (cmd === '!approve' || cmd === '!deny') pool = state.proposals.filter((p) => p.status === 'pending').map((p) => String(p.id));
2095
+ else return;
2096
+ }
2097
+ const hits = pool.filter((c) => c.startsWith(prefix));
2098
+ if (!hits.length) return;
2099
+ if (hits.length === 1) termInput.value = head + hits[0] + (sp < 0 ? ' ' : '');
2100
+ else { termInput.value = head + commonPrefix(hits); toast(hits.join(' ')); }
2101
+ }
2102
+ termInput.addEventListener('keydown', (ev) => {
2103
+ if (ev.key === 'Tab' && !ev.shiftKey) { ev.preventDefault(); complete(); }
2104
+ else if (ev.key === 'ArrowUp') {
2105
+ ev.preventDefault();
2106
+ if (state.histIdx > 0) { state.histIdx--; termInput.value = state.history[state.histIdx]; }
2107
+ } else if (ev.key === 'ArrowDown') {
2108
+ ev.preventDefault();
2109
+ if (state.histIdx < state.history.length - 1) { state.histIdx++; termInput.value = state.history[state.histIdx]; }
2110
+ else { state.histIdx = state.history.length; termInput.value = ''; }
2111
+ }
2112
+ });
2113
+ document.addEventListener('keydown', (ev) => {
2114
+ if (ev.key !== '/' || ev.ctrlKey || ev.metaKey || ev.altKey || STATE.route.view !== 'overview') return;
2115
+ const t = ev.target, tag = t && t.tagName;
2116
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable)) return;
2117
+ ev.preventDefault(); termInput.focus();
2118
+ });
2119
+
2120
+ function renderIdentity() {
2121
+ const you = state.workflow && state.workflow.you;
2122
+ const access = STATE.lock && STATE.lock.locked ? 'locked (unlock to approve)' : 'unlocked';
2123
+ $('identity').textContent = you ? `You are ${you.nick} · ${access}` : '';
2124
+ }
2125
+
2126
+ /* ---------- nav counters ---------- */
2127
+ function renderNav() {
2128
+ const b = navBadges(STATE.navInc, STATE.navProp, STATE.rules, Boolean(STATE.approvalStatus && STATE.approvalStatus.paused));
2129
+ const set = (sel, badge) => {
2130
+ const btn = document.querySelector(sel);
2131
+ const c = btn.querySelector('.count');
2132
+ c.textContent = badge.text;
2133
+ c.hidden = !badge.text;
2134
+ btn.setAttribute('aria-label', badge.label);
2135
+ };
2136
+ set('nav [data-nav="services"]', b.services);
2137
+ set('nav [data-nav="rules"]', b.rules);
2138
+ }
2139
+ function setNavData(incidents, proposals) {
2140
+ STATE.navInc = Array.isArray(incidents) ? incidents : [];
2141
+ STATE.navProp = Array.isArray(proposals) ? proposals : [];
2142
+ renderNav();
2143
+ renderDemoBanner();
2144
+ if (STATE.route.view === 'services' && Array.isArray(STATE.services)) renderServices();
2145
+ }
2146
+ // A change in the muted set redraws the incident lists, so the "muted" tag follows a toggle made anywhere.
2147
+ function setMutedIds(ids) {
2148
+ if (JSON.stringify(ids) === JSON.stringify(STATE.mutedIds)) return;
2149
+ STATE.mutedIds = ids;
2150
+ if (Array.isArray(state.incidents) && state.incidents.length) renderIncidents(state.incidents, true);
2151
+ const d = STATE.serviceDetail;
2152
+ if (d && STATE.route.view === 'service') { d.incKey = null; loadServiceLists(); }
2153
+ }
2154
+ // Counters need the open incidents, the pending proposals and the rules on every view (plain reads, no token).
2155
+ async function loadNavData() {
2156
+ const [i, p, r, m] = await Promise.allSettled([api('/api/incidents'), api('/api/proposals?status=pending'), api('/api/rules'), api('/api/mutes')]);
2157
+ if (r.status === 'fulfilled' && Array.isArray(r.value)) STATE.rules = r.value;
2158
+ if (m.status === 'fulfilled') setMutedIds(mutedIdsOf(m.value));
2159
+ setNavData(i.status === 'fulfilled' ? i.value : STATE.navInc, p.status === 'fulfilled' ? p.value : STATE.navProp);
2160
+ }
2161
+ const findIncident = (id) => state.incidents.concat(STATE.navInc).find((i) => String(i.id) === String(id));
2162
+
2163
+ /* ---------- data loading ---------- */
2164
+ async function loadIncidents() { const i = await api('/api/incidents'); state.incidents = i; renderIncidents(i); renderProposals(); return i; }
2165
+ async function loadProposals() { state.proposals = await api('/api/proposals'); renderProposals(); }
2166
+ // UX-12: while locked, say why step 5 will not work (the guide's own code is pinned, so this is a separate line).
2167
+ function updateGuideLock() { $('guideLockHint').textContent = guideLockText(state.workflow, Boolean(STATE.lock && STATE.lock.locked)); }
2168
+ async function loadWorkflow() {
2169
+ try { state.workflow = await api('/api/workflow'); }
2170
+ catch (e) { state.workflow = null; }
2171
+ renderGuide(); updateGuideLock(); renderIdentity(); renderProposals();
2172
+ }
2173
+
2174
+ let refreshing = false;
2175
+ async function refresh() {
2176
+ if (refreshing) return;
2177
+ refreshing = true;
2178
+ try {
2179
+ const [s, i, e, p] = await Promise.allSettled([api('/api/stats'), api('/api/incidents'), api('/api/events?limit=60'), api('/api/proposals'), loadWorkflow()]);
2180
+ if (i.status === 'fulfilled') { state.incidents = i.value; renderIncidents(i.value); }
2181
+ if (p.status === 'fulfilled') state.proposals = p.value;
2182
+ renderProposals();
2183
+ if (e.status === 'fulfilled') renderEvents(e.value);
2184
+ if (s.status === 'fulfilled') {
2185
+ renderStats(s.value);
2186
+ if (e.status === 'fulfilled') {
2187
+ $('ev-h').textContent = s.value.total_events > s.value.buffer_capacity
2188
+ ? `Séance log (latest ${e.value.length.toLocaleString()} of ${s.value.total_events.toLocaleString()})`
2189
+ : 'Séance log';
2190
+ }
2191
+ }
2192
+ } catch (err) { /* try again next tick */ }
2193
+ finally { refreshing = false; }
2194
+ }
2195
+
2196
+ $('storm').onclick = storm;
2197
+ $('sendForm').onsubmit = async (ev) => {
2198
+ ev.preventDefault();
2199
+ try { await post('/api/ingest', { source: $('source').value, line: $('line').value, host: 'dashboard' }); $('line').value = ''; }
2200
+ catch (e) { unreachable(); }
2201
+ refresh();
2202
+ };
2203
+
2204
+ /* ---------- lock and unlock ---------- */
2205
+ function applyLock() {
2206
+ const has = Boolean(storedToken());
2207
+ const ls = lockState(STATE.uiConfig, has);
2208
+ STATE.lock = ls;
2209
+ $('lockText').textContent = headerLockText(has, ls);
2210
+ $('unlockBtn').hidden = has || ls.mode === 'off';
2211
+ $('lockBtn').hidden = !has;
2212
+ document.querySelectorAll('[data-action]').forEach(lockButton);
2213
+ updatePropNote();
2214
+ updateDiscLock();
2215
+ updateGuideLock();
2216
+ renderIdentity();
2217
+ }
2218
+ function openUnlock(note) {
2219
+ $('tokenNote').textContent = note || TOKEN_PROMPT_TEXT;
2220
+ const file = STATE.uiConfig && STATE.uiConfig.token_file;
2221
+ $('tokenFile').textContent = file ? `The token is in the file ${file}` : '';
2222
+ $('tokenForm').classList.remove('hidden');
2223
+ $('unlockBtn').setAttribute('aria-expanded', 'true');
2224
+ $('tokenInput').focus();
2225
+ }
2226
+ function closeUnlock() {
2227
+ $('tokenInput').value = '';
2228
+ $('tokenForm').classList.add('hidden');
2229
+ $('unlockBtn').setAttribute('aria-expanded', 'false');
2230
+ }
2231
+ function wireUnlock() {
2232
+ $('unlockBtn').onclick = () => openUnlock();
2233
+ $('tokenCancel').onclick = () => { closeUnlock(); $('unlockBtn').focus(); };
2234
+ $('lockBtn').onclick = () => { clearToken(); applyLock(); setStatus('Locked'); $('unlockBtn').focus(); };
2235
+ // Save asks the hub before it says Unlocked: a privileged read that changes nothing (the discovery dismissals list).
2236
+ let checking = false;
2237
+ $('tokenForm').onsubmit = async (ev) => {
2238
+ ev.preventDefault();
2239
+ if (checking) return;
2240
+ const value = $('tokenInput').value.trim();
2241
+ $('tokenInput').value = '';
2242
+ if (!tokenShapeOk(value)) { $('tokenNote').textContent = 'That is not a token: 1 to 200 printable characters, no spaces.'; return; }
2243
+ const kept = saveToken(value);
2244
+ checking = true;
2245
+ setStatus('Checking the token...');
2246
+ let status = 200, failure = null;
2247
+ try { await request('GET', '/api/discovery/dismissals'); } catch (e) { failure = e; status = e && typeof e.status === 'number' ? e.status : 0; }
2248
+ checking = false;
2249
+ const out = unlockOutcome(status);
2250
+ if (!out.ok) {
2251
+ // A 401 was already handled by request(): token cleared, "token rejected" shown, this form reopened with the message.
2252
+ if (status !== 401) {
2253
+ clearToken();
2254
+ applyLock();
2255
+ const why = (failure && failure.authText) || out.text;
2256
+ setStatus(why);
2257
+ toast(why);
2258
+ openUnlock(why);
2259
+ }
2260
+ return;
2261
+ }
2262
+ closeUnlock();
2263
+ applyLock();
2264
+ setStatus(unlockStatusText(out, kept));
2265
+ toast('Unlocked. Approve and Deny are ready.');
2266
+ $('lockBtn').focus();
2267
+ };
2268
+ }
2269
+ async function loadUiConfig() {
2270
+ let cfg = null;
2271
+ try { cfg = await request('GET', '/api/ui-config'); } catch (e) { cfg = null; }
2272
+ STATE.uiConfig = cfg && typeof cfg === 'object' && typeof cfg.enforce_access === 'boolean' ? cfg : UI_FALLBACK;
2273
+ const file = STATE.uiConfig.token_file;
2274
+ $('tokenFile').textContent = file ? `The token is in the file ${file}` : '';
2275
+ $('hubVersion').textContent = versionText(STATE.uiConfig);
2276
+ $('homeVersion').textContent = versionText(STATE.uiConfig);
2277
+ STATE.demo = STATE.uiConfig.demo === true;
2278
+ renderDemoBanner();
2279
+ renderHomeDemo();
2280
+ tourStart();
2281
+ applyLock();
2282
+ if (STATE.lock.mode === 'unknown') setStatus('access mode unknown');
2283
+ }
2284
+
2285
+ /* ---------- navigation ---------- */
2286
+ const ENTER = {}; // view name -> function(route), filled by the view code below and in later tasks
2287
+ function showRoute() {
2288
+ const r = parseRoute(here.hash), closed = homeClosedFlag(here.hash);
2289
+ const before = STATE.route.view;
2290
+ STATE.route = r;
2291
+ if (closed) { homeNote = HOME_COPY.closed; history.replaceState(null, '', '#/home'); } // shown once: the hash is cleaned
2292
+ document.body.dataset.route = r.view; // CSS swaps the app header for Home's own top bar
2293
+ if ((before === 'home') !== (r.view === 'home')) window.scrollTo(0, 0);
2294
+ if (r.view !== 'service') closeLive(true);
2295
+ document.querySelectorAll('main > [data-view]').forEach((n) => { n.hidden = n.dataset.view !== r.view; });
2296
+ const active = r.view === 'service' ? 'services' : r.view;
2297
+ document.querySelectorAll('nav [data-nav]').forEach((b) => {
2298
+ if (b.dataset.nav === active) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current');
2299
+ });
2300
+ if (ENTER[r.view]) ENTER[r.view](r);
2301
+ tourRoute(r.view);
2302
+ }
2303
+
2304
+ /* ---------- services list ---------- */
2305
+ const STATE_CLASS = { active: 'st-active', idle: 'st-idle', never_seen: 'st-never' };
2306
+ function focusKeyButton(label, key, handler, cls, ariaLabel) {
2307
+ const b = el('button', cls === undefined ? 'ghost small' : cls, label);
2308
+ b.type = 'button';
2309
+ if (ariaLabel) b.setAttribute('aria-label', ariaLabel); // the visible text stays inside the name
2310
+ b.dataset.focusKey = key;
2311
+ b.onclick = handler;
2312
+ return b;
2313
+ }
2314
+ // The Mute button of a service (and, for Unassigned, its inline confirmation). `again` redraws the host.
2315
+ // Only Mute is a token action (data-action, locked while locked); Unmute is a plain button and stays enabled.
2316
+ function muteConfirmRow(s, again) {
2317
+ const row = el('div', 'mute-confirm');
2318
+ row.setAttribute('role', 'group');
2319
+ row.setAttribute('aria-label', `Confirm muting ${s.name}`);
2320
+ row.append(el('p', 'meta', MUTE_UNASSIGNED_TEXT));
2321
+ const go = actionButton('svc-mute', 'Mute Unassigned', () => setMute(s, true), 'ghost small warn mute-btn');
2322
+ const no = focusKeyButton('Cancel', `${s.id}:mute-cancel`, () => { STATE.muteConfirm = null; again(); }, 'ghost small mute-btn');
2323
+ row.append(go, no);
2324
+ return row;
2325
+ }
2326
+ function muteControls(s, again) {
2327
+ const muted = s.muted === true;
2328
+ const view = muteLabel(muted, Boolean(STATE.lock && STATE.lock.locked));
2329
+ const aria = muteAriaLabel(muted, String(s.name));
2330
+ const click = () => askMute(s, muted, again);
2331
+ const b = view.pressed ? el('button', 'ghost small mute-btn', view.text) : actionButton('svc-mute', view.text, click, 'ghost small mute-btn', aria);
2332
+ b.type = 'button';
2333
+ b.setAttribute('aria-pressed', String(view.pressed));
2334
+ b.setAttribute('aria-label', aria);
2335
+ b.dataset.focusKey = `${s.id}:mute`;
2336
+ if (view.pressed) b.onclick = click;
2337
+ b.disabled = view.disabled;
2338
+ b.title = view.title;
2339
+ const out = [b];
2340
+ if (STATE.muteConfirm === s.id && !muted) out.push(muteConfirmRow(s, again));
2341
+ return out;
2342
+ }
2343
+ function focusByKey(key) {
2344
+ const n = Array.from(document.querySelectorAll('[data-focus-key]')).find((x) => x.dataset.focusKey === key);
2345
+ if (n) n.focus();
2346
+ }
2347
+ // Muting Unassigned drops every unmatched event, so it asks first, inline; focus goes to Cancel.
2348
+ function askMute(s, muted, again) {
2349
+ if (!muted && s.builtin) { STATE.muteConfirm = s.id; again(); focusByKey(`${s.id}:mute-cancel`); return; }
2350
+ setMute(s, !muted);
2351
+ }
2352
+ async function setMute(s, on) {
2353
+ const path = `/api/services/${encodeURIComponent(s.id)}/mute`;
2354
+ try { await request(on ? 'PUT' : 'DELETE', path); }
2355
+ catch (e) { setStatus(e.authText || errorText(e.status, e.body)); return; }
2356
+ STATE.muteConfirm = null;
2357
+ toast(muteToast(on ? 'mute' : 'unmute', String(s.name)));
2358
+ await Promise.allSettled([loadNavData(), STATE.route.view === 'services' ? loadServices() : null, STATE.route.view === 'service' ? loadServiceDetail() : null]);
2359
+ }
2360
+ function redrawServices() { lastSvcKey = null; renderServices(); }
2361
+ function serviceCard(s, now) {
2362
+ const c = el('article', 'svc-card');
2363
+ const top = el('div', 'top');
2364
+ top.append(el('h3', '', String(s.name)), el('span', `pill ${STATE_CLASS[s.state] || 'st-unknown'}`, stateLabel('service', s.state)));
2365
+ const mutedText = mutePillText(s);
2366
+ if (mutedText) top.append(el('span', 'pill muted', mutedText));
2367
+ c.append(top, el('div', 'meta', `id ${s.id}`));
2368
+ if (s.builtin) c.append(el('div', 'meta', 'built in'));
2369
+ const open = Number(s.open_incidents) || 0;
2370
+ const facts = el('div', 'meta facts-line');
2371
+ facts.append(el('span', '', `last seen ${relTime(s.last_seen, now)}`), el('span', '', `${Number(s.error_rate) || 0} errors/min`), el('span', '', `${open} open incident${open === 1 ? '' : 's'}`));
2372
+ c.append(facts);
2373
+ const dropped = droppedText(Number(s.events_dropped));
2374
+ if (dropped) c.append(el('div', 'meta', dropped));
2375
+ if (s.builtin) c.append(el('div', 'meta', 'Events no service claims yet. Add a service or run discovery to claim them.'));
2376
+ const waiting = pendingFor(STATE.navProp, s.id);
2377
+ if (waiting) top.append(el('span', 'pill pending', `${waiting} ${waiting === 1 ? 'fix' : 'fixes'} waiting`));
2378
+ const sources = Array.isArray(s.log_sources) ? s.log_sources : [];
2379
+ if (sources.length) {
2380
+ const ul = el('ul');
2381
+ for (const ls of sources) {
2382
+ const li = el('li');
2383
+ li.append(el('div', '', String(ls.path)));
2384
+ li.append(el('div', 'meta', `${ls.format} · ${stateLabel('source', ls.status)} · ${Number(ls.lines_dropped) || 0} lines dropped`));
2385
+ if (ls.last_error) li.append(el('div', 'err', capText(ls.last_error, 300)));
2386
+ ul.append(li);
2387
+ }
2388
+ c.append(ul);
2389
+ }
2390
+ const actions = el('div', 'actions');
2391
+ actions.append(focusKeyButton('Open', `${s.id}:open`, () => { here.hash = `#/services/${encodeURIComponent(s.id)}`; }, undefined, `Open ${s.name}`));
2392
+ if (!s.builtin) actions.append(focusKeyButton('Edit', `${s.id}:edit`, () => renderServiceForm(s), undefined, `Edit ${s.name}`));
2393
+ actions.append(...muteControls(s, redrawServices));
2394
+ c.append(actions);
2395
+ return c;
2396
+ }
2397
+ let lastSvcKey = null;
2398
+ function renderServices() {
2399
+ const list = sortServices(Array.isArray(STATE.services) ? STATE.services : []);
2400
+ const now = Date.now() / 1000;
2401
+ const key = JSON.stringify([list, Math.floor(now / 30), list.map((s) => pendingFor(STATE.navProp, s.id)), STATE.muteConfirm]);
2402
+ if (key === lastSvcKey) return;
2403
+ lastSvcKey = key;
2404
+ const box = $('svcList');
2405
+ const f = document.activeElement;
2406
+ const focusKey = f && box.contains(f) ? f.dataset.focusKey : null;
2407
+ box.replaceChildren();
2408
+ if (!list.some((s) => !s.builtin)) {
2409
+ const empty = el('div', 'svc-card');
2410
+ empty.append(el('p', 'empty', 'No services yet. Run discovery or add one.'));
2411
+ const a = el('div', 'actions');
2412
+ a.append(focusKeyButton('Discover local apps', 'empty:discover', () => { here.hash = '#/discovery'; }, ''));
2413
+ a.append(focusKeyButton('Add service', 'empty:add', () => openServiceForm(null), 'ghost'));
2414
+ empty.append(a);
2415
+ box.append(empty);
2416
+ }
2417
+ for (const s of list) box.append(serviceCard(s, now));
2418
+ if (focusKey) {
2419
+ const n = Array.from(box.querySelectorAll('[data-focus-key]')).find((x) => x.dataset.focusKey === focusKey);
2420
+ if (n) n.focus();
2421
+ }
2422
+ }
2423
+ async function loadServices() {
2424
+ try {
2425
+ STATE.services = await request('GET', '/api/services');
2426
+ renderServices();
2427
+ } catch (e) { setStatus(errorText(e.status, e.body)); }
2428
+ }
2429
+ /* ---------- add and edit form ---------- */
2430
+ function textInput(id, value, max) {
2431
+ const i = el('input');
2432
+ i.type = 'text'; i.id = id; i.value = value || ''; i.maxLength = max; i.autocomplete = 'off'; i.spellcheck = false;
2433
+ return i;
2434
+ }
2435
+ const SRC_ROWS = new WeakMap(); // table row -> its inputs and source id
2436
+ let srcRowSeq = 0;
2437
+ function sourceRow(src) {
2438
+ const n = ++srcRowSeq;
2439
+ const tr = el('tr');
2440
+ const path = textInput(`svcFSrc${n}Path`, src ? src.path : '', 1024);
2441
+ if (src) path.disabled = true; // the path of a source cannot change: remove the row and add a new one
2442
+ const fmt = el('select');
2443
+ fmt.id = `svcFSrc${n}Fmt`;
2444
+ const formats = STATE.uiConfig.formats.slice();
2445
+ if (src && !formats.includes(src.format)) formats.push(src.format);
2446
+ for (const f of formats) { const o = el('option', '', f); o.value = f; fmt.append(o); }
2447
+ fmt.value = src ? src.format : formats[0];
2448
+ const on = el('input');
2449
+ on.type = 'checkbox'; on.id = `svcFSrc${n}On`; on.checked = src ? Boolean(src.enabled) : true;
2450
+ const rm = el('button', 'ghost small warn', 'Remove');
2451
+ rm.type = 'button';
2452
+ rm.onclick = () => { tr.remove(); };
2453
+ for (const cell of [field('Path', path), field('Format', fmt), field('Enabled', on), rm]) { const td = el('td'); td.append(cell); tr.append(td); }
2454
+ SRC_ROWS.set(tr, { id: src ? src.id : '', path, fmt, on });
2455
+ return tr;
2456
+ }
2457
+ // Show the Services page and open the form on it (an edit when s is given), focusing ocusId when it names a field.
2458
+ // The route is shown first so the focus lands on a visible field.
2459
+ function openServiceForm(s, focusId) {
2460
+ if (here.hash !== '#/services') here.hash = '#/services';
2461
+ showRoute();
2462
+ renderServiceForm(s, focusId);
2463
+ }
2464
+ function renderServiceForm(s, focusId) {
2465
+ const create = !s;
2466
+ STATE.svcForm = { mode: create ? 'create' : 'edit', original: s || null };
2467
+ const box = $('svcFormBox');
2468
+ box.replaceChildren();
2469
+ const f = el('form', 'svc-form');
2470
+ f.setAttribute('aria-label', create ? 'Add service' : 'Edit service');
2471
+ f.append(el('h3', '', create ? 'Add service' : `Edit ${s.name}`));
2472
+ const nameIn = textInput('svcFName', s ? s.name : '', 200);
2473
+ f.append(field('Name', nameIn));
2474
+ if (create) {
2475
+ // The id follows the name until the user types in it.
2476
+ const idIn = textInput('svcFId', '', 40);
2477
+ let idEdited = false;
2478
+ idIn.addEventListener('input', () => { idEdited = true; });
2479
+ nameIn.addEventListener('input', () => { if (!idEdited) idIn.value = slugify(nameIn.value); });
2480
+ f.append(field('Id', idIn));
2481
+ }
2482
+ f.append(field('Hosts (comma separated)', textInput('svcFHosts', s ? (s.hosts || []).join(', ') : '', 4000)));
2483
+ const appsIn = textInput('svcFApps', s ? (s.app_names || []).join(', ') : '', 4000);
2484
+ f.append(field('App names (comma separated)', appsIn));
2485
+ if (create) {
2486
+ // Create mode only: App names follows the name until the user types in it. An edit never rewrites saved names.
2487
+ let appsEdited = false;
2488
+ appsIn.addEventListener('input', () => { appsEdited = true; });
2489
+ nameIn.addEventListener('input', () => { if (!appsEdited) appsIn.value = defaultAppNames(nameIn.value); });
2490
+ }
2491
+ const protos = el('fieldset');
2492
+ protos.append(el('legend', '', 'Protocols'));
2493
+ STATE.uiConfig.protocols.forEach((p, i) => {
2494
+ const c = el('input');
2495
+ c.type = 'checkbox'; c.id = `svcFProto${i}`; c.value = p; c.checked = Boolean(s && (s.protocols || []).includes(p));
2496
+ protos.append(field(p, c));
2497
+ });
2498
+ protos.append(el('div', 'meta', 'Which feeds belong to this service. Leave empty to match by host or app name only.'));
2499
+ f.append(protos);
2500
+ f.append(field('Code folder', textInput('svcFCode', s ? s.code_folder || '' : '', 1024)));
2501
+ f.append(el('h4', '', 'Log files'));
2502
+ const wrap = el('div', 'table-wrap');
2503
+ const table = el('table', 'sources');
2504
+ const tbody = el('tbody');
2505
+ tbody.id = 'svcFSources';
2506
+ for (const ls of (s && s.log_sources) || []) tbody.append(sourceRow(ls));
2507
+ table.append(tbody); wrap.append(table); f.append(wrap);
2508
+ const addRow = el('button', 'ghost small', 'Add log file');
2509
+ addRow.type = 'button';
2510
+ addRow.onclick = () => { const tr = sourceRow(null); tbody.append(tr); SRC_ROWS.get(tr).path.focus(); };
2511
+ const save = actionButton('svc-save', 'Save', () => saveService(), '');
2512
+ const cancel = el('button', 'ghost', 'Cancel');
2513
+ cancel.type = 'button';
2514
+ cancel.onclick = () => { box.replaceChildren(); STATE.svcForm = null; $('svcAdd').focus(); };
2515
+ const actions = el('div', 'actions');
2516
+ actions.append(addRow, save, cancel);
2517
+ const msg = el('div', 'meta');
2518
+ msg.id = 'svcFMsg';
2519
+ msg.setAttribute('role', 'status');
2520
+ f.onsubmit = (ev) => { ev.preventDefault(); if (!save.disabled) saveService(); };
2521
+ f.append(actions, msg);
2522
+ box.append(f);
2523
+ const target = focusId && $(focusId) ? $(focusId) : $('svcFName');
2524
+ target.focus();
2525
+ }
2526
+ function readServiceForm() {
2527
+ const idIn = $('svcFId');
2528
+ return {
2529
+ id: idIn ? idIn.value.trim() : '',
2530
+ name: $('svcFName').value.trim(),
2531
+ hosts: splitList($('svcFHosts').value),
2532
+ app_names: splitList($('svcFApps').value),
2533
+ protocols: STATE.uiConfig.protocols.filter((p, i) => { const c = $(`svcFProto${i}`); return Boolean(c && c.checked); }),
2534
+ code_folder: $('svcFCode').value.trim(),
2535
+ rows: Array.from($('svcFSources').children).map((tr) => {
2536
+ const r = SRC_ROWS.get(tr);
2537
+ return { id: r.id, path: r.path.value.trim(), format: r.fmt.value, enabled: r.on.checked, tr };
2538
+ }),
2539
+ };
2540
+ }
2541
+ // Sequential save: the service, then the log-source operations (POST, PATCH, DELETE). The first failure stops
2542
+ // the run and shows the server's text; what was already saved stays, and the form keeps editing it.
2543
+ async function saveService() {
2544
+ const st = STATE.svcForm;
2545
+ if (!st || st.busy) return; // a double click must not send the create or a log-source POST twice
2546
+ st.busy = true;
2547
+ try {
2548
+ const msg = $('svcFMsg');
2549
+ msg.textContent = 'Saving...';
2550
+ const form = readServiceForm();
2551
+ const fail = (e) => { msg.textContent = errorText(e.status, e.body); };
2552
+ if (st.mode === 'create') {
2553
+ try { st.original = await request('POST', '/api/services', serviceCreateBody(form)); }
2554
+ catch (e) { fail(e); return; }
2555
+ st.mode = 'edit';
2556
+ if (!Array.isArray(st.original.log_sources)) st.original.log_sources = [];
2557
+ $('svcFId').disabled = true;
2558
+ } else {
2559
+ const patch = servicePatch(st.original, form);
2560
+ if (Object.keys(patch).length) {
2561
+ try { Object.assign(st.original, await request('PATCH', `/api/services/${encodeURIComponent(st.original.id)}`, patch)); }
2562
+ catch (e) { fail(e); return; }
2563
+ }
2564
+ }
2565
+ const sid = encodeURIComponent(st.original.id);
2566
+ const sources = st.original.log_sources || [];
2567
+ const diff = diffSources(sources, form.rows);
2568
+ for (const a of diff.add) {
2569
+ let created;
2570
+ try { created = await request('POST', `/api/services/${sid}/log-sources`, { path: a.path, format: a.format, enabled: a.enabled }); }
2571
+ catch (e) { fail(e); return; }
2572
+ const row = SRC_ROWS.get(form.rows[a.index].tr);
2573
+ row.id = created.id; row.path.disabled = true;
2574
+ sources.push(created);
2575
+ }
2576
+ for (const u of diff.update) {
2577
+ try { Object.assign(sources.find((x) => x.id === u.id), await request('PATCH', `/api/services/${sid}/log-sources/${encodeURIComponent(u.id)}`, u.patch)); }
2578
+ catch (e) { fail(e); return; }
2579
+ }
2580
+ for (const id of diff.remove) {
2581
+ try { await request('DELETE', `/api/services/${sid}/log-sources/${encodeURIComponent(id)}`); }
2582
+ catch (e) { fail(e); return; }
2583
+ sources.splice(sources.findIndex((x) => x.id === id), 1);
2584
+ }
2585
+ msg.textContent = 'Saved.';
2586
+ STATE.svcForm = null;
2587
+ $('svcFormBox').replaceChildren();
2588
+ setStatus(`Service ${st.original.id} saved`);
2589
+ lastSvcKey = null;
2590
+ loadServices();
2591
+ } finally {
2592
+ st.busy = false;
2593
+ }
2594
+ }
2595
+ ENTER.overview = () => { refresh(); fetchChat(); };
2596
+ ENTER.services = () => { lastSvcKey = null; loadServices(); };
2597
+
2598
+ /* ---------- service detail ---------- */
2599
+ function setSlotsHidden(hidden) { document.querySelectorAll('#view-service [data-slot]').forEach((n) => { n.hidden = hidden; }); }
2600
+ function showServiceGone() {
2601
+ closeLive(true);
2602
+ $('svcDetail').hidden = true;
2603
+ setSlotsHidden(true);
2604
+ $('svcGone').hidden = false;
2605
+ $('svcBack').focus();
2606
+ }
2607
+ function renderServiceHeader(s) {
2608
+ $('svcDetail').hidden = false;
2609
+ $('svcGone').hidden = true;
2610
+ setSlotsHidden(false);
2611
+ $('svcName').textContent = String(s.name);
2612
+ const pill = $('svcPill');
2613
+ pill.className = `pill ${STATE_CLASS[s.state] || 'st-unknown'}`;
2614
+ pill.textContent = stateLabel('service', s.state);
2615
+ pill.hidden = false;
2616
+ $('svcId').textContent = String(s.id);
2617
+ $('svcState').textContent = stateLabel('service', s.state);
2618
+ $('svcSeen').textContent = relTime(s.last_seen, Date.now() / 1000);
2619
+ $('svcRate').textContent = String(s.error_rate);
2620
+ $('svcOpen').textContent = String(s.open_incidents);
2621
+ const hint = serviceMatchHint(s);
2622
+ $('svcHint').textContent = hint;
2623
+ $('svcHint').hidden = !hint;
2624
+ const editField = hint ? hintEditField(s) : '';
2625
+ const hintEdit = $('svcHintEdit');
2626
+ hintEdit.hidden = !editField;
2627
+ hintEdit.onclick = () => openServiceForm(s, editField);
2628
+ const mutedText = mutePillText(s);
2629
+ $('svcMuted').textContent = mutedText;
2630
+ $('svcMuted').hidden = !mutedText;
2631
+ const dropped = droppedText(Number(s.events_dropped));
2632
+ $('svcDropped').textContent = dropped;
2633
+ $('svcDropped').hidden = !dropped;
2634
+ renderMuteSlot(s);
2635
+ }
2636
+ function renderMuteSlot(s) {
2637
+ const box = $('svcMute');
2638
+ const f = document.activeElement;
2639
+ const key = f && box.contains(f) ? f.dataset.focusKey : null;
2640
+ box.replaceChildren(...muteControls(s, () => { const d = STATE.serviceDetail; if (d && d.status) renderServiceHeader(d.status); }));
2641
+ if (key) focusByKey(key);
2642
+ }
2643
+ async function loadServiceDetail() {
2644
+ const d = STATE.serviceDetail;
2645
+ if (!d) return;
2646
+ try {
2647
+ const s = await request('GET', `/api/services/${encodeURIComponent(d.id)}`);
2648
+ if (STATE.serviceDetail !== d) return;
2649
+ d.status = s;
2650
+ renderServiceHeader(s);
2651
+ } catch (e) {
2652
+ if (STATE.serviceDetail !== d) return;
2653
+ if (e.status === 404) showServiceGone();
2654
+ else setStatus(errorText(e.status, e.body));
2655
+ }
2656
+ }
2657
+ // Incidents and proposals of one service: the hub filters by service before it applies the limit.
2658
+ function renderIncidentsFor(list) {
2659
+ const box = $('svcIncidents');
2660
+ box.replaceChildren();
2661
+ if (!list.length) { box.append(el('p', 'empty', 'No incidents for this service.')); return; }
2662
+ for (const i of list) {
2663
+ const sev = Number.isInteger(i.severity) ? i.severity : 7;
2664
+ const d = el('article', `incident sev-${sev}${i.resolved ? ' resolved' : ''}`);
2665
+ d.append(el('h3', '', `${String(i.category).toUpperCase()} on ${i.host} ×${i.count}`));
2666
+ const meta = el('div', 'meta', `${sevName(sev)} · id ${i.id}${i.resolved ? ' · resolved' : ' · open'}`);
2667
+ const mutedTag = mutedIncidentTag(i, STATE.mutedIds);
2668
+ if (mutedTag) meta.append(' ', el('span', 'pill muted', mutedTag));
2669
+ d.append(meta);
2670
+ d.append(el('div', 'sample', i.sample), el('p', '', i.hypothesis));
2671
+ appendIncidentActions(d, i, true);
2672
+ box.append(d);
2673
+ }
2674
+ }
2675
+ function renderServiceProposals(list) {
2676
+ const box = $('svcProposals');
2677
+ box.replaceChildren();
2678
+ updatePropNote();
2679
+ const sorted = list.slice().sort((a, b) => (b.created || 0) - (a.created || 0));
2680
+ if (!sorted.length) { box.append(el('p', 'empty', 'No proposals for this service.')); return; }
2681
+ for (const p of sorted) box.append(renderProposalCard(p, `incident ${p.incident_id}`, 'svcPropNote'));
2682
+ }
2683
+ function resetServiceLists() {
2684
+ const d = STATE.serviceDetail;
2685
+ if (d) { d.incKey = null; d.propKey = null; }
2686
+ $('svcIncidents').replaceChildren();
2687
+ $('svcProposals').replaceChildren();
2688
+ }
2689
+ async function loadServiceLists() {
2690
+ const d = STATE.serviceDetail;
2691
+ if (!d) return;
2692
+ const id = encodeURIComponent(d.id);
2693
+ const [inc, prop] = await Promise.allSettled([
2694
+ request('GET', `/api/incidents?service_id=${id}&limit=100`),
2695
+ request('GET', `/api/proposals?service_id=${id}`),
2696
+ ]);
2697
+ if (STATE.serviceDetail !== d) return;
2698
+ if (inc.status === 'fulfilled' && Array.isArray(inc.value)) {
2699
+ const key = JSON.stringify(inc.value);
2700
+ // never wipe a propose form being typed in; the next poll renders the list
2701
+ if (key !== d.incKey && !document.querySelector('#svcIncidents form.propose')) { d.incKey = key; renderIncidentsFor(inc.value); }
2702
+ }
2703
+ if (prop.status === 'fulfilled' && Array.isArray(prop.value)) {
2704
+ const key = JSON.stringify(prop.value);
2705
+ if (key !== d.propKey) { d.propKey = key; renderServiceProposals(prop.value); }
2706
+ }
2707
+ }
2708
+ function openServiceDetail(id) {
2709
+ STATE.serviceDetail = { id, status: null };
2710
+ resetPermissionsPanel();
2711
+ startLive(id);
2712
+ resetServiceLists();
2713
+ loadServiceLists();
2714
+ $('svcName').textContent = id;
2715
+ $('svcPill').hidden = true;
2716
+ $('svcMuted').hidden = true;
2717
+ $('svcDropped').hidden = true;
2718
+ $('svcMute').replaceChildren();
2719
+ for (const k of ['svcId', 'svcState', 'svcSeen', 'svcRate', 'svcOpen']) $(k).textContent = '';
2720
+ $('svcGone').hidden = true;
2721
+ $('svcDetail').hidden = false;
2722
+ setSlotsHidden(false);
2723
+ loadServiceDetail();
2724
+ }
2725
+ ENTER.service = (r) => openServiceDetail(r.id);
2726
+
2727
+ /* ---------- Kiro permissions panel ---------- */
2728
+ // Fetched on the first open of the panel for this service, never on page load; shown as text only.
2729
+ function renderPermissionsPanel() {
2730
+ const panel = $('permPanel');
2731
+ panel.addEventListener('toggle', () => { if (panel.open) loadPermissions(); });
2732
+ $('permCopy').onclick = copyPermissions;
2733
+ }
2734
+ function resetPermissionsPanel() {
2735
+ STATE.permFor = null;
2736
+ $('permPanel').open = false;
2737
+ $('permText').textContent = '';
2738
+ $('permMsg').textContent = '';
2739
+ }
2740
+ async function loadPermissions() {
2741
+ const d = STATE.serviceDetail;
2742
+ if (!d || STATE.permFor === d.id) return;
2743
+ STATE.permFor = d.id;
2744
+ $('permMsg').textContent = 'Loading...';
2745
+ try {
2746
+ const text = await request('GET', `/api/services/${encodeURIComponent(d.id)}/permissions-snippet`, undefined, 'text');
2747
+ if (STATE.serviceDetail !== d) return;
2748
+ $('permText').textContent = String(text);
2749
+ $('permMsg').textContent = '';
2750
+ } catch (e) {
2751
+ STATE.permFor = null; // the next open tries again
2752
+ if (STATE.serviceDetail !== d) return;
2753
+ $('permMsg').textContent = e.status === 404 ? 'not available yet' : errorText(e.status, e.body);
2754
+ }
2755
+ }
2756
+ function copyPermissions() {
2757
+ const pre = $('permText');
2758
+ const text = pre.textContent;
2759
+ if (!text) return;
2760
+ copyText(text, pre, $('permCopy'), $('permCopyMsg')); // the same Copied / Copy failed pattern as Home
2761
+ }
2762
+
2763
+ /* ---------- live log (SSE) ---------- */
2764
+ // One EventSource per open service detail. The message text goes in with textContent only; rows are capped.
2765
+ const LOG_MSG_SHORT = 500, LOG_MSG_LONG = 4096, LOG_QUEUE_MAX = 500;
2766
+ const ROW_EV = new WeakMap(); // row -> its event, for the client-side filters
2767
+ function streamUrl(id, lastId) {
2768
+ const base = `/api/services/${encodeURIComponent(id)}/stream`;
2769
+ return lastId > 0 ? `${base}?after=${lastId}` : `${base}?tail=100`;
2770
+ }
2771
+ function showLiveStatus(L) {
2772
+ const parts = [];
2773
+ if (L.note) parts.push(L.note);
2774
+ if (L.paused) parts.push(`Paused · ${L.queue.length} new`);
2775
+ $('liveStatus').textContent = parts.join(' · ');
2776
+ }
2777
+ function addLiveRow(ev) {
2778
+ const L = STATE.live;
2779
+ if (!L) return;
2780
+ const box = $('liveBox');
2781
+ const row = el('div', 'row live');
2782
+ const msg = String(ev.message === null || ev.message === undefined ? '' : ev.message);
2783
+ const label = ev.severity_name || sevName(ev.severity);
2784
+ const cls = SEV_NAMES.includes(label) ? label : 'unknown';
2785
+ const host = `${ev.host === null || ev.host === undefined ? '' : ev.host}: `;
2786
+ const text = el('span', 'm', host + capText(msg, LOG_MSG_SHORT));
2787
+ const cell = el('div', 'cell');
2788
+ cell.append(text);
2789
+ if (msg.length > LOG_MSG_SHORT) {
2790
+ const more = el('button', 'ghost small', 'show more');
2791
+ more.type = 'button';
2792
+ more.onclick = () => { text.textContent = host + capText(msg, LOG_MSG_LONG); row.classList.add('open'); more.remove(); };
2793
+ cell.append(more);
2794
+ }
2795
+ row.append(el('span', 'meta', fmtTime(ev.ts)), el('span', `sev-${cls}`, String(label)), cell);
2796
+ ROW_EV.set(row, ev);
2797
+ row.hidden = !rowMatches(ev, L.sev, L.text);
2798
+ box.append(row);
2799
+ while (box.childElementCount > 500) box.firstElementChild.remove();
2800
+ if (L.auto) box.scrollTop = box.scrollHeight;
2801
+ }
2802
+ function addSystemRow(text) {
2803
+ const box = $('liveBox');
2804
+ const row = el('div', 'row live sys');
2805
+ row.append(el('span', 'meta', ''), el('span', '', 'system'), el('div', 'cell', text));
2806
+ box.append(row);
2807
+ while (box.childElementCount > 500) box.firstElementChild.remove();
2808
+ }
2809
+ function applyLiveFilter() {
2810
+ const L = STATE.live;
2811
+ if (!L) return;
2812
+ for (const row of $('liveBox').children) {
2813
+ const ev = ROW_EV.get(row);
2814
+ if (ev) row.hidden = !rowMatches(ev, L.sev, L.text);
2815
+ }
2816
+ }
2817
+ function onLiveMessage(L, m) {
2818
+ if (STATE.live !== L) return;
2819
+ let ev = null;
2820
+ try { ev = JSON.parse(m.data); } catch (e) { return; }
2821
+ if (!ev || typeof ev !== 'object' || !Number.isInteger(ev.id) || !isNewer(ev.id, L.lastId)) return;
2822
+ L.lastId = ev.id;
2823
+ L.fails = 0;
2824
+ if (L.note) { L.note = ''; showLiveStatus(L); }
2825
+ if (L.paused) {
2826
+ L.queue.push(ev);
2827
+ if (L.queue.length > LOG_QUEUE_MAX) L.queue.shift();
2828
+ showLiveStatus(L);
2829
+ } else addLiveRow(ev);
2830
+ }
2831
+ function onLiveDropped(L, m) {
2832
+ if (STATE.live !== L) return;
2833
+ let n = 0;
2834
+ try { n = Number(JSON.parse(m.data).count) || 0; } catch (e) { n = 0; }
2835
+ addSystemRow(`${n} events were skipped`);
2836
+ }
2837
+ function onLiveClosed(L, src, m) {
2838
+ src.close(); // the server ends the response after a closed frame: stop the browser's own reconnect first
2839
+ if (L.source === src) L.source = null;
2840
+ if (STATE.live !== L) return;
2841
+ let reason = '';
2842
+ try { reason = String(JSON.parse(m.data).reason || ''); } catch (e) { reason = ''; }
2843
+ if (reason === 'service_deleted') { L.stopped = true; L.note = 'this service was deleted; the live log stopped'; showLiveStatus(L); return; }
2844
+ if (reason === 'max_age') { openLive(); return; }
2845
+ scheduleLive();
2846
+ }
2847
+ function onLiveError(L, src) {
2848
+ src.close(); // never let the browser reconnect on its own: that would hold a second slot
2849
+ if (L.source !== src || STATE.live !== L) return;
2850
+ L.source = null;
2851
+ L.note = L.fails >= 2 ? 'live log disconnected: too many live logs open (limit 20) or the hub is down' : 'live log disconnected, reconnecting...';
2852
+ showLiveStatus(L);
2853
+ scheduleLive();
2854
+ }
2855
+ function scheduleLive() {
2856
+ const L = STATE.live;
2857
+ if (!L || L.stopped || L.timer || document.visibilityState !== 'visible') return;
2858
+ const wait = nextBackoff(L.fails);
2859
+ L.fails += 1;
2860
+ L.timer = setTimeout(() => { L.timer = null; openLive(); }, wait * 1000);
2861
+ }
2862
+ function openLive() {
2863
+ const L = STATE.live;
2864
+ if (!L || L.stopped || L.source || document.visibilityState !== 'visible') return;
2865
+ if (L.timer) { clearTimeout(L.timer); L.timer = null; }
2866
+ const src = new EventSource(streamUrl(L.id, L.lastId));
2867
+ L.source = src;
2868
+ src.onmessage = (m) => onLiveMessage(L, m);
2869
+ src.addEventListener('dropped', (m) => onLiveDropped(L, m));
2870
+ src.addEventListener('closed', (m) => onLiveClosed(L, src, m));
2871
+ src.onerror = () => onLiveError(L, src);
2872
+ }
2873
+ function closeLive(forget) {
2874
+ const L = STATE.live;
2875
+ if (!L) return;
2876
+ if (L.timer) { clearTimeout(L.timer); L.timer = null; }
2877
+ if (L.source) { L.source.close(); L.source = null; }
2878
+ if (forget) STATE.live = null;
2879
+ }
2880
+ function startLive(id) {
2881
+ closeLive(true);
2882
+ const L = { id, source: null, timer: null, lastId: 0, fails: 0, paused: false, queue: [], auto: true, sev: 7, text: '', stopped: false, note: '' };
2883
+ STATE.live = L;
2884
+ $('liveBox').replaceChildren();
2885
+ $('livePause').textContent = 'Pause';
2886
+ $('liveAuto').checked = true;
2887
+ $('liveSev').value = '7';
2888
+ $('liveText').value = '';
2889
+ showLiveStatus(L);
2890
+ openLive();
2891
+ }
2892
+ function toggleLivePause() {
2893
+ const L = STATE.live;
2894
+ if (!L) return;
2895
+ L.paused = !L.paused;
2896
+ $('livePause').textContent = L.paused ? 'Resume' : 'Pause';
2897
+ if (!L.paused) { const q = L.queue; L.queue = []; for (const ev of q) addLiveRow(ev); }
2898
+ showLiveStatus(L);
2899
+ }
2900
+ function wireLive() {
2901
+ $('livePause').onclick = toggleLivePause;
2902
+ $('liveAuto').onchange = () => { if (STATE.live) STATE.live.auto = $('liveAuto').checked; };
2903
+ $('liveSev').onchange = () => { if (STATE.live) { STATE.live.sev = Number($('liveSev').value); applyLiveFilter(); } };
2904
+ $('liveText').oninput = () => { if (STATE.live) { STATE.live.text = $('liveText').value.trim(); applyLiveFilter(); } };
2905
+ }
2906
+ // A hidden tab holds no stream slot; coming back resumes from the last id.
2907
+ function liveVisibility() {
2908
+ const L = STATE.live;
2909
+ if (!L || STATE.route.view !== 'service') return;
2910
+ if (document.visibilityState === 'hidden') closeLive(false);
2911
+ else { L.fails = 0; openLive(); }
2912
+ }
2913
+
2914
+ /* ---------- rule form and rule from a proposal ---------- */
2915
+ const RULE_CATEGORIES = ['memory', 'disk', 'network', 'security', 'crash', 'unknown'];
2916
+ const RULE_FALLBACK = {
2917
+ most_urgent_severity: { min: 3, max: 4, default: 3 },
2918
+ max_per_hour: { min: 1, max: 10, default: 3 },
2919
+ max_per_incident: { min: 1, max: 3, default: 1 },
2920
+ max_files: { min: 1, max: 20, default: 5 },
2921
+ max_lines: { min: 1, max: 500, default: 100 },
2922
+ expires_days: { min: 1, max: 29, default: 7 },
2923
+ };
2924
+ let ruleFormSeq = 0;
2925
+ // One read of the approval status for the form's bounds, only when the page has none yet.
2926
+ async function ensureApprovalStatus() {
2927
+ if (STATE.approvalStatus) return STATE.approvalStatus;
2928
+ try { STATE.approvalStatus = await request('GET', '/api/approvals/status'); } catch (e) { /* the fallback numbers are used */ }
2929
+ return STATE.approvalStatus || null;
2930
+ }
2931
+ function numberInput(id, b, value) {
2932
+ const i = el('input');
2933
+ i.type = 'number'; i.id = id; i.min = String(b.min); i.max = String(b.max); i.step = '1'; i.value = String(value);
2934
+ return i;
2935
+ }
2936
+ // The shared rule form. `defaults` is the hub's rule-defaults (or null for a new rule); the caller adds its own
2937
+ // confirm button to `actions`, so the lock registry sees the right action id.
2938
+ function renderRuleForm(defaults, mode) {
2939
+ const n = ++ruleFormSeq;
2940
+ const create = mode === 'create';
2941
+ const edit = mode === 'edit';
2942
+ const bounds = STATE.approvalStatus && STATE.approvalStatus.bounds;
2943
+ const sb = boundOf(bounds, 'most_urgent_severity', RULE_FALLBACK.most_urgent_severity);
2944
+ const hb = boundOf(bounds, 'max_per_hour', RULE_FALLBACK.max_per_hour);
2945
+ const ib = boundOf(bounds, 'max_per_incident', RULE_FALLBACK.max_per_incident);
2946
+ const fb = boundOf(bounds, 'max_files', RULE_FALLBACK.max_files);
2947
+ const lb = boundOf(bounds, 'max_lines', RULE_FALLBACK.max_lines);
2948
+ const eb = boundOf(bounds, 'expires_days', RULE_FALLBACK.expires_days);
2949
+ const dayBound = { min: Math.max(1, eb.min), max: Math.min(29, eb.max), default: 7 };
2950
+ const d = defaults || {};
2951
+ const pick = (key, b) => (typeof d[key] === 'number' ? d[key] : b.default);
2952
+ const f = el('form', 'rule-form');
2953
+ f.append(el('h4', '', mode === 'proposal' ? 'Always approve fixes like this' : edit ? 'Edit rule' : 'New rule'));
2954
+ let svc = null, mtype = null, valText = null, valCat = null, first = null;
2955
+ if (create) {
2956
+ const eligible = (Array.isArray(STATE.services) ? STATE.services : []).filter((s) => !s.builtin && s.code_folder);
2957
+ svc = el('select');
2958
+ svc.id = `ruleF${n}Svc`;
2959
+ for (const s of eligible) { const o = el('option', '', `${s.name} (${s.id})`); o.value = s.id; svc.append(o); }
2960
+ mtype = el('select');
2961
+ mtype.id = `ruleF${n}Type`;
2962
+ for (const t of ['signature', 'category']) { const o = el('option', '', t); o.value = t; mtype.append(o); }
2963
+ valText = textInput(`ruleF${n}Value`, '', 200);
2964
+ valCat = el('select');
2965
+ valCat.id = `ruleF${n}Cat`;
2966
+ const cats = bounds && Array.isArray(bounds.categories) ? bounds.categories.filter((c) => typeof c === 'string') : RULE_CATEGORIES;
2967
+ for (const c of cats) { const o = el('option', '', c); o.value = c; valCat.append(o); }
2968
+ const textField = field('Signature text', valText);
2969
+ const catField = field('Category', valCat);
2970
+ catField.hidden = true;
2971
+ mtype.onchange = () => { const isCat = mtype.value === 'category'; textField.hidden = isCat; catField.hidden = !isCat; };
2972
+ f.append(field('Service (with a code folder)', svc), field('Match on', mtype), textField, catField);
2973
+ if (!eligible.length) f.append(el('p', 'meta', 'No service has a code folder yet. Set one in the service form first.'));
2974
+ first = svc;
2975
+ } else {
2976
+ const facts = el('dl', 'facts');
2977
+ facts.append(el('dt', '', 'Service'), el('dd', '', String(d.service_id || '')), el('dt', '', 'Matches'), el('dd', '', `${d.match_type || ''} ${d.match_value || ''}`));
2978
+ f.append(facts);
2979
+ }
2980
+ const match = () => (create
2981
+ ? { service_id: svc.value, match_type: mtype.value, match_value: mtype.value === 'category' ? valCat.value : valText.value.trim() }
2982
+ : { service_id: d.service_id, match_type: d.match_type, match_value: d.match_value });
2983
+ const sev = numberInput(`ruleF${n}Sev`, sb, pick('most_urgent_severity', sb));
2984
+ const per = numberInput(`ruleF${n}Hour`, hb, pick('max_per_hour', hb));
2985
+ const inc = numberInput(`ruleF${n}Inc`, ib, pick('max_per_incident', ib));
2986
+ const files = numberInput(`ruleF${n}Files`, fb, pick('max_files', fb));
2987
+ const lines = numberInput(`ruleF${n}Lines`, lb, pick('max_lines', lb));
2988
+ const days = edit ? null : numberInput(`ruleF${n}Days`, dayBound, dayBound.default);
2989
+ const note = textInput(`ruleF${n}Note`, d.note || '', 200);
2990
+ const grid = el('div', 'grid-n');
2991
+ grid.append(field('Severity floor (0 most urgent)', sev), field('Max per hour', per), field('Max per incident', inc),
2992
+ field('Max files', files), field('Max lines', lines));
2993
+ if (days) grid.append(field('Expires in (days)', days));
2994
+ f.append(grid, field('Note (optional)', note));
2995
+ const words = el('p', 'meta');
2996
+ const read = () => Object.assign(match(), {
2997
+ most_urgent_severity: clampInt(sev.value, sb.min, sb.max), max_per_hour: clampInt(per.value, hb.min, hb.max),
2998
+ max_per_incident: clampInt(inc.value, ib.min, ib.max), max_files: clampInt(files.value, fb.min, fb.max),
2999
+ max_lines: clampInt(lines.value, lb.min, lb.max), days: days ? clampInt(days.value, dayBound.min, dayBound.max) : null, note: note.value.trim(),
3000
+ });
3001
+ const describe = () => {
3002
+ const v = read();
3003
+ if (!v.match_value) { words.textContent = 'Type the signature to match.'; return; }
3004
+ words.textContent = `This rule approves fixes for service ${v.service_id || '?'} that match ${v.match_type || '?'} "${v.match_value || '?'}", for incidents at ${sevFloorText(v.most_urgent_severity)}, at most ${v.max_per_hour} per hour and ${v.max_per_incident} per incident, up to ${v.max_files} files and ${v.max_lines} lines each${v.days ? `, for ${v.days} day(s)` : ''}.`;
3005
+ };
3006
+ f.addEventListener('input', describe);
3007
+ f.addEventListener('change', describe);
3008
+ describe();
3009
+ f.append(words);
3010
+ const actions = el('div', 'actions');
3011
+ const msg = el('div', 'meta');
3012
+ msg.setAttribute('role', 'status');
3013
+ f.append(actions, msg);
3014
+ return { form: f, read, actions, msg, first: first || sev };
3015
+ }
3016
+ async function openRuleFromProposal(p, host, note) {
3017
+ const open = host.querySelector('form.rule-form');
3018
+ if (open) { open.querySelector('input').focus(); return; }
3019
+ note.textContent = 'Loading...';
3020
+ let defaults;
3021
+ try { defaults = await request('GET', `/api/proposals/${encodeURIComponent(p.id)}/rule-defaults`); }
3022
+ catch (e) { note.textContent = e.authText || errorText(e.status, e.body); return; }
3023
+ await ensureApprovalStatus();
3024
+ note.textContent = '';
3025
+ const rf = renderRuleForm(defaults, 'proposal');
3026
+ const cancel = el('button', 'ghost', 'Cancel');
3027
+ cancel.type = 'button';
3028
+ cancel.onclick = () => { rf.form.remove(); };
3029
+ rf.actions.append(actionButton('rule-from-proposal', 'Confirm rule', () => confirmRuleFromProposal(p, defaults, rf), ''), cancel);
3030
+ host.append(rf.form);
3031
+ rf.first.focus();
3032
+ }
3033
+ // The only place that creates a rule from a proposal: only after the user pressed Confirm.
3034
+ async function confirmRuleFromProposal(p, defaults, rf) {
3035
+ if (rf.busy) return;
3036
+ rf.busy = true;
3037
+ rf.msg.textContent = 'Saving...';
3038
+ try {
3039
+ const r = await request('POST', `/api/proposals/${encodeURIComponent(p.id)}/rule`, ruleOverrides(defaults, rf.read()));
3040
+ rf.form.remove();
3041
+ setStatus(`Rule ${r && r.id ? r.id : ''} created`);
3042
+ await loadRules();
3043
+ await refreshProposalViews();
3044
+ } catch (e) { rf.msg.textContent = e.authText || errorText(e.status, e.body); }
3045
+ finally { rf.busy = false; }
3046
+ }
3047
+
3048
+ /* ---------- rules, pause banner ---------- */
3049
+ function rulesMsg(text) { $('rulesMsg').textContent = text || ''; }
3050
+ function keyed(b, key) { b.dataset.focusKey = key; return b; }
3051
+ // Column titles: the same text as the table headers; shown beside each value when the rows stack on a phone (UX-07).
3052
+ const RULE_COLS = ['Id', 'Service', 'Matches', 'Severity floor', 'Expires', 'Limits', 'Uses (hour / total)', 'Status', 'Source proposal', 'Actions'];
3053
+ const AUDIT_COLS = ['Time', 'Actor', 'Action', 'Subject', 'Detail'];
3054
+ function ruleRow(r, now) {
3055
+ const tr = el('tr');
3056
+ let col = 0;
3057
+ const cell = (text) => { const td = el('td', '', text); td.setAttribute('data-label', RULE_COLS[col]); col += 1; tr.append(td); return td; };
3058
+ cell(String(r.id));
3059
+ cell(String(r.service_id));
3060
+ cell(`${r.match_type}: ${r.match_value}`);
3061
+ cell(sevFloorText(r.most_urgent_severity));
3062
+ cell(countdown(r.expires_at, now));
3063
+ cell(`${r.max_per_hour}/hour · ${r.max_per_incident}/incident · ${r.max_files} files · ${r.max_lines} lines`);
3064
+ cell(`${r.uses_last_hour} / ${r.use_count}`);
3065
+ const st = cell(stateLabel('rule', r.status));
3066
+ if (r.status === 'suspended' && r.status_reason) st.append(el('div', 'meta', String(r.status_reason).replace(/\b(?:rest|client):\S+/g, actorText)));
3067
+ cell(r.source_proposal_id ? String(r.source_proposal_id) : '');
3068
+ const td = el('td');
3069
+ td.setAttribute('data-label', RULE_COLS[col]);
3070
+ const box = el('div', 'actions');
3071
+ td.append(box);
3072
+ tr.append(td);
3073
+ if (r.status === 'active') box.append(keyed(actionButton('rule-pause', 'Pause', () => pauseRule(r), undefined, `Pause rule ${r.id}`), `${r.id}:pause`));
3074
+ if (r.status === 'active' || r.status === 'suspended') box.append(keyed(actionButton('rule-revoke', 'Revoke', () => revokeRule(r), 'ghost small warn', `Revoke rule ${r.id}`), `${r.id}:revoke`));
3075
+ if (r.status === 'suspended') box.append(keyed(actionButton('rule-enable', 'Re-enable', () => enableRule(r), undefined, `Re-enable rule ${r.id}`), `${r.id}:enable`));
3076
+ if (r.status === 'active' || r.status === 'suspended') box.append(keyed(actionButton('rule-edit', 'Edit', () => openRuleForm(r), undefined, `Edit rule ${r.id}`), `${r.id}:edit`));
3077
+ return tr;
3078
+ }
3079
+ let lastRulesKey = null;
3080
+ function renderRules() {
3081
+ const list = Array.isArray(STATE.rules) ? STATE.rules : [];
3082
+ const now = Date.now() / 1000;
3083
+ const tools = $('rulesTools');
3084
+ if (!tools.firstElementChild) {
3085
+ tools.append(actionButton('rule-create', 'New rule', () => openRuleForm(null)), actionButton('rules-pause-all', 'Pause all', pauseAll, 'ghost small warn'));
3086
+ }
3087
+ const key = JSON.stringify([list, Math.floor(now / 30)]);
3088
+ if (key === lastRulesKey) return;
3089
+ lastRulesKey = key;
3090
+ const body = $('rulesBody');
3091
+ const f = document.activeElement;
3092
+ const focusKey = f && body.contains(f) ? f.dataset.focusKey : null;
3093
+ body.replaceChildren();
3094
+ if (!list.length) {
3095
+ const tr = el('tr');
3096
+ const td = el('td', 'empty', 'No rules yet. Approve a fix, then choose "Always approve fixes like this".');
3097
+ td.colSpan = 10;
3098
+ tr.append(td);
3099
+ body.append(tr);
3100
+ }
3101
+ for (const r of list) body.append(ruleRow(r, now));
3102
+ if (focusKey) {
3103
+ const n = Array.from(body.querySelectorAll('[data-focus-key]')).find((x) => x.dataset.focusKey === focusKey);
3104
+ if (n) n.focus();
3105
+ }
3106
+ }
3107
+ async function loadRules() {
3108
+ try {
3109
+ STATE.rules = await request('GET', '/api/rules');
3110
+ renderRules();
3111
+ } catch (e) { setStatus(e.authText || errorText(e.status, e.body)); }
3112
+ }
3113
+ async function loadApprovalStatus() {
3114
+ try { STATE.approvalStatus = await request('GET', '/api/approvals/status'); }
3115
+ catch (e) { return; }
3116
+ renderPausedBanner();
3117
+ }
3118
+ // The banner is on every view while auto-approval is paused; Resume widens, so it needs the token.
3119
+ function renderPausedBanner() {
3120
+ const s = STATE.approvalStatus;
3121
+ const b = $('pausedBanner');
3122
+ if (!s || !s.paused) { b.hidden = true; b.replaceChildren(); STATE.bannerKey = ''; return; }
3123
+ const key = `${s.paused_by}|${s.paused_at}`;
3124
+ if (key === STATE.bannerKey && !b.hidden) return;
3125
+ STATE.bannerKey = key;
3126
+ b.replaceChildren();
3127
+ const when = typeof s.paused_at === 'number' ? ` at ${fmtTime(s.paused_at)}` : '';
3128
+ b.append(el('span', '', `Auto-approval is paused. No rule approves anything. Paused by ${s.paused_by || 'unknown'}${when}. `));
3129
+ b.append(actionButton('rules-resume', 'Resume', resumeRules));
3130
+ b.hidden = false;
3131
+ }
3132
+ // Reduce actions: no token, one confirmation first. A 429 shows the hub's Retry-After through authText.
3133
+ async function reduceCall(path, okText) {
3134
+ try { await request('POST', path); }
3135
+ catch (e) { rulesMsg(e.authText || errorText(e.status, e.body)); return; }
3136
+ rulesMsg(okText);
3137
+ setStatus(okText);
3138
+ await Promise.allSettled([loadRules(), loadApprovalStatus()]);
3139
+ }
3140
+ async function pauseRule(r) {
3141
+ if (!window.confirm(`Pause rule ${r.id}? It stops approving until it is re-enabled (re-enabling needs the admin token).`)) return;
3142
+ await reduceCall(`/api/rules/${encodeURIComponent(r.id)}/pause`, `Rule ${r.id} paused`);
3143
+ }
3144
+ async function revokeRule(r) {
3145
+ if (!window.confirm(`Revoke rule ${r.id}? A revoked rule cannot be used again.`)) return;
3146
+ await reduceCall(`/api/rules/${encodeURIComponent(r.id)}/revoke`, `Rule ${r.id} revoked`);
3147
+ }
3148
+ async function pauseAll() {
3149
+ if (!window.confirm('Pause every rule? Nothing is auto-approved until you resume (resuming needs the admin token).')) return;
3150
+ await reduceCall('/api/rules/pause', 'Auto-approval paused');
3151
+ }
3152
+ // The hub's own clock (seconds): approvals/status `now` when it has one, else the Date header of the last answer.
3153
+ function serverNowSeconds() {
3154
+ const st = STATE.approvalStatus;
3155
+ if (st && typeof st.now === 'number') return st.now;
3156
+ return typeof STATE.serverDate === 'number' ? STATE.serverDate : null;
3157
+ }
3158
+ // Days to an absolute expires_at from the hub's clock (the default is 7 days from its now); null when unknown.
3159
+ function createExpiry(days) {
3160
+ const now = serverNowSeconds();
3161
+ return now === null ? null : expiryFromDays(now + 7 * 86400, days);
3162
+ }
3163
+ // Opened only by a click on New rule or Edit; nothing here runs on load.
3164
+ async function openRuleForm(rule) {
3165
+ const box = $('ruleFormBox');
3166
+ box.replaceChildren();
3167
+ await ensureApprovalStatus();
3168
+ if (!rule) { try { STATE.services = await request('GET', '/api/services'); } catch (e) { /* the form says no service qualifies */ } }
3169
+ const rf = renderRuleForm(rule, rule ? 'edit' : 'create');
3170
+ const save = rule
3171
+ ? actionButton('rule-edit', 'Save changes', () => saveRule(rule, rf), '')
3172
+ : actionButton('rule-create', 'Create rule', () => saveRule(null, rf), '');
3173
+ const cancel = el('button', 'ghost', 'Cancel');
3174
+ cancel.type = 'button';
3175
+ cancel.onclick = () => { box.replaceChildren(); };
3176
+ rf.form.onsubmit = (ev) => { ev.preventDefault(); if (!save.disabled) saveRule(rule, rf); };
3177
+ rf.actions.append(save, cancel);
3178
+ box.append(rf.form);
3179
+ rf.first.focus();
3180
+ }
3181
+ async function saveRule(rule, rf) {
3182
+ if (rf.busy) return; // a double click must not send the request twice
3183
+ rf.busy = true;
3184
+ rf.msg.textContent = 'Saving...';
3185
+ try {
3186
+ const v = rf.read();
3187
+ if (rule) {
3188
+ const patch = ruleOverrides(rule, v);
3189
+ if (!Object.keys(patch).length) { rf.msg.textContent = 'Nothing changed.'; return; }
3190
+ await request('PATCH', `/api/rules/${encodeURIComponent(rule.id)}`, patch);
3191
+ } else {
3192
+ const body = {
3193
+ service_id: v.service_id, match_type: v.match_type, match_value: v.match_value,
3194
+ most_urgent_severity: v.most_urgent_severity, max_per_hour: v.max_per_hour, max_per_incident: v.max_per_incident,
3195
+ max_files: v.max_files, max_lines: v.max_lines,
3196
+ };
3197
+ const when = createExpiry(v.days);
3198
+ if (v.days !== 7 && when !== null) body.expires_at = when;
3199
+ if (v.note) body.note = v.note;
3200
+ await request('POST', '/api/rules', body);
3201
+ }
3202
+ $('ruleFormBox').replaceChildren();
3203
+ rulesMsg('Rule saved.');
3204
+ setStatus('Rule saved');
3205
+ await loadRules();
3206
+ } catch (e) { rf.msg.textContent = e.authText || errorText(e.status, e.body); }
3207
+ finally { rf.busy = false; }
3208
+ }
3209
+ async function enableRule(r) {
3210
+ try { await request('POST', `/api/rules/${encodeURIComponent(r.id)}/enable`); }
3211
+ catch (e) { rulesMsg(e.authText || errorText(e.status, e.body)); return; }
3212
+ rulesMsg(`Rule ${r.id} re-enabled`);
3213
+ await loadRules();
3214
+ }
3215
+ async function resumeRules() {
3216
+ try { await request('POST', '/api/rules/resume'); }
3217
+ catch (e) { setStatus(e.authText || errorText(e.status, e.body)); return; }
3218
+ setStatus('Auto-approval resumed');
3219
+ await Promise.allSettled([loadRules(), loadApprovalStatus()]);
3220
+ }
3221
+ /* ---------- audit trail ---------- */
3222
+ STATE.audit = { rows: [], key: null, done: false, open: new Set(), shown: null };
3223
+ function fmtStamp(ts) { return new Date(ts * 1000).toLocaleString([], { hour12: false }); }
3224
+ function auditKey() { return `${$('auditSvc').value}|${$('auditRule').value.trim()}`; }
3225
+ function auditUrl(before) {
3226
+ const p = ['limit=100'];
3227
+ const svc = $('auditSvc').value;
3228
+ if (svc) p.push(`service_id=${encodeURIComponent(svc)}`);
3229
+ const rule = $('auditRule').value.trim();
3230
+ if (rule) p.push(`rule_id=${encodeURIComponent(rule)}`);
3231
+ if (before !== undefined) p.push(`before=${before}`);
3232
+ return `/api/audit?${p.join('&')}`;
3233
+ }
3234
+ function auditRow(r) {
3235
+ const tr = el('tr');
3236
+ const actor = el('td', '', actorText(r.actor));
3237
+ actor.title = String(r.actor);
3238
+ const subject = el('td', '', subjectText(r.subject));
3239
+ subject.title = String(r.subject);
3240
+ tr.append(el('td', '', fmtStamp(r.ts)), actor, el('td', '', actionText(r.action)), subject);
3241
+ const full = String(r.detail === null || r.detail === undefined ? '' : r.detail);
3242
+ const open = STATE.audit.open.has(r.id);
3243
+ const td = el('td');
3244
+ tr.append(td);
3245
+ Array.from(tr.children).forEach((c, i) => c.setAttribute('data-label', AUDIT_COLS[i]));
3246
+ td.append(el('span', '', open ? capText(full, 4096) : capText(full, 300)));
3247
+ if (!open && full.length > 300) {
3248
+ const more = el('button', 'ghost small', 'show more');
3249
+ more.type = 'button';
3250
+ more.onclick = () => { STATE.audit.open.add(r.id); renderAudit(); };
3251
+ td.append(more);
3252
+ }
3253
+ return tr;
3254
+ }
3255
+ function renderAudit() {
3256
+ const A = STATE.audit;
3257
+ const key = `${A.rows.map((r) => r.id).join(',')}|${Array.from(A.open).join(',')}|${A.done}`;
3258
+ if (key === A.shown) return;
3259
+ A.shown = key;
3260
+ const body = $('auditBody');
3261
+ body.replaceChildren();
3262
+ if (!A.rows.length) {
3263
+ const tr = el('tr');
3264
+ const td = el('td', 'empty', 'No audit rows yet.');
3265
+ td.colSpan = 5;
3266
+ tr.append(td);
3267
+ body.append(tr);
3268
+ }
3269
+ for (const r of A.rows) body.append(auditRow(r));
3270
+ $('auditMore').hidden = A.done || !A.rows.length;
3271
+ }
3272
+ // Every 5 s: the newest page for the current filter, merged so the rows already loaded stay.
3273
+ async function refreshAudit() {
3274
+ const A = STATE.audit;
3275
+ const key = auditKey();
3276
+ let rows;
3277
+ try { rows = await request('GET', auditUrl()); }
3278
+ catch (e) { $('auditMsg').textContent = e.authText || errorText(e.status, e.body); return; }
3279
+ if (!Array.isArray(rows) || key !== auditKey()) return; // the filter changed while waiting
3280
+ $('auditMsg').textContent = '';
3281
+ const fresh = key !== A.key || !A.rows.length;
3282
+ if (key !== A.key) { A.key = key; A.rows = []; A.done = false; A.open = new Set(); }
3283
+ A.rows = mergeAudit(A.rows, rows);
3284
+ if (fresh && rows.length < 100) A.done = true;
3285
+ renderAudit();
3286
+ }
3287
+ async function loadMoreAudit() {
3288
+ const A = STATE.audit;
3289
+ if (!A.rows.length) return;
3290
+ const oldest = A.rows[A.rows.length - 1].id; // the smallest id shown
3291
+ let rows;
3292
+ try { rows = await request('GET', auditUrl(oldest)); }
3293
+ catch (e) { $('auditMsg').textContent = e.authText || errorText(e.status, e.body); return; }
3294
+ if (!Array.isArray(rows)) return;
3295
+ A.rows = mergeAudit(A.rows, rows);
3296
+ if (rows.length < 100) A.done = true;
3297
+ renderAudit();
3298
+ }
3299
+ // The service filter lists the hub's services (a read, done when the Rules view is entered).
3300
+ async function loadAuditServices() {
3301
+ let list;
3302
+ try { list = await request('GET', '/api/services'); } catch (e) { return; }
3303
+ if (!Array.isArray(list)) return;
3304
+ const sel = $('auditSvc');
3305
+ const current = sel.value;
3306
+ sel.replaceChildren();
3307
+ const all = el('option', '', 'all services');
3308
+ all.value = '';
3309
+ sel.append(all);
3310
+ for (const s of list) { const o = el('option', '', `${s.name} (${s.id})`); o.value = String(s.id); sel.append(o); }
3311
+ sel.value = current;
3312
+ }
3313
+ function wireAudit() {
3314
+ $('auditSvc').onchange = () => refreshAudit();
3315
+ $('auditRule').onchange = () => refreshAudit();
3316
+ $('auditMore').onclick = loadMoreAudit;
3317
+ }
3318
+ ENTER.rules = () => { loadRules(); loadApprovalStatus(); loadAuditServices(); refreshAudit(); };
3319
+
3320
+ /* ---------- discovery: scan start and polling ---------- */
3321
+ // Nothing here runs on load: the scan starts only from the click handler of the button (R4.5).
3322
+ const DISCOVERY_EXPLAINER = 'Lists running processes and listening ports on this machine. It never reads log contents, and nothing leaves this machine.';
3323
+ const LIMITED_TEXT = 'some processes were not visible without admin rights';
3324
+ const SCAN_GIVE_UP_MS = 45000;
3325
+ function discMsg(text) { const t = text || ''; if ($('discStatus').textContent !== t) $('discStatus').textContent = t; } // an identical text is not written again, so the live region speaks once
3326
+ function scanRunning() { return Boolean(STATE.scan && STATE.scan.state === 'running'); }
3327
+ function updateDiscLock() {
3328
+ $('discLockHint').textContent = STATE.lock && STATE.lock.locked ? 'Scanning needs the admin token. Unlock first.' : '';
3329
+ }
3330
+ function renderDiscovery() {
3331
+ $('discExplainer').textContent = DISCOVERY_EXPLAINER;
3332
+ updateDiscLock();
3333
+ const slot = $('discScanSlot');
3334
+ if (!slot.firstElementChild) slot.append(actionButton('scan-start', 'Discover local apps', startScan, ''));
3335
+ const dslot = $('discDismissSlot');
3336
+ if (!dslot.firstElementChild) dslot.append(actionButton('dismissals-clear', 'Show dismissed apps again', clearDismissals));
3337
+ const sc = STATE.scan;
3338
+ $('discLimited').textContent = sc && sc.limited ? LIMITED_TEXT : '';
3339
+ $('discScan').hidden = !(sc && sc.state === 'running');
3340
+ if (!sc) discMsg('');
3341
+ else if (sc.state === 'running') discMsg(scanStateText(sc.state));
3342
+ else if (sc.state === 'failed') discMsg(`scan failed: ${capText(sc.reason || 'unknown reason', 300)}`);
3343
+ else if (sc.state === 'done') discMsg(sc.suggestions.length ? '' : emptyScanText(sc));
3344
+ const empty = $('discEmptySlot');
3345
+ const none = Boolean(sc && sc.state === 'done' && !sc.suggestions.length);
3346
+ if (!none) empty.replaceChildren();
3347
+ else if (!empty.firstElementChild) {
3348
+ empty.append(focusKeyButton('Add a service by hand', 'disc:add', () => openServiceForm(null), 'ghost'));
3349
+ empty.append(focusKeyButton('Try the demo', 'disc:demo', () => { here.hash = '#/home'; startDemo(); }, 'ghost')); // Home shows the progress and any failure
3350
+ }
3351
+ renderSuggestions(sc);
3352
+ }
3353
+ function adoptScan(id) {
3354
+ STATE.scan = { id, state: 'running', limited: false, suggestions: [], startedAt: Date.now(), polling: false };
3355
+ renderDiscovery();
3356
+ pollScan();
3357
+ }
3358
+ async function startScan() {
3359
+ if (scanRunning()) return;
3360
+ discMsg('Starting scan...');
3361
+ try {
3362
+ const r = await request('POST', '/api/discovery/scan');
3363
+ adoptScan(String(r.scan_id));
3364
+ } catch (e) {
3365
+ if (e.status === 409 && e.body && typeof e.body.scan_id === 'string') { adoptScan(e.body.scan_id); return; }
3366
+ discMsg(e.authText || errorText(e.status, e.body));
3367
+ }
3368
+ }
3369
+ async function pollScan() {
3370
+ const sc = STATE.scan;
3371
+ if (!sc || sc.state !== 'running' || sc.polling) return;
3372
+ if (Date.now() - sc.startedAt > SCAN_GIVE_UP_MS) { sc.state = 'stalled'; discMsg('scan is taking too long; check again'); return; }
3373
+ sc.polling = true;
3374
+ try {
3375
+ const d = await request('GET', `/api/discovery/scans/${encodeURIComponent(sc.id)}`);
3376
+ if (STATE.scan !== sc) return;
3377
+ sc.state = d.state === 'done' || d.state === 'failed' ? d.state : 'running';
3378
+ sc.limited = Boolean(d.limited);
3379
+ sc.reason = typeof d.reason === 'string' ? d.reason : '';
3380
+ sc.suggestions = Array.isArray(d.suggestions) ? d.suggestions : [];
3381
+ sc.processes_seen = d.processes_seen;
3382
+ sc.listeners_seen = d.listeners_seen;
3383
+ } catch (e) {
3384
+ if (STATE.scan !== sc) return;
3385
+ if (e.status === 404) { sc.state = 'expired'; discMsg('scan expired, run it again'); return; }
3386
+ discMsg(e.authText || errorText(e.status, e.body));
3387
+ } finally { sc.polling = false; }
3388
+ renderDiscovery();
3389
+ }
3390
+ /* ---------- discovery: suggestion review, accept and dismiss ---------- */
3391
+ const CODE_FOLDER_HELP = 'Auto-approved fixes may only change files in this folder. You can also set it later.';
3392
+ let discSeq = 0;
3393
+ function renderSuggestionCard(s) {
3394
+ const card = el('article', 'svc-card');
3395
+ const evidence = s.evidence || {};
3396
+ const top = el('div', 'top');
3397
+ top.append(el('h3', '', String(s.name)), el('span', 'pill', `confidence: ${s.confidence}`));
3398
+ const ports = Array.isArray(evidence.ports) ? evidence.ports.join(', ') : '';
3399
+ card.append(top, el('div', 'meta', `process ${evidence.process || 'unknown'} · pid ${evidence.pid === null || evidence.pid === undefined ? 'n/a' : evidence.pid} · ${Number(evidence.process_count) || 0} process(es) · ports ${ports || 'none'}`));
3400
+ if (s.state === 'accepted') {
3401
+ card.append(el('div', 'meta', `accepted as service ${s.service_id}`));
3402
+ const a = el('div', 'actions');
3403
+ a.append(focusKeyButton('Open service', `${s.suggestion_id}:open`, () => { here.hash = `#/services/${encodeURIComponent(s.service_id)}`; }));
3404
+ card.append(a);
3405
+ return card;
3406
+ }
3407
+ const n = ++discSeq;
3408
+ const idIn = textInput(`discF${n}Id`, s.app_id, 40);
3409
+ const nameIn = textInput(`discF${n}Name`, s.name, 200);
3410
+ const codeIn = textInput(`discF${n}Code`, '', 1024);
3411
+ const f = el('form', 'svc-form');
3412
+ f.append(field('Id', idIn), field('Name', nameIn), field('Code folder (optional)', codeIn), el('div', 'meta', CODE_FOLDER_HELP));
3413
+ const fs = el('fieldset');
3414
+ fs.append(el('legend', '', 'Candidate log files'));
3415
+ const rows = [];
3416
+ (Array.isArray(s.candidate_log_paths) ? s.candidate_log_paths : []).forEach((c, k) => {
3417
+ const cb = el('input');
3418
+ cb.type = 'checkbox'; cb.id = `discF${n}Use${k}`;
3419
+ cb.checked = Boolean(c.exists && !c.watched_by);
3420
+ const path = textInput(`discF${n}Path${k}`, c.path, 1024);
3421
+ const fmt = el('select');
3422
+ fmt.id = `discF${n}Fmt${k}`;
3423
+ const formats = STATE.uiConfig.formats.slice();
3424
+ if (!formats.includes(c.format)) formats.push(c.format);
3425
+ for (const x of formats) { const o = el('option', '', x); o.value = x; fmt.append(o); }
3426
+ fmt.value = c.format;
3427
+ const line = el('div', 'cand');
3428
+ line.append(field('Use', cb), field('Path', path), field('Format', fmt));
3429
+ line.append(el('div', 'meta', !c.exists ? 'not found' : c.readable === false ? 'not readable' : 'exists'));
3430
+ if (c.watched_by) {
3431
+ cb.checked = false;
3432
+ cb.disabled = true;
3433
+ line.append(el('div', 'meta', `already watched by ${c.watched_by}`));
3434
+ }
3435
+ fs.append(line);
3436
+ rows.push({ cb, path, fmt, c });
3437
+ });
3438
+ f.append(fs);
3439
+ const read = () => ({
3440
+ id: idIn.value.trim(), name: nameIn.value.trim(), code_folder: codeIn.value, app_names: [],
3441
+ rows: rows.map((r) => ({ checked: r.cb.checked, path: r.path.value.trim(), format: r.fmt.value, watched_by: r.c.watched_by || null })),
3442
+ });
3443
+ const msg = el('div', 'meta');
3444
+ msg.setAttribute('role', 'status');
3445
+ const accept = actionButton('suggestion-accept', 'Accept', () => acceptSuggestion(s, card, read, msg), '');
3446
+ const dismiss = actionButton('suggestion-dismiss', 'Dismiss', () => dismissSuggestion(s, card, msg));
3447
+ const actions = el('div', 'actions');
3448
+ actions.append(accept, dismiss);
3449
+ f.onsubmit = (ev) => { ev.preventDefault(); if (!accept.disabled) acceptSuggestion(s, card, read, msg); };
3450
+ f.append(actions, msg);
3451
+ card.append(f);
3452
+ return card;
3453
+ }
3454
+ function renderSuggestions(sc) {
3455
+ const key = sc && sc.state === 'done' ? JSON.stringify(sc.suggestions) : '';
3456
+ if (key === STATE.shownKey) return; // never rebuild the cards while the user is typing in one
3457
+ STATE.shownKey = key;
3458
+ const box = $('discList');
3459
+ box.replaceChildren();
3460
+ if (!sc || sc.state !== 'done') return;
3461
+ for (const s of sc.suggestions) box.append(renderSuggestionCard(s));
3462
+ }
3463
+ function noteSuggestionChange(sc) { STATE.shownKey = sc.state === 'done' ? JSON.stringify(sc.suggestions) : ''; }
3464
+ async function acceptSuggestion(s, card, read, msg) {
3465
+ if (card.dataset.busy === 'yes') return; // a double click must not accept twice
3466
+ card.dataset.busy = 'yes';
3467
+ msg.textContent = 'Saving...';
3468
+ try {
3469
+ const r = await request('POST', `/api/discovery/suggestions/${encodeURIComponent(s.suggestion_id)}/accept`, buildAcceptBody(read()));
3470
+ const service = r && r.service ? r.service : {};
3471
+ const done = Object.assign({}, s, { state: 'accepted', service_id: String(service.id || '') });
3472
+ const sc = STATE.scan;
3473
+ if (sc) { sc.suggestions = sc.suggestions.map((x) => (x.suggestion_id === s.suggestion_id ? done : x)); noteSuggestionChange(sc); }
3474
+ card.replaceWith(renderSuggestionCard(done));
3475
+ lastSvcKey = null;
3476
+ } catch (e) {
3477
+ msg.textContent = e.authText || errorText(e.status, e.body);
3478
+ if (e.status === 409) refreshScan(msg.textContent);
3479
+ } finally { delete card.dataset.busy; }
3480
+ }
3481
+ async function dismissSuggestion(s, card, msg) {
3482
+ try { await request('POST', `/api/discovery/suggestions/${encodeURIComponent(s.suggestion_id)}/dismiss`); }
3483
+ catch (e) { msg.textContent = e.authText || errorText(e.status, e.body); return; }
3484
+ const sc = STATE.scan;
3485
+ if (sc) { sc.suggestions = sc.suggestions.filter((x) => x.suggestion_id !== s.suggestion_id); noteSuggestionChange(sc); }
3486
+ card.remove();
3487
+ const scanBtn = $('discScanSlot').firstElementChild;
3488
+ if (scanBtn) scanBtn.focus();
3489
+ }
3490
+ async function clearDismissals() {
3491
+ try {
3492
+ const r = await request('DELETE', '/api/discovery/dismissals');
3493
+ discMsg(`Cleared ${Number(r && r.cleared) || 0} dismissed app(s). Run discovery again to see them.`);
3494
+ } catch (e) { discMsg(e.authText || errorText(e.status, e.body)); }
3495
+ }
3496
+ // One read of the finished scan (after a 409 from accept), so the list shows what the hub now says.
3497
+ async function refreshScan(note) {
3498
+ const sc = STATE.scan;
3499
+ if (!sc || sc.state === 'running') return;
3500
+ try {
3501
+ const d = await request('GET', `/api/discovery/scans/${encodeURIComponent(sc.id)}`);
3502
+ if (STATE.scan !== sc) return;
3503
+ sc.suggestions = Array.isArray(d.suggestions) ? d.suggestions : [];
3504
+ sc.limited = Boolean(d.limited);
3505
+ renderDiscovery();
3506
+ discMsg(note);
3507
+ } catch (e) {
3508
+ if (e.status === 404) { sc.state = 'expired'; discMsg('scan expired, run it again'); }
3509
+ }
3510
+ }
3511
+ ENTER.discovery = () => renderDiscovery();
3512
+
3513
+ /* ---------- home and the demo flow ---------- */
3514
+ var homeNote = ''; // the one-time "Demo closed" message; cleared by the close button or the timer, never shown twice
3515
+ let homeNoteTimer = 0;
3516
+ let homeStripKey = '';
3517
+ const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
3518
+ function renderHome() {
3519
+ showHomeNote();
3520
+ renderHomeDemo();
3521
+ loadHome();
3522
+ }
3523
+ function showHomeNote() {
3524
+ $('homeNote').hidden = !homeNote;
3525
+ $('homeNoteText').textContent = homeNote;
3526
+ if (homeNote && !homeNoteTimer) armHomeNote();
3527
+ }
3528
+ // Hide after NOTICE_HIDE_MS; while the pointer is over the notice or the focus is in it, wait another round.
3529
+ function armHomeNote() {
3530
+ clearTimeout(homeNoteTimer);
3531
+ homeNoteTimer = setTimeout(() => {
3532
+ const box = $('homeNote');
3533
+ if (box.matches(':hover') || box.contains(document.activeElement)) { armHomeNote(); return; }
3534
+ dismissHomeNote(false);
3535
+ }, NOTICE_HIDE_MS);
3536
+ }
3537
+ function dismissHomeNote(byUser) {
3538
+ const box = $('homeNote');
3539
+ const hadFocus = box.contains(document.activeElement);
3540
+ clearTimeout(homeNoteTimer);
3541
+ homeNoteTimer = 0;
3542
+ homeNote = '';
3543
+ box.hidden = true;
3544
+ $('homeNoteText').textContent = '';
3545
+ if (byUser || hadFocus) $('main').focus({ preventScroll: true }); // the button is gone: keep the keyboard on the page, not on <body>
3546
+ }
3547
+ async function loadHome() {
3548
+ const real = !STATE.demo;
3549
+ const [s, v, d] = await Promise.allSettled([api('/api/stats'), api('/api/services'), real ? api('/api/demo/status') : Promise.resolve(null)]);
3550
+ if (d.status === 'fulfilled') {
3551
+ const run = d.value && d.value.state === 'running' && loopbackOrigin(d.value.url) ? d.value.url : null;
3552
+ if (run !== STATE.demoRunning) { STATE.demoRunning = run; renderHomeDemo(); }
3553
+ }
3554
+ const stats = s.status === 'fulfilled' ? s.value : null;
3555
+ const items = homeStripItems(stats, v.status === 'fulfilled' ? v.value : null);
3556
+ const note = homeStripNote(stats);
3557
+ const key = JSON.stringify([items, note]);
3558
+ if (key === homeStripKey) return;
3559
+ homeStripKey = key;
3560
+ const box = $('homeStrip');
3561
+ box.replaceChildren();
3562
+ for (const it of items) {
3563
+ const cell = el('div', 'hm-stat');
3564
+ cell.append(el('dt', '', it.label), el('dd', '', it.value));
3565
+ box.append(cell);
3566
+ }
3567
+ $('homeStripNote').textContent = note;
3568
+ }
3569
+ // One state for every "Try the demo" button on Home: label, busy flag, and the text under it (one live region).
3570
+ function renderHomeDemo() {
3571
+ const d = STATE.demoStart;
3572
+ const busy = d.state === 'starting' || d.state === 'ready';
3573
+ let label = 'Try the demo';
3574
+ if (STATE.demo) label = 'Back to the demo';
3575
+ else if (d.state === 'starting') label = 'Starting...';
3576
+ else if (d.state === 'ready') label = 'Opening...';
3577
+ else if (d.state === 'failed') label = 'Try again';
3578
+ else if (STATE.demoRunning) label = 'Open the running demo';
3579
+ document.querySelectorAll('[data-demo-btn]').forEach((b) => {
3580
+ if (b.textContent !== label) b.textContent = label;
3581
+ b.dataset.busy = busy ? 'yes' : 'no'; // not disabled: a disabled button would drop the keyboard focus
3582
+ b.setAttribute('aria-busy', String(busy));
3583
+ });
3584
+ let text = d.text || '';
3585
+ if (!text && !STATE.demo && STATE.demoRunning) text = HOME_COPY.running;
3586
+ $('homeDemoStatus').textContent = text;
3587
+ $('homeDemoStatus2').textContent = text;
3588
+ $('homeDemoStop').hidden = STATE.demo || d.state !== 'idle' || !STATE.demoRunning;
3589
+ }
3590
+ function goToDemo(url) {
3591
+ const target = demoTarget(url);
3592
+ if (!target) {
3593
+ request('POST', '/api/demo/stop').catch(() => { /* nothing to stop */ });
3594
+ STATE.demoStart = { state: 'failed', since: STATE.demoStart.since, text: 'The hub gave an address this page does not trust, so the demo was not opened.', retry: true };
3595
+ renderHomeDemo();
3596
+ return;
3597
+ }
3598
+ here.assign(target);
3599
+ }
3600
+ async function startDemo() {
3601
+ if (STATE.demo) { here.hash = '#/overview'; return; }
3602
+ if (STATE.demoStart.state === 'starting' || STATE.demoStart.state === 'ready') return;
3603
+ if (STATE.demoRunning) { goToDemo(STATE.demoRunning); return; }
3604
+ const since = Date.now();
3605
+ STATE.demoStart = { state: 'starting', since, text: HOME_COPY.starting, retry: false };
3606
+ renderHomeDemo();
3607
+ let last = null, settled = false;
3608
+ request('POST', '/api/demo/start').then((r) => { last = r; settled = true; }, (e) => { last = { state: 'failed', reason: demoFailReason(e.status, e.body) }; settled = true; });
3609
+ for (;;) {
3610
+ await sleep(DEMO_POLL_MS);
3611
+ if (STATE.demoStart.since !== since) return;
3612
+ if (!settled) { try { last = await request('GET', '/api/demo/status'); } catch (e) { /* the clock ends the wait */ } }
3613
+ const next = demoStartState(STATE.demoStart, last, Date.now());
3614
+ STATE.demoStart = Object.assign({ since }, next);
3615
+ renderHomeDemo();
3616
+ if (next.state === 'ready') { goToDemo(last.url); return; }
3617
+ if (next.state === 'failed') { request('POST', '/api/demo/stop').catch(() => { /* already stopped */ }); return; }
3618
+ }
3619
+ }
3620
+ async function stopRunningDemo() {
3621
+ try { await request('POST', '/api/demo/stop'); } catch (e) { toast(friendlyError(e.status)); return; }
3622
+ STATE.demoRunning = null;
3623
+ renderHomeDemo();
3624
+ }
3625
+ async function exitDemo() {
3626
+ const b = $('demoExit');
3627
+ if (b.dataset.busy === 'yes') return;
3628
+ b.dataset.busy = 'yes';
3629
+ b.textContent = HOME_COPY.exiting;
3630
+ let back = STATE.uiConfig.return_url;
3631
+ try {
3632
+ const r = await request('POST', '/api/demo/exit');
3633
+ if (r && typeof r.return_url === 'string') back = r.return_url;
3634
+ } catch (e) {
3635
+ if (e.status !== 0) { b.dataset.busy = 'no'; b.textContent = 'Exit demo'; toast(friendlyError(e.status)); return; }
3636
+ } // status 0: the demo hub already went away, which is what Exit wants
3637
+ here.assign(returnTarget(back));
3638
+ }
3639
+ function renderDemoBanner() {
3640
+ $('demoBanner').hidden = STATE.demo !== true;
3641
+ if (STATE.demo !== true) return;
3642
+ const open = STATE.navInc.filter((i) => !i.resolved).length;
3643
+ $('demoHint').textContent = demoHint(open, STATE.navProp.length);
3644
+ }
3645
+ // Copy with the clipboard when the browser allows it; else select the text so Ctrl+C works. The button itself
3646
+ // says Copied or Copy failed for COPY_RESET_MS; `live` (a visually hidden status region) says the same out loud.
3647
+ const copyTimers = new WeakMap();
3648
+ async function copyText(text, node, button, live) {
3649
+ let ok = false;
3650
+ try { await navigator.clipboard.writeText(text); ok = true; } catch (e) { ok = false; }
3651
+ if (!ok) { const sel = window.getSelection(); if (sel) sel.selectAllChildren(node); }
3652
+ const f = copyFeedback(ok);
3653
+ button.textContent = f.label;
3654
+ live.textContent = f.say;
3655
+ clearTimeout(copyTimers.get(button));
3656
+ copyTimers.set(button, setTimeout(() => { button.textContent = 'Copy'; live.textContent = ''; }, COPY_RESET_MS));
3657
+ }
3658
+ const HOME_GO = { overview: '#/overview', discovery: '#/discovery', services: '#/services' };
3659
+ function wireHome() {
3660
+ document.querySelectorAll('[data-demo-btn]').forEach((b) => { b.onclick = startDemo; });
3661
+ $('homeDemoStop').onclick = stopRunningDemo;
3662
+ $('demoExit').onclick = exitDemo;
3663
+ $('homeNoteClose').onclick = () => dismissHomeNote(true);
3664
+ document.querySelectorAll('[data-go]').forEach((b) => { b.onclick = () => { if (Object.prototype.hasOwnProperty.call(HOME_GO, b.dataset.go)) here.hash = HOME_GO[b.dataset.go]; }; });
3665
+ document.querySelectorAll('[data-scroll]').forEach((b) => { b.onclick = () => { const h = $(b.dataset.scroll); if (h) h.focus(); }; });
3666
+ const msg = $('homeCopyMsg');
3667
+ for (const c of HOME_INSTALL) {
3668
+ const node = document.querySelector(`[data-cmd="${c.id}"]`);
3669
+ node.textContent = c.cmd;
3670
+ const btn = document.querySelector(`[data-copy="${c.id}"]`);
3671
+ btn.onclick = () => copyText(c.cmd, node, btn, msg);
3672
+ }
3673
+ $('homeMcp').textContent = HOME_MCP;
3674
+ $('copyMcp').onclick = () => copyText(HOME_MCP, $('homeMcp'), $('copyMcp'), msg);
3675
+ }
3676
+ ENTER.home = () => renderHome();
3677
+
3678
+ /* ---------- guided tour (demo only) ---------- */
3679
+ // The step and the open flag live in sessionStorage under TOUR_KEY (this tab only). The token is never involved.
3680
+ const TOUR_KEY = 'cm_tour';
3681
+ function tourSave() { try { sessionStorage.setItem(TOUR_KEY, tourSerialize(STATE.tour)); } catch (e) { /* storage unavailable: the tour still works for this page */ } }
3682
+ function tourLoad() { try { return tourParse(sessionStorage.getItem(TOUR_KEY)); } catch (e) { return tourParse(null); } }
3683
+ // Outline the step's target when it is on screen. The outline is static; the pulse is CSS and only without reduced motion.
3684
+ // Returns the first outlined node that is on screen (or null).
3685
+ function tourHighlight(targets) {
3686
+ document.querySelectorAll('.tour-target').forEach((n) => n.classList.remove('tour-target'));
3687
+ let first = null;
3688
+ for (const t of targets) {
3689
+ const node = document.querySelector(`[data-tour="${t}"]`);
3690
+ if (!node || node.offsetParent === null) continue;
3691
+ node.classList.add('tour-target');
3692
+ if (!first) first = node;
3693
+ }
3694
+ return first;
3695
+ }
3696
+ // On a phone the fixed panel covers the lower half, so the target goes to the top; on a desktop it moves as little as it can.
3697
+ function tourScroll(node) { node.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: matchMedia('(max-width: 640px)').matches ? 'start' : 'nearest' }); }
3698
+ let tourScrollNext = false; // set by a route change: the next time a target shows up, scroll it into view once
3699
+ function tourMarks() { return STATE.demo === true && STATE.tour.open ? tourTargets(tourState(STATE.tour).step, STATE.route.view) : []; }
3700
+ // The scheduler's pass: a target drawn after the step began (an app's Mute row) gets its outline. It scrolls only once,
3701
+ // right after a route change, so it never pulls the page away from a user who is reading.
3702
+ function tourMark() {
3703
+ const want = tourMarks();
3704
+ const have = Array.from(document.querySelectorAll('.tour-target')).map((n) => n.dataset.tour);
3705
+ const shown = want.filter((t) => { const n = document.querySelector(`[data-tour="${t}"]`); return n && n.offsetParent !== null; });
3706
+ if (JSON.stringify(shown) === JSON.stringify(have)) return;
3707
+ const first = tourHighlight(want);
3708
+ if (first && tourScrollNext) { tourScrollNext = false; tourScroll(first); }
3709
+ }
3710
+ function tourRender(focusTitle) {
3711
+ const on = STATE.demo === true && STATE.tour.open;
3712
+ document.body.classList.toggle('tour-open', on);
3713
+ $('tour').hidden = !on;
3714
+ $('tourShow').hidden = !(STATE.demo === true && !STATE.tour.open);
3715
+ if (!on) { tourHighlight([]); return; }
3716
+ const step = TOUR_STEPS[tourState(STATE.tour).step], lab = tourLabels(STATE.tour);
3717
+ const lock = tourLockNote(step.id, Boolean(STATE.lock && STATE.lock.locked));
3718
+ $('tourCount').textContent = lab.counter;
3719
+ $('tourBody').textContent = lock ? `${step.body} ${lock}` : step.body;
3720
+ $('tourTitle').textContent = step.title;
3721
+ $('tourBack').disabled = lab.backDisabled;
3722
+ $('tourNext').textContent = lab.next;
3723
+ const first = tourHighlight(tourMarks());
3724
+ if (first && (focusTitle || tourScrollNext)) { tourScrollNext = false; tourScroll(first); }
3725
+ if (focusTitle) $('tourTitle').focus({ preventScroll: true });
3726
+ }
3727
+ function tourApply(next, focus) {
3728
+ const changed = next.step !== STATE.tour.step || next.open !== STATE.tour.open;
3729
+ STATE.tour = next;
3730
+ if (changed) tourSave();
3731
+ tourRender(focus === true && changed && next.open);
3732
+ }
3733
+ function tourDispatch(action, focus) { tourApply(tourReduce(STATE.tour, action), focus); }
3734
+ function tourRoute(view) { if (STATE.demo !== true) return; tourScrollNext = true; tourDispatch({ type: 'route', view }, true); }
3735
+ function tourStart() {
3736
+ if (STATE.demo !== true) { tourRender(false); return; }
3737
+ tourApply(tourLoad(), false);
3738
+ tourRoute(STATE.route.view);
3739
+ }
3740
+ function wireTour() {
3741
+ const skip = () => { tourDispatch({ type: 'skip' }, false); $('tourShow').focus(); };
3742
+ $('tourBack').onclick = () => tourDispatch({ type: 'back' }, true);
3743
+ $('tourNext').onclick = () => { if (tourLabels(STATE.tour).last) { $('demoExit').click(); return; } tourDispatch({ type: 'next' }, true); };
3744
+ $('tourSkip').onclick = skip;
3745
+ $('tourShow').onclick = () => tourDispatch({ type: 'show' }, true);
3746
+ $('tour').addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); skip(); } });
3747
+ }
3748
+
3749
+ /* ==== INIT ==== */
3750
+ function init() {
3751
+ if (here.hash === '#selftest') { runSelfTest(); return; } // no request of any kind in this mode
3752
+ document.querySelectorAll('nav [data-nav]').forEach((b) => { b.onclick = () => { here.hash = `#/${b.dataset.nav}`; }; });
3753
+ window.addEventListener('hashchange', showRoute);
3754
+ wireHome();
3755
+ wireTour();
3756
+ wireUnlock();
3757
+ wireLive();
3758
+ wireAudit();
3759
+ document.addEventListener('visibilitychange', liveVisibility);
3760
+ renderPermissionsPanel();
3761
+ $('svcBack').onclick = () => { here.hash = '#/services'; };
3762
+ $('svcAdd').onclick = () => renderServiceForm(null);
3763
+ applyLock();
3764
+ loadUiConfig();
3765
+ loadApprovalStatus();
3766
+ loadNavData();
3767
+ showRoute();
3768
+ refresh(); fetchChat();
3769
+ startScheduler();
3770
+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { if (STATE.route.view === 'overview') { fetchChat(); refresh(); } } });
3771
+ }
3772
+ init();
3773
+ </script>
3774
+ </body>
3775
+ </html>