arkaos 2.40.0 → 2.41.0

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.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 2.40.0
1
+ 2.41.0
package/arka/SKILL.md CHANGED
@@ -185,8 +185,9 @@ violation (squad-routing, arka-supremacy, spec-driven, mandatory-qa).
185
185
 
186
186
  | Command | Description |
187
187
  |---------|-------------|
188
- | `/arka status` | System status (version, departments, agents, active projects). Includes **LLM costs (24h)** section: top-line cost + cache hit rate + call count from `core.runtime.llm_cost_telemetry.summarise(period="today")`. |
188
+ | `/arka status` | System status (version, departments, agents, active projects). Includes **LLM costs (24h)** section: top-line cost + cache hit rate + call count from `core.runtime.llm_cost_telemetry.summarise(period="today")`. Also includes **Enforcement (24h)** section: total calls, block rate, top blocked tools/reasons from `core.governance.enforcement_telemetry.summarise(period="today")` (PR19 v2.41.0). |
189
189
  | `/arka costs [period]` | LLM cost visibility — aggregates telemetry by day/week/month/all, with top expensive sessions. See `arka/skills/costs/SKILL.md`. Shells out to `python -m core.runtime.llm_cost_telemetry_cli <period>`. |
190
+ | `/arka enforcement [period]` | Enforcement compliance — aggregates flow-marker enforcement telemetry by day/week/month/all. Shows block rate, top blocked tools, top reasons. Shells out to `python -m core.governance.enforcement_telemetry_cli <period>`. |
190
191
  | `/arka standup` | Daily standup (projects, priorities, blockers, updates) |
191
192
  | `/arka monitor` | System health monitoring |
192
193
  | `/arka onboard <path>` | Onboard an existing project into ArkaOS |
