loki-mode 7.2.0 → 7.4.8

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/README.md CHANGED
@@ -49,6 +49,45 @@ Or skip scaffolding and go straight to a quick task:
49
49
  loki quick "build a landing page with a signup form"
50
50
  ```
51
51
 
52
+ ---
53
+
54
+ ## Runtime Architecture
55
+
56
+ Loki Mode is in the middle of a phased migration from a Bash-based runtime to a TypeScript/Bun runtime. The work is happening on the `feat/bun-migration` branch and is being shipped incrementally.
57
+
58
+ **What ships today:**
59
+
60
+ - A small set of read-only commands is routed to the Bun runtime when `bun` is on `PATH`. The router lives in `bin/loki` and currently routes: `version`, `--version`, `-v`, `status`, `stats`, `doctor`, `provider` (covers `provider show` and `provider list`), `memory` (covers `memory list` and `memory index`).
61
+ - Every other command continues to execute on the existing Bash CLI (`autonomy/loki`).
62
+ - If `bun` is not on `PATH`, the shim falls through to Bash silently. Existing users without Bun installed see no behavior change.
63
+
64
+ **Rollback flag:**
65
+
66
+ Force every command to take the legacy Bash path:
67
+
68
+ ```bash
69
+ LOKI_LEGACY_BASH=1 loki <cmd>
70
+ ```
71
+
72
+ This is the documented escape hatch for any user who hits a regression on the Bun route. The Bash path remains the source of truth through Phase 5.
73
+
74
+ **Phase 6 (planned, calendar TBD):**
75
+
76
+ The next major release sunsets the Bash runtime entirely. There is no firm calendar date. Users who need to stay on the Bash route should pin the last v7.x release.
77
+
78
+ **Cost:**
79
+
80
+ - Adds a Bun runtime dependency (Bun 1.3.0 or newer recommended; the shim works as long as `bun` resolves).
81
+ - Adds a Bun toolchain to the system (Bun itself is roughly 50 MB installed via `brew install` or the official curl installer). The published `loki-ts/dist/loki.js` bundle inside the npm tarball is approximately 152 KB.
82
+ - Speedup on the ported commands is measured in `.loki/metrics/migration_bench_soak.jsonl` and analysed in [ADR-001](docs/architecture/ADR-001-runtime-migration.md). Recorded soak results show roughly 3x to 5x faster execution on the ported commands (per-command range 2.9x to 5.0x); treat as indicative, not contractual.
83
+
84
+ **More:**
85
+
86
+ - [UPGRADING.md](UPGRADING.md) -- per-version upgrade and rollback guidance.
87
+ - [ADR-001: Runtime Migration](docs/architecture/ADR-001-runtime-migration.md) -- design rationale and phase definitions.
88
+
89
+ ---
90
+
52
91
  <details>
53
92
  <summary><strong>Other install methods</strong></summary>
54
93
 
package/SKILL.md CHANGED
@@ -3,12 +3,14 @@ name: loki-mode
3
3
  description: Multi-agent autonomous startup system. Triggers on "Loki Mode". Takes PRD to deployed product with minimal human intervention. Requires --dangerously-skip-permissions flag.
4
4
  ---
5
5
 
6
- # Loki Mode v7.2.0
6
+ # Loki Mode v7.4.8
7
7
 
8
8
  **You are an autonomous agent. You make decisions. You do not ask questions. You do not stop.**
9
9
 
10
10
  **New in v5.0.0:** Multi-provider support (Claude/Codex/Gemini/Cline/Aider), abstract model tiers, degraded mode for non-Claude providers. See `skills/providers.md`.
11
11
 
12
+ **Runtime migration in progress:** A bash-to-Bun migration is underway on the `feat/bun-migration` branch. The first phase (shipped in v7.3.0) routes a small set of read-only commands -- `version`, `status`, `stats`, `doctor`, `provider show/list`, `memory list/index` -- through a Bun runtime via `bin/loki`. Every other command remains on the Bash runtime (`autonomy/loki`). Rollback is available with `LOKI_LEGACY_BASH=1`. See `UPGRADING.md` and `docs/architecture/ADR-001-runtime-migration.md` for the full plan.
13
+
12
14
  ---
13
15
 
14
16
  ## PRIORITY 1: Load Context (Every Turn)
@@ -320,4 +322,4 @@ The following features are documented in skill modules but not yet fully automat
320
322
  | Quality gates 3-reviewer system | Implemented (v5.35.0) | 5 specialist reviewers in `skills/quality-gates.md`; execution in run.sh |
321
323
  | Benchmarks (HumanEval, SWE-bench) | Infrastructure only | Runner scripts and datasets exist in `benchmarks/`; no published results |
322
324
 
323
- **v7.2.0 | [Autonomi](https://www.autonomi.dev/) flagship product | ~260 lines core**
325
+ **v7.4.8 | [Autonomi](https://www.autonomi.dev/) flagship product | ~260 lines core**
package/VERSION CHANGED
@@ -1 +1 @@
1
- 7.2.0
1
+ 7.4.8
package/autonomy/loki CHANGED
@@ -31,6 +31,13 @@ BOLD='\033[1m'
31
31
  DIM='\033[2m'
32
32
  NC='\033[0m'
33
33
 
34
+ # v7.4.5 (BUG-15 bash route): honor NO_COLOR convention (https://no-color.org/)
35
+ # Mirrors the equivalent fix in loki-ts/src/util/colors.ts. Required for parity
36
+ # when the shim falls through to the bash route (e.g., when bun is missing).
37
+ if [ -n "${NO_COLOR:-}" ]; then
38
+ RED=''; GREEN=''; YELLOW=''; BLUE=''; CYAN=''; BOLD=''; DIM=''; NC=''
39
+ fi
40
+
34
41
  # Logging functions (portable across bash/zsh)
35
42
  log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
36
43
  log_error() { echo -e "${RED}[ERROR]${NC} $*"; }
@@ -2529,7 +2536,8 @@ if reviews_total > 0:
2529
2536
  if gate_failures:
2530
2537
  failure_parts = [f'{k} ({v})' for k, v in gate_failures.items() if v > 0]
2531
2538
  if failure_parts:
2532
- print(f' Gate failures: {', '.join(failure_parts)}')
2539
+ sep = ', '
2540
+ print(f' Gate failures: {sep.join(failure_parts)}')
2533
2541
  print()
2534
2542
 
2535
2543
  # Efficiency
package/bin/loki ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env bash
2
+ #===============================================================================
3
+ # Loki Mode shim
4
+ #
5
+ # Routes commands ported in Phase 2 (bash->Bun migration) to the Bun CLI;
6
+ # everything else falls through to autonomy/loki (bash).
7
+ #
8
+ # Set LOKI_LEGACY_BASH=1 to force bash for every command (rollback flag).
9
+ # See docs/architecture/ADR-001-runtime-migration.md and
10
+ # /Users/lokesh/.claude/plans/polished-waddling-stardust.md.
11
+ #===============================================================================
12
+ set -euo pipefail
13
+
14
+ # Resolve script directory (handles symlinks like the bash CLI does).
15
+ _resolve_path() {
16
+ local script="$1"
17
+ if command -v realpath &>/dev/null; then
18
+ realpath "$script" 2>/dev/null || echo "$script"
19
+ else
20
+ while [ -L "$script" ]; do
21
+ local dir
22
+ dir=$(dirname "$script")
23
+ script=$(readlink "$script")
24
+ [[ "$script" != /* ]] && script="$dir/$script"
25
+ done
26
+ echo "$script"
27
+ fi
28
+ }
29
+
30
+ SCRIPT_PATH=$(_resolve_path "$0")
31
+ SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
32
+ REPO_ROOT=$(cd "$SCRIPT_DIR/.." 2>/dev/null && pwd)
33
+ BASH_CLI="$REPO_ROOT/autonomy/loki"
34
+
35
+ # Resolve which Bun entry to use:
36
+ # 1. LOKI_TS_ENTRY=... -- explicit override (custom builds, tests)
37
+ # 2. BUN_FROM_SOURCE=1 -- prefer src/cli.ts (used by bench --compare-dist
38
+ # and during Phase 3 development before dist ships)
39
+ # 3. dist/loki.js exists -- production path (npm/Docker/Homebrew artifact)
40
+ # 4. fall back to src -- in-repo development before first build
41
+ #
42
+ # v7.4.2 fix (BUG-1): BUN_FROM_SOURCE=1 used to hard-fail on npm/Docker/brew
43
+ # installs because src/ is excluded by .npmignore. Now we warn once and fall
44
+ # back to dist if src/cli.ts is missing.
45
+ if [ -n "${LOKI_TS_ENTRY:-}" ]; then
46
+ BUN_CLI="$LOKI_TS_ENTRY"
47
+ elif [ "${BUN_FROM_SOURCE:-0}" = "1" ] || [ "${BUN_FROM_SOURCE:-}" = "true" ]; then
48
+ if [ -f "$REPO_ROOT/loki-ts/src/cli.ts" ]; then
49
+ BUN_CLI="$REPO_ROOT/loki-ts/src/cli.ts"
50
+ elif [ -f "$REPO_ROOT/loki-ts/dist/loki.js" ]; then
51
+ echo "WARN: BUN_FROM_SOURCE set but loki-ts/src/cli.ts missing (typical for npm/Docker/brew installs); using dist/loki.js" >&2
52
+ BUN_CLI="$REPO_ROOT/loki-ts/dist/loki.js"
53
+ else
54
+ echo "ERROR: BUN_FROM_SOURCE set but neither src/cli.ts nor dist/loki.js found; falling through to bash" >&2
55
+ exec "$BASH_CLI" "$@"
56
+ fi
57
+ elif [ -f "$REPO_ROOT/loki-ts/dist/loki.js" ]; then
58
+ BUN_CLI="$REPO_ROOT/loki-ts/dist/loki.js"
59
+ elif [ -f "$REPO_ROOT/loki-ts/src/cli.ts" ]; then
60
+ BUN_CLI="$REPO_ROOT/loki-ts/src/cli.ts"
61
+ else
62
+ # Neither dist nor src available; fall through to bash silently.
63
+ exec "$BASH_CLI" "$@"
64
+ fi
65
+
66
+ # Force-fall-through to bash when the rollback flag is set.
67
+ if [ "${LOKI_LEGACY_BASH:-0}" = "1" ] || [ "${LOKI_LEGACY_BASH:-}" = "true" ]; then
68
+ exec "$BASH_CLI" "$@"
69
+ fi
70
+
71
+ # Bun must be installed for the new path; if it isn't, fall through to bash
72
+ # silently rather than fail. This keeps users on systems without Bun working.
73
+ if ! command -v bun &>/dev/null; then
74
+ exec "$BASH_CLI" "$@"
75
+ fi
76
+
77
+ # Commands ported in Phase 2 -- route to Bun. Everything else goes to bash.
78
+ # Two-token routes (provider show/list, memory list/index) match on the first
79
+ # token only; the Bun dispatcher handles subcommand routing internally.
80
+ case "${1:-}" in
81
+ version|--version|-v|status|stats|doctor|provider|memory)
82
+ exec bun "$BUN_CLI" "$@"
83
+ ;;
84
+ *)
85
+ exec "$BASH_CLI" "$@"
86
+ ;;
87
+ esac
package/bin/loki-mode.js CHANGED
@@ -1,17 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Loki Mode CLI wrapper for npm distribution
4
- * Delegates to the bash CLI
3
+ * Loki Mode npm wrapper.
4
+ *
5
+ * Delegates to bin/loki (the runtime-aware shim) so that ported commands
6
+ * route through the Bun runtime when bun is on PATH and unported commands
7
+ * fall through to autonomy/loki (bash). Pre-v7.4.7 this script bypassed
8
+ * the shim and went straight to bash, which silently disabled the Bun
9
+ * route for users invoking the `loki-mode` binary instead of `loki`.
5
10
  */
6
11
 
7
12
  const { spawn } = require('child_process');
8
13
  const path = require('path');
9
14
 
10
- const lokiScript = path.join(__dirname, '..', 'autonomy', 'loki');
15
+ const shim = path.join(__dirname, 'loki');
11
16
  const args = process.argv.slice(2);
12
17
 
13
- const child = spawn(lokiScript, args, {
14
- stdio: 'inherit'
18
+ const child = spawn(shim, args, {
19
+ stdio: 'inherit',
15
20
  });
16
21
 
17
22
  child.on('close', (code) => {
@@ -20,6 +25,6 @@ child.on('close', (code) => {
20
25
 
21
26
  child.on('error', (err) => {
22
27
  console.error('Error running loki:', err.message);
23
- console.error('Make sure bash is available on your system');
28
+ console.error('Make sure bash is available on your system (bin/loki shim requires /bin/bash).');
24
29
  process.exit(1);
25
30
  });
@@ -7,7 +7,7 @@ Modules:
7
7
  control: Session control API (start/stop/pause/resume)
8
8
  """
9
9
 
10
- __version__ = "7.2.0"
10
+ __version__ = "7.4.8"
11
11
 
12
12
  # Expose the control app for easy import
13
13
  try:
@@ -0,0 +1,76 @@
1
+ # ARM64 Image Verification
2
+
3
+ This document describes the manual procedure to verify that a published `asklokesh/loki-mode` Docker image actually runs on a real ARM64 host. CI does not exercise the runtime on ARM64; see `docs/UNREACHABLE-TESTS.md` for the rationale.
4
+
5
+ This procedure should be run by a maintainer (or any contributor with an ARM64 host) after each release that bumps the published image tag.
6
+
7
+ ---
8
+
9
+ ## Prerequisites
10
+
11
+ - An ARM64 host. Examples:
12
+ - Apple Silicon Mac (M1, M2, M3, or M4).
13
+ - AWS Graviton instance.
14
+ - Raspberry Pi 4 or 5 with a 64-bit OS.
15
+ - Docker Engine or Docker Desktop installed and running.
16
+ - Network access to Docker Hub.
17
+
18
+ Confirm the host is genuinely ARM64:
19
+
20
+ ```bash
21
+ uname -m
22
+ # expected output: arm64 (macOS) or aarch64 (Linux)
23
+ ```
24
+
25
+ If the output is anything else (`x86_64`, `amd64`), this procedure does not apply -- you need an ARM64 host.
26
+
27
+ ---
28
+
29
+ ## Procedure
30
+
31
+ Replace `7.X.Y` with the tag you intend to verify.
32
+
33
+ ```bash
34
+ docker run --rm --platform linux/arm64 asklokesh/loki-mode:7.X.Y loki version
35
+ ```
36
+
37
+ The `--platform linux/arm64` flag forces Docker to pull the ARM64 variant of the manifest list even if a multi-arch image is being served. This catches the case where the image was published as x86_64-only by accident.
38
+
39
+ ### Expected output
40
+
41
+ The command prints the version string of the bundled CLI and exits 0. The exact format follows the bash CLI's `version` command. A non-zero exit, a Python or Bun runtime error, or a missing-binary error all indicate a broken ARM64 build.
42
+
43
+ ### Additional smoke checks
44
+
45
+ Run a few more commands to surface ARM64-specific runtime issues:
46
+
47
+ ```bash
48
+ docker run --rm --platform linux/arm64 asklokesh/loki-mode:7.X.Y loki doctor
49
+ docker run --rm --platform linux/arm64 asklokesh/loki-mode:7.X.Y loki status
50
+ ```
51
+
52
+ `loki doctor` prints the runtime environment summary (Bun version, Python version, provider CLIs detected). On the published image, the absence of any provider CLI is expected; the doctor command itself should still complete without an internal error.
53
+
54
+ `loki status` reads `.loki/` state. With no mounted state directory, it should report `stopped` or an equivalent empty state -- not crash.
55
+
56
+ ---
57
+
58
+ ## Recording the result
59
+
60
+ When verification passes, note it in the release commit body or in the GitHub Release notes under a "Verified channels" section. Include:
61
+
62
+ - Host architecture (`uname -m` output)
63
+ - Host OS (`uname -s` plus distribution if Linux)
64
+ - Docker version (`docker --version`)
65
+ - Image tag verified
66
+ - Date of verification
67
+
68
+ When verification fails, open an issue with the same details plus the full output of the failing command. Do not promote the release to "stable" until the failure is fixed.
69
+
70
+ ---
71
+
72
+ ## Why this is manual
73
+
74
+ The `parity-drift.yml` and image-publish workflows use `buildx` with QEMU emulation, which produces a multi-arch manifest but does not exercise the runtime on real ARM64 silicon. QEMU translation can mask runtime issues that only surface on real hardware (for example, native binary dependencies, mmap layout differences, or timing-sensitive code).
75
+
76
+ Until the project provisions an ARM64 self-hosted runner, this manual procedure is the only honest verification.
@@ -2,7 +2,7 @@
2
2
 
3
3
  The flagship product of [Autonomi](https://www.autonomi.dev/). Complete installation instructions for all platforms and use cases.
4
4
 
5
- **Version:** v7.2.0
5
+ **Version:** v7.4.8
6
6
 
7
7
  ---
8
8
 
@@ -91,6 +91,26 @@ loki setup-skill
91
91
 
92
92
  ---
93
93
 
94
+ ## PyPI / Python SDK
95
+
96
+ **The `loki` CLI is NOT available via `pip install loki-mode`.** PyPI hosts only the
97
+ Python REST client SDK at `loki-mode-sdk` (v7.4.8+). The dashboard, MCP server,
98
+ and orchestrator components ship via npm, Docker, and Homebrew only.
99
+
100
+ ```bash
101
+ # Install the Python REST client only
102
+ pip install loki-mode-sdk
103
+
104
+ # Install the full CLI (recommended)
105
+ npm install -g loki-mode # or: brew tap asklokesh/tap && brew install loki-mode
106
+ ```
107
+
108
+ The naming asymmetry (`loki-mode` on npm vs `loki-mode-sdk` on PyPI) is
109
+ intentional: PyPI's `loki-mode` namespace is reserved for a future server
110
+ package, while `loki-mode-sdk` is the thin client.
111
+
112
+ ---
113
+
94
114
  ## Quick Start
95
115
 
96
116
  ```bash
