PRAANA Architecture
Some sections may lag later releases.
PRAANA is a single-process TypeScript CLI coding agent built around two memory systems:
- Adaptive Context — within-session working memory
- File Memory — deliberately saved cross-session knowledge in scoped markdown files
No daemon, no RPC server, no multi-process coordination.
Directory Structure
src/
main.ts — CLI entry point, TTY guard, slash commands, OpenTUI+Solid launch, headless `run` dispatch
headless-run.ts — Non-TTY one-shot runner (`praana run`) for Harbor / CI / scripts
headless-usage.ts — Export turn usage into Harbor AgentContext
turn.ts — Per-turn orchestration (prompt → LLM → concurrent tools → banners)
session.ts — Session lifecycle (create/resume/end) & memory init
hooks/ — Internal turn-loop hook registry + builtin plan-mode / validate / risk / circuit / write-path / LSP / verify / redact handlers
validate/ — Always-on pre-validation + error enrichment (issue #577)
risk/ — Risk-tier classify + confirm lock (issue #580)
circuit/ — Loop gate + headless token/time wrap-up (issue #578)
redact/ — Always-on secret detectors for tool results and logged tool-call args (issue #579)
verify/ — Post-edit syntax, scoped tsc, reverse-import test-impact (issue #576; `[verify]`)
compile-classic.ts — Classic-mode prompt assembly (full verbatim history)
compiler.ts — Legacy budget-band compiler (unit tests only)
state-graph.ts — Tiered state management (active/soft/hard) & two-pass auto-hydrate (substring + BM25)
state-graph-checkpoint.ts — O(1) resume: persist/restore StateGraph snapshot (tiers, touchedTurn) after each turn
event-log.ts — Append-only JSONL event persistence with fsyncSync durability; in-memory parse cache (re-reads disk only on mtime/size change)
logger.ts — Daily-rotated app + session logs via pino-roll; atomic current.log symlink for safe concurrent-session startup
token-estimate.ts — Unicode-aware token heuristic (Latin/CJK/emoji/ZWJ); canonical shared estimator for all budget calculations
context-pressure.ts — Density-weighted effective-token accounting; raw-token safety net; resolves compaction config
cosine-similarity.ts — Cosine similarity for Float32Array embedding vectors; shared by context scoring and memory dedup
hash.ts — SHA-256 hashing utility; shared by session scope construction and skill scope keys
model-resolver.ts — /model parsing and provider+model resolution
provider-catalog.ts — live model catalogs (HTTP `/models` + Bedrock control plane) + 6h disk cache
bedrock/ — Amazon Bedrock region, credentials, live chat-model catalog helpers
credentials.ts — Credential store (`~/.praana/credentials.json`); key resolution
user-settings.ts — Persistent UX prefs (`~/.praana/settings.json`) applied as session defaults
update/ — Version check cache, install-kind detect, `praana upgrade` / auto_update
llm.ts / llm/ — Native model building and protocol drivers; first-party OpenAI GPT-5.4+ (5.x) / GPT-6 use Responses, older ids and Chat overrides use Chat Completions
config.ts — Multi-source JSON/TOML config loading & deep-merge (allowlists append-merge)
types.ts — Core shared TypeScript types
ui.ts — CLI output formatting, banners, and text colors
ui/tui/ — OpenTUI + Solid terminal shell (prompt, transcript, chrome, overlays, setup, login, download consent)
native/ — Lazy loader for `@praana/natives` (npm package, or `praana-natives.node` beside the binary); soft-fails when the addon is missing
lsp/ — JSON-RPC Language Server client and manager (stdio; crash restart, multi-root); opt-in via `[lsp]`
utils/
bm25.ts — Shared BM25 tokenization, scoring, and corpus statistics
context-engine/
index.ts — ContextEngine facade (store, ledger, extraction, checkpoint, telemetry, workflow patterns)
types.ts — Engine-level interfaces; WorkflowPattern
artifact-store.ts — Content-addressed blob store; stub cards by default, distilled summaries stored for stats (never rendered in prompts)
turn-ledger.ts — Append-only typed turn records with BM25 search
distiller.ts — DistillerRegistry, sync/deferred dispatch, intensity selection
classify.ts — Fast regex-based content-type classification
summarize.ts — Stub card builder (buildArtifactCard); legacy summarizeGeneric kept for reference; re-exports estimateTokens from token-estimate.ts
extraction.ts — Post-turn deterministic extraction (TurnDigest, activity, errors)
turn-digest.ts — TurnDigest extraction and state-graph diffing
activity-log.ts — ActivityEntry derivation and rolling buffer
error-tracker.ts — Open error tracking and test-pass/fail detection
checkpoint.ts — SessionCheckpoint reconciliation, rendering, replay from digests
state-snapshot.ts — StateGraph snapshot and diff for decision/constraint extraction
scoring.ts — Context-unit scoring (pin + recency + max(BM25, semantic) + hydrate boost) and budget selection
embedding-cache.ts — Per-turn embedding cache; precomputes vectors for all context units concurrently; invalidated when unit set changes between turns
engine-compiler.ts — Multi-resolution budget-band compiler; injects workflow context section when matching patterns exist
bm25.ts — Re-exports shared BM25 utilities for context-unit and turn-search scoring
density.ts — SectionDensityKind → weight table; densityWeight() used by engine-compiler for weighted pressure
turn-recorder.ts — Per-turn event recording for the turn ledger
event-lineage.ts — Trace artifacts back to producing turns, decisions, files
telemetry.ts — Per-session telemetry: pressure events, retrieval rates, distiller savings
workflow-tracker.ts — Workflow pattern tracking: extract tool sequences + artifact types, persist to workflow_patterns table, render compact Workflow Context section
db.ts — SQLite schema for all engine tables: artifacts, turns, checkpoint, scorecard, workflow_patterns
distillers/
git-diff.ts — Diff hunk compaction with context reduction
npm-test.ts — Test output: failure detail + summary lines, per-line 4K char cap, output ≤ input invariant
tsc-errors.ts — Build error deduplication
rg-results.ts — Search result dedup and top-k
generic.ts — GenericDistiller (prose/code/json head-tail + JSON compaction) and LogDistiller (log template mining); summaries feed stats, not cards
tools/
index.ts — Tool registry (all tool definitions combined)
tool-def.ts — Type helper for defining tools
system.ts — shell, read_file, write_file, edit_file, read_and_summarize, batch_write, batch_edit
search-code.ts — search_code: native grep via @praana/natives (file:line:column matches with context)
find-files.ts — find_files: fuzzy/glob path search via @praana/natives
code-intel.ts — code_* tree-sitter tools (issue #418 Phase 1)
lsp.ts — lsp_diagnostics / lsp_format / hover / completions / definition / references / code actions (issue #418 Phases 2–4; client in `src/lsp/`)
run-tests.ts — run_tests: structured test runner with per-language adapters in `test-runner/` (issue #589)
git.ts — git_status / git_diff / git_commit: structured git tools (issue #432; first #533 harness ship)
knowledge.ts — retrieve_artifact, context_summary, search_turn_events, event_lineage
memory.ts — Adaptive Context state-graph tools (tasks, decisions, constraints, notes)
git-context.ts — shared getGitContext / findGitRoot / findGitBranch helpers
file-memory/ — Markdown file store, scoped paths, index, recall and tools
memory/ — Embedder backends (transformers, Ollama) and download consent; SQLite memory.db remains in use by context-engine and skill stats
skills/
index.ts — SkillRuntime: discovery, load tracking, telemetry (engine mode); buildSkillMetadataCatalog with usefulness-ranked ordering
skill-stats-store.ts — Cross-session skill effectiveness: loadUsefulness (dual-scope), flush (boost/decay), co-occurrence recording
types.ts — SkillRecord (with scope), LoadedSkill (with used flag), SkillEffect, telemetry types
Harbor / Terminal-Bench installed-agent adapter lives under harbor_eval/ (runs praana run --incognito inside the task container).
Logging
PRAANA writes two rolling logs via pino-roll:
- App log:
~/.praana/logs/praana.YYYY-MM-DD.N.log, with acurrent.logsymlink fortail -fconvenience. - Session system log:
~/.praana/sessions/<id>/system.YYYY-MM-DD.N.log, also exposed viacurrent.log.
Because current.log lives in a shared directory, two simultaneous sessions could collide on its creation. The logger creates the symlink itself with symlink: false in pino-roll and an atomic temp-file + renameSync replacement, so concurrent initAppLogFile() calls never hit the EEXIST TOCTOU race from pino-roll's default symlink handling. The symlink is refreshed on every log roll so it stays pointed at the active file. If the OS forbids symlinks (Windows without Developer Mode or an elevated token, EPERM), current.log is skipped and startup continues — rotating files still write.
Runtime Architecture (Turn Flow)
User input
→ main.ts interactive TTY entrypoint
→ runTurn(session, input) in turn.ts
1) append user_message event
2) select mode:
Engine: context_engine.enabled=true AND ContextEngine initialized (default)
Classic: context engine disabled, or enabled but init failed
3) [engine only] auto-hydrate matching peripheral state (two-pass: substring keyword + BM25 relevance)
4) [engine only] capture StateGraph snapshot (for post-turn diff)
5) [engine only] ingest tool results through distillers; classic passes through
6) compile prompt:
Engine: compileEngineWithMetrics (budget bands + scored units + checkpoint)
Classic: compileClassicWithMetrics (system frame + skill catalog + full history)
7) piStream() with tools (tool set varies by mode — see Tools)
8) log tool_call / tool_result + context_action events
9) append agent_message event
10) [engine only] flush deferred distillations, append turn record to ledger
11) [engine only] extract TurnDigest (deterministic, no LLM)
12) [engine only] reconcile SessionCheckpoint from digest
13) increment turn count
14) [engine only] apply tier demotion rules + cleanupStaleSkills()
15) persist state graph checkpoint (session.persistStateGraphCheckpoint())
16) print per-turn memory/prompt banner
Session Boundary Flow
SESSION START:
Session.create()
→ init EventLog + StateGraph
→ initialize file memory store (if enabled)
→ build and cache the capped global/project memory index once for prompt injection
SESSION RESUME:
Session.resume(sessionId)
→ load state_graph_checkpoint.json if present → O(1) StateGraph restore (tiers + touchedTurn preserved)
→ replay only context_action events that occurred after the checkpoint's last_event_id
→ restore model override from the last model_override system_note
→ re-init file memory and build the index once
SESSION END:
Session.end(reason, transcriptEvents)
→ close session resources and event log
→ no summarizer or automatic promotion into file memory
State Model (Adaptive Context)
Defined in src/types.ts:
export type StateObjectKind = "task" | "decision" | "constraint" | "note";
export type StateTier = "active" | "soft" | "hard";
export interface StateObject {
id: string; // ULID
kind: StateObjectKind;
tier: StateTier;
payload: StatePayload; // TaskPayload | DecisionPayload | ConstraintPayload | NotePayload
created: number; // unix ms
updated: number; // unix ms
lastTouched: number; // unix ms
}
Tier Behavior in Prompts
| Tier | Prompt Representation | When |
|---|---|---|
| Active | Full payload | Current working set |
| Soft | Summarized one-liner | Recently idle |
| Hard | Minimal anchor (ID) | Older context, available via hydrate |
Tier Demotion
Managed dynamically after each turn in src/turn.ts:
active→softafteridle_soft_after_turns(default: 20 turns since last touched)active/soft→hardafteridle_hard_after_turns(default: 50 turns since last touched)
Auto-Hydration
Before a turn prompt is compiled, stateGraph.autoHydrate(userInput) runs two passes against peripheral state objects:
- Substring keyword match — extracts keywords (alphanumeric strings $\ge 3$ characters, filtering common English stop words) and matches them against the searchable text representation of peripheral objects. Fast and catches exact references.
- BM25 relevance — scores remaining peripheral objects with
bm25Relevance(query, text). Objects scoring $\ge 0.15$ (theBM25_HYDRATE_THRESHOLD) are promoted even when no substring keywords matched. This catches fuzzy overlap that substring matching misses — for example, when a user mentions "S3 upload" and a peripheral object about "AWS bucket" gets promoted.
Returns AutoHydrateResult[] with { id, text, method } (method is "substring" or "bm25"). The text field is passed through to context-unit scoring for hydrate_boost calculation (see Scoring below). Promotions are logged as context_action events with reason: "auto_hydrate" and hydrate_method: "substring" | "bm25".
Event Log
Location: ~/.praana/sessions/<session_id>/events.jsonl
In-memory cache: After the first read, EventLog maintains a parsed event index in memory. On every subsequent readAll, readLast, search, or replayContextActions call it checks mtime and size via statSync; if unchanged it returns the cached array directly — no JSONL re-parsing. append() updates the cache inline before writing to disk, so the cache never drifts. getLastEvent() is O(1) direct cache access.
Each line is a single JSON line representing an Event:
user_messageagent_messagetool_calltool_resultcontext_actionsystem_note
Writing uses writeSync followed by fsyncSync to guarantee durable persistence on every event. Rebuilding state on session resume replays context_action events.
Agents use search_transcript for BM25 + case-insensitive substring search over canonical session records, including compacted/stubbed turns, or full/ranged content and neighbors by ID. It searches the current reset epoch by default; include_previous_resets=true permits access across earlier /clear epochs. Search excludes assistant messages calling search_transcript and search_transcript results (ID fetch still works). Artifact-backed results use logged tool output paired by tool and call ID in the same reset epoch and retain artifactId; artifact-only records may still require retrieve_artifact for the original bytes. Canonical call IDs are unique per session: the writer keeps provider IDs when they are non-empty and unused and synthesizes canon_<turn>_<n> otherwise (live turns and provider requests keep the provider's IDs), so artifact pairing is skipped for synthesized IDs. search_session_log provides keyword AND/OR search over other session events and is the fallback for legacy sessions without a canonical transcript. Neither tool is recall, which queries cross-session file memories.
Compiler
PRAANA has two runtime compile paths. Selection happens in turn.ts:
const useEngineCompiler = contextEngineEnabled && !!session.contextEngine;
const classicMode = !useEngineCompiler;
- Engine mode —
context_engine.enabled = trueandContextEngineinitialized successfully at session start. - Classic mode — engine disabled, or enabled but initialization failed (falls back to full classic behaviour).
src/compiler.ts (compileWithMetrics) is retained for unit tests only; it is not used at runtime.
Engine mode (context_engine.enabled = true, engine initialized)
src/context-engine/engine-compiler.ts constructs a multi-resolution prompt from budget bands:
- Band 1 (always): System frame, AGENTS.md, skills — existing allocation.
- Band 2 (always): Active user request + last 2 full turns verbatim — ~3000 tokens.
- Band 3 (always): SessionCheckpoint (pinned) — ~2000 tokens. Reconciled deterministically from
TurnDigestafter each turn. Sections: active request, session narrative, plan history, constraints, decisions (with retained rationale), files, findings, errors, activity. See Session Checkpoint below. - Band 4 (scored): Fact cards, artifact cards, activity entries — ~3000 tokens.
- Band 5 (scored): Older turn digests — ~2000 tokens.
- Band 6 (remaining): File memory index, low-priority state — remainder.
Context units are scored with a 5-term model: pin_boost × W_pin + recency(age) × W_recency + max(BM25 × W_relevance, semantic_similarity × W_semantic) + hydrate_boost × W_hydrate. BM25 handles exact keyword overlap; embedding cosine similarity handles semantic paraphrases (e.g. "auth middleware" vs "authentication handler"). The effective relevance term is max(bm25, semantic) so either signal can win. The hydrate boost is the maximum bm25Relevance(ht, unitContent) across all auto-hydrated object texts — it gives a lift to context units (e.g. older turn digests) that discuss the same objects the user just implicitly referenced. Default weights: w_pin=1.0, w_recency=0.5, w_relevance=0.3, w_semantic=0.3, w_hydrate_boost=0.2. Embeddings are precomputed per compile pass and cached in a session-scoped LRU cache; when the embedder is unavailable or fails, scoring falls back to BM25-only.
Pressure monitoring uses density-weighted effective tokens: contextPressure = weightedTokens / usableBudget. Each section kind has a hardcoded weight in src/context-engine/density.ts (decisions/constraints/plans = 1.0; open errors = 0.8; narrative/file/peripheral = 0.6; verbatim turns = 0.9; turn digests/artifacts = 0.4; findings/activity/fixed errors = 0.25). Low-density filler counts less toward pressure so a prompt full of error traces does not trigger compaction as aggressively as one full of architectural decisions. >0.70 triggers compaction (drop older digests, tighten checkpoint findings/activity budgets). >0.85 triggers emergency (keep checkpoint decisions/constraints/plans/open errors only — omit findings, activity, fixed errors — plus last 2 verbatim turns and current artifact cards). Raw-token safety net: when estimated raw prompt tokens exceed the usable budget or raw fill exceeds emergency_at, emergency mode is forced even if weighted pressure is lower. Section token caps (findings 300, scored bands 3000/2000) bound worst-case raw size; /stats shows both raw and weighted fill.
Score logging: in debug mode, scores.jsonl records every context unit's score breakdown per turn. Inspect via /why <unit-id>.
Session Checkpoint
src/context-engine/checkpoint.ts maintains a structured within-session summary that survives when turns scroll out of the verbatim window (turns 7+). It is reconciled from TurnDigest data — never by the LLM — to prevent drift.
| Section | Behaviour |
|---|---|
| Active request | Latest user intent (overwritten each turn) |
| Session narrative | Rolling prose from meaningful turns (decisions, constraints, errors, file writes, intent changes). Max 20 entries, 400-token render budget |
| Plan | Current plan + superseded one-liners with completion hints. Extracted from assistant step lists via pattern matching. 400-token budget |
| Constraints | Append-only, never dropped. Includes implicit constraints auto-extracted from user messages |
| Decisions | Summary + rationale; compact after 10 idle turns but rationale is never dropped. 800-token budget |
| Files in play | Evicted after 10 idle turns |
| Findings | Rolling artifact refs, oldest evicted at 30 entries. 300-token budget |
| Errors | Open errors full detail; fixed errors one-liners |
| Activity | Rolling 15 entries from activity log |
Implicit knowledge capture has two layers: (1) the system frame nudges the agent to call add_constraint / add_note for preferences and corrections — this is the primary mechanism because the LLM is the language-understanding component, not regex; (2) extractImplicitConstraints() in turn-digest.ts is a minimal safety net that only captures the syntactically unambiguous "not X, Y" correction pattern. Patterns like "let's use", "we use", "I prefer", "how about" are NOT regex-matched because natural language is too varied — those are the LLM's responsibility via the nudge.
Classic mode (compile-classic.ts)
When classic mode is active, src/compile-classic.ts builds a flat prompt with no token-budget truncation and no Adaptive Context sections:
- System frame — cwd, session ID, tool descriptions, AGENTS.md project context, skills guidance (use
load_skillwhen relevant). - Skills catalog — name + description only;
load_skill(skill_id)loads full body on demand. No pre-injected bodies, no residency tiers. - File Memory — startup index (if enabled).
- Conversation history — full verbatim event log (
readAll()), excludingcontext_actionandsystem_note. Tool results are not truncated. - Current input — latest user message.
Runtime differences from engine mode:
| Engine mode | Classic mode | |
|---|---|---|
| Compiler | compileEngineWithMetrics |
compileClassicWithMetrics |
| History | Budget bands + checkpoint + scored digests | Full verbatim log |
| StateGraph tools | Available | Hidden from tool list |
| Engine tools | Available | Hidden |
| SkillRuntime | Load tracker + eviction (engine only) | Not present (plain agent) |
| Auto-hydrate / tier demotion | Yes | Skipped |
| TurnDigest / checkpoint | Yes | Skipped |
/why scores |
Available (debug) | N/A |
Classic mode uses a growing transcript with no working-memory tiering and no automatic compaction. Set measurement_mode = true to write engine telemetry while running classic mode (development/debug only).
Legacy compiler (compiler.ts)
The original 5-section budget-band allocator (compileWithMetrics) remains in the tree for regression tests only. It applied per-section token budgets, truncated recent turns, and included Adaptive Context active/peripheral sections. Runtime no longer uses this path.
Tools
Defined in src/tools/ using Zod 4 schemas and converted to JSON Schema (draft-07) with Zod's built-in z.toJSONSchema (normalizeToolParameters in src/turn.ts): objects reject unknown properties and integers carry no implicit bounds. tests/fixtures/tool-parameter-schemas.json pins the exact schema the model sees for every tool. The registered tool set depends on compile mode (describeTools({ contextEngineEnabled, classicMode })).
Shared tools (classic and engine mode)
search_session_log(query, kinds?, limit?)— keyword search over the current session event logsearch_transcript(query?, id?, include_previous_resets?, limit?, context_messages?, offset?, max_chars?)— BM25 + case-insensitive substring search over canonical session records, including compacted/stubbed turns; current reset epoch by default, withinclude_previous_resets=truefor cross-/clearaccess. Full/ranged content and neighbors by ID; search excludes assistant messages callingsearch_transcriptandsearch_transcriptresults (ID fetch still works). Sessions without a canonical transcript must usesearch_session_loginstead. Artifact-backed results use logged output paired by tool and call ID in the same reset epoch and retainartifactId.
System Tools (src/tools/system.ts)
shell(command, timeout?)— executes a bash command with timeout (default: 30s); optional sandbox allowlist via[shell]read_file(path, offset?, limit?)— reads a file with optional positive-integer pagination limits; each call is capped at the smaller of 2,000 lines and a quarter of the model's context window in estimated tokens, long lines are cut at 2,000 characters, and the result always carriestotal_lines,returned_lines(the number of lines in this result) plustruncated/notewith theoffsetfor the next part when anything was cutread_and_summarize(path)— structured file overview (size, line count, head/tail preview)write_file(path, content)— writes or overwrites a file (creates parent directories)edit_file(path, oldText, newText)— replaces text based on exact, unique matching (optional diff preview)batch_write(files[])/batch_edit(edits[])— multi-file create/replace in one turnweb_fetch(url, focus?)— GET a public http(s) URL and return readable text (untrusted data; private networks blocked)
Shell spawn uses node:child_process with detached (new process group on POSIX) and process.kill(-pid) plus SIGTERM→SIGKILL settle so orphaned children like find cannot hang the session. Bun.Terminal (Bun.spawn({ terminal }), Bun ≥1.3.5 / improved in 1.4) is a suitable future primitive for a PTY-backed interactive shell (vim, pagers, password prompts) without node-pty. It is not a drop-in replacement for the current spawn path: it does not provide equivalent process-tree cancellation, and it is not a UI replacement for OpenTUI. Do not switch the shell tool to Bun.spawn/Bun.Terminal until tree-kill semantics match.
Code Search (src/tools/search-code.ts)
search_code(pattern, path?, globs?, max_results?, ...)— native grep via@praana/natives(file:line:column matches)find_files(pattern, mode?, path?, max_results?, ...)— fuzzy/glob path search via@praana/nativescode_*— tree-sitter symbol/import/parse tools (Phase 1 of #418; optional native addon; availability probed at session start and shown in banner//stats/system frame — see Native Addon)lsp_diagnostics/lsp_format/lsp_hover/lsp_completions/lsp_definition/lsp_references/lsp_code_actions/lsp_apply_code_action— opt-in LSP client against configured external servers (Phases 2–4 of #418;[lsp]config). Dead servers restart with backoff (max 3 per root); JS workspace members and nested git repos get separate processes (cap 8).code_*remains the fast name-based path.- Post-edit verification (issue #576;
[verify], default off) attaches averifypayload on successfulwrite_file/edit_file/batch_*: tree-sitter syntax, scopedtsc --noEmit, and reverse-importbun testselection. No new tools. Never runs afterlsp_format/lsp_apply_code_action. Soft-fail never flipsok: true.
Git Tools (src/tools/git.ts, issues #432 + #586)
git_status()— structured working-tree status (branch, ahead/behind, staged/unstaged/untracked/conflicted)git_diff(staged?, path?, context?)— structured diff (files, hunks, insertion/deletion stats); large output becomes a"diff"artifact with a stub cardgit_commit(message, paths?, all?)— commit with guardrails (blocked in plan mode; optional TTY confirm viaedit.confirm; does not push)git_branches(base?, include_remote?, limit?)— branch list with last commit + ahead/behind vs base (read-only; allowed in plan mode)git_log(branch?, path?, max_count?, since?)— recent history with structured commits (read-only; allowed in plan mode)
Shared helpers live in src/git-context.ts. Structured git tools (#432 + #586) are the harness's git surface under epic #533; design notes are kept internally. Prompt size control for large diffs is lossless artifact + stub card + retrieve_artifact — not a prompt-embedded git-diff distiller.
File Memory Tools (src/file-memory/tools.ts)
remember(scope, type, name, description, body)— deliberately save or update a memoryrecall(query?, name?, scope?)— search both scopes or look up a nameforget_memory(name, scope?)— hard-delete a named memory
Adaptive Context Tools (src/tools/memory.ts — engine mode only)
create_task(title, description?)— creates a task in working memorycomplete_task(id)— marks a task as done, auto-demoting it to thesofttierretract_task(id)— tombstones a state object (any kind)add_constraint(text)— records a constraint in working memorydecide(summary, rationale)— records a decision in working memoryadd_note(text)— records a note in working memorysoft_unload(id)/hard_unload(id)/hydrate(id)— tier managementlist_state()— lists all state objects with their IDs, kinds, tiers, and summaries
Context Engine Tools (src/tools/knowledge.ts — engine mode only)
retrieve_artifact(id, options?)— retrieves raw artifact content with optional grep/line/jsonPath selectorscontext_summary()— current checkpoint + open errors + recent activity + session statssearch_turn_events(query)— BM25 search over turn ledgerevent_lineage(artifactId)— trace artifact → producing turn → decisions → related artifacts
File Memory
src/file-memory/ stores markdown files with frontmatter in global ~/.praana/memory and project ~/.praana/projects/<key>/memory directories. Project keys isolate project memories; global memories are shared across projects. At start or resume the store builds a capped index of the newest memories once and injects it into the prompt; recall searches both scopes or reads a named memory. The model saves explicitly using remember and removes with forget_memory. Notes, constraints, decisions and artifacts are not automatically promoted, and session end does not summarize the transcript into memory. Incognito permits reads but blocks writes and deletions. The context engine and skill statistics still use SQLite independently of file memory.
Skill Effectiveness Feedback Loop
Source: src/skills/skill-stats-store.ts, src/skills/skill-stats-db.ts
At session start, SkillStatsStore.loadUsefulness() performs a dual-scope read from memory.db's skill_stats(skill_id, scope, usefulness, load_count, used_count, last_loaded_at) table — global skills first, project overrides on collision — and returns a Map<string, number> used to sort the skill catalog by descending usefulness. At session end (engine mode only), flush() updates each skill's score:
- Boost (α = 0.15): skill was loaded and
markResidentSkillsUsed()fired after a non-load_skilltool ran. - Decay (β = 0.05): skill was loaded but never used.
- No change: skill was never loaded this session.
Co-occurrence pairs (skills resident together during a used turn) are recorded to skill_cooccurrence(scope, skill_a, skill_b, count) for a future ranking consumer (#505). The scope field (context:<hash(gitRoot)> for project skills, "" for global) prevents cross-project bleed — a project's custom skill score does not pollute scores in other repos.
Workflow Pattern Tracking
Source: src/context-engine/workflow-tracker.ts, src/context-engine/db.ts
After each session ends, persistSessionPattern() extracts:
- Tool sequence — globally-deduplicated first-occurrence-ordered list of tools called this session.
- Artifact types — frequency-sorted list of artifact kind labels (e.g.
git_diff,tsc_errors,shell_output).
Both are stored in workflow_patterns(task_type, tool_sequence_json, artifact_types_json, hit_count, last_seen_at) keyed by hash(taskType + toolSequence + artifactTypes). Rows older than 30 days are pruned via pruneExpiredPatterns() inside runShutdownMaintenance().
At compile time, renderWorkflowContext() queries patterns matching the current taskType, selects the top-N by hit_count, and renders a compact Workflow Context section injected into the prompt just before the session checkpoint. This gives the engine a prior over which tools and artifact types are likely to appear — without adding it to the scored pool. Patterns for a different task type are never included, so a coding session's workflow history does not bleed into a debugging session.
The rendered section also surfaces a typical lean tool sequence from the highest-hit pattern that includes at least one mutating tool (e.g. edit_file, write_file, shell). Read-heavy patterns that contain read_file but no mutating tools are treated as exploratory thrashing and are not promoted; when such patterns are present, an avoid note reminds the agent to avoid read-heavy exploratory loops and to batch edits. The whole section is capped at roughly 200 tokens; if the initial render exceeds the budget, the avoid note and then the sequence hint are dropped before the core tool/artifact summary.
Telemetry Scorecard
Source: src/context-engine/db.ts (scorecard table), src/context-engine/telemetry.ts, ScorecardTracker in session/turn
One row per session in the context-engine SQLite DB. No text content is stored — only numeric signals:
| Signal group | What's tracked |
|---|---|
| Context | retrieve_artifact calls, repeat file-reads, search_turn_events calls, pressure events, compaction triggers |
| Memory | recall call count and recall-used % |
| Skills | unique skill loads, total load events, reloads, underloads (loaded but never used), token cost |
| Resume | read-path digests and skill catalog ids for dedup across resumed sessions |
Active when: context_engine.enabled = true (always) or measurement_mode = true (classic/debug — scorecard-only DB, no engine tables). Counters persist across resume via persistProgress() called after every turn.
Query: /scorecard in-session shows the current session row. For cross-session A/B analysis, query the scorecard table in the context-engine DB directly. Headless substrate for evals: praana run + Harbor adapter (harbor_eval/). The fixed A/B task suite + scoring (#424) is not shipped yet.
Plan Mode, Repeat-Read Interceptor, and Session UX
Plan mode (issue #547)
/plan on is user-armed only (no auto-detect, no Plan-Before-Execute system-frame rule). Session.planMode holds the state; src/plan-mode.ts is the source of truth for the mutation set and approval-word detection.
/plan <on|off|execute>toggles the gate. Bare/planprints current state. The armed state surfaces in the status/glance bars.- While armed, mutating tools are blocked (
write_file,edit_file,git_commit,lsp_format,lsp_apply_code_action, branch-creating shell); read-only tools stay allowed. - Approval words (
go/execute/proceed/continue) leave an armed plan; deferral phrases ("continue reading") do not. - Plan mode persists via a
system_noteevent replayed bySession.resume. - Always-on risk confirm (#580) runs after validate and before write-path: TTY
[y/N]forrm,git reset, force-push,git clean -f,gh issue close/gh pr merge, package installs, and writes outside cwd. Headless fail-closes those classes unless listed in[risk].allow. Concurrent confirms are serialized so stdin does not interleave.
Repeat reads (issues #545, #799)
read_file always returns the requested contents from disk, including a repeat read of an unchanged file (issue #799 removed the artifact-card interceptor). The scorecard still counts the repeat: the read index records the path and its mtime for the running session (it is not restored on resume, so the first re-read after a resume is not counted) and is invalidated on any write/edit. In engine mode the compiled prompt includes a "Files Read This Session" index (path → artifact_id) so the agent can optionally use retrieve_artifact(id) instead of re-reading.
Each call is capped (issue #811): at most MAX_READ_LINES (2,000) lines and at most a quarter of the model's context window in estimateTokens units (src/token-estimate.ts; 100k-token fallback window when the window is unknown), with at least one line always returned. A single line longer than MAX_LINE_CHARS (2,000 characters) is cut with a … [line truncated, N chars] marker, so a minified file cannot become one huge line. An explicit limit is applied first and then capped the same way. The result always carries total_lines and returned_lines (the number of file lines in content, 0 for an empty result); when the cap cut lines or a long line was cut it also carries truncated: true and a note naming the 1-indexed lines returned and, when lines remain, the offset that reads the next part. content stays pure file lines — no note text — and the artifact range comes from returned_lines, so sourceLineStart/sourceLineEnd stay exact even when the last returned line is blank. In engine mode source_total_lines is stored alongside the line range and carried onto the verbatim turn reference, the artifact card, the files-read index line, and retrieve_artifact, so later turns still see total_lines, the returned range, and the next offset. The window reaches the tool through getContextWindowTokens, wired in runTurn; there is no config key. Binary-file refusal and a per-turn history budget are not part of this (the latter belongs to mid-turn compaction).
Resume hardening (issues #523, #546)
praana resumewith no session id resolves the most recent session for the current cwd; if none exists it prints a short notice and starts a fresh session instead of exiting.- On resume, a stale-task banner lists tasks/decisions left open in the previous session.
Scorecard nudges and agent hints (issues #549, #550)
Beyond the /scorecard table, the telemetry loop feeds back into the live session:
- Turn-footer nudges surface when no-op tool calls recur, recall hit-rate is low, or read/retrieve churn fires.
- Engine-mode agent hints are injected into the system frame when churn fires or recall-used % is low, noting the repeated access (the hint states the fact; it gives no instruction).
End-of-session epilogue (issue #519)
/exit (and natural shutdown) prints a single honest epilogue instead of a misleading consolidation header, returns snapshotted memory stats from shutdown, and prints a 12-char resume id that uniquely identifies the session for praana resume <id>.
Shared agent policy (issue #228)
Engine and classic modes share one mode-neutral agent policy injected into the system frame: instruction precedence, treating tool output as untrusted data, evidence-first assertions, and concise tool-use norms. Independent tool calls in one assistant response execute concurrently; parallel mutating tools targeting the same path are rejected by write-path guards. The prose tool-schema list was removed from the system prompt — the structured tool definitions passed to the provider remain the authoritative interface. Adaptive Context instructions stay engine-only.
Concurrent tool execution (issue #260)
After the LLM streams tool calls, turn.ts runs pre_tool_call hooks then executes the pending batch concurrently. Builtin hooks: plan-mode, then always-on validate (#577: missing paths, unread edit_file, shell cwd/PATH), then risk confirm (#580), then the circuit loop gate (#578), then write-path acquire. Mutating tools in plan mode are denied; confirm-tier actions prompt (TTY) or fail closed (headless); the 3rd identical mutating call within a turn is blocked, while repeated failures on the same path or command add a re-read advisory to the result instead of blocking (counts reset each turn); reads and test commands are never loop-gated; same-path concurrent writes fail fast. After execute, post_tool_call runs LSP post-edit, optional [verify], error enrich, secret redaction (#579), circuit error-count, then write-path release. Headless [circuit] max_tokens / max_wall_ms skip the pending batch and run one no-tool wrap-up. Tool results and a copy of tool-call args are redacted for the prompt, events.jsonl, and the TUI; execute still receives original args. Independent reads, searches, and recall calls are safe to batch.
Onboarding, credentials, and settings
- Credential store (
~/.praana/credentials.json): preferred over bare env for API keys; setup/login can adopt an env key into the store. /login//logout: add or remove a provider credential (and optionally switch the active provider). Bedrock uses ambient AWS credentials or a pasted Bedrock API key (bearer token)./settings: persists UX defaults to~/.praana/settings.json(model,provider,thinking,incognito,debug,theme,auto_update). Session/model//thinking//incognito//debugdo not auto-write settings — only/settings set//settings resetdo.auto_update(off by default) installs the latest GitHub Release in the background on TTY start when a newer npm version exists./reasoning <level>: session override forllm.reasoning_effort(off/minimal/low/medium/high/xhigh); persisted via areasoning_effort_overridesystem note.
Headless run and Harbor
praana run "<instruction>"(or--prompt/--max-steps) runs a non-TTY one-shot session — used by Harbor / CI. Optional[circuit] max_tokens/max_wall_mstrigger a one-shot wrap-up instead of executing the next tool batch.harbor_eval/ships an installed-agent adapter that installs Bun + PRAANA in the task container and invokespraana run --incognito.
Standalone binary and release packaging
bun run build:compilerunsscripts/compile.ts→dist/praana(host platform);--target bun-linux-x64,--outfile …. It uses@opentui/solid/bun-pluginand setscompile.autoloadBunfig = falseso launching from a cwd with an OpenTUIbunfig.tomlpreload does not fail withpreload not found. Preferbin/praana.jsforbun add -g/ npm-style installs.- Baked
--version: exact git tagv{package.json version}with a clean tree → that version; otherwise{version}-dev.<shortsha>[.dirty]so branch builds are not mistaken for a release. - Release CI (
.github/workflows/release-please.yml): after quality-gate (typecheck + tests), builds five targets — linux x64/arm64 and darwin arm64 with--target, darwin-x64 and windows-x64 as native host compiles without--target— and smoke-runs--versionon each.package-releasethen runsbun run package:binaries --allow-missingto packpraana-<os>-<arch>.tar.gz(zip on Windows) +SHA256SUMS: each archive is the platform executable pluspraana-natives.nodeandpraana-natives.json; targets whose binary did not build are skipped. Archives upload to the GitHub Release. - Standalone contract: the
praanaexecutable plus onepraana-natives.nodebeside it (search, tree-sitter, ONNX embed).loadNative()tries@praana/nativesfirst, thenpraana-natives.nodenext toprocess.execPath. Model weights still download to~/.praana/models/on first use (consent unchanged). install.sh→~/.local/bin(or/usr/local/binas root) on Linux/macOS;install.ps1→%USERPROFILE%\.local\binon Windows. Both always download the latest GitHub Release (which can lagmain); a--versionsmoke failure is fatal, doctor native/search mismatches are warnings.
Configuration
Config files are deep-merged from lower to higher precedence (later overrides earlier):
- Global JSON:
~/.praana/praana.config.json - Global TOML:
~/.praana/config.toml - Local JSON:
./praana.config.json - Local TOML:
./praana.config.toml
[llm]
provider = "openrouter" # openrouter | openai | deepseek | groq | xai | fireworks | together | ollama | opencode | anthropic | google | mistral | amazon-bedrock
model = "deepseek/deepseek-v4-pro" # any model supported by the chosen provider
# region = "us-east-1" # amazon-bedrock only; else AWS_REGION / AWS_DEFAULT_REGION / us-east-1
# reasoning_effort = "medium" # off | minimal | low | medium | high | xhigh
# Optional fallback used when the primary returns a timeout, HTTP 429/529, or an empty response.
# An idle timeout or a connect timeout goes straight to the fallback. Other failures retry once on the primary.
# fallback_provider = "openrouter"
# fallback_model = "moonshotai/kimi-k2.7-code"
[memory]
enabled = true
# File memories use global and project directories under ~/.praana.
[compiler]
token_budget = 100000
recent_turns = 10
recent_turns_token_budget = 30000
[tiers]
idle_soft_after_turns = 20
idle_hard_after_turns = 50
[context_engine]
enabled = true # false = classic mode (full verbatim transcript)
measurement_mode = false # write telemetry in classic mode (debug)
artifact_inline_threshold = 400
artifact_ttl_turns = 50
checkpoint_enabled = true # narrative, plan history, constraints, decisions w/ rationale
[context_engine.distiller]
default_intensity = "full" # lite | full
[context_engine.scoring]
w_pin = 1.0
w_recency = 0.5
w_relevance = 0.3
w_semantic = 0.3 # embedding similarity; combined with BM25 via max()
w_hydrate_boost = 0.2 # boost for context units overlapping auto-hydrated objects
[context_engine.pressure]
compact_at = 0.70
emergency_at = 0.85
[tools]
[tools.web]
enabled = true # web_fetch; allow_domains / deny_domains (deny wins); private nets always blocked
[session]
log_dir = "~/.praana/sessions"
Env Vars
PRAANA_MODEL— overrides default modelPRAANA_CONTEXT_ENGINE— overridescontext_engine.enabledPRAANA_MEASUREMENT_MODE— overridescontext_engine.measurement_mode- Provider-specific keys:
OPENROUTER_API_KEY,OPENAI_API_KEY,OPENCODE_API_KEY,DEEPSEEK_API_KEY, etc. - Amazon Bedrock:
AWS_ACCESS_KEY_ID/AWS_PROFILE/ web identity / container role, orAWS_BEARER_TOKEN_BEDROCK/ stored Bedrock API key; region viallm.regionorAWS_REGION/AWS_DEFAULT_REGION
Mid-session model switching
/model is handled by model-resolver.ts and validated before the switch toast appears. Bare /model opens a searchable TUI selector (search by provider or model id).
Syntax: /model [provider] <model-id> — provider is optional and space-separated only (not provider/model as a single token unless it is the model id on the current provider).
Resolution order:
- pi-ai static catalog (
getModel(provider, id)) - Live provider catalog via
provider-catalog.ts(6-hour disk cache at~/.praana/provider-catalog-cache.json) — HTTPGET {baseUrl}/modelsfor OpenAI-compatible providers; Bedrock control-plane APIs foramazon-bedrock - Reject with an error toast if still unknown
Live catalog providers: OpenRouter, OpenCode, OpenAI, DeepSeek, Groq, xAI, Fireworks, Together, Ollama (OpenAI-compatible GET {baseUrl}/models). Amazon Bedrock uses ListFoundationModels + ListInferenceProfiles — chat-capable TEXT models only, preferring inference profile IDs. Anthropic, Google, and Mistral rely on pi-ai static catalogs only.
Persistence: successful switches write model_override and optionally provider_override system notes to the event log. session.ts restores the latest overrides on resume. Routing prefixes like openrouter/ or opencode/ are stripped before API calls.
Automatic fallback
If [llm] fallback_provider and fallback_model are set, runTurn() retries once on the primary model after an HTTP 429 or 529 (or a provider status of 429 or 529), an empty response, or a premature stream end. A bare 429 or 529 in other text, such as a token count, is not a rate limit. An idle timeout and a connect timeout are not retried on the same model at this step. When automatic fallback is allowed, that model is asked next; otherwise the error is shown immediately. If a same-model retry was made and it also fails, the turn attempts the configured fallback provider/model. The fallback is committed only when its stream delivered a done event and a usable answer: a normal stop, a tool call, or a length stop that includes text. An empty stop, an abort, a close with no done event, or a length stop with no text is not committed. The primary model stays active, fallback text is not shown, and the turn reports the primary failure. A committed switch appends provider_override/model_override system notes to the event log, shows Switched to <provider>/<model> after <reason>, and continues the turn; the override then persists for the rest of the session and survives resume. An idle timeout is recorded in that reason as idle timeout after Ns (or ms). An explicit /model choice from the user takes precedence and disables automatic fallback for that turn.
UI and Slash Commands
PRAANA launches the OpenTUI + Solid terminal shell (src/ui/tui/) on an interactive TTY. Headless / non-TTY use praana run instead. The TUI is Solid end-to-end for Prompt, transcript, chrome/toast/spinner, overlays, setup, login, and download consent. Buffered shell output and thinking-text rendering when /thinking on are supported. Styling is plain data (SpanStyle in src/ui/tui/theme.ts) applied via native <span style> / <text attributes> — no ANSI strings. Each user turn in the transcript is marked with a coral ❯ prefix in a fixed two-column box (TUI_STYLE.accent) whose flexGrow text box hangs wrapped and multi-line text under the first character; the prefix is layout only and is never part of the stored message text, and a selection that spans a user row copies the message without it (the glyph renderable contributes no selected text, so ❯ cannot reach the clipboard). All keyboard handling goes through @opentui/keymap (KeymapProvider + useBindings layers; the prompt's autocomplete/history keys use per-binding enabled gating on a focus-scoped layer).
Slash commands are handled by src/slash-commands.ts:
/exit— ends the session and quits (epilogue + 12-char resume id)/clear— resets in-session context while keeping the same session ID. Clears working memory (StateGraph + engine extraction/checkpoint cache), hides prior turns from the compiled prompt via areset_boundaryevent in the log, recalculates context pressure for the glance bar, and clears the TUI transcript. The full event log is retained for audit/resume./new— ends the current session, reloads config, and starts a fresh session with a new ID and banner. Clears the TUI transcript./state— lists all state objects and tiers, or prints an empty-state guidance message/stats— prints session metadata plus working-memory and file-memory counts/scorecard— per-session telemetry scorecard/digest— prints the current file-memory index/events— lists the last 20 events in the event log/recall <query>— searches file memories/model [provider] <id>— switch model (bare/modelopens searchable selector; validated via pi-ai + live catalog)/reasoning <level>— set reasoning effort (off/minimal/low/medium/high/xhigh)/sessions— lists last 15 historical sessions for easy resuming/incognito <on|off>— blocks or allows file-memory writes; reads remain available/debug— toggles detailed tool block tracing and compiles turns to files underprompts/(andscores.jsonlin engine mode)/thinking <on|off>— toggles visibility of LLM reasoning stream/why <id>— explains why a context unit was included or excluded from the last compiled prompt (engine mode only)/login [provider]— add or update a provider credential/logout [provider]— remove a provider's credentials/settings— view/set persistent UX prefs (~/.praana/settings.json)/shell <cmd>— runs a shell command inline in the transcript (also! <cmd>prefix)/plan <on|off|execute>— toggles plan mode (blocks mutating tools until approved)/help— prints slash commands documentation
CLI: praana --incognito, praana --debug, praana --config <path>, praana resume [<session_id>] (no id / 12-char prefix supported), praana run "<instruction>", praana setup (also praana init), praana upgrade (alias praana update), praana doctor, praana providers, praana models, and praana --version. Harbor adapter: harbor_eval/. See src/app-banner.ts and src/cli-args.ts for the full list.