@@ -0,0 +1,144 @@
1
+ """Enforcement telemetry summarizer (PR19 v2.41.0).
2
+
3
+ Reads ``~/.arkaos/telemetry/enforcement.jsonl`` (the JSONL stream the
4
+ PreToolUse hook appends to on every gated tool decision) and produces
5
+ compact summaries for ``/arka status`` and downstream tuning.
6
+
7
+ Mirrors the pattern of ``core.runtime.llm_cost_telemetry`` so periods,
8
+ malformed-line tolerance, and zero-division safety behave the same way
9
+ across the two telemetry surfaces. Read-only — never writes to the
10
+ JSONL itself.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from collections import Counter
17
+ from dataclasses import dataclass, field
18
+ from datetime import datetime, timedelta, timezone
19
+ from pathlib import Path
20
+ from typing import Any, Iterable
21
+
22
+ DEFAULT_PATH: Path = Path.home() / ".arkaos" / "telemetry" / "enforcement.jsonl"
23
+ _VALID_PERIODS: frozenset[str] = frozenset({"today", "week", "month", "all"})
24
+ _TOP_N: int = 5
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class EnforcementSummary:
29
+ """Aggregated enforcement telemetry over a time slice."""
30
+ period: str
31
+ total_calls: int
32
+ blocked_calls: int
33
+ block_rate: float
34
+ bypass_used: int
35
+ top_blocked_tools: list[tuple[str, int]] = field(default_factory=list)
36
+ top_block_reasons: list[tuple[str, int]] = field(default_factory=list)
37
+ corrupt_line_count: int = 0
38
+
39
+
40
+ def summarise(period: str, *, path: Path | None = None) -> EnforcementSummary:
41
+ """Return an EnforcementSummary for the requested period.
42
+
43
+ period: one of "today", "week", "month", "all".
44
+ path: override telemetry source (used by tests; defaults to DEFAULT_PATH).
45
+ """
46
+ if period not in _VALID_PERIODS:
47
+ raise ValueError(f"invalid period: {period!r}")
48
+ src = path or DEFAULT_PATH
49
+ cutoff = _period_cutoff(period)
50
+ entries, corrupt = _read_jsonl(src, cutoff)
51
+ return _build_summary(period, entries, corrupt)
52
+
53
+
54
+ def _period_cutoff(period: str, now: datetime | None = None) -> datetime | None:
55
+ ref = now or datetime.now(timezone.utc)
56
+ if period == "today":
57
+ return ref.replace(hour=0, minute=0, second=0, microsecond=0)
58
+ if period == "week":
59
+ return ref - timedelta(days=7)
60
+ if period == "month":
61
+ return ref - timedelta(days=30)
62
+ return None
63
+
64
+
65
+ def _read_jsonl(src: Path, cutoff: datetime | None) -> tuple[list[dict[str, Any]], int]:
66
+ if not src.exists():
67
+ return [], 0
68
+ entries: list[dict[str, Any]] = []
69
+ corrupt = 0
70
+ # Line-stream the file to keep memory O(1) regardless of telemetry size.
71
+ # A runaway hook could grow this file to multiple GB; reading it whole
72
+ # would OOM the /arka status / /arka enforcement caller.
73
+ try:
74
+ with src.open("r", encoding="utf-8", errors="replace") as fh:
75
+ for line in fh:
76
+ if not line.strip():
77
+ continue
78
+ try:
79
+ entry = json.loads(line)
80
+ except json.JSONDecodeError:
81
+ corrupt += 1
82
+ continue
83
+ if not isinstance(entry, dict):
84
+ corrupt += 1
85
+ continue
86
+ if cutoff is not None and not _within_cutoff(entry, cutoff):
87
+ continue
88
+ entries.append(entry)
89
+ except OSError:
90
+ return entries, corrupt
91
+ return entries, corrupt
92
+
93
+
94
+ def _within_cutoff(entry: dict[str, Any], cutoff: datetime) -> bool:
95
+ ts = _parse_ts(entry.get("ts"))
96
+ if ts is None:
97
+ return False
98
+ return ts >= cutoff
99
+
100
+
101
+ def _parse_ts(raw: Any) -> datetime | None:
102
+ if not isinstance(raw, str) or not raw:
103
+ return None
104
+ try:
105
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
106
+ except ValueError:
107
+ return None
108
+ if parsed.tzinfo is None:
109
+ parsed = parsed.replace(tzinfo=timezone.utc)
110
+ return parsed
111
+
112
+
113
+ def _build_summary(
114
+ period: str,
115
+ entries: Iterable[dict[str, Any]],
116
+ corrupt: int,
117
+ ) -> EnforcementSummary:
118
+ total = 0
119
+ blocked = 0
120
+ bypass = 0
121
+ blocked_tools: Counter[str] = Counter()
122
+ block_reasons: Counter[str] = Counter()
123
+ for entry in entries:
124
+ total += 1
125
+ if entry.get("bypass_used"):
126
+ bypass += 1
127
+ if entry.get("allow") is False:
128
+ blocked += 1
129
+ tool = str(entry.get("tool", ""))
130
+ reason = str(entry.get("reason", ""))
131
+ if tool:
132
+ blocked_tools[tool] += 1
133
+ if reason:
134
+ block_reasons[reason] += 1
135
+ return EnforcementSummary(
136
+ period=period,
137
+ total_calls=total,
138
+ blocked_calls=blocked,
139
+ block_rate=(blocked / total) if total else 0.0,
140
+ bypass_used=bypass,
141
+ top_blocked_tools=blocked_tools.most_common(_TOP_N),
142
+ top_block_reasons=block_reasons.most_common(_TOP_N),
143
+ corrupt_line_count=corrupt,
144
+ )
@@ -0,0 +1,67 @@
1
+ """CLI entry for the enforcement telemetry summarizer (PR19 v2.41.0).
2
+
3
+ Invoked as ``python -m core.governance.enforcement_telemetry_cli <period>``
4
+ where ``<period>`` is one of: today, week, month, all.
5
+
6
+ Output is plain markdown so it renders cleanly in both the terminal and
7
+ the ``/arka status`` skill which concatenates it into its report.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import sys
13
+
14
+ from core.governance.enforcement_telemetry import (
15
+ EnforcementSummary,
16
+ summarise,
17
+ )
18
+
19
+
20
+ def _fmt_rate(value: float) -> str:
21
+ return f"{value * 100:.2f}%"
22
+
23
+
24
+ def _sanitize_md(value: str) -> str:
25
+ """Strip markdown-breaking characters before rendering JSONL strings.
26
+
27
+ Telemetry is local-writer-only, but a malformed tool/reason value (newline,
28
+ backtick) can still distort the markdown if /arka status pipes the output
29
+ to a UI. Belt-and-braces against passive corruption, not active attack.
30
+ """
31
+ return value.replace("\n", " ").replace("\r", " ").replace("`", "").strip()
32
+
33
+
34
+ def _render(summary: EnforcementSummary) -> str:
35
+ lines = [
36
+ f"# Enforcement — {summary.period}",
37
+ "",
38
+ f"- Calls: **{summary.total_calls}**",
39
+ f"- Blocked: **{summary.blocked_calls}** ({_fmt_rate(summary.block_rate)})",
40
+ f"- Bypass used (`ARKA_BYPASS_FLOW=1`): **{summary.bypass_used}**",
41
+ ]
42
+ if summary.top_blocked_tools:
43
+ lines += ["", "## Top blocked tools"]
44
+ for tool, count in summary.top_blocked_tools:
45
+ lines.append(f"- `{_sanitize_md(tool)}` — {count}")
46
+ if summary.top_block_reasons:
47
+ lines += ["", "## Top block reasons"]
48
+ for reason, count in summary.top_block_reasons:
49
+ lines.append(f"- {_sanitize_md(reason)} — {count}")
50
+ if summary.corrupt_line_count:
51
+ lines += ["", f"_(skipped {summary.corrupt_line_count} corrupt line(s))_"]
52
+ return "\n".join(lines)
53
+
54
+
55
+ def main(argv: list[str]) -> int:
56
+ period = argv[1] if len(argv) > 1 else "today"
57
+ try:
58
+ summary = summarise(period)
59
+ except ValueError as exc:
60
+ print(f"error: {exc}", file=sys.stderr)
61
+ return 2
62
+ print(_render(summary))
63
+ return 0
64
+
65
+
66
+ if __name__ == "__main__":
67
+ raise SystemExit(main(sys.argv))
@@ -214,11 +214,10 @@ class Decision:
214
214
  if self.allow:
