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.
- chimericmesh/__init__.py +3 -0
- chimericmesh/__main__.py +119 -0
- chimericmesh/agent/__init__.py +21 -0
- chimericmesh/agent/codesearch.py +131 -0
- chimericmesh/agent/digest.py +131 -0
- chimericmesh/agent/errors.py +38 -0
- chimericmesh/agent/feed.py +47 -0
- chimericmesh/agent/limits.py +98 -0
- chimericmesh/agent/ports.py +32 -0
- chimericmesh/agent/routes.py +92 -0
- chimericmesh/agent/service.py +116 -0
- chimericmesh/agent/snippet.py +135 -0
- chimericmesh/agent/verify.py +215 -0
- chimericmesh/agent/watch.py +156 -0
- chimericmesh/api.py +626 -0
- chimericmesh/approvals/__init__.py +25 -0
- chimericmesh/approvals/errors.py +72 -0
- chimericmesh/approvals/format.py +76 -0
- chimericmesh/approvals/irc.py +54 -0
- chimericmesh/approvals/ledger.py +149 -0
- chimericmesh/approvals/limits.py +87 -0
- chimericmesh/approvals/manager.py +935 -0
- chimericmesh/approvals/matching.py +107 -0
- chimericmesh/approvals/models.py +251 -0
- chimericmesh/approvals/ports.py +36 -0
- chimericmesh/approvals/routes.py +220 -0
- chimericmesh/approvals/rulebook.py +337 -0
- chimericmesh/approvals/schema.py +64 -0
- chimericmesh/approvals/scope.py +104 -0
- chimericmesh/approvals/validate.py +215 -0
- chimericmesh/catalog/demo_apps.json +41 -0
- chimericmesh/catalog/legacy_apps.json +612 -0
- chimericmesh/commands.py +223 -0
- chimericmesh/connectors/__init__.py +1 -0
- chimericmesh/connectors/config.py +55 -0
- chimericmesh/connectors/framing.py +132 -0
- chimericmesh/connectors/limiter.py +42 -0
- chimericmesh/connectors/manager.py +252 -0
- chimericmesh/connectors/offsets.py +157 -0
- chimericmesh/connectors/schema.py +31 -0
- chimericmesh/connectors/submit.py +26 -0
- chimericmesh/connectors/syslog_tcp.py +141 -0
- chimericmesh/connectors/tailer.py +236 -0
- chimericmesh/connectors/tailread.py +288 -0
- chimericmesh/demo/__init__.py +1 -0
- chimericmesh/demo/agent.py +32 -0
- chimericmesh/demo/apps/__init__.py +1 -0
- chimericmesh/demo/apps/__main__.py +83 -0
- chimericmesh/demo/apps/common.py +163 -0
- chimericmesh/demo/apps/mail_bridge.py +48 -0
- chimericmesh/demo/apps/orders_api.py +31 -0
- chimericmesh/demo/apps/spooler.py +28 -0
- chimericmesh/demo/config.py +38 -0
- chimericmesh/demo/engine.py +68 -0
- chimericmesh/demo/env.py +46 -0
- chimericmesh/demo/hub.py +172 -0
- chimericmesh/demo/launcher.py +165 -0
- chimericmesh/demo/ports.py +44 -0
- chimericmesh/demo/routes.py +81 -0
- chimericmesh/demo/samples.py +32 -0
- chimericmesh/demo/scenario.py +95 -0
- chimericmesh/demo/supervisor.py +267 -0
- chimericmesh/demo/watch.py +46 -0
- chimericmesh/diagnostics.py +253 -0
- chimericmesh/discovery/__init__.py +17 -0
- chimericmesh/discovery/accept.py +131 -0
- chimericmesh/discovery/catalog.py +313 -0
- chimericmesh/discovery/collect.py +131 -0
- chimericmesh/discovery/dismissals.py +46 -0
- chimericmesh/discovery/engine.py +41 -0
- chimericmesh/discovery/errors.py +34 -0
- chimericmesh/discovery/expand.py +151 -0
- chimericmesh/discovery/manager.py +220 -0
- chimericmesh/discovery/match.py +177 -0
- chimericmesh/discovery/models.py +174 -0
- chimericmesh/discovery/parse.py +166 -0
- chimericmesh/discovery/probe.py +69 -0
- chimericmesh/discovery/routes.py +129 -0
- chimericmesh/discovery/runner.py +147 -0
- chimericmesh/discovery/schema.py +25 -0
- chimericmesh/discovery/text.py +53 -0
- chimericmesh/events.py +74 -0
- chimericmesh/fsperms.py +72 -0
- chimericmesh/hub.py +757 -0
- chimericmesh/listeners.py +162 -0
- chimericmesh/mcp_server.py +199 -0
- chimericmesh/mute/__init__.py +10 -0
- chimericmesh/mute/models.py +14 -0
- chimericmesh/mute/mutelist.py +51 -0
- chimericmesh/mute/routes.py +49 -0
- chimericmesh/mute/schema.py +29 -0
- chimericmesh/mute/store.py +94 -0
- chimericmesh/notify.py +47 -0
- chimericmesh/parsers/__init__.py +12 -0
- chimericmesh/parsers/formats.py +23 -0
- chimericmesh/parsers/irc.py +91 -0
- chimericmesh/parsers/logctx.py +143 -0
- chimericmesh/parsers/ncsa.py +57 -0
- chimericmesh/parsers/plain.py +17 -0
- chimericmesh/parsers/syslog.py +82 -0
- chimericmesh/parsers/syslogtext.py +62 -0
- chimericmesh/parsers/telnet.py +56 -0
- chimericmesh/parsers/w3c.py +58 -0
- chimericmesh/parsers/xferlog.py +31 -0
- chimericmesh/replay.py +108 -0
- chimericmesh/replay_irc.py +202 -0
- chimericmesh/services/__init__.py +39 -0
- chimericmesh/services/access.py +224 -0
- chimericmesh/services/asgi.py +107 -0
- chimericmesh/services/deps.py +42 -0
- chimericmesh/services/errors.py +49 -0
- chimericmesh/services/limiter.py +130 -0
- chimericmesh/services/models.py +160 -0
- chimericmesh/services/paths.py +139 -0
- chimericmesh/services/registry.py +638 -0
- chimericmesh/services/routes.py +161 -0
- chimericmesh/services/schema.py +48 -0
- chimericmesh/services/status.py +239 -0
- chimericmesh/services/tagging.py +63 -0
- chimericmesh/services/token.py +129 -0
- chimericmesh/services/validate.py +184 -0
- chimericmesh/store/__init__.py +43 -0
- chimericmesh/store/audit.py +89 -0
- chimericmesh/store/config.py +88 -0
- chimericmesh/store/connection.py +98 -0
- chimericmesh/store/errors.py +65 -0
- chimericmesh/store/events.py +430 -0
- chimericmesh/store/incidents.py +292 -0
- chimericmesh/store/migrations.py +109 -0
- chimericmesh/store/models.py +49 -0
- chimericmesh/store/ports.py +61 -0
- chimericmesh/store/proposals.py +215 -0
- chimericmesh/store/schema.py +102 -0
- chimericmesh/store/store.py +173 -0
- chimericmesh/store/tx.py +143 -0
- chimericmesh/store/writer.py +315 -0
- chimericmesh/web/__init__.py +1 -0
- chimericmesh/web/feed.py +212 -0
- chimericmesh/web/index.html +3775 -0
- chimericmesh/web/sse.py +74 -0
- chimericmesh/web/stream.py +64 -0
- chimericmesh-0.2.2.dist-info/METADATA +537 -0
- chimericmesh-0.2.2.dist-info/RECORD +147 -0
- chimericmesh-0.2.2.dist-info/WHEEL +5 -0
- chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
- chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
- chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""REST routes of the agent loop (owner ``agent-loop``). Read-only: no route writes, none takes the admin token.
|
|
2
|
+
This is the only file of the package that may import the web stack. Every handler is ``async def`` (store T2).
|
|
3
|
+
Numbers are clamped here (R1.2, R1.3, R4.2); the text of every response is cleaned in the facade (R1.7).
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
import re
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
from fastapi import APIRouter, HTTPException, Query, Request
|
|
9
|
+
from fastapi.responses import JSONResponse, PlainTextResponse
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
|
|
11
|
+
from .errors import InvalidQuery, NoCodeFolder, SearchBusy, TooManyWaiters, UnknownProposal, UnknownService
|
|
12
|
+
from .limits import DEFAULT_EVENTS, MAX_EVENTS, MAX_EXCLUDE, MAX_ID_LEN, MAX_MINUTES, clamp
|
|
13
|
+
from .service import AgentService
|
|
14
|
+
MAX_CURSOR = 2**62 # an id beyond this cannot exist; keeps the SQL bind value in range
|
|
15
|
+
_EXCLUDE_ID = re.compile(r"[A-Za-z0-9_.:-]{1,%d}" % MAX_ID_LEN)
|
|
16
|
+
class VerifyBody(BaseModel):
|
|
17
|
+
"""A size bound only; the 1 to 20 rule is check 3.1c of verify, which answers 200 with reasons."""
|
|
18
|
+
model_config = ConfigDict(extra="forbid")
|
|
19
|
+
files: list[Annotated[str, StringConstraints(max_length=1100)]] = Field(max_length=200)
|
|
20
|
+
def _not_found() -> HTTPException:
|
|
21
|
+
return HTTPException(404, "service not found")
|
|
22
|
+
def _unprocessable(detail: str, field: str | None = None) -> JSONResponse:
|
|
23
|
+
body = {"detail": detail} if field is None else {"detail": detail, "field": field}
|
|
24
|
+
return JSONResponse(body, status_code=422)
|
|
25
|
+
def build_router(agent: AgentService) -> APIRouter:
|
|
26
|
+
router = APIRouter()
|
|
27
|
+
@router.get("/api/services/{service_id}/events")
|
|
28
|
+
async def service_events(service_id: str, limit: int = DEFAULT_EVENTS, after_id: int = 0,
|
|
29
|
+
min_severity: int | None = None):
|
|
30
|
+
try:
|
|
31
|
+
return await agent.service_events(
|
|
32
|
+
service_id, clamp(limit, 1, MAX_EVENTS), clamp(after_id, 0, MAX_CURSOR),
|
|
33
|
+
None if min_severity is None else clamp(min_severity, 0, 7))
|
|
34
|
+
except UnknownService:
|
|
35
|
+
raise _not_found() from None
|
|
36
|
+
@router.get("/api/services/{service_id}/digest")
|
|
37
|
+
async def digest(service_id: str, minutes: int = 15):
|
|
38
|
+
try:
|
|
39
|
+
return await agent.digest(service_id, clamp(minutes, 1, MAX_MINUTES))
|
|
40
|
+
except UnknownService:
|
|
41
|
+
raise _not_found() from None
|
|
42
|
+
@router.get("/api/services/{service_id}/code-search")
|
|
43
|
+
async def code_search(service_id: str, query: str | None = None):
|
|
44
|
+
if query is None:
|
|
45
|
+
return _unprocessable("query is required", "query")
|
|
46
|
+
try:
|
|
47
|
+
return await agent.code_search(service_id, query)
|
|
48
|
+
except UnknownService:
|
|
49
|
+
raise _not_found() from None
|
|
50
|
+
except NoCodeFolder:
|
|
51
|
+
return _unprocessable("service has no code folder")
|
|
52
|
+
except InvalidQuery as exc:
|
|
53
|
+
return _unprocessable(str(exc), "query")
|
|
54
|
+
except SearchBusy as exc:
|
|
55
|
+
raise HTTPException(429, "search busy", headers={"Retry-After": str(exc.retry_after)}) from None
|
|
56
|
+
@router.post("/api/proposals/{pid}/verify")
|
|
57
|
+
async def verify(pid: str, body: VerifyBody):
|
|
58
|
+
try:
|
|
59
|
+
return agent.verify(pid, body.files)
|
|
60
|
+
except UnknownProposal:
|
|
61
|
+
raise HTTPException(404, "proposal not found") from None
|
|
62
|
+
@router.get("/api/watch/next")
|
|
63
|
+
async def watch_next(request: Request, timeout_seconds: int = 25,
|
|
64
|
+
service_id: str | None = Query(None, max_length=64),
|
|
65
|
+
exclude_ids: list[str] | None = Query(None)):
|
|
66
|
+
exclude = exclude_ids or []
|
|
67
|
+
if len(exclude) > MAX_EXCLUDE:
|
|
68
|
+
return _unprocessable(f"at most {MAX_EXCLUDE} ids", "exclude_ids")
|
|
69
|
+
if not all(_EXCLUDE_ID.fullmatch(item) for item in exclude):
|
|
70
|
+
return _unprocessable("every id is 1 to %d characters of letters, digits and _ . : -" % MAX_ID_LEN,
|
|
71
|
+
"exclude_ids")
|
|
72
|
+
if service_id is not None and not agent.knows_service(service_id):
|
|
73
|
+
raise _not_found()
|
|
74
|
+
queue = agent.watch
|
|
75
|
+
timeout = max(queue.wait_min, min(timeout_seconds, queue.wait_max))
|
|
76
|
+
try:
|
|
77
|
+
return await queue.next(timeout=timeout, service_id=service_id, exclude=frozenset(exclude),
|
|
78
|
+
is_disconnected=request.is_disconnected)
|
|
79
|
+
except TooManyWaiters as exc:
|
|
80
|
+
raise HTTPException(429, "too many waiters", headers={"Retry-After": str(exc.retry_after)}) from None
|
|
81
|
+
@router.get("/api/services/{service_id}/permissions-snippet")
|
|
82
|
+
async def permissions_snippet(service_id: str, test_command: str | None = None):
|
|
83
|
+
try:
|
|
84
|
+
text = agent.permissions_snippet(service_id, test_command)
|
|
85
|
+
except UnknownService:
|
|
86
|
+
raise _not_found() from None
|
|
87
|
+
except NoCodeFolder:
|
|
88
|
+
return _unprocessable("service has no code folder")
|
|
89
|
+
except InvalidQuery as exc:
|
|
90
|
+
return _unprocessable(str(exc), "test_command")
|
|
91
|
+
return PlainTextResponse(text, media_type="text/plain; charset=utf-8")
|
|
92
|
+
return router
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""The facade of the agent loop: the only class that touches the injected ports (design decision 1).
|
|
2
|
+
It reads events, incidents and proposals through ``StateView``, services through ``ServiceRegistry`` and
|
|
3
|
+
approvals through the three-method ``ApprovalReader``. It writes nothing and imports no ``hub``.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
import asyncio
|
|
7
|
+
import threading
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from chimericmesh.diagnostics import Incident
|
|
10
|
+
from .codesearch import search_code, validate_query
|
|
11
|
+
from .digest import Window, build_digest, collect_window
|
|
12
|
+
from .errors import NoCodeFolder, SearchBusy, UnknownProposal, UnknownService
|
|
13
|
+
from .feed import service_events
|
|
14
|
+
from .limits import clean_mapping, clean_text
|
|
15
|
+
from .ports import AgentPorts
|
|
16
|
+
from .snippet import DEFAULT_TEST_COMMAND, build_snippet
|
|
17
|
+
from .verify import VerifyInputs, evaluate_verify
|
|
18
|
+
from .watch import UNASSIGNED, WatchQueue
|
|
19
|
+
MAX_SEARCHES = 2
|
|
20
|
+
class AgentService:
|
|
21
|
+
def __init__(self, ports: AgentPorts) -> None:
|
|
22
|
+
self._ports = ports
|
|
23
|
+
self.watch = WatchQueue(ports)
|
|
24
|
+
self._running = 0 # code-search worker threads; changed on the loop thread only
|
|
25
|
+
# --- lookups -----------------------------------------------------------------------------------
|
|
26
|
+
def _service(self, service_id: str):
|
|
27
|
+
"""The registered service, or ``UnknownService`` (also for the ``unassigned`` pseudo service, R1.5)."""
|
|
28
|
+
if not isinstance(service_id, str) or service_id == UNASSIGNED:
|
|
29
|
+
raise UnknownService(service_id)
|
|
30
|
+
svc = self._ports.registry.get(service_id)
|
|
31
|
+
if svc is None:
|
|
32
|
+
raise UnknownService(service_id)
|
|
33
|
+
return svc
|
|
34
|
+
def knows_service(self, service_id: str) -> bool:
|
|
35
|
+
"""For the long poll filter: a registered id or ``unassigned``."""
|
|
36
|
+
return service_id == UNASSIGNED or self._ports.registry.get(service_id) is not None
|
|
37
|
+
# --- reads -------------------------------------------------------------------------------------
|
|
38
|
+
async def service_events(self, service_id: str, limit: int, after_id: int, min_severity: int | None) -> dict:
|
|
39
|
+
self._service(service_id)
|
|
40
|
+
return await service_events(self._ports.state, service_id, limit=limit, after_id=after_id,
|
|
41
|
+
min_severity=min_severity)
|
|
42
|
+
async def digest(self, service_id: str, minutes: int) -> dict:
|
|
43
|
+
self._service(service_id)
|
|
44
|
+
state = self._ports.state
|
|
45
|
+
window = Window.ending(state.now(), minutes)
|
|
46
|
+
events, truncated = await collect_window(state, service_id, window)
|
|
47
|
+
incidents = state.incidents(service_id=service_id)
|
|
48
|
+
return build_digest(service_id, window, events, incidents, scanned=len(events), truncated=truncated)
|
|
49
|
+
async def code_search(self, service_id: str, query: str) -> dict:
|
|
50
|
+
svc = self._service(service_id)
|
|
51
|
+
folder = svc.code_folder
|
|
52
|
+
if not folder:
|
|
53
|
+
raise NoCodeFolder("service has no code folder")
|
|
54
|
+
validate_query(query) # InvalidQuery before a slot is taken
|
|
55
|
+
if self._running >= MAX_SEARCHES:
|
|
56
|
+
raise SearchBusy(retry_after=2)
|
|
57
|
+
stop = threading.Event()
|
|
58
|
+
protected = tuple(self._ports.protected_dirs)
|
|
59
|
+
loop = asyncio.get_running_loop()
|
|
60
|
+
# The slot is released by the worker's completion, not by this task: a cancelled task whose thread is
|
|
61
|
+
# still running keeps its slot (G2, R1-L3). ``search_code`` is looked up here so tests can replace it.
|
|
62
|
+
worker = loop.create_task(asyncio.to_thread(search_code, folder, query, protected_dirs=protected,
|
|
63
|
+
cancelled=stop.is_set))
|
|
64
|
+
self._running += 1
|
|
65
|
+
worker.add_done_callback(self._release)
|
|
66
|
+
try:
|
|
67
|
+
result = await asyncio.shield(worker)
|
|
68
|
+
finally:
|
|
69
|
+
stop.set()
|
|
70
|
+
return {"service_id": service_id,
|
|
71
|
+
"hits": [{"file": clean_text(h.file), "line": h.line, "text": clean_text(h.text, 200)}
|
|
72
|
+
for h in result.hits],
|
|
73
|
+
"truncated": result.truncated}
|
|
74
|
+
def _release(self, task: asyncio.Future) -> None:
|
|
75
|
+
self._running = max(0, self._running - 1)
|
|
76
|
+
if not task.cancelled():
|
|
77
|
+
task.exception() # retrieved: a failed search of a cancelled caller is not logged twice
|
|
78
|
+
# --- verify ------------------------------------------------------------------------------------
|
|
79
|
+
def verify(self, proposal_id: str, files: Sequence[str]) -> dict:
|
|
80
|
+
"""One synchronous block, so the inputs are one consistent snapshot (G1)."""
|
|
81
|
+
ports = self._ports
|
|
82
|
+
prop = ports.state.get_proposal(proposal_id)
|
|
83
|
+
if prop is None:
|
|
84
|
+
raise UnknownProposal(proposal_id)
|
|
85
|
+
reader = ports.approvals
|
|
86
|
+
rule_id = prop.approved_by_rule
|
|
87
|
+
rule = reader.rule(rule_id) if reader is not None and rule_id else None
|
|
88
|
+
svc = ports.registry.get(prop.service_id) if prop.service_id else None
|
|
89
|
+
inputs = VerifyInputs(
|
|
90
|
+
proposal_id=prop.id, status=prop.status, approved_by_rule=rule_id,
|
|
91
|
+
declared_files=tuple(prop.files) if isinstance(prop.files, list) else None,
|
|
92
|
+
approval=reader.approval_of(prop) if reader is not None else None,
|
|
93
|
+
rule_status=None if rule is None else rule.status,
|
|
94
|
+
rule_code_folder=None if rule is None else rule.code_folder,
|
|
95
|
+
rule_expires_at=None if rule is None else rule.expires_at,
|
|
96
|
+
paused=bool(reader.status().paused) if reader is not None else False,
|
|
97
|
+
approvals_available=reader is not None,
|
|
98
|
+
code_folder=None if svc is None else (svc.code_folder or None), has_service=svc is not None,
|
|
99
|
+
now=ports.state.now(), protected_dirs=tuple(ports.protected_dirs))
|
|
100
|
+
result = evaluate_verify(inputs, files)
|
|
101
|
+
return {"ok": result.ok, "reasons": list(result.reasons), "status": clean_text(result.status, 20),
|
|
102
|
+
"approval": clean_mapping(result.approval),
|
|
103
|
+
"declared_files": [clean_text(f) for f in result.declared_files]}
|
|
104
|
+
# --- snippet and wiring helpers ------------------------------------------------------------------
|
|
105
|
+
def permissions_snippet(self, service_id: str, test_command: str | None) -> str:
|
|
106
|
+
svc = self._service(service_id)
|
|
107
|
+
return build_snippet(svc, workspace_root=self._ports.workspace_root,
|
|
108
|
+
test_command=test_command or DEFAULT_TEST_COMMAND)
|
|
109
|
+
def code_folder_for_incident(self, inc: Incident) -> str | None:
|
|
110
|
+
"""The live code folder of the incident's service, or ``None`` (B6)."""
|
|
111
|
+
if inc.service_id is None:
|
|
112
|
+
return None
|
|
113
|
+
svc = self._ports.registry.get(inc.service_id)
|
|
114
|
+
return None if svc is None else (svc.code_folder or None)
|
|
115
|
+
def aclose(self) -> None:
|
|
116
|
+
self.watch.close()
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""The permissions snippet (R5.4 to R5.8). Pure text; nothing here writes a Kiro file (F5).
|
|
2
|
+
The text is YAML with leading comments. Every value that comes from outside (service id, folder, workspace
|
|
3
|
+
root, test command) is cleaned and quoted with ``json.dumps``, so it cannot inject a rule or a line.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Callable, Mapping
|
|
11
|
+
from chimericmesh.approvals.scope import PROTECTED_PATTERNS
|
|
12
|
+
from chimericmesh.services.paths import path_in_code_folder
|
|
13
|
+
from .errors import InvalidQuery, NoCodeFolder
|
|
14
|
+
from .limits import clean_text
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
ENV_ROOT = "CHIMERICMESH_WORKSPACE_ROOT"
|
|
17
|
+
DEFAULT_TEST_COMMAND = "python -m pytest -q"
|
|
18
|
+
STATE_FILE = ".chimericmesh-active-proposal"
|
|
19
|
+
_COMMAND = re.compile(r"[A-Za-z0-9_.:/ -]{1,80}")
|
|
20
|
+
_BAD_WORDS = frozenset({"curl", "wget", "nc", "ncat", "powershell", "pwsh", "bash", "sh", "cmd"})
|
|
21
|
+
_SHORT_C = re.compile(r"^-[A-Za-z0-9]*c") # -c, -qc, -Sc: inline code or an alternative config
|
|
22
|
+
_GLOB_CHARS = frozenset("*?[]{}")
|
|
23
|
+
def validate_test_command(value: str) -> str:
|
|
24
|
+
"""The one command the snippet may show as a shell example. Raises ``InvalidQuery``."""
|
|
25
|
+
if not isinstance(value, str):
|
|
26
|
+
raise InvalidQuery("test_command must be text")
|
|
27
|
+
text = value.strip()
|
|
28
|
+
if not text or not _COMMAND.fullmatch(text):
|
|
29
|
+
raise InvalidQuery("test_command must be 1 to 80 characters of letters, digits and _ . : / - or space")
|
|
30
|
+
for token in text.split():
|
|
31
|
+
base = re.split(r"[\\/]", token)[-1].lower()
|
|
32
|
+
if base.endswith(".exe"):
|
|
33
|
+
base = base[:-4]
|
|
34
|
+
if base in _BAD_WORDS or _SHORT_C.match(token):
|
|
35
|
+
raise InvalidQuery("test_command contains a command that is not allowed")
|
|
36
|
+
return text
|
|
37
|
+
def find_workspace_root(environ: Mapping[str, str], cwd: str, *,
|
|
38
|
+
exists: Callable[[str], bool] = os.path.isdir) -> str | None:
|
|
39
|
+
"""``CHIMERICMESH_WORKSPACE_ROOT`` when it is an existing absolute directory; ``None`` (workspace unknown,
|
|
40
|
+
no allow line) with one warning when it is set but invalid; else the nearest ancestor of ``cwd`` that has a
|
|
41
|
+
``.kiro`` directory (R1-M3); else ``cwd``."""
|
|
42
|
+
raw = environ.get(ENV_ROOT)
|
|
43
|
+
if raw is not None and str(raw).strip():
|
|
44
|
+
value = str(raw).strip()
|
|
45
|
+
try:
|
|
46
|
+
valid = os.path.isabs(value) and bool(exists(value))
|
|
47
|
+
except (OSError, ValueError):
|
|
48
|
+
valid = False
|
|
49
|
+
if valid:
|
|
50
|
+
return value
|
|
51
|
+
log.warning("%s is not an existing absolute directory; the permissions snippet has no allow line", ENV_ROOT)
|
|
52
|
+
return None
|
|
53
|
+
here = cwd
|
|
54
|
+
while True:
|
|
55
|
+
try:
|
|
56
|
+
if exists(os.path.join(here, ".kiro")):
|
|
57
|
+
return here
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
pass
|
|
60
|
+
parent = os.path.dirname(here)
|
|
61
|
+
if not parent or parent == here:
|
|
62
|
+
return cwd
|
|
63
|
+
here = parent
|
|
64
|
+
def _text(value: object, limit: int = 300) -> str:
|
|
65
|
+
"""Printable text only (no control, no line separator), cut to ``limit``."""
|
|
66
|
+
return "".join(c for c in clean_text(value, limit) if c.isprintable())
|
|
67
|
+
def _quoted(value: object, limit: int = 300) -> str:
|
|
68
|
+
return json.dumps(_text(value, limit), ensure_ascii=False)
|
|
69
|
+
def _relative_allow(folder: str, workspace_root: str | None) -> str | None:
|
|
70
|
+
"""The workspace-relative glob for ``folder``, or ``None`` when no safe allow line exists."""
|
|
71
|
+
if not workspace_root or not isinstance(workspace_root, str) or not isinstance(folder, str):
|
|
72
|
+
return None
|
|
73
|
+
if not path_in_code_folder(workspace_root, folder): # strict descendant only
|
|
74
|
+
return None
|
|
75
|
+
try:
|
|
76
|
+
rel = os.path.relpath(os.path.realpath(folder), os.path.realpath(workspace_root))
|
|
77
|
+
except (OSError, ValueError):
|
|
78
|
+
return None
|
|
79
|
+
rel = rel.replace(os.sep, "/")
|
|
80
|
+
if (not rel or rel == "." or rel.startswith(("/", "~", "!", "../")) or ".." in rel.split("/")
|
|
81
|
+
or "\\" in rel or len(rel) > 200 or any(c in _GLOB_CHARS for c in rel) or not rel.isprintable()
|
|
82
|
+
or re.match(r"^[A-Za-z]:", rel)):
|
|
83
|
+
return None
|
|
84
|
+
return rel + "/**"
|
|
85
|
+
def build_snippet(service, *, workspace_root: str | None, test_command: str = DEFAULT_TEST_COMMAND) -> str:
|
|
86
|
+
"""The text for ``service`` (anything with ``id`` and ``code_folder``). Raises ``NoCodeFolder`` when the
|
|
87
|
+
service has no folder and ``InvalidQuery`` for an unsafe ``test_command``."""
|
|
88
|
+
folder = getattr(service, "code_folder", None)
|
|
89
|
+
if not folder:
|
|
90
|
+
raise NoCodeFolder("service has no code folder")
|
|
91
|
+
command = validate_test_command(test_command)
|
|
92
|
+
allow = _relative_allow(folder, workspace_root)
|
|
93
|
+
lines = [
|
|
94
|
+
"# Mode: AUTONOMOUS (hands-off). This file is a standing allow for edits inside one code folder.",
|
|
95
|
+
"# Prompt mode is the default (no snippet): do not paste this file unless you want hands-off edits.",
|
|
96
|
+
"# Trade-off: edits inside the folder no longer prompt, including edits for a proposal that is still pending.",
|
|
97
|
+
"# The gate then rests on the prompt text, verify_proposal and the audit trail, which a prompt-injected",
|
|
98
|
+
"# agent could ignore. Everything outside the folder keeps asking.",
|
|
99
|
+
"#",
|
|
100
|
+
"# Where to put it: the user-scoped file ~/.kiro/settings/permissions.yaml applies to",
|
|
101
|
+
"# every Kiro session and agent of this OS user, not only mesh-watcher. The workspace-scoped file",
|
|
102
|
+
"# ~/.kiro/workspace-roots/<hash>/permissions.yaml limits the rule to this workspace and is preferred",
|
|
103
|
+
"# (the hash must be looked up on your machine).",
|
|
104
|
+
"# A relative deny glob in the user-scoped file may apply in every workspace of this user, so put the",
|
|
105
|
+
"# deny lines in the workspace-scoped file.",
|
|
106
|
+
"#",
|
|
107
|
+
"# Checked against the saved https://kiro.dev/docs/permissions/ page (2026-11-23): rule fields are",
|
|
108
|
+
"# capability, match, effect and exclude. fs_write globs: * stays inside one path component, ** crosses",
|
|
109
|
+
"# separators, a pattern without a wildcard also matches its children. Shell match: only * is a wildcard;",
|
|
110
|
+
"# compound commands (; && || |) are split and each part is checked; cmd.exe commands always ask.",
|
|
111
|
+
"# Verify before pasting; this file is not read by the hub or the agent.",
|
|
112
|
+
"# Globs are workspace-relative; whether the ~/ and relative forms match is a check live in the IDE.",
|
|
113
|
+
f"# Workspace root used: {_quoted(workspace_root) if workspace_root else '(unknown)'}",
|
|
114
|
+
f"# Service: {_quoted(getattr(service, 'id', ''), 80)}",
|
|
115
|
+
"rules:",
|
|
116
|
+
]
|
|
117
|
+
if allow is not None:
|
|
118
|
+
lines += [" - capability: fs_write", " effect: allow", f" match: [{json.dumps(allow, ensure_ascii=False)}]"]
|
|
119
|
+
else:
|
|
120
|
+
lines += [" # Code folder is outside the open workspace (or equals it, or has a glob character in its path).",
|
|
121
|
+
" # The fix still runs, Kiro prompts for each write. No allow line is emitted."]
|
|
122
|
+
lines += [" - capability: fs_write", " effect: deny",
|
|
123
|
+
" match: [" + ", ".join(json.dumps(p) for p in PROTECTED_PATTERNS) + "]",
|
|
124
|
+
" # Optional: exactly one test command. It runs code the agent has just written, with your rights.",
|
|
125
|
+
" # Remove the leading # to enable it. No wildcard, no shell metacharacters.",
|
|
126
|
+
"# - capability: shell",
|
|
127
|
+
f"# match: [{json.dumps(command)}]",
|
|
128
|
+
"# effect: allow",
|
|
129
|
+
" # Optional, only if you installed the mesh-verify-write hook: the one state file it reads.",
|
|
130
|
+
"# - capability: fs_write",
|
|
131
|
+
f"# match: [{json.dumps(STATE_FILE)}]",
|
|
132
|
+
"# effect: allow",
|
|
133
|
+
"# Everything else keeps asking: other folders, other files, every other shell command.",
|
|
134
|
+
""]
|
|
135
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Verify: may the agent edit these files for this proposal right now? (R3.1, R3.2). Pure and total.
|
|
2
|
+
|
|
3
|
+
The six checks are the sub-criteria 3.1a to 3.1f of the design (review L8). ``ok`` is true exactly when none
|
|
4
|
+
of 3.1a to 3.1e and 3.1f fails (3.1e compares nothing with a declared list, but since task 4.4 it refuses a
|
|
5
|
+
protected name such as ``.env`` for a user approval without declared files); the note of 3.1f does not make
|
|
6
|
+
``ok`` false. The
|
|
7
|
+
function reads the proposal column ``approved_by_rule`` and never the ``decided_by`` text, so an IRC nick
|
|
8
|
+
such as ``rule:r1`` cannot pass as a rule approval. Reasons are fixed texts: they never contain a file name,
|
|
9
|
+
an action, a signature or any other log-derived text.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
import ntpath
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
from chimericmesh.approvals.scope import PROTECTED_PATTERNS, check_file, glob_to_regex
|
|
21
|
+
from chimericmesh.services.paths import path_in_code_folder
|
|
22
|
+
|
|
23
|
+
from .limits import RULE_APPROVAL_WINDOW, clean_text
|
|
24
|
+
|
|
25
|
+
MAX_FILES = 20
|
|
26
|
+
MAX_PATH = 300
|
|
27
|
+
_CONTROL = re.compile("[\\x00-\\x1f\\x7f-\\x9f\\ud800-\\udfff]")
|
|
28
|
+
_PROTECTED = tuple(glob_to_regex(p) for p in PROTECTED_PATTERNS)
|
|
29
|
+
_STATUS_WORDS = ("pending", "approved", "denied", "done")
|
|
30
|
+
NO_FOLDER_NOTE = "no code folder, path scope not checked"
|
|
31
|
+
FAILSAFE = "the proposal could not be verified"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class VerifyInputs:
|
|
36
|
+
proposal_id: str
|
|
37
|
+
status: str
|
|
38
|
+
approved_by_rule: str | None
|
|
39
|
+
declared_files: tuple[str, ...] | None
|
|
40
|
+
approval: Mapping[str, object] | None # from ``approvals.approval_of``
|
|
41
|
+
rule_status: str | None # None when the rule is unknown
|
|
42
|
+
rule_code_folder: str | None
|
|
43
|
+
rule_expires_at: float | None
|
|
44
|
+
paused: bool
|
|
45
|
+
approvals_available: bool
|
|
46
|
+
code_folder: str | None # the live folder of the incident's service
|
|
47
|
+
has_service: bool
|
|
48
|
+
now: float
|
|
49
|
+
protected_dirs: tuple[str, ...]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True)
|
|
53
|
+
class VerifyResult:
|
|
54
|
+
ok: bool
|
|
55
|
+
reasons: tuple[str, ...]
|
|
56
|
+
status: str
|
|
57
|
+
approval: Mapping[str, object] | None
|
|
58
|
+
declared_files: tuple[str, ...]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _is_abs(path: str) -> bool:
|
|
62
|
+
return os.path.isabs(path) or ntpath.isabs(path)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _number(value: object) -> bool:
|
|
66
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _valid_text(value: object) -> bool:
|
|
70
|
+
return isinstance(value, str) and 0 < len(value) <= MAX_PATH and not _CONTROL.search(value)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def normalize_file(code_folder: str | None, raw: str, *,
|
|
74
|
+
normcase: Callable[[str], str] = os.path.normcase) -> str | None:
|
|
75
|
+
"""A comparison key: absolute, ``normpath`` and ``normcase``. A relative entry is joined to the code
|
|
76
|
+
folder (the auto-approval convention for *declared* files). ``None`` for an empty or invalid string, and
|
|
77
|
+
for a relative entry when there is no code folder."""
|
|
78
|
+
if not _valid_text(raw):
|
|
79
|
+
return None
|
|
80
|
+
if _is_abs(raw):
|
|
81
|
+
return normcase(os.path.normpath(raw))
|
|
82
|
+
if isinstance(code_folder, str) and code_folder:
|
|
83
|
+
return normcase(os.path.normpath(os.path.join(code_folder, raw)))
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def samefolder(a: str | None, b: str | None, *, normcase: Callable[[str], str] = os.path.normcase) -> bool:
|
|
88
|
+
"""Same folder after ``normpath`` (which drops a trailing separator) and ``normcase``."""
|
|
89
|
+
if not isinstance(a, str) or not isinstance(b, str) or not a or not b:
|
|
90
|
+
return False
|
|
91
|
+
return normcase(os.path.normpath(a)) == normcase(os.path.normpath(b))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _status_reason(status: object) -> str | None:
|
|
95
|
+
if status == "approved":
|
|
96
|
+
return None
|
|
97
|
+
word = status if status in _STATUS_WORDS else "unknown"
|
|
98
|
+
return f"proposal status is {word}, not approved"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _rule_reason(inp: VerifyInputs, normcase: Callable[[str], str]) -> str | None:
|
|
102
|
+
"""3.1b: None when a user approval or a rule approval that is still valid, else the first failing part."""
|
|
103
|
+
if inp.approved_by_rule is None:
|
|
104
|
+
return None
|
|
105
|
+
rid = clean_text(inp.approved_by_rule, 40)
|
|
106
|
+
if not inp.approvals_available or not isinstance(inp.rule_status, str):
|
|
107
|
+
return f"rule {rid} is unknown"
|
|
108
|
+
if inp.rule_status != "active":
|
|
109
|
+
return f"rule {rid} is {clean_text(inp.rule_status, 20)}"
|
|
110
|
+
if inp.paused:
|
|
111
|
+
return "auto-approval is paused"
|
|
112
|
+
if not _number(inp.now) or not _number(inp.rule_expires_at) or not inp.now < inp.rule_expires_at:
|
|
113
|
+
return f"rule {rid} has expired"
|
|
114
|
+
if not samefolder(inp.rule_code_folder, inp.code_folder, normcase=normcase):
|
|
115
|
+
return f"rule {rid} was bound to another code folder"
|
|
116
|
+
approved_at = inp.approval.get("approved_at") if isinstance(inp.approval, Mapping) else None
|
|
117
|
+
if not _number(approved_at):
|
|
118
|
+
return "rule approval time is unknown"
|
|
119
|
+
if not inp.now - approved_at <= RULE_APPROVAL_WINDOW:
|
|
120
|
+
return "rule approval is older than 30 minutes"
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _protected_name(folder: str, path: str, realpath: Callable[[str], str],
|
|
125
|
+
normcase: Callable[[str], str]) -> bool:
|
|
126
|
+
"""True when ``path`` (as written, or after resolving links) lies in ``folder`` under a protected pattern.
|
|
127
|
+
Only the ``PROTECTED_PATTERNS`` part of ``check_file`` runs here: never the extension rule (open item O13)."""
|
|
128
|
+
pairs = ((normcase(path), normcase(folder)), (normcase(realpath(path)), normcase(realpath(folder))))
|
|
129
|
+
for target, base in pairs:
|
|
130
|
+
try:
|
|
131
|
+
rel = os.path.relpath(target, base).replace(os.sep, "/")
|
|
132
|
+
except ValueError: # another drive: not inside the folder, 3.1f reports it
|
|
133
|
+
continue
|
|
134
|
+
if rel != ".." and not rel.startswith("../") and any(rx.match(rel) for rx in _PROTECTED):
|
|
135
|
+
return True
|
|
136
|
+
return False
|
|
137
|
+
|
|
138
|
+
def _files_reason(files: object) -> tuple[str | None, list[tuple[int, str]]]:
|
|
139
|
+
"""3.1c: the reason (or None) and the valid entries (1-based index, path) of the first 20."""
|
|
140
|
+
if not isinstance(files, (list, tuple)) or not 1 <= len(files) <= MAX_FILES:
|
|
141
|
+
reason = "files must list 1 to 20 paths"
|
|
142
|
+
entries = list(files)[:MAX_FILES] if isinstance(files, (list, tuple)) else []
|
|
143
|
+
else:
|
|
144
|
+
reason, entries = None, list(files)
|
|
145
|
+
valid: list[tuple[int, str]] = []
|
|
146
|
+
for n, entry in enumerate(entries, start=1):
|
|
147
|
+
if not _valid_text(entry):
|
|
148
|
+
reason = reason or f"file {n} is not a valid path"
|
|
149
|
+
elif not _is_abs(entry):
|
|
150
|
+
reason = reason or f"file {n} must be an absolute path"
|
|
151
|
+
else:
|
|
152
|
+
valid.append((n, entry))
|
|
153
|
+
return reason, valid
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def evaluate_verify(inp: VerifyInputs, files: Sequence[str], *,
|
|
157
|
+
realpath: Callable[[str], str] = os.path.realpath,
|
|
158
|
+
normcase: Callable[[str], str] = os.path.normcase) -> VerifyResult:
|
|
159
|
+
"""Run 3.1a to 3.1f. One reason per failed check, in that order. Never raises."""
|
|
160
|
+
try:
|
|
161
|
+
return _evaluate(inp, files, realpath, normcase)
|
|
162
|
+
except Exception: # noqa: BLE001 - total by contract: any surprise is a refusal
|
|
163
|
+
return VerifyResult(False, (FAILSAFE,), "unknown", None, ())
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _evaluate(inp: VerifyInputs, files: object, realpath: Callable[[str], str],
|
|
167
|
+
normcase: Callable[[str], str]) -> VerifyResult:
|
|
168
|
+
reasons: list[str] = []
|
|
169
|
+
folder = inp.code_folder if isinstance(inp.code_folder, str) and inp.code_folder else None
|
|
170
|
+
declared = inp.declared_files
|
|
171
|
+
if declared is None and inp.approved_by_rule is not None:
|
|
172
|
+
declared = () # a rule approval always carries a declared list
|
|
173
|
+
declared_view = tuple(d for d in declared if isinstance(d, str)) if isinstance(declared, (list, tuple)) else ()
|
|
174
|
+
|
|
175
|
+
for reason in (_status_reason(inp.status), _rule_reason(inp, normcase)): # 3.1a, 3.1b
|
|
176
|
+
if reason is not None:
|
|
177
|
+
reasons.append(reason)
|
|
178
|
+
files_reason, valid = _files_reason(files) # 3.1c
|
|
179
|
+
if files_reason is not None:
|
|
180
|
+
reasons.append(files_reason)
|
|
181
|
+
|
|
182
|
+
if declared is not None: # 3.1d (3.1e: none)
|
|
183
|
+
keys = {k for k in (normalize_file(folder, d, normcase=normcase) for d in declared_view) if k is not None}
|
|
184
|
+
protected = tuple(p for p in (inp.protected_dirs or ()) if isinstance(p, str))
|
|
185
|
+
for n, path in valid:
|
|
186
|
+
key = normalize_file(folder, path, normcase=normcase)
|
|
187
|
+
if key is None or key not in keys:
|
|
188
|
+
reasons.append(f"file {n} was not declared in the proposal")
|
|
189
|
+
break
|
|
190
|
+
if folder is not None and check_file(folder, path, protected_dirs=protected, realpath=realpath,
|
|
191
|
+
normcase=normcase) is not None:
|
|
192
|
+
reasons.append(f"file {n} is outside the allowed scope")
|
|
193
|
+
break
|
|
194
|
+
|
|
195
|
+
elif folder is not None: # 3.1e (O13)
|
|
196
|
+
for n, path in valid:
|
|
197
|
+
if _protected_name(folder, path, realpath, normcase):
|
|
198
|
+
reasons.append(f"file {n} is a protected file")
|
|
199
|
+
break
|
|
200
|
+
|
|
201
|
+
note: str | None = None
|
|
202
|
+
if folder is None: # 3.1f
|
|
203
|
+
note = NO_FOLDER_NOTE
|
|
204
|
+
else:
|
|
205
|
+
for n, path in valid:
|
|
206
|
+
if not path_in_code_folder(folder, path, realpath=realpath, normcase=normcase):
|
|
207
|
+
reasons.append(f"file {n} is outside the code folder")
|
|
208
|
+
break
|
|
209
|
+
|
|
210
|
+
status = inp.status if inp.status in _STATUS_WORDS else "unknown"
|
|
211
|
+
approval = dict(inp.approval) if isinstance(inp.approval, Mapping) else None
|
|
212
|
+
ok = not reasons
|
|
213
|
+
if note is not None:
|
|
214
|
+
reasons.append(note)
|
|
215
|
+
return VerifyResult(ok, tuple(reasons), status, approval, declared_view)
|