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,3 @@
1
+ """ChimericMesh: legacy protocols stitched to modern AI agents via MCP."""
2
+
3
+ __version__ = "0.2.2"
@@ -0,0 +1,119 @@
1
+ """The `chimericmesh` command (also ``python -m chimericmesh``): start the hub, rotate the token, run the MCP server."""
2
+ import logging
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+ import uvicorn
7
+ from . import __version__, fsperms
8
+ from .api import create_app
9
+ from .services import AccessConfigError
10
+ from .services.token import TokenStore, resolve_token_path
11
+ from .store import StoreCorruptError, StoreOpenError
12
+ from .store.config import describe_startup, resolve_home
13
+ USAGE = """usage: chimericmesh [start | token --rotate | mcp | demo | --version | --help]
14
+
15
+ start start the hub (the default; ports and bind come from CHIMERICMESH_* environment variables)
16
+ token --rotate write a new admin token file and print its path
17
+ mcp run the MCP server on stdio, for Kiro (set CHIMERICMESH_URL if the hub is not on port 8000)
18
+ demo run the guided demo on its own, without touching your hub
19
+ --version print the version
20
+ --help print this text
21
+
22
+ `python -m chimericmesh` takes the same arguments."""
23
+ GRACEFUL_SHUTDOWN_SECONDS = 3 # uvicorn cancels a request that is still held after this long (R1-M2)
24
+ class MeshServer(uvicorn.Server):
25
+ """A server whose exit request first wakes every held `wait_for_work` call.
26
+ Uvicorn waits for in-flight requests before it runs the lifespan teardown, so a held long poll would keep
27
+ the hub open for up to its full wait. `aclose` makes each waiter return `timeout` at once.
28
+ """
29
+ def handle_exit(self, sig: int, frame) -> None:
30
+ agent = getattr(self.config.app.state, "agent", None)
31
+ if agent is not None:
32
+ agent.aclose()
33
+ super().handle_exit(sig, frame)
34
+ def build_server(app, host: str, port: int) -> uvicorn.Server:
35
+ """The server `main` runs. A helper so a test can inspect the configuration."""
36
+ config = uvicorn.Config(app, host=host, port=port, log_level="info",
37
+ timeout_graceful_shutdown=GRACEFUL_SHUTDOWN_SECONDS)
38
+ return MeshServer(config)
39
+ def rotate_token() -> int:
40
+ """Replace the token file and print its path, never the token. A running hub keeps its old token until restart."""
41
+ path = resolve_token_path(os.environ, Path(resolve_home()))
42
+ try:
43
+ if not path.parent.is_dir():
44
+ os.makedirs(path.parent, exist_ok=True)
45
+ fsperms.secure_dir(path.parent)
46
+ # The old content is not read: replacing an invalid file is exactly what --rotate is for.
47
+ TokenStore(path, "").rotate()
48
+ except OSError as exc:
49
+ print(f"token: could not replace {path}: {type(exc).__name__}", file=sys.stderr)
50
+ return 1
51
+ print(path)
52
+ return 0
53
+ def start() -> None:
54
+ """Start the hub and block until it stops."""
55
+ try:
56
+ app = create_app()
57
+ except StoreCorruptError as exc:
58
+ print(f"store: {exc.path} is not a valid SQLite database; it was left untouched", file=sys.stderr)
59
+ sys.exit(2)
60
+ except StoreOpenError as exc:
61
+ print(f"store: {exc}", file=sys.stderr)
62
+ sys.exit(2)
63
+ except AccessConfigError as exc:
64
+ print(f"access: {exc}", file=sys.stderr)
65
+ sys.exit(2)
66
+ bind = os.environ.get("CHIMERICMESH_BIND", "127.0.0.1")
67
+ port = int(os.environ.get("CHIMERICMESH_HTTP_PORT", 8000))
68
+ logging.getLogger("chimericmesh").warning(describe_startup(app.state.store.path))
69
+ print(f"ChimericMesh is running at http://{bind}:{port} (Home page: Try the demo)", flush=True)
70
+ token_path = app.state.access.token_path
71
+ if token_path is not None:
72
+ print(f"admin token file: {token_path}", flush=True)
73
+ build_server(app, bind, port).run()
74
+ def run_mcp() -> None:
75
+ """The stdio MCP server, as `python -m chimericmesh.mcp_server` runs it."""
76
+ from .mcp_server import mcp
77
+ mcp.run()
78
+ def run_demo() -> None:
79
+ """`chimericmesh demo`: the guided demo in this process, on its own throwaway data."""
80
+ from .demo import hub
81
+ code = hub.run_foreground()
82
+ if code:
83
+ sys.exit(code)
84
+
85
+
86
+ def run_demo_hub(args: list[str]) -> None:
87
+ """Internal: the throwaway hub the demo starts. Not listed in --help."""
88
+ from .demo import hub
89
+ sys.exit(hub.run_child(args))
90
+
91
+
92
+ def _usage_error() -> None:
93
+ print(USAGE, file=sys.stderr)
94
+ sys.exit(2)
95
+ def main(argv: list[str] | None = None) -> None:
96
+ args = list(sys.argv[1:] if argv is None else argv)
97
+ command, rest = (args[0], args[1:]) if args else ("start", [])
98
+ if command == "demo-hub":
99
+ run_demo_hub(rest)
100
+ elif command in ("--help", "-h") and not rest:
101
+ print(USAGE)
102
+ sys.exit(0)
103
+ elif command == "--version" and not rest:
104
+ print(f"chimericmesh {__version__}")
105
+ sys.exit(0)
106
+ elif command == "token" and rest == ["--rotate"]:
107
+ sys.exit(rotate_token())
108
+ elif rest:
109
+ _usage_error()
110
+ elif command == "start":
111
+ start()
112
+ elif command == "mcp":
113
+ run_mcp()
114
+ elif command == "demo":
115
+ run_demo()
116
+ else:
117
+ _usage_error()
118
+ if __name__ == "__main__":
119
+ main()
@@ -0,0 +1,21 @@
1
+ """Agent loop: read-only helpers that let one Kiro session watch the hub and verify an approval.
2
+
3
+ Pure re-exports only. This file imports no web framework; ``agent.routes`` is imported by ``api.py`` only.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from .errors import (
8
+ AgentError,
9
+ InvalidQuery,
10
+ NoCodeFolder,
11
+ SearchBusy,
12
+ TooManyWaiters,
13
+ UnknownProposal,
14
+ UnknownService,
15
+ )
16
+ from .ports import AgentPorts, ApprovalReader
17
+
18
+ __all__ = [
19
+ "AgentError", "AgentPorts", "ApprovalReader", "InvalidQuery", "NoCodeFolder", "SearchBusy",
20
+ "TooManyWaiters", "UnknownProposal", "UnknownService",
21
+ ]
@@ -0,0 +1,131 @@
1
+ """Literal code search inside one service's code folder (R1.4). Pure over a folder tree, bounded, and total.
2
+
3
+ Runs in a worker thread (``asyncio.to_thread``) with immutable inputs; it touches no hub object. The query is
4
+ text, never a regular expression. Only source files are read (``SOURCE_SUFFIXES``, open item O6), never a
5
+ protected file (``PROTECTED_PATTERNS``), never anything that resolves outside the folder. Containment is one ``realpath`` per file (the design note of
6
+ 2026-11-22: three calls per file made 2000 files exceed 5 s on Windows).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import time
13
+ from collections.abc import Callable, Iterable, Sequence
14
+ from dataclasses import dataclass
15
+
16
+ from chimericmesh.approvals.scope import PROTECTED_PATTERNS, SOURCE_SUFFIXES, glob_to_regex
17
+ from chimericmesh.diagnostics import SKIP_DIRS
18
+
19
+ from .errors import InvalidQuery
20
+ from .limits import MAX_FILE_BYTES, MAX_FILES_SCANNED, MAX_HITS, MAX_QUERY, SEARCH_SECONDS, clean_text
21
+
22
+ HIT_TEXT = 200
23
+ MAX_REL_PATH = 300
24
+ _PROTECTED = tuple(glob_to_regex(p) for p in PROTECTED_PATTERNS)
25
+ _UNSAFE = re.compile("[\\x00-\\x1f\\x7f-\\x9f\\ud800-\\udfff]")
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Hit:
30
+ file: str # relative to the code folder, "/" separators
31
+ line: int # 1-based
32
+ text: str # the stripped line, at most 200 characters, no control characters
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class SearchResult:
37
+ hits: tuple[Hit, ...]
38
+ truncated: bool
39
+
40
+
41
+ def validate_query(query: object) -> str:
42
+ """The query when it is 1 to 100 characters without control characters, else ``InvalidQuery``."""
43
+ if not isinstance(query, str) or not 1 <= len(query) <= MAX_QUERY or _UNSAFE.search(query):
44
+ raise InvalidQuery("query must be 1 to 100 characters without control characters")
45
+ return query
46
+
47
+
48
+ def _protected(rel: str) -> bool:
49
+ return any(rx.match(rel) for rx in _PROTECTED)
50
+
51
+
52
+ def _within(path: str, base: str) -> bool:
53
+ try:
54
+ return path != base and os.path.commonpath([path, base]) == base
55
+ except ValueError:
56
+ return False
57
+
58
+
59
+ def _read(path: str) -> str | None:
60
+ try:
61
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
62
+ return fh.read(MAX_FILE_BYTES + 1)
63
+ except (OSError, ValueError):
64
+ return None
65
+
66
+
67
+ def search_code(folder: str, query: str, *, protected_dirs: Sequence[str] = (),
68
+ clock: Callable[[], float] = time.monotonic, cancelled: Callable[[], bool] = lambda: False,
69
+ realpath: Callable[[str], str] = os.path.realpath,
70
+ normcase: Callable[[str], str] = os.path.normcase,
71
+ walk: Callable[..., Iterable[tuple[str, list[str], list[str]]]] = os.walk,
72
+ getsize: Callable[[str], int] = os.path.getsize,
73
+ read_text: Callable[[str], str | None] = _read) -> SearchResult:
74
+ """Up to 10 hits for ``query`` (case-insensitive, literal) under ``folder``.
75
+
76
+ ``truncated`` is true when the search stopped early: an eleventh hit, 2000 files visited, 5 seconds on
77
+ ``clock``, or ``cancelled()``. Directories and files are visited in sorted order, so the result is
78
+ deterministic.
79
+ """
80
+ needle = validate_query(query).casefold()
81
+ started = clock()
82
+ hits: list[Hit] = []
83
+ visited = 0
84
+ try:
85
+ base = normcase(realpath(folder))
86
+ prot_dirs = [normcase(realpath(p)) for p in protected_dirs]
87
+ except (OSError, ValueError):
88
+ return SearchResult((), False)
89
+
90
+ def stop() -> SearchResult:
91
+ return SearchResult(tuple(hits), True)
92
+
93
+ for dirpath, dirnames, filenames in walk(folder, followlinks=False):
94
+ rel_dir = os.path.relpath(dirpath, folder).replace(os.sep, "/")
95
+ prefix = "" if rel_dir == "." else rel_dir + "/"
96
+ dirnames[:] = sorted(d for d in dirnames
97
+ if d not in SKIP_DIRS and not _protected(normcase(f"{prefix}{d}/_")))
98
+ for name in sorted(filenames):
99
+ if visited >= MAX_FILES_SCANNED or cancelled() or clock() - started > SEARCH_SECONDS:
100
+ return stop()
101
+ visited += 1
102
+ path = os.path.join(dirpath, name)
103
+ rel = normcase(f"{prefix}{name}")
104
+ if len(rel) > MAX_REL_PATH or _UNSAFE.search(rel): # a name that cannot be reported safely
105
+ continue
106
+ if _protected(rel) or os.path.splitext(name)[1].lower() not in SOURCE_SUFFIXES:
107
+ continue
108
+ try:
109
+ if getsize(path) > MAX_FILE_BYTES:
110
+ continue
111
+ except (OSError, ValueError):
112
+ continue
113
+ try:
114
+ real = normcase(realpath(path))
115
+ except (OSError, ValueError):
116
+ continue
117
+ if not _within(real, base): # a symlink that leaves the folder
118
+ continue
119
+ real_rel = os.path.relpath(real, base).replace(os.sep, "/")
120
+ if (_protected(real_rel) or os.path.splitext(real)[1].lower() not in SOURCE_SUFFIXES
121
+ or any(_within(real, d) for d in prot_dirs)):
122
+ continue
123
+ text = read_text(path)
124
+ if text is None:
125
+ continue
126
+ for number, line in enumerate(text.split("\n"), start=1):
127
+ if needle in line.casefold():
128
+ if len(hits) >= MAX_HITS:
129
+ return stop()
130
+ hits.append(Hit(prefix + name, number, clean_text(line.strip(), HIT_TEXT)))
131
+ return SearchResult(tuple(hits), False)
@@ -0,0 +1,131 @@
1
+ """The digest of one service over a time window (R1.3). Deterministic, no model output.
2
+
3
+ Window arithmetic uses the event ``ts`` (the message time) and the hub clock for the window end. Event ids are
4
+ assigned in ingest order, so for live traffic ``ts`` grows with the id and the window start is found by a
5
+ binary search over ids. For replayed logs with old timestamps the digest is empty or partial and says so
6
+ through ``scanned`` (open item O1).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Sequence
11
+ from dataclasses import dataclass
12
+
13
+ from chimericmesh import diagnostics
14
+ from chimericmesh.diagnostics import Incident
15
+ from chimericmesh.events import Event
16
+ from chimericmesh.store.ports import StateView
17
+
18
+ from .limits import MAX_MINUTES, cap_items, clamp, clean_text
19
+
20
+ SCAN_CAP = 20_000
21
+ PAGE = 100
22
+ FUTURE_RUN = 200 # this many consecutive events past the window end stop the scan (R1-M7)
23
+ TOP_SIGNATURES = 10
24
+ MAX_INCIDENTS = 20
25
+ SAMPLE_CHARS = 200
26
+ SLICES = 5
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Window:
31
+ start: float
32
+ end: float
33
+ minutes: int
34
+
35
+ @classmethod
36
+ def ending(cls, end: float, minutes: int) -> "Window":
37
+ minutes = clamp(minutes, 1, MAX_MINUTES)
38
+ return cls(start=end - 60 * minutes, end=end, minutes=minutes)
39
+
40
+
41
+ def _first_not_before(state: StateView, service_id: str, start: float):
42
+ async def probe(mid: int) -> bool:
43
+ """True when the first event of the service after ``mid`` is not older than the window start."""
44
+ found = await state.events_after(mid, 1, service_id=service_id)
45
+ return not found or found[0].ts >= start
46
+ return probe
47
+
48
+
49
+ async def collect_window(state: StateView, service_id: str, window: Window, *,
50
+ scan_cap: int = SCAN_CAP) -> tuple[list[Event], bool]:
51
+ """Every event of the service read from the window start on (oldest first) and a ``truncated`` flag.
52
+
53
+ The list can hold events outside the window (a skipped future-dated event, an older one); the digest
54
+ counts only the ones inside it. ``scanned`` for the digest is ``len(events)``.
55
+ """
56
+ newest = await _newest_id(state)
57
+ if newest <= 0:
58
+ return [], False
59
+ probe = _first_not_before(state, service_id, window.start)
60
+ low, high = 0, newest # smallest id after which every event is inside the window
61
+ while low < high:
62
+ mid = (low + high) // 2
63
+ if await probe(mid):
64
+ high = mid
65
+ else:
66
+ low = mid + 1
67
+ events: list[Event] = []
68
+ cursor, future_run = low, 0
69
+ while len(events) < scan_cap:
70
+ page = await state.events_after(cursor, min(PAGE, scan_cap - len(events)), service_id=service_id)
71
+ if not page:
72
+ return events, False
73
+ for ev in page:
74
+ events.append(ev)
75
+ cursor = ev.id
76
+ future_run = future_run + 1 if ev.ts > window.end else 0
77
+ if future_run >= FUTURE_RUN:
78
+ return events, True
79
+ more = await state.events_after(cursor, 1, service_id=service_id)
80
+ return events, bool(more)
81
+
82
+
83
+ async def _newest_id(state: StateView) -> int:
84
+ latest = state.recent(1)
85
+ return max((ev.id for ev in latest), default=0)
86
+
87
+
88
+ def _event_key(ev: Event) -> tuple:
89
+ return (ev.ts, ev.id, ev.message, ev.severity, ev.host, ev.app, ev.source)
90
+
91
+
92
+ def build_digest(service_id: str, window: Window, events: Sequence[Event], incidents: Sequence[Incident],
93
+ *, scanned: int, truncated: bool) -> dict:
94
+ """Pure and total. Events and incidents outside the window are ignored; the order of the input does not
95
+ change the result. ``incidents`` are the ones the caller chose for this service."""
96
+ minutes = max(window.minutes, 1)
97
+ inside = sorted((ev for ev in events if window.start <= ev.ts <= window.end), key=_event_key)
98
+
99
+ severity_counts = {str(n): 0 for n in range(8)}
100
+ slice_len = minutes * 12
101
+ slice_counts = [0] * SLICES
102
+ groups: dict[str, dict] = {}
103
+ for ev in inside:
104
+ severity_counts[str(ev.severity)] += 1
105
+ slice_counts[min(SLICES - 1, int((ev.ts - window.start) / slice_len))] += 1
106
+ sig = diagnostics.signature(ev.message)
107
+ group = groups.get(sig)
108
+ if group is None:
109
+ groups[sig] = {"signature": sig, "count": 1, "first_ts": ev.ts, "last_ts": ev.ts,
110
+ "sample": ev.message, "most_severe": ev.severity}
111
+ else: # ``inside`` is sorted by ts, so the first event stays earliest
112
+ group["count"] += 1
113
+ group["last_ts"] = max(group["last_ts"], ev.ts)
114
+ group["most_severe"] = min(group["most_severe"], ev.severity)
115
+ ranked = sorted(groups.values(), key=lambda g: (-g["count"], g["first_ts"], g["signature"]))
116
+ top = [{**g, "signature": clean_text(g["signature"]), "sample": clean_text(g["sample"], SAMPLE_CHARS)}
117
+ for g in ranked[:TOP_SIGNATURES]]
118
+
119
+ opened = sorted((inc for inc in incidents if window.start <= inc.first_seen <= window.end),
120
+ key=lambda inc: (-inc.first_seen, inc.id))[:MAX_INCIDENTS]
121
+ opened_view = [{"id": clean_text(inc.id), "category": clean_text(inc.category), "severity": inc.severity,
122
+ "count": inc.count, "opening": inc.opening, "first_seen": inc.first_seen} for inc in opened]
123
+
124
+ step = (window.end - window.start) / SLICES if window.end > window.start else 0.0
125
+ slices = [{"start": window.start + i * step, "end": window.end if i == SLICES - 1 else window.start + (i + 1) * step,
126
+ "events": n, "per_minute": round(n / (minutes / SLICES), 2)} for i, n in enumerate(slice_counts)]
127
+ envelope = {"service_id": service_id, "minutes": window.minutes,
128
+ "window": {"start": window.start, "end": window.end}, "total_events": len(inside),
129
+ "severity_counts": severity_counts, "top_signatures": top, "slices": slices,
130
+ "scanned": scanned, "truncated": bool(truncated)}
131
+ return cap_items(envelope, "incidents_opened", opened_view)
@@ -0,0 +1,38 @@
1
+ """Errors of the agent loop. The REST layer maps each to a status code; messages carry no log text."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class AgentError(Exception):
6
+ """Base class."""
7
+
8
+
9
+ class UnknownService(AgentError):
10
+ """Unknown service id, or the ``unassigned`` pseudo service (404)."""
11
+
12
+
13
+ class UnknownProposal(AgentError):
14
+ """Unknown proposal id (404)."""
15
+
16
+
17
+ class NoCodeFolder(AgentError):
18
+ """The service has no code folder (422)."""
19
+
20
+
21
+ class InvalidQuery(AgentError):
22
+ """A query or test command that is empty, too long or unsafe (422)."""
23
+
24
+
25
+ class TooManyWaiters(AgentError):
26
+ """All long-poll slots are taken (429 with ``Retry-After``)."""
27
+
28
+ def __init__(self, retry_after: int = 5) -> None:
29
+ super().__init__("too many waiters")
30
+ self.retry_after = retry_after
31
+
32
+
33
+ class SearchBusy(AgentError):
34
+ """Two code searches are already running (429)."""
35
+
36
+ def __init__(self, retry_after: int = 2) -> None:
37
+ super().__init__("search busy")
38
+ self.retry_after = retry_after
@@ -0,0 +1,47 @@
1
+ """Service events: a cursor over one service's events, oldest first (R1.2). Read-only; text is cleaned."""
2
+ from __future__ import annotations
3
+
4
+ from chimericmesh.events import Event
5
+ from chimericmesh.store.ports import StateView
6
+
7
+ from .limits import DEFAULT_EVENTS, MAX_EVENTS, cap_items, clamp, clean_text
8
+
9
+ SCAN_CAP = 1000 # events looked at per call, kept or not
10
+ PAGE = 100
11
+
12
+
13
+ def _view(ev: Event) -> dict:
14
+ return {"id": ev.id, "ts": ev.ts, "source": clean_text(ev.source), "host": clean_text(ev.host),
15
+ "app": clean_text(ev.app), "severity": ev.severity, "message": clean_text(ev.message)}
16
+
17
+
18
+ async def service_events(state: StateView, service_id: str, *, limit: int = DEFAULT_EVENTS, after_id: int = 0,
19
+ min_severity: int | None = None) -> dict:
20
+ """Up to ``limit`` (1 to 100) events of ``service_id`` with an id above ``after_id``.
21
+
22
+ ``min_severity`` keeps events with ``severity <= min_severity`` (a lower number is more severe).
23
+ ``next_after_id`` is the id of the last event *scanned*, so a caller that filters still makes progress;
24
+ it equals ``after_id`` when nothing was scanned, and the id of the last kept event when the 20 KB cap
25
+ cut the list.
26
+ """
27
+ limit = clamp(limit, 1, MAX_EVENTS)
28
+ after = max(after_id, 0)
29
+ worst = None if min_severity is None else clamp(min_severity, 0, 7)
30
+ kept: list[Event] = []
31
+ cursor, scanned, done = after, 0, False
32
+ while not done and len(kept) < limit and scanned < SCAN_CAP:
33
+ page = await state.events_after(cursor, min(PAGE, SCAN_CAP - scanned), service_id=service_id)
34
+ if not page:
35
+ break
36
+ for ev in page:
37
+ cursor, scanned = ev.id, scanned + 1
38
+ if ev.service_id == service_id and (worst is None or ev.severity <= worst):
39
+ kept.append(ev)
40
+ if len(kept) >= limit or scanned >= SCAN_CAP:
41
+ done = True
42
+ break
43
+ items = [_view(ev) for ev in kept]
44
+ out = cap_items({"service_id": service_id, "next_after_id": cursor, "truncated": False}, "events", items)
45
+ if len(out["events"]) < len(items):
46
+ out["next_after_id"] = out["events"][-1]["id"] if out["events"] else after
47
+ return out
@@ -0,0 +1,98 @@
1
+ """Limits and safe text of the agent loop (R1.7). Pure and total; stdlib only.
2
+
3
+ Log text is untrusted. ``clean_text`` and ``cap_items`` are applied in the service layer, so every client
4
+ of a route gets stripped and capped text, not only Kiro.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import logging
10
+ import os
11
+ import re
12
+ from collections.abc import Mapping
13
+
14
+ log = logging.getLogger(__name__)
15
+
16
+ MAX_FIELD = 500 # characters per log-derived string field (R1.7)
17
+ MAX_RESPONSE_BYTES = 20_480 # per response (R1.7)
18
+ MAX_EVENTS, DEFAULT_EVENTS = 100, 25
19
+ MAX_MINUTES = 240
20
+ MAX_QUERY = 100
21
+ MAX_HITS = 10
22
+ MAX_FILES_SCANNED = 2000
23
+ MAX_FILE_BYTES = 512 * 1024
24
+ SEARCH_SECONDS = 5.0
25
+ WAIT_MIN, TICK, MAX_WAITERS = 1, 0.5, 4
26
+ WAIT_CEILING = 25 # hard ceiling; configuration can only lower the wait
27
+ MAX_EXCLUDE, MAX_ID_LEN = 200, 40
28
+ RULE_APPROVAL_WINDOW = 1800 # equals ApprovalSettings.rule_approval_ttl; a test asserts it
29
+
30
+ _ENV_WAIT = "CHIMERICMESH_WATCH_MAX_WAIT"
31
+ _UNSAFE = re.compile("[\\x00-\\x1f\\x7f-\\x9f\\ud800-\\udfff]")
32
+
33
+
34
+ def clean_text(value: object, limit: int = MAX_FIELD) -> str:
35
+ """``str(value)`` without control characters or lone surrogates, cut to ``limit`` characters."""
36
+ if value is None:
37
+ return ""
38
+ try:
39
+ text = value if isinstance(value, str) else str(value)
40
+ except Exception: # noqa: BLE001 - total by contract
41
+ return ""
42
+ if limit <= 0:
43
+ return ""
44
+ return _UNSAFE.sub("", text)[:limit]
45
+
46
+
47
+ def clamp(value: int, low: int, high: int) -> int:
48
+ return max(low, min(high, value))
49
+
50
+
51
+ def clean_mapping(value: object, limit: int = MAX_FIELD) -> dict | None:
52
+ """A copy of a mapping with every text key and value passed through ``clean_text``. Numbers, booleans and
53
+ ``None`` are kept; anything else becomes cleaned text. ``None`` for a value that is not a mapping."""
54
+ if not isinstance(value, Mapping):
55
+ return None
56
+ out: dict = {}
57
+ for key, item in value.items():
58
+ if isinstance(item, str):
59
+ item = clean_text(item, limit)
60
+ elif not (item is None or isinstance(item, (bool, int, float))):
61
+ item = clean_text(item, limit)
62
+ out[clean_text(key, 80)] = item
63
+ return out
64
+ def _size(envelope: Mapping[str, object]) -> int:
65
+ return len(json.dumps(envelope, separators=(",", ":"), ensure_ascii=False).encode("utf-8", "replace"))
66
+
67
+
68
+ def cap_items(envelope: dict, key: str, items: list[dict], *, max_bytes: int = MAX_RESPONSE_BYTES) -> dict:
69
+ """Put the longest prefix of ``items`` under ``envelope[key]`` that keeps the JSON at ``max_bytes`` or
70
+ less. ``truncated`` is set to True only when items were dropped. An empty list always fits."""
71
+ whole = dict(envelope, **{key: list(items)})
72
+ if _size(whole) <= max_bytes:
73
+ return whole
74
+ low, high = 0, len(items) # the largest prefix length that fits lies in [low, high]
75
+ while low < high:
76
+ mid = (low + high + 1) // 2
77
+ if _size(dict(envelope, **{key: items[:mid], "truncated": True})) <= max_bytes:
78
+ low = mid
79
+ else:
80
+ high = mid - 1
81
+ return dict(envelope, **{key: list(items[:low]), "truncated": True})
82
+
83
+
84
+ def watch_max_wait(environ: Mapping[str, str] | None = None) -> int:
85
+ """The longest ``wait_for_work`` hold in seconds. The setting can only lower the ceiling (R1-M6)."""
86
+ env = os.environ if environ is None else environ
87
+ raw = env.get(_ENV_WAIT)
88
+ if raw is None or not str(raw).strip():
89
+ return WAIT_CEILING
90
+ try:
91
+ value = int(str(raw).strip())
92
+ except ValueError:
93
+ log.warning("%s is not an integer; using %s", _ENV_WAIT, WAIT_CEILING)
94
+ return WAIT_CEILING
95
+ return clamp(value, WAIT_MIN, WAIT_CEILING)
96
+
97
+
98
+ WAIT_MAX = watch_max_wait()
@@ -0,0 +1,32 @@
1
+ """The injected interfaces of the agent loop (review M2). This module never imports the hub."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Protocol, runtime_checkable
7
+
8
+ from chimericmesh.approvals.models import ApprovalStatus, Rule
9
+ from chimericmesh.services.registry import ServiceRegistry
10
+ from chimericmesh.store.models import Proposal
11
+ from chimericmesh.store.ports import StateView
12
+
13
+
14
+ @runtime_checkable
15
+ class ApprovalReader(Protocol):
16
+ """A three-method protocol that ``ApprovalManager`` already satisfies. Nothing here can create,
17
+ patch, enable, resume, revoke or pause a rule (R1-L2)."""
18
+
19
+ def approval_of(self, prop: Proposal) -> dict | None: ...
20
+
21
+ def rule(self, rule_id: str) -> Rule | None: ...
22
+
23
+ def status(self) -> ApprovalStatus: ...
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class AgentPorts:
28
+ state: StateView
29
+ registry: ServiceRegistry
30
+ approvals: ApprovalReader | None # None only in unit tests; every rule approval then fails verify
31
+ protected_dirs: Sequence[str]
32
+ workspace_root: str | None # snippet only