215
215
  return ""
216
216
  return (
217
- f"[ARKA:ENFORCEMENT] Flow marker missing. "
218
- f"Emit `[arka:routing] <dept> -> <lead>` or `[arka:trivial] <reason>` "
219
- f"before any tool that mutates state "
220
- f"(Write/Edit/MultiEdit/NotebookEdit/Task/Skill, or Bash with effect commands like rm/mv/git commit/npm install). "
221
- f"Reason: {self.reason}"
217
+ f"[ARKA:ENFORCEMENT] Missing `[arka:routing] <dept> -> <lead>` or "
218
+ f"`[arka:trivial] <reason>` before "
219
+ f"Write/Edit/MultiEdit/NotebookEdit/Task/Skill/Bash-effect. "
220
+ f"Bypass once with `ARKA_BYPASS_FLOW=1`. Reason: {self.reason}."
222
221
  )
223
222
 
224
223
 
@@ -0,0 +1,63 @@
1
+ // ~/.arkaos/config.json seed/migration (PR19 v2.41.0).
2
+ //
3
+ // Run on every `npx arkaos install` and `npx arkaos@latest update`.
4
+ // Idempotent: writes `hooks.hardEnforcement = true` only when the key
5
+ // is unset. Explicit user choice (true OR false) is preserved.
6
+ //
7
+ // Returns a status object:
8
+ // { action: "created" | "added-key" | "noop"
9
+ // | "preserved-user-false" | "rewrote-corrupt" }
10
+ // so the installer caller can log a human-readable line per run.
11
+
12
+ import {
13
+ existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, copyFileSync,
14
+ } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join, dirname } from "node:path";
17
+
18
+ export function seedArkaosConfig({ home = homedir() } = {}) {
19
+ const cfgPath = join(home, ".arkaos", "config.json");
20
+
21
+ if (!existsSync(cfgPath)) {
22
+ writeConfig(cfgPath, { hooks: { hardEnforcement: true } });
23
+ return { action: "created", path: cfgPath };
24
+ }
25
+
26
+ let config;
27
+ try {
28
+ config = JSON.parse(readFileSync(cfgPath, "utf-8"));
29
+ if (typeof config !== "object" || config === null) {
30
+ throw new Error("config root is not an object");
31
+ }
32
+ } catch {
33
+ // Corrupt JSON — keep the broken copy for recovery, write safe default.
34
+ const backup = `${cfgPath}.broken-${Date.now()}`;
35
+ try { copyFileSync(cfgPath, backup); } catch { /* best effort */ }
36
+ writeConfig(cfgPath, { hooks: { hardEnforcement: true } });
37
+ return { action: "rewrote-corrupt", path: cfgPath, backup };
38
+ }
39
+
40
+ config.hooks = config.hooks && typeof config.hooks === "object" ? config.hooks : {};
41
+ const current = config.hooks.hardEnforcement;
42
+
43
+ if (current === true) {
44
+ return { action: "noop", path: cfgPath };
45
+ }
46
+ if (current === false) {
47
+ return { action: "preserved-user-false", path: cfgPath };
48
+ }
49
+
50
+ // Key unset (undefined, null, or any non-boolean) — set to true.
51
+ config.hooks.hardEnforcement = true;
52
+ writeConfig(cfgPath, config);
53
+ return { action: "added-key", path: cfgPath };
54
+ }
55
+
56
+ function writeConfig(cfgPath, payload) {
57
+ mkdirSync(dirname(cfgPath), { recursive: true });
58
+ // Atomic write: render to a sibling .tmp then rename. Prevents partial-write
59
+ // corruption if the process is interrupted between open and close.
60
+ const tmp = `${cfgPath}.tmp-${process.pid}`;
61
+ writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n");
62
+ renameSync(tmp, cfgPath);
63
+ }
@@ -275,6 +275,26 @@ export async function install({ runtime, path, force, skipSystem, withOllama })
275
275
 