package/docs/SLO.md ADDED
@@ -0,0 +1,52 @@
1
+ # Service Level Objectives
2
+
3
+ This document records baseline targets for the user-visible behavior of the CLI and the runner. These are honest first-pass targets. **No SLI/SLO infrastructure is shipped yet.** Tracking is manual, via the parity-drift workflow and soak-window observation.
4
+
5
+ The targets below should be treated as goals, not contracts. They will be revised as measurement infrastructure is built out.
6
+
7
+ ---
8
+
9
+ ## Latency
10
+
11
+ | Command | Route | p99 target | Source of measurement |
12
+ |---------|-------|------------|----------------------|
13
+ | `loki version` | Bun | < 100 ms | `.loki/metrics/migration_bench_soak.jsonl` (recorded p95 ~30 ms; p99 not recorded but headroom is large) |
14
+ | `loki version` | Bash | < 200 ms | `.loki/metrics/migration_bench_soak.jsonl` (recorded p95 ~141 ms) |
15
+ | `loki status` | either route | < 500 ms | not currently measured in CI; manual observation only |
16
+
17
+ **Caveats:**
18
+
19
+ - The soak file records p50 and p95, not p99. The p99 targets above assume modest tail behavior on top of the recorded p95. They should be tightened or loosened once a proper p99 measurement is in place.
20
+ - All numbers are wall-clock cold starts measured via `hyperfine` on developer hardware. Latency on slower machines (low-end CI runners, ARM64 emulated, containers under heavy load) will be worse.
21
+
22
+ ---
23
+
24
+ ## Parity
25
+
26
+ | Property | Target | Measurement |
27
+ |----------|--------|-------------|
28
+ | Byte-divergence between Bash and Bun routes for the ported commands | 0 divergences | `parity-drift.yml` workflow runs the Bun and Bash routes side by side; any non-empty diff fails the job |
29
+
30
+ The eight commands currently in scope: `version`, `status`, `stats`, `doctor`, `provider show`, `provider list`, `memory list`, `memory index`.
31
+
32
+ ---
33
+
34
+ ## Reliability
35
+
36
+ | Metric | Target | Status |
37
+ |--------|--------|--------|
38
+ | `loki start` completion rate on standard PRDs | 99% | aspirational; no automated measurement yet |
39
+ | Dashboard availability when invoked from `loki start` | 99.9% per session | aspirational; no automated measurement yet |
40
+ | Pre-publish tarball validation pass rate before any release | 100% | enforced manually per `CLAUDE.md` "Pre-Publish Validation"; failure blocks release |
41
+
42
+ The reliability numbers above are explicitly aspirational. The system does not currently emit a "completion / non-completion" signal that could be aggregated into a reliability number across users. The 99% target represents what the maintainer wants to be true, not what is currently measured.
43
+
44
+ ---
45
+
46
+ ## Notes on measurement
47
+
48
+ - The only continuous SLI shipping today is the parity-drift workflow.
49
+ - Latency measurements are recorded in `.loki/metrics/migration_bench_soak.jsonl` when a benchmark run is performed; they are not collected continuously.
50
+ - Reliability is tracked by manual review during the v7.3.0 soak window.
51
+
52
+ These are baseline targets. They will be revised when SLI/SLO infrastructure ships.
@@ -0,0 +1,123 @@
1
+ # Unreachable Tests
2
+
3
+ This document is an honest log of test scenarios that the project cannot exercise in CI today, why each one is blocked, and what (if anything) substitutes for the missing coverage.
4
+
5
+ The intent is to keep this list short and embarrassing so the gaps stay visible. If a row here can be closed, close it.
6
+
7
+ ---
8
+
9
+ ## Real Claude / Codex / Gemini API calls
10
+
11
+ **What we cannot test in CI:** end-to-end runs that actually invoke a hosted Claude, OpenAI Codex, or Google Gemini agent loop with real credentials.
12
+
13
+ **Blocker:**
14
+
15
+ - Per-call cost. A full PRD run can rack up double-digit dollars per provider; running on every PR is not affordable.
16
+ - Auth. Storing real provider tokens in CI gives any contributor on a fork-PR an attack surface to exfiltrate them. We do not pass secrets to fork PRs by policy.
17
+ - Agent-loop safety. A real provider call has full tool-use authority and can take destructive actions (file writes, shell commands) that are unsafe to run unattended in CI.
18
+
19
+ **Manual procedure that closes the gap:**
20
+
21
+ Run the relevant `tests/integration/` script locally with real credentials in a sandbox container or VM.
22
+
23
+ **Partial substitute we ship:**
24
+
25
+ - Provider loader unit tests under `tests/test-provider-loader.sh` cover flag selection, model name mapping, and fallback wiring without invoking the provider.
26
+ - The Bun test suite uses recorded fixtures for `build_prompt` and the runner state machine.
27
+
28
+ ---
29
+
30
+ ## Windows runtime
31
+
32
+ **What we cannot test in CI:** Loki Mode running natively on Windows (PowerShell or cmd, or Windows-native bash).
33
+
34
+ **Blocker:** No Windows host in the CI pool. The runtime relies heavily on POSIX bash semantics; Windows bash via WSL is the only realistic path and we have not provisioned a runner for it.
35
+
36
+ **Manual procedure that closes the gap:**
37
+
38
+ Install on a Windows host with WSL2 + Ubuntu, run `loki doctor` and the smoke commands, file an issue with the output. Document any divergence in `docs/PLATFORM-SUPPORT.md` (file does not exist yet -- create it on first finding).
39
+
40
+ **Partial substitute we ship:**
41
+
42
+ None. Windows is not a supported platform today.
43
+
44
+ ---
45
+
46
+ ## Real ARM64 runtime
47
+
48
+ **What we cannot test in CI:** the published Docker image actually starting up and answering `loki version` on a real ARM64 host.
49
+
50
+ **Blocker:** GitHub Actions provides ARM64 emulation via QEMU under buildx, but we do not have an ARM64 runner in the pool. Buildx can produce the image; it cannot meaningfully exercise the runtime.
51
+
52
+ **Manual procedure that closes the gap:**
53
+
54
+ See `docs/ARM64-VERIFICATION.md` for the manual verification procedure on an Apple Silicon Mac or another ARM64 host.
55
+
56
+ **Partial substitute we ship:**
57
+
58
+ - `buildx` produces the multi-arch image and verifies the build does not fail.
59
+ - The same TypeScript/Bun runtime ships unchanged across architectures, so x86_64 unit tests cover most of the runtime logic.
60
+
61
+ ---
62
+
63
+ ## Real PRD end-to-end
64
+
65
+ **What we cannot test in CI:** a real PRD running through the full RARV loop to completion, with provider calls, code generation, tests, and deploy artifacts.
66
+
67
+ **Blocker:**
68
+
69
+ - Cost (see "Real Claude / Codex / Gemini API calls" above).
70
+ - Nondeterminism. The provider's output varies, so an end-to-end pass/fail signal is noisy.
71
+ - Wall-clock duration. A standard PRD takes 30-90 minutes; CI runners time out long before.
72
+
73
+ **Manual procedure that closes the gap:**
74
+
75
+ Maintainer runs the templated PRDs under `templates/` against the current build before a release and inspects the output. This is captured in the release checklist informally.
76
+
77
+ **Partial substitute we ship:**
78
+
79
+ - Unit tests against recorded provider outputs for the prompt builder and council voter.
80
+ - Smoke tests of the runner state machine that exercise every phase transition without invoking a provider.
81
+
82
+ ---
83
+
84
+ ## 1-hour-plus stress runs
85
+
86
+ **What we cannot test in CI:** sessions that run for an hour or more to surface memory leaks, file-descriptor leaks, or queue churn under sustained load.
87
+
88
+ **Blocker:** GitHub-hosted runner minutes. A one-hour test on every PR would consume the project's monthly minute allocation in a few days.
89
+
90
+ **Manual procedure that closes the gap:**
91
+
92
+ Run `./benchmarks/run-benchmarks.sh` on a self-hosted machine for the full duration and capture process metrics with `ps`/`top` / a simple sampling script. Record findings under `.loki/metrics/`.
93
+
94
+ **Partial substitute we ship:**
95
+
96
+ - The completion council circuit breaker and budget breaker are unit-tested for trigger logic.
97
+ - The dashboard tracks per-iteration cost and context usage; large regressions show up in `.loki/metrics/efficiency/`.
98
+
99
+ ---
100
+
101
+ ## Brew install via the real tap
102
+
103
+ **What we cannot test in CI:** `brew tap asklokesh/tap && brew install loki-mode` against the real tap and a real macOS host.
104
+
105
+ **Blocker:**
106
+
107
+ - Running `brew install` on a CI runner mutates the runner's Homebrew prefix. This interferes with subsequent jobs on the same runner (GitHub-hosted runners are ephemeral, but the side effects still apply for the remainder of the job).
108
+ - Cross-tap mutation in CI risks accidentally publishing a broken formula if the install path is reused for verification.
109
+
110
+ **Manual procedure that closes the gap:**
111
+
112
+ Maintainer runs the brew install on a clean macOS host (or a fresh VM) after every release and checks `loki version` plus a smoke command. Verification is captured in the release checklist.
113
+
114
+ **Partial substitute we ship:**
115
+
116
+ - The `homebrew-tap` repository's CI lints the formula on every update.
117
+ - Tarball validation in `CLAUDE.md` "Pre-Publish Validation" exercises the npm path, which shares most of the same artifacts.
118
+
119
+ ---
120
+
121
+ ## How to use this document
122
+
123
+ When you discover a new untestable scenario, add it here. When you close a gap, remove the row. Keep the document short.
@@ -0,0 +1,229 @@
1
+ # ADR-001: Migrate Loki orchestrator off bash
2
+
3
+ **Status:** Proposed (feature/bun-migration branch)
4
+ **Date:** 2026-04-25
5
+ **Decision driver:** `autonomy/run.sh` is 11,327 lines of bash and `autonomy/loki` is 22,304 lines. Both are fragile, hard to refactor, untyped, and the upstream RARV-C audit (v6.81 plan) flagged them as the single biggest architectural debt.
6
+
7
+ ## Context: facts the user asked me to verify
8
+
9
+ ### 1. Did Anthropic acquire Bun?
10
+
11
+ **YES, verified.** Anthropic acquired Bun (Oven, Inc.) in December 2025. Bun remains MIT-licensed and open-source. Anthropic is positioning Bun as the runtime infrastructure for Claude Code, the Claude Agent SDK, and future AI coding products.
12
+
13
+ Sources:
14
+ - [Bun Blog: Bun is joining Anthropic](https://bun.com/blog/bun-joins-anthropic)
15
+ - [Anthropic: Anthropic acquires Bun as Claude Code reaches $1B milestone](https://www.anthropic.com/news/anthropic-acquires-bun-as-claude-code-reaches-usd1b-milestone)
16
+
17
+ ### 2. Is Bun faster than bash for our workload?
18
+
19
+ **Two-layer answer with REAL benchmarks.**
20
+
21
+ #### Layer 1: trivial hello-world cold start (hyperfine, 100 runs)
22
+
23
+ | Runtime | Cold start mean | vs bash |
24
+ |---|---|---|
25
+ | **Go binary** (compiled) | **1.8 ms** | **2.5x faster** |
26
+ | **bash hello-world** | **4.5 ms** | baseline |
27
+ | **Bun binary** (`bun build --compile`) | 6.9 ms | 1.5x slower |
28
+ | **Bun script** (`bun foo.ts`) | 7.6 ms | 1.7x slower |
29
+ | **Python3 script** | 20.3 ms | 4.5x slower |
30
+ | **Node.js script** | 45.2 ms | 10x slower |
31
+
32
+ For a trivial 1-line script, bash beats Bun by ~3 ms.
33
+
34
+ #### Layer 2: real Loki workload (50 runs, side-by-side, scripts/bench.ts)
35
+
36
+ | Runtime | `loki version` mean | vs bash |
37
+ |---|---|---|
38
+ | **bash autonomy/loki version** | **106.71 ms** (min 96.54, max 125.35) | baseline |
39
+ | **bun loki-ts/src/cli.ts version** | **12.36 ms** (min 11.63, max 13.52) | **8.63x FASTER** |
40
+
41
+ **This is the finding that flips the analysis.** When the bash script is 22,304 lines (the actual `autonomy/loki`), bash re-parses the entire AST every invocation. That parse cost dwarfs Bun's runtime startup cost by ~10x. **Bun is 8.6x faster than actual Loki bash.**
42
+
43
+ The user's premise ("Bun is faster than bash, no speed compromise") is correct for actual Loki workloads, even though it's false for hello-world.
44
+
45
+ **Why the gap:** bash has no bytecode cache. Every `loki version` invocation re-parses 22k lines of shell. Bun parses TypeScript once at install (or even at compile time with `--compile`), then executes machine code. The asymmetry grows with script size:
46
+
47
+ | Script size | Bash startup | Bun startup |
48
+ |---|---|---|
49
+ | 1 line | 4.5 ms | 7.6 ms (1.7x slower) |
50
+ | 22,304 lines (real `autonomy/loki`) | 106.71 ms | 12.36 ms (**8.63x FASTER**) |
51
+
52
+ So: **for hello-world bash wins; for our actual codebase Bun wins decisively, by an order of magnitude.**
53
+
54
+ ### 3. What about the npm distribution requirement?
55
+
56
+ User constraint: "people use npm, I want to keep it the same way."
57
+
58
+ | Runtime | npm distribution path | Complexity |
59
+ |---|---|---|
60
+ | **Bash** (today) | `package.json` `bin` field points to shell script | Trivial; current state |
61
+ | **Bun runtime** | `npm install -g loki-mode` ships TS, requires Bun installed via `npm install -g bun` (peer) OR Bun standalone in postinstall | Medium; peer dependency convention |
62
+ | **Bun compiled binary** | `bun build --compile` → 60 MB binary per platform; npm postinstall downloads correct binary (esbuild model) | Medium; per-platform binaries |
63
+ | **Go binary** | Same model as Bun compiled — npm postinstall downloads platform binary (esbuild, biome, vite-rust, swc all use this) | Medium; mature pattern |
64
+ | **Python** | npm postinstall would shell out to `pip install` or bundle Python — fragile, two package managers | High; do not recommend |
65
+ | **Node.js** | Native — no postinstall needed | Trivial; but Node is 10x slower than bash on cold start |
66
+
67
+ All three viable options (Bun runtime, Bun compiled, Go binary) keep the `npm install -g loki-mode` UX. Users see no change.
68
+
69
+ ## Three options, honestly compared
70
+
71
+ ### Option A: Go
72
+
73
+ **Pro:**
74
+ - **Only language that strictly beats bash.** 2.5x faster cold-start (1.8 ms vs 4.5 ms). User's "no speed compromise" requirement is met without caveats.
75
+ - Single static binary, ~2.4 MB (vs 60 MB Bun binary).
76
+ - Mature CLI ecosystem (Docker, kubectl, Terraform, Helm all use Go).
77
+ - Strict typing prevents whole class of bash quoting bugs.
78
+ - Cross-compile to all platforms from any platform.
79
+
80
+ **Con:**
81
+ - Loki team has zero Go in the codebase today.
82
+ - Anthropic does NOT own Go; less strategic alignment.
83
+ - Rewriting 33,000+ lines of bash to idiomatic Go is a 3-6 month effort.
84
+ - Goroutines/channels are different mental model than bash + Python orchestration.
85
+
86
+ **Distribution via npm:** Same pattern as esbuild — npm postinstall downloads the right platform binary. Mature, ~5 MB compressed per arch.
87
+
88
+ ### Option B: Bun runtime + TypeScript
89
+
90
+ **Pro:**
91
+ - **Anthropic owns Bun.** Strategic alignment with the company that owns the model we depend on.
92
+ - Native shell built in (`Bun.$\`echo hello\``) — minimal friction porting bash idioms.
93
+ - Bun's `npm install` is 20-40x faster than npm — every CI run faster.
94
+ - TypeScript: types catch bugs bash can't.
95
+ - Anthropic-funded development means Bun improvements specifically target AI agent workloads.
96
+ - 98% Node.js compatibility — npm packages work directly.
97
+
98
+ **Con:**
99
+ - **1.7x SLOWER than bash on trivial cold-start** (7.6 ms vs 4.5 ms). The user explicitly said "no speed compromise". This is a genuine compromise, even if 3 ms is humanly invisible.
100
+ - Bun runtime must be installed separately OR shipped via postinstall (60 MB if compiled).
101
+ - Less mature than Node (Bun 1.3 in 2026; some npm packages still hit edge cases).
102
+
103
+ **Distribution via npm:** Either (a) declare Bun as a peer dep and prompt user `npm install -g bun`; (b) ship `--compile` binary via postinstall.
104
+
105
+ ### Option C: Hybrid (recommended)
106
+
107
+ **Pro:**
108
+ - Keep tiny scripts in bash (where it wins by 3 ms): `loki version`, `loki status`, anything <100 LOC.
109
+ - Migrate the 11k-line orchestrator (`run.sh`) and 22k-line CLI (`autonomy/loki`) to Bun TypeScript — where compiled+typed wins.
110
+ - Keep `memory/`, `providers/`, `mcp/` in Python — they're already mature, no reason to rewrite.
111
+ - Anthropic alignment via Bun for the parts that matter.
112
+ - No speed regression for trivial commands; large gains for orchestrator.
113
+
114
+ **Con:**
115
+ - Three runtimes in the codebase (bash + Bun + Python) — operational complexity.
116
+ - Cross-runtime debugging harder than monorepo.
117
+
118
+ **Distribution:** Bun shipped via npm postinstall as compiled binary; bash remains as-is; Python unchanged.
119
+
120
+ ## Recommendation
121
+
122
+ **Option B (Bun runtime + TypeScript) — full migration, not hybrid.**
123
+
124
+ Reasons:
125
+
126
+ 1. **The Layer 2 benchmark inverts the speed argument.** Bun is 8.6x FASTER than actual Loki bash because `autonomy/loki` is 22,304 lines that re-parse every invocation. The user's "no speed compromise" rule is met decisively, with margin.
127
+ 2. **Anthropic strategic alignment.** Anthropic owns Bun. Loki uses Claude. Aligning runtime and model owner reduces dependency-versioning friction over time.
128
+ 3. **TypeScript pays the maintainability dividend** that 33k lines of bash will never deliver. Type checking catches whole classes of bugs (the kind we hit in v6.81-v7.2 cycles).
129
+ 4. **Hybrid is now harder to justify.** When bash loses by 8.6x on the actual workload, keeping it for 3 ms theoretical wins on hello-world is bad engineering.
130
+ 5. **Go would still be 2-4x faster than Bun** in absolute cold-start, but: zero existing Go in the codebase, no Anthropic alignment, larger rewrite cost, no JS ecosystem reuse. Unless Loki specifically targets the sub-millisecond CLI category (which it doesn't — every command runs in a multi-second/minute autonomous loop), the absolute speed delta doesn't justify the strategic cost.
131
+
132
+ **If user explicitly wants the absolute fastest:** Go (Option A) is 2.5x faster than Bun. But for orchestrator-heavy work where most time is spent waiting on Claude API calls, the difference is invisible.
133
+
134
+ ## Migration plan (Option C)
135
+
136
+ ### Phase 1: Scaffold (this branch, no behavior change)
137
+ - Create `loki-ts/` directory parallel to `autonomy/`
138
+ - `package.json` with Bun as engine, TypeScript config
139
+ - Port ONE simple command: `loki ts-version` (proves the toolchain)
140
+ - Add Bun to CI matrix (alongside existing Node/Python)
141
+ - **No user-visible change.** All existing commands route to bash.
142
+
143
+ ### Phase 2: Sub-commands
144
+ - Migrate read-only commands: `loki provider show`, `loki status`, `loki stats`, `loki memory list`
145
+ - Each migrated command goes through `loki-ts/` with bash as fallback flag
146
+ - Performance benchmark each: must be ≤ 2x bash cold start
147
+
148
+ ### Phase 3: Build/release tooling
149
+ - Replace npm publish with `bun publish` in CI
150
+ - Replace dashboard-ui esbuild with `bun build` (already 4-5x faster)
151
+ - Replace pytest where possible with `bun test` for non-Python tests
152
+ - Measure: full CI wall time, npm install time
153
+
154
+ ### Phase 4: build_prompt + RARV-C migration
155
+ - Port `build_prompt` (the 360-line bash function) to TypeScript
156
+ - Port `run_autonomous` outer loop
157
+ - Keep all Python subprocess invocations untouched (they're already fine)
158
+ - Side-by-side validation: same prompt output character-by-character
159
+ - Fallback flag: `LOKI_LEGACY_BASH=true` reverts
160
+
161
+ ### Phase 5: completion-council + code-review
162
+ - Port `council_should_stop` and `run_code_review` to TypeScript
163
+ - Same validation discipline
164
+
165
+ ### Phase 6: Sunset bash (only after 30 days clean in production)
166
+ - Remove `LOKI_LEGACY_BASH` flag
167
+ - Delete `autonomy/run.sh` and `autonomy/loki` (keep in git history)
168
+ - Bash → Bun migration complete
169
+
170
+ ## What we can do better for releases (Anthropic owns Bun → leverage)
171
+
172
+ | Today | Tomorrow | Win |
173
+ |---|---|---|
174
+ | `npm publish` (45-60 sec) | `bun publish` | ~5x faster CI publish |
175
+ | `npm install -g loki-mode` for users | Same UX, `bun install` under the hood when available | 20-40x faster install (verified) |
176
+ | Tests via `npm test` (Node 20-25 sec) | `bun test` for non-Python | ~10x faster test runs |
177
+ | Dashboard build with esbuild (122 ms) | `bun build` | 2-4x faster |
178
+ | Per-iteration cold start in run.sh: bash 4.5ms × N | Compiled Bun start once, run 100s | Net negative if iteration count low; net positive for sessions >5 iterations |
179
+ | Python `mcp/server.py` | Stays Python (already good) | No change |
180
+
181
+ ## Risks I'm not hiding
182
+
183
+ 1. **Migration drift:** TS port may behave subtly differently from bash. Mitigation: side-by-side test harness comparing outputs.
184
+ 2. **Bun beta-feature churn:** Even though Bun 1.3 is stable, Anthropic may push it in directions that break us. Mitigation: pin Bun version in `package.json` engines.
185
+ 3. **60 MB binary** if we ship `--compile`. Half a Loki Docker image. Mitigation: ship runtime peer dep instead of compiled binary in v8.
186
+ 4. **Three-runtime codebase** is real cognitive overhead for new contributors. Mitigation: clear `CONTRIBUTING.md` table of "what runtime owns what."
187
+ 5. **Bun's npm shipping pattern** is less proven than Go's. Mitigation: keep npm registry as primary distribution; add Homebrew (already exists) as a Bun-bundled alternative.
188
+
189
+ ## Concrete next steps if approved
190
+
191
+ 1. Scaffold `loki-ts/` with `package.json`, `tsconfig.json`, `src/cli.ts` (this PR)
192
+ 2. Port `cmd_version` to `loki-ts/src/commands/version.ts` (proof of concept)
193
+ 3. Add `bun-test.yml` GitHub workflow alongside existing `test.yml`
194
+ 4. Set acceptance criteria: every Phase 2+ command must benchmark within 2x of bash cold-start AND be type-checked via `bun typecheck`
195
+ 5. Ship Phase 1 as v8.0.0-alpha.1 (pre-release, opt-in) — does not affect default users
196
+
197
+ ---
198
+
199
+ ## Appendix: real benchmark data captured on this machine
200
+
201
+ Hyperfine 100 runs, 5 warmup, hello-world equivalent:
202
+
203
+ ```
204
+ bash /tmp/loki-bench-bash.sh 4.5 ± 0.4 ms baseline
205
+ bun-compiled-binary 6.9 ± 0.4 ms 1.53x slower
206
+ bun /tmp/loki-bench-bun.ts 7.6 ± 0.4 ms 1.69x slower
207
+ node /tmp/loki-bench-node.js 45.2 ± 1.0 ms 10.04x slower
208
+ python3 /tmp/loki-bench-py.py 20.3 ± 0.5 ms 4.51x slower
209
+ go-compiled-binary 1.8 ± 0.3 ms 2.5x FASTER
210
+ ```
211
+
212
+ Local versions:
213
+ - bash 5.x (macOS shipped /bin/bash 3.2 + brew bash)
214
+ - Bun 1.3.13
215
+ - Node v25.9.0
216
+ - Python 3.x
217
+ - Go 1.26.1
218
+
219
+ These are real numbers from this exact Mac, not from a vendor blog. Run hyperfine yourself to reproduce.
220
+
221
+ **Layer 2** (real Loki workload, 50 runs via `loki-ts/scripts/bench.ts`):
222
+ ```
223
+ bash autonomy/loki version 106.71 ms (min 96.54, max 125.35)
224
+ bun loki-ts/src/cli.ts version 12.36 ms (min 11.63, max 13.52)
225
+
226
+ bun is 8.63x FASTER than bash on the actual Loki entry point
227
+ ```
228
+
229
+ The 22,304-line `autonomy/loki` re-parses every invocation. Bun parses TS once, executes machine code thereafter. The asymmetry is the core argument for migration.
@@ -0,0 +1,341 @@
1
+ // @bun
2
+ var Q0=Object.defineProperty;var X0=(z)=>z;function Z0(z,Q){this[z]=X0.bind(null,Q)}var r=(z,Q)=>{for(var $ in Q)Q0(z,$,{get:Q[$],enumerable:!0,configurable:!0,set:Z0.bind(Q,$)})};var g=(z,Q)=>()=>(z&&(Q=z(z=0)),Q);var K0=import.meta.require;var P1={};r(P1,{lokiDir:()=>E,homeLokiDir:()=>B1,findSkillDir:()=>B0,findRepoRootForVersion:()=>W1,REPO_ROOT:()=>y});import{resolve as k,dirname as H1}from"path";import{fileURLToPath as H0}from"url";import{existsSync as u}from"fs";import{homedir as x1}from"os";function W0(){let z=L1;for(let Q=0;Q<6;Q++){if(u(k(z,"VERSION"))&&u(k(z,"autonomy/run.sh")))return z;let $=H1(z);if($===z)break;z=$}return k(L1,"..","..","..")}function W1(z){let Q=z;for(let $=0;$<6;$++){if(u(k(Q,"VERSION"))&&u(k(Q,"autonomy/run.sh")))return Q;let X=H1(Q);if(X===Q)break;Q=X}return k(z,"..","..","..")}function E(){return process.env.LOKI_DIR??k(process.cwd(),".loki")}function B1(){return k(x1(),".loki")}function B0(){let z=[y,k(x1(),".claude/skills/loki-mode"),process.cwd()];for(let Q of z)if(u(k(Q,"SKILL.md"))&&u(k(Q,"autonomy/run.sh")))return Q;return null}var L1,y;var h=g(()=>{L1=H1(H0(import.meta.url));y=W0()});var S1={};r(S1,{runOrThrow:()=>J0,run:()=>I,commandVersion:()=>M0,commandExists:()=>R,ShellError:()=>U1});async function I(z,Q={}){let $=Bun.spawn({cmd:[...z],stdout:"pipe",stderr:"pipe",env:Q.env?{...process.env,...Q.env}:process.env,cwd:Q.cwd}),X;if(Q.timeoutMs&&Q.timeoutMs>0)X=setTimeout(()=>$.kill(),Q.timeoutMs);let[Z,H,W]=await Promise.all([new Response($.stdout).text(),new Response($.stderr).text(),$.exited]);if(X)clearTimeout(X);return{stdout:Z,stderr:H,exitCode:W}}async function J0(z,Q={}){let $=await I(z,Q);if($.exitCode!==0)throw new U1(`command failed (${$.exitCode}): ${z.join(" ")}`,$.exitCode,$.stdout,$.stderr);return $}async function R(z){let Q=j0(z),$=await I(["sh","-c",`command -v ${Q}`],{timeoutMs:5000});if($.exitCode===0)return $.stdout.trim()||null;return null}function j0(z){if(!/^[A-Za-z0-9._/-]+$/.test(z))throw Error(`refused to shell-escape suspect token: ${z}`);return z}async function M0(z,Q="--version"){if(!await R(z))return null;let X=await I([z,Q],{timeoutMs:5000});if(X.exitCode!==0)return null;return((X.stdout||X.stderr).split(/\r?\n/)[0]?.trim()??"")||null}var U1;var m=g(()=>{U1=class U1 extends Error{message;exitCode;stdout;stderr;constructor(z,Q,$,X){super(z);this.message=z;this.exitCode=Q;this.stdout=$;this.stderr=X;this.name="ShellError"}}});function N(z){return Y0?"":z}var Y0,S,x,_,A3,G,F,A,K;var p=g(()=>{Y0=(process.env.NO_COLOR??"").length>0;S=N("\x1B[0;31m"),x=N("\x1B[0;32m"),_=N("\x1B[1;33m"),A3=N("\x1B[0;34m"),G=N("\x1B[0;36m"),F=N("\x1B[1m"),A=N("\x1B[2m"),K=N("\x1B[0m")});import{existsSync as P0}from"fs";async function a(){if(t!==void 0)return t;let z="/opt/homebrew/bin/python3.12";if(P0(z))return t=z,z;let Q=await R("python3.12");if(Q)return t=Q,Q;let $=await R("python3");return t=$,$}async function s(z,Q={}){let $=await a();if(!$)return{stdout:"",stderr:"python3 not found",exitCode:127};return I([$,"-c",z],Q)}var t;var Q1=g(()=>{m()});var v1={};r(v1,{runStatus:()=>y0});import{existsSync as L,readFileSync as e,readdirSync as C1,statSync as f1}from"fs";import{resolve as w,basename as E0}from"path";async function N0(){if(await R("jq"))return!0;return process.stdout.write(`${S}Error: jq is required but not installed.${K}
3
+ `),process.stdout.write(`Install with:
4
+ `),process.stdout.write(` brew install jq (macOS)
5
+ `),process.stdout.write(` apt install jq (Debian/Ubuntu)
6
+ `),process.stdout.write(` yum install jq (RHEL/CentOS)
7
+ `),!1}function X1(z){if(!Number.isFinite(z)||z<=0)return!1;try{return process.kill(z,0),!0}catch{return!1}}function Z1(z){if(!L(z))return null;try{let Q=e(z,"utf-8").trim();if(!Q)return null;let $=Number.parseInt(Q,10);return Number.isFinite($)?$:null}catch{return null}}function C0(z){let Q=[],$=Z1(w(z,"loki.pid"));if($!==null&&X1($))Q.push(`global:${$}`);let X=w(z,"sessions");if(L(X)){let Z=[];try{Z=C1(X)}catch{Z=[]}for(let H of Z){let W=w(X,H);try{if(!f1(W).isDirectory())continue}catch{continue}let B=w(W,"loki.pid"),j=Z1(B);if(j!==null&&X1(j))Q.push(`${H}:${j}`)}}if(L(z)){let Z=[];try{Z=C1(z)}catch{Z=[]}for(let H of Z){if(!H.startsWith("run-")||!H.endsWith(".pid"))continue;let W=w(z,H);try{if(!f1(W).isFile())continue}catch{continue}let B=E0(H,".pid").slice(4),j=Z1(W);if(j!==null&&X1(j)){if(!Q.some((T)=>T.startsWith(`${B}:`)))Q.push(`${B}:${j}`)}}}return Q}async function g1(z,Q){let $=await I(["jq","-r",z,Q]);if($.exitCode!==0)return null;return $.stdout.trim()}function y1(z,Q){try{let $=e(z,"utf-8"),Z=JSON.parse($)[Q];if(typeof Z==="number"){if(Q==="budget_used"){let H=Math.round(Z*100)/100;if(Number.isInteger(H))return String(H);return String(H)}return String(Z)}if(Z===void 0||Z===null)return"0";return String(Z)}catch{return"0"}}function h1(z,Q,$){try{let X=e(z,"utf-8"),H=JSON.parse(X)[Q];if(typeof H==="number"&&Number.isFinite(H))return H;return $}catch{return $}}async function f0(){let z=E();if(!await N0())return 1;if(!L(z))return process.stdout.write(`${F}Loki Mode Status${K}
8
+ `),process.stdout.write(`
9
+ `),process.stdout.write(`${_}No active session found.${K}
10
+ `),process.stdout.write(`Loki Mode has not been initialized in this directory.
11
+ `),process.stdout.write(`
12
+ `),process.stdout.write(`To start a session:
13
+ `),process.stdout.write(` loki start <prd> - Start with a PRD file
14
+ `),process.stdout.write(` loki start - Start without a PRD
15
+ `),process.stdout.write(`
16
+ `),process.stdout.write(`${A}Current directory: ${process.cwd()}${K}
17
+ `),0;process.stdout.write(`${F}Loki Mode Status${K}
18
+ `),process.stdout.write(`
19
+ `);let Q="",$=w(z,"state","provider");if(L($))try{Q=e($,"utf-8").trim()}catch{Q=""}let X=Q||process.env.LOKI_PROVIDER||"claude",Z="full features";switch(X){case"codex":case"gemini":case"aider":Z="degraded mode";break;case"cline":Z="near-full mode";break;default:Z="full features";break}process.stdout.write(`${G}Provider:${K} ${X} (${Z})
20
+ `),process.stdout.write(`${A} Switch with: loki provider set <claude|codex|gemini|cline|aider>${K}
21
+ `),process.stdout.write(`
22
+ `);let H=C0(z);if(H.length>0){process.stdout.write(`${x}Active Sessions: ${H.length}${K}
23
+ `);for(let V of H){let U=V.indexOf(":"),Y=U>=0?V.slice(0,U):V,b=U>=0?V.slice(U+1):"";if(Y==="global")process.stdout.write(` ${G}[global]${K} PID ${b}
24
+ `);else process.stdout.write(` ${G}[#${Y}]${K} PID ${b}
25
+ `)}process.stdout.write(`
26
+ `),process.stdout.write(`${A} Stop specific: loki stop <session-id>${K}
27
+ `),process.stdout.write(`${A} Stop all: loki stop${K}
28
+ `),process.stdout.write(`
29
+ `)}if(L(w(z,"PAUSE")))process.stdout.write(`${_}Status: PAUSED${K}
30
+ `),process.stdout.write(`${A} Resume with: loki resume${K}
31
+ `),process.stdout.write(`
32
+ `);else if(L(w(z,"STOP")))process.stdout.write(`${S}Status: STOPPED${K}
33
+ `),process.stdout.write(`${A} Clear with: loki resume${K}
34
+ `),process.stdout.write(`
35
+ `);let W=w(z,"STATUS.txt");if(L(W)){process.stdout.write(`${G}Session Info:${K}
36
+ `);try{process.stdout.write(e(W,"utf-8"))}catch{}process.stdout.write(`
37
+ `)}let B=w(z,"state","orchestrator.json");if(L(B)){process.stdout.write(`${G}Orchestrator State:${K}
38
+ `);let V=await g1('.currentPhase // "unknown"',B);process.stdout.write(`${V??"unknown"}
39
+ `)}let j=w(z,"queue","pending.json");if(L(j)){let V=await g1('if type == "array" then length elif .tasks then .tasks | length else 0 end',j);process.stdout.write(`${G}Pending Tasks:${K} ${V??"0"}
40
+ `)}let O=w(z,"metrics","budget.json");if(L(O)){let V=y1(O,"budget_limit"),U=y1(O,"budget_used");if(V!=="0")process.stdout.write(`${G}Budget:${K} $${U} / $${V}
41
+ `);else process.stdout.write(`${G}Cost:${K} $${U} (no limit)
42
+ `)}let T=w(z,"state","context-usage.json");if(L(T)){let V=h1(T,"window_size",200000),U=h1(T,"used_tokens",0),Y=0;if(V>0)Y=Math.floor(U*100/V);process.stdout.write(`${G}Context:${K} ${Y}% (${U} / ${V} tokens)
43
+ `)}let P=w(z,"dashboard","dashboard.pid");if(L(P)){let V=Z1(P);if(V!==null&&X1(V)){let U=process.env.LOKI_DASHBOARD_PORT||"57374";process.stdout.write(`${G}Dashboard:${K} http://127.0.0.1:${U}/
44
+ `)}}return process.stdout.write(`
45
+ `),process.stdout.write(`${A} Tip: loki context show - detailed token breakdown${K}
46
+ `),process.stdout.write(`${A} Tip: loki code overview - codebase intelligence${K}
47
+ `),0}async function g0(){let z=await a();if(!z)return process.stderr.write(`{"error": "Failed to generate JSON status. Ensure python3 is available."}
48
+ `),1;let Q=y,$=E(),X=process.env.LOKI_DASHBOARD_PORT||"57374",Z=process.env.LOKI_PROVIDER||"claude",H=await I([z,"-c",b0,Q,$,X,Z],{timeoutMs:30000});if(H.exitCode!==0)return process.stderr.write(`{"error": "Failed to generate JSON status. Ensure python3 is available."}
49
+ `),1;return process.stdout.write(H.stdout),0}async function y0(z){let Q=[...z];while(Q.length>0){let $=Q[0];if($==="--json")return g0();if($==="--help"||$==="-h")return process.stdout.write(`Usage: loki status [--json]
50
+ `),0;return process.stdout.write(`${S}Unknown flag: ${$}${K}
51
+ `),process.stdout.write(`Usage: loki status [--json]
52
+ `),1}return f0()}var b0=`
53
+ import json, os, sys, time
54
+
55
+ skill_dir = sys.argv[1]
56
+ loki_dir = sys.argv[2]
57
+ dashboard_port = sys.argv[3]
58
+ env_provider = sys.argv[4]
59
+ result = {}
60
+
61
+ # Version
62
+ version_file = os.path.join(skill_dir, 'VERSION')
63
+ if os.path.isfile(version_file):
64
+ with open(version_file) as f:
65
+ result['version'] = f.read().strip()
66
+ else:
67
+ result['version'] = 'unknown'
68
+
69
+ # Check if session exists
70
+ if not os.path.isdir(loki_dir):
71
+ result['status'] = 'inactive'
72
+ result['phase'] = None
73
+ result['iteration'] = 0
74
+ result['provider'] = env_provider
75
+ result['dashboard_url'] = None
76
+ result['pid'] = None
77
+ result['elapsed_time'] = 0
78
+ result['task_counts'] = {'total': 0, 'completed': 0, 'failed': 0, 'pending': 0}
79
+ print(json.dumps(result, indent=2))
80
+ sys.exit(0)
81
+
82
+ # Status from signals and session.json
83
+ if os.path.isfile(os.path.join(loki_dir, 'PAUSE')):
84
+ result['status'] = 'paused'
85
+ elif os.path.isfile(os.path.join(loki_dir, 'STOP')):
86
+ result['status'] = 'stopped'
87
+ else:
88
+ session_file = os.path.join(loki_dir, 'session.json')
89
+ if os.path.isfile(session_file):
90
+ try:
91
+ with open(session_file) as f:
92
+ session = json.load(f)
93
+ result['status'] = session.get('status', 'unknown')
94
+ except Exception:
95
+ result['status'] = 'unknown'
96
+ else:
97
+ result['status'] = 'unknown'
98
+
99
+ # Phase and iteration from dashboard-state.json
100
+ ds_file = os.path.join(loki_dir, 'dashboard-state.json')
101
+ if os.path.isfile(ds_file):
102
+ try:
103
+ with open(ds_file) as f:
104
+ ds = json.load(f)
105
+ result['phase'] = ds.get('phase', ds.get('currentPhase'))
106
+ result['iteration'] = ds.get('iteration', ds.get('currentIteration', 0))
107
+ except Exception:
108
+ result['phase'] = None
109
+ result['iteration'] = 0
110
+ else:
111
+ orch_file = os.path.join(loki_dir, 'state', 'orchestrator.json')
112
+ if os.path.isfile(orch_file):
113
+ try:
114
+ with open(orch_file) as f:
115
+ orch = json.load(f)
116
+ result['phase'] = orch.get('currentPhase')
117
+ result['iteration'] = orch.get('currentIteration', 0)
118
+ except Exception:
119
+ result['phase'] = None
120
+ result['iteration'] = 0
121
+ else:
122
+ result['phase'] = None
123
+ result['iteration'] = 0
124
+
125
+ # Provider
126
+ provider_file = os.path.join(loki_dir, 'state', 'provider')
127
+ if os.path.isfile(provider_file):
128
+ with open(provider_file) as f:
129
+ result['provider'] = f.read().strip()
130
+ else:
131
+ result['provider'] = env_provider
132
+
133
+ # PID
134
+ pid_file = os.path.join(loki_dir, 'loki.pid')
135
+ if os.path.isfile(pid_file):
136
+ try:
137
+ with open(pid_file) as f:
138
+ result['pid'] = int(f.read().strip())
139
+ except (ValueError, Exception):
140
+ result['pid'] = None
141
+ else:
142
+ result['pid'] = None
143
+
144
+ # Elapsed time from session.json
145
+ session_file = os.path.join(loki_dir, 'session.json')
146
+ if os.path.isfile(session_file):
147
+ try:
148
+ with open(session_file) as f:
149
+ session = json.load(f)
150
+ start_time = session.get('start_time', session.get('startTime'))
151
+ if start_time:
152
+ if isinstance(start_time, (int, float)):
153
+ result['elapsed_time'] = int(time.time() - start_time)
154
+ else:
155
+ from datetime import datetime
156
+ dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
157
+ result['elapsed_time'] = int(time.time() - dt.timestamp())
158
+ else:
159
+ result['elapsed_time'] = 0
160
+ except Exception:
161
+ result['elapsed_time'] = 0
162
+ else:
163
+ result['elapsed_time'] = 0
164
+
165
+ # Dashboard URL
166
+ dashboard_pid_file = os.path.join(loki_dir, 'dashboard', 'dashboard.pid')
167
+ dashboard_url = None
168
+ if os.path.isfile(dashboard_pid_file):
169
+ try:
170
+ with open(dashboard_pid_file) as f:
171
+ dpid = int(f.read().strip())
172
+ os.kill(dpid, 0)
173
+ dashboard_url = 'http://127.0.0.1:' + dashboard_port + '/'
174
+ except (ProcessLookupError, PermissionError, ValueError, Exception):
175
+ pass
176
+ result['dashboard_url'] = dashboard_url
177
+
178
+ # Task counts from queue files
179
+ task_counts = {'total': 0, 'completed': 0, 'failed': 0, 'pending': 0}
180
+ queue_dir = os.path.join(loki_dir, 'queue')
181
+ if os.path.isdir(queue_dir):
182
+ for name, key in [('pending.json', 'pending'), ('completed.json', 'completed'), ('failed.json', 'failed')]:
183
+ fpath = os.path.join(queue_dir, name)
184
+ if os.path.isfile(fpath):
185
+ try:
186
+ with open(fpath) as f:
187
+ data = json.load(f)
188
+ if isinstance(data, list):
189
+ task_counts[key] = len(data)
190
+ elif isinstance(data, dict) and 'tasks' in data:
191
+ task_counts[key] = len(data['tasks'])
192
+ except Exception:
193
+ pass
194
+ task_counts['total'] = task_counts['pending'] + task_counts['completed'] + task_counts['failed']
195
+ result['task_counts'] = task_counts
196
+
197
+ print(json.dumps(result, indent=2))
198
+ `;var m1=g(()=>{m();Q1();p();h()});var l1={};r(l1,{runStats:()=>c0,computeStats:()=>c1});import{readdirSync as u1,readFileSync as h0,statSync as p1}from"fs";import{join as C}from"path";function l(z){try{if(!p1(z).isFile())return null;return JSON.parse(h0(z,"utf-8"))}catch{return null}}function J1(z){try{return p1(z).isDirectory()}catch{return!1}}function v0(z){if(!J1(z))return[];try{let Q=u1(z).filter(($)=>$.startsWith("iteration-")&&$.endsWith(".json"));return Q.sort(),Q.map(($)=>C(z,$))}catch{return[]}}function d(z){return Math.trunc(z).toLocaleString("en-US")}function q1(z){let Q=Math.trunc(z);if(Q<60)return`${Q}s`;let $=Math.trunc(Q/3600),X=Math.trunc(Q%3600/60),Z=Q%60;if($>0)return`${$}h ${String(X).padStart(2,"0")}m`;return`${X}m ${String(Z).padStart(2,"0")}s`}function f(z,Q=0){let $=Math.pow(10,Q);return Math.round(z*$)/$}function o(z,Q){return z.toFixed(Q)}function G1(z,Q){return z.length>=Q?z:z+" ".repeat(Q-z.length)}function m0(z){let Q="N/A",$=0,X=l(C(z,"state","orchestrator.json"));if(X&&typeof X==="object"){if(typeof X.currentPhase==="string")Q=X.currentPhase;if(typeof X.currentIteration==="number")$=X.currentIteration}let Z=C(z,"metrics","efficiency"),H=v0(Z),W=[];for(let q of H){let M=l(q);if(M&&typeof M==="object")W.push(M)}if(W.length>0)$=Math.max($,W.length);let B=W.reduce((q,M)=>q+(M.input_tokens??0),0),j=W.reduce((q,M)=>q+(M.output_tokens??0),0),O=B+j,T=W.reduce((q,M)=>q+(M.cost_usd??0),0),P=W.reduce((q,M)=>q+(M.duration_seconds??0),0),V=0,U=0,Y=l(C(z,"metrics","budget.json"));if(Y&&typeof Y==="object"){if(typeof Y.budget_limit==="number")V=Y.budget_limit;if(typeof Y.budget_used==="number")U=Y.budget_used}let b=0,z1=0,n=l(C(z,"state","quality-gates.json"));if(n&&typeof n==="object"){if(Array.isArray(n)){for(let q of n)if(z1+=1,q===!0)b+=1;else if(q&&typeof q==="object"){let M=q;if(M.passed===!0||M.status==="passed")b+=1}}else for(let q of Object.values(n))if(typeof q==="boolean"){if(z1+=1,q)b+=1}else if(q&&typeof q==="object"){z1+=1;let M=q;if(M.passed===!0||M.status==="passed")b+=1}}let _1={},$1=l(C(z,"quality","gate-failure-count.json"));if($1&&typeof $1==="object"&&!Array.isArray($1)){let q={};for(let[M,D]of Object.entries($1))if(typeof D==="number")q[M]=D;_1=q}let T1=0,I1=0,w1=0,K1=C(z,"quality");if(J1(K1)){let q=[];try{q=u1(K1)}catch{q=[]}for(let M of q){if(!M.endsWith(".json")||M==="gate-failure-count.json")continue;let D=l(C(K1,M));if(!D||typeof D!=="object")continue;if(!(("verdict"in D)||("approved"in D)||("reviewers"in D)))continue;T1+=1;let F1=(D.verdict??"").toString().toLowerCase();if(D.approved===!0||["approved","approve","pass"].includes(F1))I1+=1;else if(["revision","revise","changes_requested","reject"].includes(F1))w1+=1}}return{phase:Q,iterationCount:$,iterations:W,totalInput:B,totalOutput:j,totalTokens:O,totalCost:T,totalDuration:P,budgetLimit:V,budgetUsed:U,gatesPassed:b,gatesTotal:z1,gateFailures:_1,reviewsTotal:T1,reviewsApproved:I1,reviewsRevision:w1}}function u0(z,Q){let $=z.iterationCount,X={session:{iterations:$,duration_seconds:z.totalDuration,phase:z.phase},tokens:{input:z.totalInput,output:z.totalOutput,total:z.totalTokens,cost_usd:f(z.totalCost,2)},quality:{gates_passed:z.gatesPassed,gates_total:z.gatesTotal,reviews_total:z.reviewsTotal,reviews_approved:z.reviewsApproved,reviews_revision:z.reviewsRevision,gate_failures:z.gateFailures},efficiency:{avg_tokens_per_iteration:$>0?f(z.totalTokens/$,0):0,avg_cost_per_iteration:$>0?f(z.totalCost/$,2):0,avg_duration_per_iteration:$>0?f(z.totalDuration/$,1):0},budget:{used:f(z.budgetUsed,2),limit:z.budgetLimit,percent:z.budgetLimit>0?f(z.budgetUsed/z.budgetLimit*100,1):0}};if(Q)X.iterations=z.iterations.map((W,B)=>({number:B+1,input_tokens:W.input_tokens??0,output_tokens:W.output_tokens??0,cost_usd:f(W.cost_usd??0,2),duration_seconds:W.duration_seconds??0}));let Z=JSON.stringify(X,null,2);function H(W,B){if(!B)return;let j=new RegExp(`("${W}": )(-?\\d+)(,?)$`,"m");Z=Z.replace(j,(O,T,P,V)=>`${T}${P}.0${V}`)}if(H("avg_duration_per_iteration",$>0&&Number.isInteger(X.efficiency.avg_duration_per_iteration)),H("percent",z.budgetLimit>0&&Number.isInteger(X.budget.percent)),H("cost_usd",$>0&&Number.isInteger(X.tokens.cost_usd)),Q)Z=Z.replace(/("cost_usd": )(-?\d+)(,?)$/gm,(W,B,j,O)=>`${B}${j}.0${O}`);return Z}function p0(z,Q){let $=[];if($.push("Loki Mode Session Statistics"),$.push("============================"),$.push(""),$.push("Session"),$.push(` Iterations completed: ${z.iterationCount}`),$.push(` Duration: ${q1(z.totalDuration)}`),$.push(` Current phase: ${z.phase}`),$.push(""),$.push("Token Usage"),z.iterations.length>0)$.push(` Input tokens: ${d(z.totalInput)}`),$.push(` Output tokens: ${d(z.totalOutput)}`),$.push(` Total tokens: ${d(z.totalTokens)}`),$.push(` Estimated cost: $${o(z.totalCost,2)}`);else $.push(" N/A (no iteration metrics found)");if($.push(""),$.push("Quality Gates"),z.gatesTotal>0){let X=Math.round(z.gatesPassed/z.gatesTotal*100);$.push(` Gates passed: ${z.gatesPassed}/${z.gatesTotal} (${X}%)`)}else $.push(" Gates passed: N/A");if(z.reviewsTotal>0){let X=[];if(z.reviewsApproved>0)X.push(`${z.reviewsApproved} approved`);if(z.reviewsRevision>0)X.push(`${z.reviewsRevision} revision requested`);let Z=X.length>0?X.join(", "):"N/A";$.push(` Code reviews: ${z.reviewsTotal} (${Z})`)}if(Object.keys(z.gateFailures).length>0){let X=Object.entries(z.gateFailures).filter(([,Z])=>Z>0).map(([Z,H])=>`${Z} (${H})`);if(X.length>0)$.push(` Gate failures: ${X.join(", ")}`)}if($.push(""),$.push("Efficiency"),z.iterationCount>0&&z.iterations.length>0){let X=Math.round(z.totalTokens/z.iterationCount),Z=z.totalCost/z.iterationCount,H=z.totalDuration/z.iterationCount;$.push(` Avg tokens/iteration: ${d(X)}`),$.push(` Avg cost/iteration: $${o(Z,2)}`),$.push(` Avg duration/iteration: ${q1(H)}`)}else $.push(" N/A (no iteration metrics found)");if($.push(""),$.push("Budget"),z.budgetLimit>0){let X=f(z.budgetUsed/z.budgetLimit*100,1),Z=Number.isInteger(X)?`${X}.0`:`${X}`;$.push(` Used: $${o(z.budgetUsed,2)} / $${o(z.budgetLimit,2)} (${Z}%)`)}else if(z.budgetUsed>0)$.push(` Used: $${o(z.budgetUsed,2)} (no limit set)`);else $.push(" N/A");if(Q&&z.iterations.length>0)$.push(""),$.push("Per-Iteration Breakdown"),z.iterations.forEach((X,Z)=>{let H=Z+1,W=G1(d(X.input_tokens??0),10),B=G1(d(X.output_tokens??0),10),j=X.cost_usd??0,O=q1(X.duration_seconds??0),T=G1(`${H}`,3);$.push(` #${T} input: ${W} output: ${B} cost: $${o(j,2)} time: ${O}`)});return $.join(`
199
+ `)}function c1(z){let Q=!1,$=!1;for(let W of z)if(W==="--json")Q=!0;else if(W==="--efficiency")$=!0;let X=E();if(!J1(X)){if(Q)return{exitCode:0,stdout:'{"error": "No active session"}'};return{exitCode:0,stdout:`${_}No active session found.${K}
200
+ Start a session with: loki start <prd>`}}let Z=m0(X);return{exitCode:0,stdout:Q?u0(Z,$):p0(Z,$)}}async function c0(z){let Q=c1(z);return console.log(Q.stdout),Q.exitCode}var d1=g(()=>{h();p()});var e1={};r(e1,{runDoctor:()=>$3,httpReachable:()=>A1,checkTool:()=>t1,checkSkills:()=>a1,checkDisk:()=>O1,buildDoctorJson:()=>i1});import{existsSync as l0,lstatSync as d0,readlinkSync as o0,statfsSync as n0}from"fs";import{homedir as n1}from"os";import{resolve as o1}from"path";function t0(z){let Q=z.match(r0);return Q?Q[1]:null}async function a0(z){try{let Q=await I([z,"--version"],{timeoutMs:5000}),$=(Q.stdout||Q.stderr||"").trim();return t0($)}catch{return null}}function r1(z,Q){let $=z.split(".").map((Z)=>parseInt(Z,10)),X=Q.split(".").map((Z)=>parseInt(Z,10));while($.length<2)$.push(0);while(X.length<2)X.push(0);for(let Z=0;Z<2;Z++){let H=$[Z]??0,W=X[Z]??0;if(Number.isNaN(H)||Number.isNaN(W))return 0;if(H!==W)return H-W}return 0}async function t1(z,Q,$,X=null){let Z=await R(Q),H=Z!==null,W=H?await a0(Q):null,B="pass";if(!H)B=$==="required"?"fail":"warn";else if(X&&W){if(r1(W,X)<0)B=$==="required"?"fail":"warn"}return{name:z,command:Q,found:H,version:W,required:$,min_version:X,status:B,path:Z}}function O1(){let z=null;try{let $=n0(n1()),X=Number($.bavail)*Number($.bsize);z=Math.round(X/1073741824*10)/10}catch{z=null}let Q="pass";if(z!==null){if(z<1)Q="fail";else if(z<5)Q="warn"}return{available_gb:z,status:Q}}async function A1(z,Q=2000){try{return(await fetch(z,{signal:AbortSignal.timeout(Q)})).ok}catch{return!1}}async function j1(z,Q=!1){let $=`import ${z}`,X=Q?30000:5000;if(!Q)return(await s($,{timeoutMs:X})).exitCode===0;let Z=await a();if(!Z)return!1;return(await I([Z,"-c",$],{timeoutMs:X})).exitCode===0}function a1(){let z=n1();return s0.map(({name:Q,dir:$})=>{let X=o1(z,$),Z=X,H=o1(X,"SKILL.md");if(l0(H))return{name:Q,path:Z,status:"pass",detail:""};try{if(d0(X).isSymbolicLink()){let B="unknown";try{B=o0(X)}catch{}return{name:Q,path:Z,status:"fail",detail:`(broken symlink -> ${B})`}}}catch{}return{name:Q,path:Z,status:"warn",detail:"(not found - run 'loki setup-skill')"}})}async function s1(){return Promise.all(i0.map(async(z)=>{return{...await t1(z.jsonName,z.cmd,z.required,z.min??null),displayName:z.displayName}}))}async function i1(){let Q=(await s1()).map(({displayName:W,...B})=>B),$=O1(),X=0,Z=0,H=0;for(let W of Q)if(W.status==="pass")X++;else if(W.status==="fail")Z++;else H++;if($.status==="pass")X++;else if($.status==="fail")Z++;else H++;return{checks:Q,disk:$,summary:{passed:X,failed:Z,warnings:H,ok:Z===0}}}function J(z){switch(z){case"pass":return`${x}PASS${K}`;case"fail":return`${S}FAIL${K}`;case"warn":return`${_}WARN${K}`}}function M1(z){let Q=z.version?` (v${z.version})`:"",$=z.displayName;if(!z.found){let X=z.required==="required"?"not found":z.required==="recommended"?"not found (recommended)":"not found (optional)";return` ${J(z.status)} ${$} - ${X}`}if(z.min_version&&z.version&&r1(z.version,z.min_version)<0){let X=z.required==="required"?"requires":"recommended";return` ${J(z.status)} ${$}${Q} - ${X} >= ${z.min_version}`}return` ${J(z.status)} ${$}${Q}`}function Y1(z,Q){if(Q==="pass")z.pass++;else if(Q==="fail")z.fail++;else z.warn++}function e0(){process.stdout.write(`${F}loki doctor${K} - Check system prerequisites
201
+
202
+ `),process.stdout.write(`Usage: loki doctor [--json]
203
+
204
+ `),process.stdout.write(`Options:
205
+ `),process.stdout.write(` --json Output machine-readable JSON
206
+
207
+ `),process.stdout.write(`Checks: node, python3, jq, git, curl, bash version,
208
+ `),process.stdout.write(` claude/codex/gemini CLIs, and disk space.
209
+ `)}async function z3(){process.stdout.write(`${F}Loki Mode Doctor${K}
210
+
211
+ `),process.stdout.write(`Checking system prerequisites...
212
+
213
+ `);let z={pass:0,fail:0,warn:0},Q=await s1(),$=new Map(Q.map((U)=>[U.command,U]));process.stdout.write(`${G}Required:${K}
214
+ `);for(let U of["node","python3","jq","git","curl"]){let Y=$.get(U);process.stdout.write(M1(Y)+`
215
+ `),Y1(z,Y.status)}process.stdout.write(`
216
+ `),process.stdout.write(`${G}AI Providers:${K}
217
+ `);let X=["claude","codex","gemini","cline","aider"],Z=!1;for(let U of X){let Y=$.get(U);if(process.stdout.write(M1(Y)+`
218
+ `),Y1(z,Y.status),Y.found)Z=!0}if(!Z)process.stdout.write(` ${J("fail")} No AI provider CLI installed -- at least one is required
219
+ `),process.stdout.write(` ${_}Install: npm install -g @anthropic-ai/claude-code${K}
220
+ `),z.fail++;process.stdout.write(`
221
+ `),process.stdout.write(`${G}API Keys:${K}
222
+ `);let H=$.get("claude").found,W=$.get("codex").found,B=$.get("gemini").found,j=process.env;if(j.ANTHROPIC_API_KEY)process.stdout.write(` ${J("pass")} ANTHROPIC_API_KEY is set
223
+ `),z.pass++;else if(H)process.stdout.write(` ${A} -- ${K} ANTHROPIC_API_KEY not set (Claude CLI uses its own login)
224
+ `);if(j.OPENAI_API_KEY)process.stdout.write(` ${J("pass")} OPENAI_API_KEY is set
225
+ `),z.pass++;else if(W)process.stdout.write(` ${A} -- ${K} OPENAI_API_KEY not set (Codex CLI uses its own login)
226
+ `);if(j.GOOGLE_API_KEY||j.GEMINI_API_KEY)process.stdout.write(` ${J("pass")} GOOGLE_API_KEY is set
227
+ `),z.pass++;else if(B)process.stdout.write(` ${A} -- ${K} GOOGLE_API_KEY not set (Gemini CLI uses its own login)
228
+ `);process.stdout.write(`
229
+ `),process.stdout.write(`${G}Skills:${K}
230
+ `);for(let U of a1())if(U.status==="pass")process.stdout.write(` ${J("pass")} ${U.name} ${A}${U.path}${K}
231
+ `),z.pass++;else if(U.status==="fail")process.stdout.write(` ${J("fail")} ${U.name} ${A}${U.detail}${K}
232
+ `),process.stdout.write(` ${_}Fix: loki setup-skill${K}
233
+ `),z.fail++;else process.stdout.write(` ${J("warn")} ${U.name} ${A}${U.detail}${K}
234
+ `),z.warn++;if(process.stdout.write(`
235
+ `),process.stdout.write(`${G}Integrations:${K}
236
+ `),await j1("mcp"))process.stdout.write(` ${J("pass")} MCP SDK (Python)
237
+ `),z.pass++;else process.stdout.write(` ${J("warn")} MCP SDK - not installed (pip3 install mcp)
238
+ `),z.warn++;if(await j1("numpy",!0))process.stdout.write(` ${J("pass")} numpy (vector search)
239
+ `),z.pass++;else process.stdout.write(` ${J("warn")} numpy - not installed (pip3 install numpy)
240
+ `),z.warn++;if(await j1("sentence_transformers",!0))process.stdout.write(` ${J("pass")} sentence-transformers (embeddings)
241
+ `),z.pass++;else process.stdout.write(` ${J("warn")} sentence-transformers - not installed (loki memory vectors setup)
242
+ `),z.warn++;if(await A1("http://localhost:8100/api/v2/heartbeat"))process.stdout.write(` ${J("pass")} ChromaDB server (port 8100)
243
+ `),z.pass++;else process.stdout.write(` ${J("warn")} ChromaDB - not running (docker start loki-chroma)
244
+ `),z.warn++;let O=process.env.LOKI_MIROFISH_URL;if(O)if(await A1(`${O}/health`))process.stdout.write(` ${J("pass")} MiroFish server (${O})
245
+ `),z.pass++;else process.stdout.write(` ${J("warn")} MiroFish - not running (loki start --mirofish-docker <image>)
246
+ `),z.warn++;if(process.env.LOKI_OTEL_ENDPOINT)process.stdout.write(` ${J("pass")} OTEL endpoint: ${process.env.LOKI_OTEL_ENDPOINT}
247
+ `),z.pass++;else process.stdout.write(` ${J("warn")} OTEL - not configured (set LOKI_OTEL_ENDPOINT)
248
+ `),z.warn++;process.stdout.write(`
249
+ `),process.stdout.write(`${G}System:${K}
250
+ `);let T=$.get("bash");process.stdout.write(M1(T)+`
251
+ `),Y1(z,T.status);let P=O1(),V=P.available_gb===null?null:Math.floor(P.available_gb);if(V===null)process.stdout.write(` ${J("warn")} Disk space: unable to determine
252
+ `),z.warn++;else if(P.status==="fail")process.stdout.write(` ${J("fail")} Disk space: ${V}GB available (need >= 1GB)
253
+ `),z.fail++;else if(P.status==="warn")process.stdout.write(` ${J("warn")} Disk space: ${V}GB available (low)
254
+ `),z.warn++;else process.stdout.write(` ${J("pass")} Disk space: ${V}GB available
255
+ `),z.pass++;if(process.stdout.write(`
256
+ `),process.stdout.write(`${F}Summary:${K} ${x}${z.pass} passed${K}, ${S}${z.fail} failed${K}, ${_}${z.warn} warnings${K}
257
+
258
+ `),z.fail>0)return process.stdout.write(`${S}Some required prerequisites are missing.${K}
259
+ `),process.stdout.write(`Install missing dependencies and run 'loki doctor' again.
260
+ `),1;if(z.warn>0)return process.stdout.write(`${_}All required checks passed with some warnings.${K}
261
+ `),0;return process.stdout.write(`${x}All checks passed. System is ready for Loki Mode.${K}
262
+ `),0}async function $3(z){let Q=!1;for(let $ of z)if($==="--json")Q=!0;else if($==="--help"||$==="-h")return e0(),0;else return process.stderr.write(`${S}Unknown option: ${$}${K}
263
+ `),process.stderr.write(`Usage: loki doctor [--json]
264
+ `),1;if(Q){let $=await i1();return process.stdout.write(JSON.stringify($,null,2)+`
265
+ `),0}return z3()}var r0,s0,i0;var z0=g(()=>{m();Q1();p();r0=/(\d+\.\d+(?:\.\d+)*)/;s0=[{name:"Claude Code",dir:".claude/skills/loki-mode"},{name:"Codex CLI",dir:".codex/skills/loki-mode"},{name:"Gemini CLI",dir:".gemini/skills/loki-mode"},{name:"Cline CLI",dir:".cline/skills/loki-mode"},{name:"Aider CLI",dir:".aider/skills/loki-mode"}];i0=[{displayName:"Node.js (>= 18)",jsonName:"Node.js",cmd:"node",required:"required",min:"18.0"},{displayName:"Python 3 (>= 3.8)",jsonName:"Python 3",cmd:"python3",required:"required",min:"3.8"},{displayName:"jq",jsonName:"jq",cmd:"jq",required:"required"},{displayName:"git",jsonName:"git",cmd:"git",required:"required"},{displayName:"curl",jsonName:"curl",cmd:"curl",required:"required"},{displayName:"bash (>= 4.0)",jsonName:"bash",cmd:"bash",required:"recommended",min:"4.0"},{displayName:"Claude CLI",jsonName:"Claude CLI",cmd:"claude",required:"optional"},{displayName:"Codex CLI",jsonName:"Codex CLI",cmd:"codex",required:"optional"},{displayName:"Gemini CLI",jsonName:"Gemini CLI",cmd:"gemini",required:"optional"},{displayName:"Cline CLI",jsonName:"Cline CLI",cmd:"cline",required:"optional"},{displayName:"Aider CLI",jsonName:"Aider CLI",cmd:"aider",required:"optional"}]});h();import{readFileSync as U0}from"fs";import{resolve as V0,dirname as q0}from"path";import{fileURLToPath as G0}from"url";var v=null;function k1(){if(v!==null)return v;let z="7.4.8";if(typeof z==="string"&&z.length>0)return v=z,v;try{let Q=q0(G0(import.meta.url)),$=W1(Q);v=U0(V0($,"VERSION"),"utf-8").trim()}catch{v="unknown"}return v}function R1(){return process.stdout.write(`Loki Mode v${k1()}
266
+ `),0}m();p();h();import{readFileSync as A0,existsSync as O0}from"fs";import{resolve as _0}from"path";var T0=["claude","codex","gemini","cline","aider"];function D1(){let z=_0(E(),"state","provider");if(!O0(z))return"";try{return A0(z,"utf-8").trim()}catch{return""}}function I0(z,Q){return z||Q||process.env.LOKI_PROVIDER||"claude"}function w0(z){let Q=D1(),$=I0(z,Q);switch(process.stdout.write(`${F}Current Provider${K}
267
+ `),process.stdout.write(`
268
+ `),process.stdout.write(`${G}Provider:${K} ${$}
269
+ `),$){case"claude":process.stdout.write(`${x}Status:${K} Full features (subagents, parallel, MCP)
270
+ `);break;case"cline":process.stdout.write(`${x}Status:${K} Near-full mode (subagents, MCP, 12+ providers)
271
+ `);break;case"codex":case"gemini":case"aider":process.stdout.write(`${_}Status:${K} Degraded mode (sequential only)
272
+ `);break;default:break}if(Q)process.stdout.write(`${A}(saved in .loki/state/provider)${K}
273
+ `);else process.stdout.write(`${A}(default - not explicitly set)${K}
274
+ `);return process.stdout.write(`
275
+ `),process.stdout.write(`Switch provider: ${G}loki provider set <name>${K}
276
+ `),process.stdout.write(`Available: ${G}loki provider list${K}
277
+ `),0}async function F0(){let Q=D1()||process.env.LOKI_PROVIDER||"claude";process.stdout.write(`${F}Available Providers${K}
278
+ `),process.stdout.write(`
279
+ `);let $=await Promise.all(T0.map(async(H)=>[H,await R(H)!==null])),X=new Map;for(let[H,W]of $)X.set(H,W?`${x}installed${K}`:`${S}not installed${K}`);let Z=[["claude","claude - Claude Code (Anthropic) "],["codex","codex - Codex CLI (OpenAI) "],["gemini","gemini - Gemini CLI (Google) "],["cline","cline - Cline (multi-provider) "],["aider","aider - Aider (terminal pair prog) "]];for(let[H,W]of Z){let B=Q===H?` ${G}(current)${K}`:"";process.stdout.write(` ${W} ${X.get(H)}${B}
280
+ `)}return process.stdout.write(`
281
+ `),process.stdout.write(`Set provider: ${G}loki provider set <name>${K}
282
+ `),0}function L0(){return process.stdout.write(`${F}Loki Mode Provider Management${K}
283
+ `),process.stdout.write(`
284
+ `),process.stdout.write(`Usage: loki provider <command>
285
+ `),process.stdout.write(`
286
+ `),process.stdout.write(`Commands:
287
+ `),process.stdout.write(` show Show current provider (default)
288
+ `),process.stdout.write(` set Set provider for this project
289
+ `),process.stdout.write(` list List available providers
290
+ `),process.stdout.write(` info Show provider details
291
+ `),process.stdout.write(` models Show resolved model configuration for all providers
292
+ `),process.stdout.write(`
293
+ `),process.stdout.write(`Examples:
294
+ `),process.stdout.write(` loki provider show
295
+ `),process.stdout.write(` loki provider set claude
296
+ `),process.stdout.write(` loki provider set codex
297
+ `),process.stdout.write(` loki provider list
298
+ `),process.stdout.write(` loki provider info gemini
299
+ `),process.stdout.write(` loki provider models
300
+ `),0}async function E1(z){let Q=z[0]??"show",$=z.slice(1);switch(Q){case"show":case"current":return w0($[0]);case"list":return F0();case"set":case"info":case"models":return x0(["provider",Q,...$]);default:return L0()}}async function x0(z){let{run:Q}=await Promise.resolve().then(() => (m(),S1)),{resolve:$}=await import("path"),{REPO_ROOT:X}=await Promise.resolve().then(() => (h(),P1)),Z=$(X,"autonomy","loki"),H=await Q([Z,...z],{env:{LOKI_LEGACY_BASH:"1"},timeoutMs:3600000});return process.stdout.write(H.stdout),process.stderr.write(H.stderr),H.exitCode}p();h();Q1();m();import{existsSync as b1,readFileSync as k0}from"fs";import{resolve as c}from"path";import{mkdir as R0}from"fs/promises";var i=c(B1(),"learnings");function V1(z){if(!b1(z))return 0;try{let Q=k0(z,"utf-8"),$=0;for(let X of Q.split(`
301
+ `))if(X.includes('"description"'))$++;return $}catch{return 0}}async function S0(){await R0(i,{recursive:!0});let z=V1(c(i,"patterns.jsonl")),Q=V1(c(i,"mistakes.jsonl")),$=V1(c(i,"successes.jsonl"));return process.stdout.write(`${F}Cross-Project Learnings${K}
302
+ `),process.stdout.write(`
303
+ `),process.stdout.write(` Patterns: ${x}${z}${K}
304
+ `),process.stdout.write(` Mistakes: ${_}${Q}${K}
305
+ `),process.stdout.write(` Successes: ${G}${$}${K}
306
+ `),process.stdout.write(`
307
+ `),process.stdout.write(`Location: ${i}
308
+ `),process.stdout.write(`
309
+ `),process.stdout.write(`Use 'loki memory show <type>' to view entries
310
+ `),0}async function D0(z){if(z){let X=`
311
+ try:
312
+ from memory.layers import IndexLayer
313
+ layer = IndexLayer('.loki/memory')
314
+ layer.update([])
315
+ print('Index rebuilt')
316
+ except ImportError:
317
+ print('Error: memory.layers module not found')
318
+ except Exception as e:
319
+ print(f'Error: {e}')
320
+ `.trim(),Z=await s(X,{cwd:y});return process.stdout.write(Z.stdout),0}let Q=c(E(),"memory","index.json");if(!b1(Q))return process.stdout.write(`No index found
321
+ `),0;let $=await s(`import json, sys; sys.stdout.write(json.dumps(json.load(open(${JSON.stringify(Q)})), indent=4) + "\\n")`);if($.exitCode!==0)return process.stdout.write(`No index found
322
+ `),0;return process.stdout.write($.stdout),0}async function N1(z){switch(z[0]??"list"){case"list":case"ls":return S0();case"index":return D0(z[1]==="rebuild");default:{let $=c(y,"autonomy","loki"),X=await I([$,"memory",...z],{env:{LOKI_LEGACY_BASH:"1"},timeoutMs:3600000});return process.stdout.write(X.stdout),process.stderr.write(X.stderr),X.exitCode}}}var $0=`Loki Mode (TypeScript port, Phase 2 of bash->Bun migration)
323
+
324
+ Usage: loki <command> [args...]
325
+
326
+ Phase 2 ported (Bun-native, fast):
327
+ version Print Loki Mode version
328
+ status [--json] Show current orchestrator status
329
+ stats [--json] [--efficiency] Session statistics
330
+ provider show [name] Show current provider
331
+ provider list List available providers and install status
332
+ memory list Cross-project learnings counts
333
+ memory index [rebuild] Show or rebuild memory index
334
+ doctor [--json] System prerequisites health check
335
+
336
+ All other commands fall through to the bash CLI (autonomy/loki).
337
+ Set LOKI_LEGACY_BASH=1 to force the bash CLI for every command.
338
+ `;async function Q3(z){let Q=z[0],$=z.slice(1);switch(Q){case void 0:case"help":case"--help":case"-h":return process.stdout.write($0),0;case"version":case"--version":case"-v":return R1();case"provider":return E1($);case"memory":return N1($);case"status":{let{runStatus:X}=await Promise.resolve().then(() => (m1(),v1));return X($)}case"stats":{let{runStats:X}=await Promise.resolve().then(() => (d1(),l1));return X($)}case"doctor":{let{runDoctor:X}=await Promise.resolve().then(() => (z0(),e1));return X($)}default:return process.stderr.write(`Unknown command: ${Q}
339
+ `),process.stderr.write($0),2}}process.on("SIGINT",()=>process.exit(130));process.on("SIGTERM",()=>process.exit(143));var X3=await Q3(Bun.argv.slice(2));process.exit(X3);
340
+
341
+ //# debugId=7F3CF7B4F1CA56A864756E2164756E21
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@loki-mode/orchestrator",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Loki Mode TypeScript orchestrator (Bun runtime). Parallel implementation alongside autonomy/run.sh during Phase 1 of the bash->Bun migration. See docs/architecture/ADR-001-runtime-migration.md.",
5
+ "private": true,
6
+ "type": "module",
7
+ "engines": {
8
+ "bun": ">=1.3.0"
9
+ },
10
+ "scripts": {
11
+ "version": "bun src/cli.ts version",
12
+ "typecheck": "bun run --bun tsc --noEmit",
13
+ "test": "bun test",
14
+ "bench": "bun run scripts/bench.ts",
15
+ "build": "bun run scripts/build.ts",
16
+ "build:binary": "bun build --compile src/cli.ts --outfile=dist/loki-ts"
17
+ },
18
+ "devDependencies": {
19
+ "@types/bun": "latest",
20
+ "typescript": "^5.6.0"
21
+ }
22
+ }
package/mcp/__init__.py CHANGED
@@ -57,4 +57,4 @@ try:
57
57
  except ImportError:
58
58
  __all__ = ['mcp']
59
59
 
60
- __version__ = '7.2.0'
60
+ __version__ = '7.4.8'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loki-mode",
3
- "version": "7.2.0",
3
+ "version": "7.4.8",
4
4
  "description": "Loki Mode by Autonomi - Multi-agent autonomous startup system for Claude Code, Codex CLI, and Gemini CLI",
5
5
  "keywords": [
6
6
  "agent",
@@ -59,7 +59,7 @@
59
59
  "license": "BUSL-1.1",
60
60
  "author": "Lokesh",
61
61
  "bin": {
62
- "loki": "autonomy/loki",
62
+ "loki": "bin/loki",
63
63
  "loki-mode": "bin/loki-mode.js"
64
64
  },
65
65
  "files": [
@@ -72,6 +72,9 @@
72
72
  "references/",
73
73
  "docs/**/*.md",
74
74
  "bin/",
75
+ "bin/loki",
76
+ "loki-ts/dist/",
77
+ "loki-ts/package.json",
75
78
  "api/",
76
79
  "events/",
77
80
  "memory/",
@@ -100,7 +103,7 @@
100
103
  ],
101
104
  "scripts": {
102
105
  "postinstall": "node bin/postinstall.js",
103
- "prepack": "find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null; find . -name '*.pyc' -delete 2>/dev/null; true",
106
+ "prepack": "find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null; find . -name '*.pyc' -delete 2>/dev/null; if command -v bun >/dev/null 2>&1; then (cd loki-ts && bun install --production && bun run build) || echo 'WARN: loki-ts build failed, using existing dist if present'; else echo 'WARN: bun not on PATH, skipping loki-ts build (using committed dist if present)'; fi; true",
104
107
  "prepublishOnly": "cd dashboard-ui && npm ci && npm run build:all",
105
108
  "test": "bash -n autonomy/run.sh && bash -n autonomy/loki && bash -n autonomy/completion-council.sh && bash -n autonomy/app-runner.sh && bash -n autonomy/prd-checklist.sh && bash -n autonomy/playwright-verify.sh && node --test tests/protocols/*.test.js && node --test tests/protocols/a2a/*.test.js && node --test tests/observability/*.test.js && node --test tests/policies/*.test.js && node --test tests/audit/*.test.js && node --test tests/integrations/*.test.js && node --test tests/integrations/jira/*.test.js && node --test tests/integrations/github/*.test.js && node --test tests/integrations/slack/*.test.js && bash tests/managed_memory/test_flag_matrix.sh && bash tests/managed_memory/test_sdk_isolation.sh && bash tests/managed_memory/test_kill_switch.sh && python3 -m unittest tests.managed_memory.test_shadow_write_mock tests.managed_memory.test_retrieve_mock && echo 'All checks passed'",
106
109
  "test:visual": "node --experimental-vm-modules node_modules/jest/bin/jest.js dashboard-ui/tests/visual-regression.test.js",
@@ -122,6 +125,9 @@
122
125
  "@opentelemetry/sdk-trace-base": "^1.30.0",
123
126
  "@opentelemetry/exporter-trace-otlp-http": "^0.57.0"
124
127
  },
128
+ "overrides": {
129
+ "protobufjs": ">=7.5.5"
130
+ },
125
131
  "devDependencies": {
126
132
  "@types/node": "^25.2.0",
127
133
  "jest": "^29.7.0",