kontiki-observer 0.2.0__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.
@@ -0,0 +1,6 @@
1
+ """Mesh readings and notes."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ SERVICE_NAME = "kontiki-observer"
6
+ __version__ = version("kontiki-observer")
@@ -0,0 +1,36 @@
1
+ # Observer configuration: journal, cron, AI run material, and deadlines.
2
+ #
3
+ # Example (all fields):
4
+ #
5
+ # app:
6
+ # sqlite_path: /var/lib/kontiki-observer/observer.sqlite
7
+ # cron: "0 7 * * *"
8
+ # ai:
9
+ # profile: ops
10
+ # prompt: /etc/kontiki-observer/prompts/reading.md
11
+ # run_timeout_seconds: 900
12
+ # recover_interval_seconds: 60
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+
15
+
16
+ class AiConfig(BaseModel):
17
+ model_config = ConfigDict(extra="forbid", strict=True)
18
+
19
+ profile: str = Field(min_length=1)
20
+ prompt: str = Field(min_length=1)
21
+
22
+
23
+ class AppConfig(BaseModel):
24
+ model_config = ConfigDict(extra="forbid", strict=True)
25
+
26
+ sqlite_path: str = Field(min_length=1)
27
+ cron: str = Field(min_length=1)
28
+ ai: AiConfig
29
+ run_timeout_seconds: int = Field(gt=0)
30
+ recover_interval_seconds: int = Field(gt=0)
31
+
32
+
33
+ class ServiceConfig(BaseModel):
34
+ model_config = ConfigDict(extra="forbid", strict=True)
35
+
36
+ app: AppConfig
@@ -0,0 +1,3 @@
1
+ from kontiki_observer.journal.delegate import JournalDelegate
2
+
3
+ __all__ = ["JournalDelegate"]
@@ -0,0 +1,244 @@
1
+ import logging
2
+ import uuid
3
+ from datetime import datetime, timedelta, timezone
4
+ from pathlib import Path
5
+
6
+ from kontiki.delegate import ServiceDelegate
7
+
8
+ from kontiki_observer.journal.notes import NoteDraft
9
+ from kontiki_observer.journal.runs import now
10
+ from kontiki_observer.journal.store import Store
11
+ from kontiki_observer.models import Scope, scope_payload
12
+
13
+ WINDOWS = {"1h": 3600, "6h": 6 * 3600, "24h": 86400, "7d": 7 * 86400}
14
+
15
+ RESPONSE_SCHEMA = {
16
+ "type": "object",
17
+ "additionalProperties": False,
18
+ "required": ["synthesis", "observations", "note_edits"],
19
+ "properties": {
20
+ "synthesis": {"type": "string", "minLength": 1},
21
+ "observations": {
22
+ "type": "array",
23
+ "items": {
24
+ "type": "object",
25
+ "additionalProperties": False,
26
+ "required": ["kind", "service", "text"],
27
+ "properties": {
28
+ "kind": {"type": "string", "minLength": 1},
29
+ "service": {"type": "string", "minLength": 1},
30
+ "text": {"type": "string", "minLength": 1},
31
+ "severity": {"type": ["string", "null"]},
32
+ "flow_id": {"type": ["string", "null"]},
33
+ "exception_id": {"type": ["string", "null"]},
34
+ "context_id": {"type": ["string", "null"]},
35
+ },
36
+ },
37
+ },
38
+ "note_edits": {
39
+ "type": "array",
40
+ "items": {
41
+ "type": "object",
42
+ "additionalProperties": False,
43
+ "required": ["op", "scope"],
44
+ "properties": {
45
+ "op": {"enum": ["add", "confirm", "revise", "reopen", "retire"]},
46
+ "scope": {
47
+ "type": "object",
48
+ "additionalProperties": False,
49
+ "required": ["kind"],
50
+ "properties": {
51
+ "kind": {"enum": ["system", "group", "service"]},
52
+ "name": {"type": "string", "minLength": 1},
53
+ },
54
+ },
55
+ "id": {"type": "string", "minLength": 1},
56
+ "text": {"type": "string", "minLength": 1},
57
+ "question": {"type": "string", "minLength": 1},
58
+ "reason": {"type": "string", "minLength": 1},
59
+ },
60
+ },
61
+ },
62
+ },
63
+ }
64
+
65
+
66
+ class JournalDelegate(ServiceDelegate):
67
+ def __init__(self, messenger):
68
+ super().__init__()
69
+ self._messenger = messenger
70
+
71
+ async def setup(self):
72
+ self._app = self.container.settings.app
73
+ self._store = Store(self._app.sqlite_path)
74
+ logging.info("kontiki-observer ready")
75
+
76
+ async def stop(self):
77
+ self._store.close()
78
+
79
+ async def open_run(self, origin, scope=None, window=None, question=None):
80
+ if origin == "auto":
81
+ if self._store.runs.auto_pending():
82
+ logging.warning("auto run already pending")
83
+ return
84
+ scope = Scope(kind="system")
85
+ window = None
86
+ since = self._store.runs.latest_auto_until()
87
+ until = now()
88
+ else:
89
+ until_at = datetime.now(timezone.utc)
90
+ since_at = until_at - timedelta(seconds=WINDOWS[window])
91
+ since = since_at.isoformat()
92
+ until = until_at.isoformat()
93
+ instructions = _prompt(self._app.ai.prompt)
94
+ payload = _input(
95
+ self._store.notes, origin, scope, window, since, until, question
96
+ )
97
+ session = await self._messenger.open_session(peer="ai")
98
+ run_id = str(uuid.uuid4())
99
+ created_at = now()
100
+ self._store.runs.create(run_id, origin, scope, window, since, until, created_at)
101
+ await session.publish(
102
+ "ai.run.requested",
103
+ {
104
+ "ref": run_id,
105
+ "profile": self._app.ai.profile,
106
+ "instructions": instructions,
107
+ "input": payload,
108
+ "response_schema": RESPONSE_SCHEMA,
109
+ },
110
+ )
111
+ logging.info("run started id=%s origin=%s", run_id, origin)
112
+ return {"id": run_id}
113
+
114
+ async def complete(self, payload):
115
+ def _normalize_observations(result):
116
+ def _text(value):
117
+ return isinstance(value, str) and value != ""
118
+
119
+ raw = result["observations"] if "observations" in result else None
120
+ if not isinstance(raw, list):
121
+ return None, "Observation is incomplete."
122
+ observations = []
123
+ for item in raw:
124
+ if not isinstance(item, dict):
125
+ return None, "Observation is incomplete."
126
+ kind = item["kind"] if "kind" in item else None
127
+ service = item["service"] if "service" in item else None
128
+ text = item["text"] if "text" in item else None
129
+ if not _text(kind) or not _text(service) or not _text(text):
130
+ return None, "Observation is incomplete."
131
+ severity = item["severity"] if "severity" in item else None
132
+ if severity is not None and kind != "anomaly":
133
+ return None, "Severity belongs only to anomaly."
134
+ observations.append(
135
+ {
136
+ "kind": kind,
137
+ "service": service,
138
+ "text": text,
139
+ "severity": severity,
140
+ "flow_id": item["flow_id"] if "flow_id" in item else None,
141
+ "exception_id": (
142
+ item["exception_id"] if "exception_id" in item else None
143
+ ),
144
+ "context_id": (
145
+ item["context_id"] if "context_id" in item else None
146
+ ),
147
+ }
148
+ )
149
+ return observations, None
150
+
151
+ ref = payload["ref"]
152
+ run = self._store.runs.pending(ref)
153
+ if run is None:
154
+ logging.warning("run terminal ignored ref=%s", ref)
155
+ return
156
+ result = payload["result"]
157
+ if not isinstance(result, dict) or "synthesis" not in result:
158
+ self._store.runs.fail(ref, "UNUSABLE_RESULT", "Synthesis is empty.")
159
+ logging.warning("run unusable id=%s", ref)
160
+ return
161
+ synthesis = result["synthesis"]
162
+ if not isinstance(synthesis, str) or synthesis == "":
163
+ self._store.runs.fail(ref, "UNUSABLE_RESULT", "Synthesis is empty.")
164
+ logging.warning("run unusable id=%s", ref)
165
+ return
166
+ observations, message = _normalize_observations(result)
167
+ if message:
168
+ self._store.runs.fail(ref, "UNUSABLE_RESULT", message)
169
+ logging.warning("run unusable id=%s", ref)
170
+ return
171
+ note_edits = []
172
+ next_notes = None
173
+ if run["origin"] == "auto":
174
+ raw = result["note_edits"] if "note_edits" in result else None
175
+ draft = NoteDraft(self._store.notes.load())
176
+ message = draft.apply_edits(raw)
177
+ if message:
178
+ self._store.runs.fail(ref, "UNUSABLE_RESULT", message)
179
+ logging.warning("run unusable id=%s", ref)
180
+ return
181
+ note_edits = draft.edits()
182
+ next_notes = draft.rows()
183
+ if not self._store.runs.ready(ref, synthesis, observations, note_edits):
184
+ return
185
+ if next_notes is not None:
186
+ self._store.notes.replace(next_notes)
187
+ logging.info("run ready id=%s origin=%s", ref, run["origin"])
188
+
189
+ async def fail(self, payload):
190
+ ref = payload["ref"]
191
+ if not self._store.runs.fail(ref, payload["code"], payload["message"]):
192
+ logging.warning("run terminal ignored ref=%s", ref)
193
+ return
194
+ logging.info("run failed id=%s code=%s", ref, payload["code"])
195
+
196
+ async def expire(self):
197
+ count = self._store.runs.expire(self._app.run_timeout_seconds)
198
+ if count:
199
+ logging.info("expired runs count=%s", count)
200
+
201
+ def get_notes(self, scope):
202
+ return self._store.notes.get(scope.kind, scope.name)
203
+
204
+ def list_reports(self):
205
+ return self._store.runs.list_reports()
206
+
207
+ def get_report(self, run_id):
208
+ return self._store.runs.get_report(run_id)
209
+
210
+
211
+ # -----
212
+ # Internal
213
+ # -----
214
+
215
+
216
+ def _prompt(path):
217
+ text = Path(path).read_text()
218
+ if text.endswith("\n"):
219
+ text = text[:-1]
220
+ return text
221
+
222
+
223
+ def _input(notes, origin, scope, window, since, until, question):
224
+ if origin == "auto":
225
+ return {
226
+ "origin": origin,
227
+ "scope": scope_payload(scope.kind, scope.name),
228
+ "since": since,
229
+ "until": until,
230
+ "notes": notes.by_scope(),
231
+ }
232
+ view = notes.get(scope.kind, scope.name)
233
+ return {
234
+ "origin": origin,
235
+ "scope": scope_payload(scope.kind, scope.name),
236
+ "window": window,
237
+ "since": since,
238
+ "until": until,
239
+ "notes": {
240
+ "established": view["established"],
241
+ "hypotheses": view["hypotheses"],
242
+ },
243
+ "question": question,
244
+ }
@@ -0,0 +1,325 @@
1
+ # Mesh notes memory: one SQLite table, two roles (opened via journal.Store).
2
+ #
3
+ # table notes flat rows (id, scope, status, text, question, position)
4
+ # │
5
+ # ├─ Notes persistence + read API
6
+ # │ load / replace
7
+ # │ get(kind, name) → {scope, established[], hypotheses[]}
8
+ # │ by_scope() → non-empty get() list (auto input)
9
+ # │
10
+ # └─ NoteDraft in-memory copy for one auto complete
11
+ # from Notes.load()
12
+ # apply_edits(note_edits) → error or None
13
+ # edits() → normalized ops for the run row
14
+ # rows() → next table for Notes.replace
15
+ #
16
+ # Read path: Notes.get / Notes.by_scope (RPC get_notes, AI input)
17
+ # Write path: NoteDraft.apply_edits → Runs.ready → Notes.replace
18
+ #
19
+ import uuid
20
+
21
+ from kontiki_observer.models import scope_payload
22
+
23
+ _UNKNOWN_ENTRY = "Note edit targets an unknown entry."
24
+ _INCOMPLETE_EDIT = "Note edit is incomplete."
25
+
26
+
27
+ class Notes:
28
+ def __init__(self, conn):
29
+ self._conn = conn
30
+ self._conn.execute(
31
+ """
32
+ CREATE TABLE IF NOT EXISTS notes (
33
+ id TEXT PRIMARY KEY,
34
+ scope_kind TEXT NOT NULL,
35
+ scope_name TEXT,
36
+ status TEXT NOT NULL,
37
+ text TEXT NOT NULL,
38
+ question TEXT,
39
+ position INTEGER NOT NULL
40
+ )
41
+ """
42
+ )
43
+ self._conn.commit()
44
+
45
+ def load(self):
46
+ rows = self._conn.execute(
47
+ "SELECT * FROM notes ORDER BY position, rowid"
48
+ ).fetchall()
49
+ return [dict(row) for row in rows]
50
+
51
+ def replace(self, entries):
52
+ with self._conn:
53
+ self._conn.execute("DELETE FROM notes")
54
+ for entry in entries:
55
+ self._conn.execute(
56
+ """
57
+ INSERT INTO notes (
58
+ id, scope_kind, scope_name, status, text, question, position
59
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
60
+ """,
61
+ (
62
+ entry["id"],
63
+ entry["scope_kind"],
64
+ entry["scope_name"],
65
+ entry["status"],
66
+ entry["text"],
67
+ entry["question"],
68
+ entry["position"],
69
+ ),
70
+ )
71
+
72
+ def get(self, kind, name):
73
+ """Established and hypotheses for one scope, with scope payload."""
74
+ content = self._split_by_status(kind, name, self.load())
75
+ return {
76
+ "scope": scope_payload(kind, name),
77
+ "established": content["established"],
78
+ "hypotheses": content["hypotheses"],
79
+ }
80
+
81
+ def by_scope(self):
82
+ """Non-empty get() results, one per scope that has notes."""
83
+ entries = self.load()
84
+ scopes = []
85
+ seen = set()
86
+ for entry in entries:
87
+ key = (entry["scope_kind"], entry["scope_name"])
88
+ if key in seen:
89
+ continue
90
+ seen.add(key)
91
+ scopes.append(key)
92
+ result = []
93
+ for kind, name in scopes:
94
+ content = self._split_by_status(kind, name, entries)
95
+ if content["established"] or content["hypotheses"]:
96
+ result.append(
97
+ {
98
+ "scope": scope_payload(kind, name),
99
+ "established": content["established"],
100
+ "hypotheses": content["hypotheses"],
101
+ }
102
+ )
103
+ return result
104
+
105
+ def _split_by_status(self, kind, name, entries):
106
+ """Rows for one scope → established / hypotheses lists."""
107
+ established = []
108
+ hypotheses = []
109
+ for entry in entries:
110
+ if not self._same_scope(entry, kind, name):
111
+ continue
112
+ if entry["status"] == "established":
113
+ established.append({"id": entry["id"], "text": entry["text"]})
114
+ else:
115
+ hypotheses.append(
116
+ {
117
+ "id": entry["id"],
118
+ "text": entry["text"],
119
+ "question": entry["question"],
120
+ }
121
+ )
122
+ return {"established": established, "hypotheses": hypotheses}
123
+
124
+ def _same_scope(self, entry, kind, name):
125
+ return entry["scope_kind"] == kind and entry["scope_name"] == name
126
+
127
+
128
+ class NoteDraft:
129
+ """In-memory copy of the notes table for one auto completion."""
130
+
131
+ def __init__(self, entries):
132
+ self._original = {entry["id"]: entry for entry in entries}
133
+ self._working = {entry["id"]: dict(entry) for entry in entries}
134
+ self._order = [entry["id"] for entry in entries]
135
+ self._edits = []
136
+ self._next_position = 0
137
+ for entry in entries:
138
+ if entry["position"] > self._next_position:
139
+ self._next_position = entry["position"]
140
+
141
+ def apply_edits(self, edits):
142
+ """Apply the AI edit list. Returns an error message, or None."""
143
+ if not isinstance(edits, list):
144
+ return _INCOMPLETE_EDIT
145
+ for edit in edits:
146
+ message = self._apply_edit(edit)
147
+ if message:
148
+ return message
149
+ return None
150
+
151
+ def edits(self):
152
+ """Normalized note_edits for the run row."""
153
+ return self._edits
154
+
155
+ def rows(self):
156
+ """Next table state for Notes.replace."""
157
+ return [
158
+ self._working[entry_id]
159
+ for entry_id in self._order
160
+ if entry_id in self._working
161
+ ]
162
+
163
+ # -----
164
+ # Internal
165
+ # -----
166
+
167
+ def _apply_edit(self, edit):
168
+ if not isinstance(edit, dict) or "op" not in edit:
169
+ return _INCOMPLETE_EDIT
170
+ op = edit["op"]
171
+ scope = self._parse_scope(edit)
172
+ if scope is None:
173
+ return _INCOMPLETE_EDIT
174
+ kind, name = scope
175
+ if op == "add":
176
+ return self._add(edit, kind, name)
177
+ entry_id = edit["id"] if "id" in edit else None
178
+ if not self._nonempty(entry_id):
179
+ return _UNKNOWN_ENTRY
180
+ if op == "confirm":
181
+ return self._confirm(entry_id, kind, name)
182
+ if op == "revise":
183
+ return self._revise(edit, entry_id, kind, name)
184
+ if op == "reopen":
185
+ return self._reopen(edit, entry_id, kind, name)
186
+ if op == "retire":
187
+ return self._retire(edit, entry_id, kind, name)
188
+ return _INCOMPLETE_EDIT
189
+
190
+ def _parse_scope(self, edit):
191
+ if "scope" not in edit or not isinstance(edit["scope"], dict):
192
+ return None
193
+ scope = edit["scope"]
194
+ if "kind" not in scope:
195
+ return None
196
+ kind = scope["kind"]
197
+ name = scope["name"] if "name" in scope else None
198
+ if kind == "system":
199
+ if name is not None:
200
+ return None
201
+ return kind, None
202
+ if kind in ("group", "service") and self._nonempty(name):
203
+ return kind, name
204
+ return None
205
+
206
+ def _existing(self, entry_id, kind, name, status):
207
+ if entry_id not in self._original:
208
+ return None
209
+ entry = self._original[entry_id]
210
+ if entry["status"] != status or not self._same_scope(entry, kind, name):
211
+ return None
212
+ return entry
213
+
214
+ def _same_scope(self, entry, kind, name):
215
+ return entry["scope_kind"] == kind and entry["scope_name"] == name
216
+
217
+ def _nonempty(self, value):
218
+ return isinstance(value, str) and value != ""
219
+
220
+ def _add(self, edit, kind, name):
221
+ text = edit["text"] if "text" in edit else None
222
+ question = edit["question"] if "question" in edit else None
223
+ if not self._nonempty(text) or not self._nonempty(question):
224
+ return _INCOMPLETE_EDIT
225
+ entry_id = str(uuid.uuid4())
226
+ self._next_position += 1
227
+ self._working[entry_id] = {
228
+ "id": entry_id,
229
+ "scope_kind": kind,
230
+ "scope_name": name,
231
+ "status": "hypothesis",
232
+ "text": text,
233
+ "question": question,
234
+ "position": self._next_position,
235
+ }
236
+ self._order.append(entry_id)
237
+ self._edits.append(
238
+ {
239
+ "op": "add",
240
+ "scope": scope_payload(kind, name),
241
+ "id": entry_id,
242
+ "text": text,
243
+ "question": question,
244
+ }
245
+ )
246
+ return None
247
+
248
+ def _confirm(self, entry_id, kind, name):
249
+ entry = self._existing(entry_id, kind, name, "hypothesis")
250
+ if entry is None or entry_id not in self._working:
251
+ return _UNKNOWN_ENTRY
252
+ self._working[entry_id]["status"] = "established"
253
+ self._edits.append(
254
+ {"op": "confirm", "scope": scope_payload(kind, name), "id": entry_id}
255
+ )
256
+ return None
257
+
258
+ def _revise(self, edit, entry_id, kind, name):
259
+ if entry_id not in self._working or not self._same_scope(
260
+ self._working[entry_id], kind, name
261
+ ):
262
+ return _UNKNOWN_ENTRY
263
+ text = self._working[entry_id]["text"]
264
+ question = self._working[entry_id]["question"]
265
+ published = {
266
+ "op": "revise",
267
+ "scope": scope_payload(kind, name),
268
+ "id": entry_id,
269
+ }
270
+ if "text" in edit:
271
+ if not self._nonempty(edit["text"]):
272
+ return _INCOMPLETE_EDIT
273
+ text = edit["text"]
274
+ published["text"] = text
275
+ if "question" in edit:
276
+ if not self._nonempty(edit["question"]):
277
+ return _INCOMPLETE_EDIT
278
+ question = edit["question"]
279
+ published["question"] = question
280
+ self._working[entry_id]["text"] = text
281
+ self._working[entry_id]["question"] = question
282
+ self._edits.append(published)
283
+ return None
284
+
285
+ def _reopen(self, edit, entry_id, kind, name):
286
+ entry = self._existing(entry_id, kind, name, "established")
287
+ question = edit["question"] if "question" in edit else None
288
+ if (
289
+ entry is None
290
+ or entry_id not in self._working
291
+ or not self._nonempty(question)
292
+ ):
293
+ if not self._nonempty(question) and entry is not None:
294
+ return _INCOMPLETE_EDIT
295
+ return _UNKNOWN_ENTRY
296
+ self._working[entry_id]["status"] = "hypothesis"
297
+ self._working[entry_id]["question"] = question
298
+ self._edits.append(
299
+ {
300
+ "op": "reopen",
301
+ "scope": scope_payload(kind, name),
302
+ "id": entry_id,
303
+ "question": question,
304
+ }
305
+ )
306
+ return None
307
+
308
+ def _retire(self, edit, entry_id, kind, name):
309
+ if entry_id not in self._working or not self._same_scope(
310
+ self._working[entry_id], kind, name
311
+ ):
312
+ return _UNKNOWN_ENTRY
313
+ reason = edit["reason"] if "reason" in edit else None
314
+ if not self._nonempty(reason):
315
+ return _INCOMPLETE_EDIT
316
+ del self._working[entry_id]
317
+ self._edits.append(
318
+ {
319
+ "op": "retire",
320
+ "scope": scope_payload(kind, name),
321
+ "id": entry_id,
322
+ "reason": reason,
323
+ }
324
+ )
325
+ return None