276
276
  // ═══ Step 14: Finalize ═══
277
277
  step(14, 14, "Finalizing...");
278
+
279
+ // PR19 v2.41.0 — seed/migrate hooks.hardEnforcement so the PreToolUse
280
+ // gate blocks tool calls without [arka:routing] on fresh installs.
281
+ // Idempotent + preserves explicit user `false`.
282
+ try {
283
+ const { seedArkaosConfig } = await import("./config-seed.js");
284
+ const seedResult = seedArkaosConfig({ home: homedir() });
285
+ if (seedResult.action === "created") {
286
+ console.log(` hardEnforcement enabled (default).`);
287
+ } else if (seedResult.action === "added-key") {
288
+ console.log(` hardEnforcement enabled (key was unset).`);
289
+ } else if (seedResult.action === "preserved-user-false") {
290
+ console.log(` hardEnforcement is OFF (user-set, preserved).`);
291
+ } else if (seedResult.action === "rewrote-corrupt") {
292
+ console.log(` config.json was corrupt — rewrote, backup at ${seedResult.backup}`);
293
+ }
294
+ } catch (err) {
295
+ console.log(` Warning: could not seed config.json (${err.message})`);
296
+ }
297
+
278
298
  const manifest = {
279
299
  version: VERSION,
280
300
  runtime,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkaos",
3
- "version": "2.40.0",
3
+ "version": "2.41.0",
4
4
  "description": "The Operating System for AI Agent Teams",
5
5
  "type": "module",
6
6
  "bin": {
package/pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "arkaos-core"
3
- version = "2.40.0"
3
+ version = "2.41.0"
4
4
  description = "Core engine for ArkaOS — The Operating System for AI Agent Teams"
5
5
  readme = "README.md"
6
6
  license = {text = "MIT"}