Commit Graph

549 Commits

Author SHA1 Message Date
kami 7b90944b61 feat(inference): pass [[models]] params through to llama-server (enables draft-MTP) (#243)
ModelConfig.params was loaded from config but never consumed — the spawn
command in DefaultModelManager was hardcoded. Thread it through: params (a
flag->value map) flattens to token order on ModelDescriptor.extraArgs and
appends to the llama-server argv. This engages Multi-Token Prediction
speculative decoding purely from config:

  [[models]]
  params = { "-md" = "/path/draft.gguf", "-ngld" = "99", "--spec-type" = "draft-mtp", "--spec-draft-n-max" = "4" }

Each entry stays a distinct argv token (no shell), so paths with spaces are safe.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 14:28:26 +04:00
kami 6010f6b6c0 feat(server): bootstrap codebase-memory index at workspace open (#242)
codebase-memory search tools failed 9/9 ("project not found or not indexed")
because index_repository was never called for the repo. After MCP servers
mount, if one advertises index_repository, invoke it once with the workspace
root (repo_path) through the normal ToolExecutor path, on a background daemon
so a slow index doesn't block startup. "fast" mode to reach usable quickest.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 14:17:00 +04:00
kami 0e1095e9ba feat(tools): clobber guard blocks file_write overwriting real code with elided stubs (#245)
A full file_write that shrinks a non-trivial existing file (>=30 non-blank
lines) by >60% into a stub with literal `...` placeholders is almost always
the model rewriting a file from memory instead of editing it — the incident
that silently broke SessionRoutes.kt (273->28 lines) in run f11afb08. Reject it
(recoverable) and steer to file_edit. Requires BOTH the hard shrink AND elision
markers, so dead-code refactors and new-file scaffolds pass untouched. Runs
before the write regardless of approval tier, so the auto-driver can't wave it
through.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 14:05:53 +04:00
kami e25e9e46fd fix(kernel): stop compaction self-deadlocking long runs on re-entrant artifact Mutex
JournalCompactionService and TierContextSummarizer wrapped their event emit
in artifactStore.flushBefore { }. But emit -> SqliteEventStore.append already
calls flushBefore internally, re-acquiring CasArtifactStore's non-reentrant
Mutex -> the coroutine parks forever (no CPU, no thread, no exception, no
terminal event). Only fires once the journal crosses the compaction threshold,
i.e. exactly on long runs.

Emit directly; append()'s own flushBefore still fsyncs artifacts before the
referencing event is persisted, so durability ordering is preserved. Adds a
regression test with a lock-holding fake store (the prior fake took no lock,
which is why the deadlock escaped tests).

Vikunja #244.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LG7sGEbVJQncHJtsbPFJZm
2026-07-17 16:17:56 +04:00
kami 9e62097c97 test(server): verify WS session stream forwards live ApprovalRequired events (#190)
SessionStreamHandler.handle() already registers the connected socket into
ApprovalCoordinator's per-session client map before entering the inbound
read loop, and ApprovalCoordinator.broadcast() (fed by ServerModule.start()'s
live subscribeAll().filter{ApprovalRequestedEvent} subscription) already
targets that map — so a gate firing after connect does reach the socket,
and CLI --auto-approve is not actually blind. Add integration coverage
(none previously existed for SessionStreamHandler) proving: (1) a live
ApprovalRequired fired post-connect reaches the socket, and (2) a
disconnected client is cleanly deregistered without disrupting delivery
to a later client on the same session — covering the 8d7c827e non-blocking
emit and 3559ea67 cleanup-on-termination invariants.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 12:18:51 +04:00
kami 1dca8c7f25 test(workflow): update shipped-workflow tool-grant expectations for codebase-memory MCP tools
Follow-up to 3e31ebcc, which granted the MCP read-only query tools to
review_loop and role_pipeline stages but left the exact-set assertions stale.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 12:15:33 +04:00
kami e5a5cddc96 feat(tools): salience-aware shell output compression — retain error lines through HeadTail (#67)
HeadTail now accepts an optional salience regex + cap: middle lines matching
it (error|fail|exception|panic|traceback|✗, case-insensitive) survive
truncation in place instead of being silently dropped, so a decisive error
buried in the middle of a long build/test log still reaches the model-facing
context entry. ShellTool's outputCompressor spec wires this in; the raw
build-gate receipt path is untouched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 12:13:31 +04:00
kami 3e31ebcc1e feat(workflows): grant codebase-memory MCP tools to code-intel stages
Explicit per-stage grants (least-privilege, invariant #5) for the mounted
codebase-memory MCP side-car:
- role_pipeline: discovery bootstraps the graph (index_repository) + grounds;
  analyst/architect/decomposer/implementer/reviewer get read-only query tools
  (search_code/search_graph/get_architecture/trace_path/get_code_snippet)
  scoped to each role. NOTE: architect flips from pure-reasoning to tool-calling.
- review_loop implement+review and task_planning planner get read-only queries.

Tools are approval-gated at T2 (server default in config.toml [[mcp]]).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 20:01:00 +04:00
kami 0a89fafd45 fix(tools): restore stdin pipe for MCP stdio transport
ChildProcess defaults stdin to /dev/null (scaffolders fail fast rather than
hang). MCP stdio is the inverse: the server reads requests from stdin and sees
EOF then exits immediately without a live pipe. spawn() now restores
Redirect.PIPE. Verified end-to-end: Correx spawns the real codebase-memory-mcp
v0.9.0 and mounts its 8 tools as mcp__codebase-memory__*.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 19:49:57 +04:00
kami 63e8b4f5d6 feat(tools): native MCP client — mount stdio MCP servers as Correx tools
Adds an MCP host layer so external MCP servers (AST/LSP code-intelligence,
package resolvers, etc.) can be mounted at startup and surface their tools/list
as first-class Correx tools named mcp__<server>__<tool>. Each MCP tool is a
Tool+ToolExecutor, so it rides the normal ToolExecutor path and inherits tier
gating, receipts, and event-recorded execution (#5) with zero special-casing;
replay reads the recorded receipt rather than re-calling the server (#8/#9).

- McpProtocol/McpStdioClient/McpTool/McpMounter in infrastructure:tools
  (stdio JSON-RPC 2.0, tools/* slice only). Capabilities empty; safety via
  default T2 tier since external side effects are opaque.
- [[mcp]] config (id/command/env/tier) + array-of-tables parsing.
- Main wires mounted servers into extraTools (main + per-workspace paths) with
  a shutdown hook; a server that fails to start is logged and skipped.
- Tests: in-process fake transport (handshake/list/call/error + tool mapping),
  [[mcp]] parser.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 19:26:01 +04:00
kami 633da3d2df feat(kernel): structured package-404 recovery evidence (#192)
The 2026-07-16 audition run-3 burned 26 inferences in install_dependencies
because a registry 404 for a hallucinated package (@types/vite) surfaced only
as raw shell output: the model retried npm, pinned versions/flags, switched to
Yarn, and probed pnpm/network before rewriting the manifest.

packageNotFoundAdvisory deterministically parses npm/yarn/pnpm 404 output,
names the offending manifest entry, and appends a directive telling the model
to edit the manifest — not retry the installer. Wired into renderToolResult
for both the nonzero-exit Success and recoverable Failure framings. Pure over
already-recorded tool output (no new event, invariant #9 unaffected).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 18:56:21 +04:00
kami 59a0ad3c2b feat(kernel): stage-global repeated-failure loop breaker (#78)
Existing read-loop/rejection-loop breakers key on CONSECUTIVE rounds, so a
single interleaved success resets them — the hole that let the 2026-07-16
audition run-3 thrash npm install against a hallucinated package across 57
inferences. Add repeatedToolFailureLoop: cumulative count per normalized
tool-failure signature within a stage; once a signature hits
stageFailureLoopLimit (default 6) the stage fails with STAGE_LOOP_BREAK_GATE
and the step handler routes straight to recovery (never retried in place).

Pure fold over recorded events (replay-safe, invariants #8/#9);
ToolExecutionFailedEvent lacks stageId so failures correlate via
invocationId -> ToolInvocationRequestedEvent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 18:50:11 +04:00
kami a2b97221d5 chore(prompt): trim performance-neutral stage operating-guidance block
Vikunja #169 audition result. The 5x5 controlled A/B
(docs/qa/QA-stage-prompt-audition-results-2026-07-16.md) found the curated
guidance block performance-neutral: 5/5 build success both variants, cost
differences within heavy-tailed noise. Trimmed to the single sentence the
gates don't already enforce (scaffolding-scope boundary); dropped the
read-before-write / verify-before-complete / use-exact-feedback nudges that
restate gate-enforced behavior. ON run 3 proved prose doesn't stop failure
loops — deterministic defenses do (filed Vikunja #191/#192, unblocked #78).
2026-07-16 18:38:16 +04:00
kami 53d8108189 feat(orchestration): plan grounding, positive-pattern mining, stage-prompt audition rig
Vikunja #167/#168/#169.

#167 PlanGrounder (infrastructure/workflow): build-prereq + touches-scope
existence grounding, emits PlanGroundingEvaluatedEvent. Deterministic fold
over recorded workspace/plan events (invariants #8/#9).

#168 positive-pattern mining (SessionOrchestratorPlanPatterns): mine
SuccessfulPlanShape from cross-session log — a locked plan whose own
workflow later completed — and inject the closest-resembling plan shape as
L0/SYSTEM advisory context for the planning stage. Keyword-Jaccard
resemblance, no LLM/embedder, replays identically. Advisory only (#3).

#169 stage-prompt audit + CORREX_STAGE_GUIDANCE ON/OFF toggle in
SessionOrchestratorExecution. RunCommand gains --intent to seed a
freestyle session over REST.

Also: workspace verification events + concept-compiler wiring. ./gradlew
check green.
2026-07-16 14:55:56 +04:00
kami ed7efb6072 Implement closed-loop workspace follow-ups 2026-07-15 23:48:12 +04:00
kami 3a48ecd24f feat(concept): heuristic concept compiler (ACR fold-in)
Promotes recurring validated failure->fix patterns into L3 as retrieval-on-demand
concepts. Deterministic core: ConceptCompilerProjection clusters
RetryAttempted->StageCompleted pairs by fingerprint (gate-agnostic), promotes at
N=3 cross-session validated fixes, never-contradicted. ConceptPromotedEvent is the
sole authoritative write (idempotent under replay); ConceptCompilerService appends
it + best-effort injects to L3 (non-authoritative, inv #6). Wired live in
ServerModule.start() on StageCompleted.

Design: docs/plans/2026-07-12-acr-concept-compiler.md

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DhFXmKe4WisSSPf9LrmmTg
2026-07-15 13:35:17 +04:00
kami d69cb12ce9 refactor: decomposition WIP (orchestrator/server/execution-plan)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DhFXmKe4WisSSPf9LrmmTg
2026-07-15 13:17:01 +04:00
kami 9b925e141d test(gate): expect uniform tool-result frame in compressed-context assertion
The tool-output framing feature (2912799f) wraps every tool result in a
'[tool exit=N]' header before it enters context. Compression still runs
(blank lines stripped); the test predated the frame and asserted the bare
compressed body. Update to the framed contract — invariant #6 unchanged.
2026-07-13 12:12:19 +04:00
kami 5d1f2ab360 chore(detekt): ratchet maxIssues 120→90 after orchestrator decomposition
kernel dropped to 85 findings (was the binding module >120 pre-split);
90 leaves ~5 slack so new violations trip the build.
2026-07-13 12:09:41 +04:00
kami 1f794dad63 refactor(kernel): decompose DefaultSessionOrchestrator into per-concern extensions
Moves the 11 private step/recovery helpers off the concrete orchestrator into
internal extension-fun files (Step: step, executeMove, enterStage,
decideGateExhaustion; Recovery: retry/route/ticket helpers). Class keeps the
override seams (run, cancel, submitApprovalDecision), the cross-module public API
(rehydrate, resume, submitClarification, submitSteering), enrich, and
validatedArtifactContent. File-private helpers the moved funs need are promoted
to internal. Pure relocation; clears TooManyFunctions on the class. kernel +
testing:kernel green; server/cli compile clean.
2026-07-13 12:06:20 +04:00
kami 670e0c4828 refactor(kernel): decompose SessionOrchestrator god-class into per-concern extensions
Splits the 3.7k-line SessionOrchestrator into the state-owning abstract class
(fields + open/abstract seams: run, cancel, runInference, mapValidationOutcome,
estimateTokens) plus behavior-preserving internal extension-fun files grouped by
concern: Artifacts, ToolExec, Workspace, Context, RepoContext, Gates, Gates2,
Workflow, Approval, Preview. Two public members consumed cross-module
(liveClarificationRequestIds, requestPlanApproval) stay on the class. Each file
kept <=10 top-level funs; pure relocation, no logic changes.

Clears LargeClass; adds no new TooManyFunctions. kernel test + detekt green;
server/cli compile clean.
2026-07-13 11:58:44 +04:00
kami 7f820bafe6 refactor(kernel): extract executeStage to extension, promote members internal
Pilot for the SessionOrchestrator god-class decomposition. Moves executeStage
(426-line stage-execution driver) out to SessionOrchestratorExecution.kt as an
internal extension fun, hoists three nested holders (RunEffectives,
ArtifactLadderOutcome, RenderedToolResult) to top-level in
SessionOrchestratorTypes.kt, and promotes class/protected members to internal so
extensions can reach them. Behavior-preserving relocation; kernel+test+server
compile green.
2026-07-13 11:44:04 +04:00
kami aee2e67c66 refactor(detekt): extract magic-number constants, wrap long lines, drop legit suppressions
Mechanical detekt cleanup across apps/core/infrastructure (behavior-preserving):
- MagicNumber 62->10: named constants + removed 'legit' MagicNumber suppressions
  (Tier level from ordinal, ReplayInferenceProvider CHARS_PER_TOKEN, ConfigLoader
  DEFAULT_* consts, capability scores, HTTP ranges, column widths, etc.)
- MaxLineLength cut to ~0 in production modules (line wraps, no logic change)
- Dropped one dead parameter (ConfigLoader.parseArray lineNum)

Structural findings (ReturnCount/LongMethod/Complexity/LargeClass) left for a
deliberate decomposition pass. Full build + detekt gate green.
2026-07-12 23:12:28 +04:00
kami 135a34eb2f merge: land vikunja-tasks audit fixes + tool-output/sampling/config work 2026-07-12 22:46:02 +04:00
kami 2912799fe0 feat(tools): bound+frame tool results, spill full output to CAS, tool_output retrieval
Tool results injected into model context are now consistently framed and
globally bounded. Success output over the floor (TOOL_RESULT_MAX_CHARS=8000)
is head/tail-truncated with a marker naming a retrieval ref; the full raw
output spills to the artifact store (CAS) and its hash is recorded on the
ToolReceipt (fullOutputHash) in the event log. Agents recover the full text
via the new read-only tool_output(ref=...) tool.

- SessionOrchestrator: frameTruncatedToolResult + renderToolResult; char-cap
  head/tail so a single pathological long line can't defeat the bound.
- ToolReceipt.fullOutputHash (additive, nullable).
- ToolOutputTool (Tier T1, no fs capability) resolves ref -> full bytes.
- Wired via extraTools in Main.kt; tool_output added to ALWAYS_AVAILABLE_READ_TOOLS.
- Failure path keeps ERROR:/FATAL: prefixes (all-rejected breaker dependency).

Tests: FrameTruncatedToolResultTest, ToolOutputToolTest.
2026-07-12 19:46:02 +04:00
kami 3a4e577b5b refactor(server): decompose DomainEventMapper god-when into per-domain files
DomainEventMapper.kt had grown into a single ~280-line `when` over every
domain event type with a ~40-line flat import list ('god mapper' smell).
Split the when body by domain area into four files, each a suspend fun
returning a MapOutcome sentinel:

- SessionEventMappers.kt   — session/workflow lifecycle + chat turns
- StageInferenceEventMappers.kt — stage transitions + inference lifecycle
- ToolEventMappers.kt      — tool exec/assessment + review findings (+ prettyToolParams)
- LifecycleEventMappers.kt — approval/clarification/proposal/narration/artifact/model/preempt

The dispatcher chains them; MapOutcome.Emit(msg?) vs MapOutcome.Skip
preserves the null-vs-unhandled distinction (a suppressed event like
ArtifactValidating returns Emit(null), not Skip). Public entry points
(DomainEventMapper class, domainEventToServerMessage, prettyToolParams)
unchanged — no behavior change, pure maintainability. Each per-domain
import list is now local to its file. DomainEventMapperTest green.

Vikunja #31.
2026-07-12 18:39:33 +04:00
kami bfd925b518 feat(tools): glob + grep read-only workspace search tools
Weak local models reached for shell find/grep -r (unjailed, dumps
.gitignore'd trees, floods context) to answer 'does frontend/ exist?' /
'where is symbol X?'. Add two jailed, gitignore-aware read-only tools:

- GlobTool (name 'glob', T1, FILE_READ+DIRECTORY_LIST): find files by
  glob pattern; survey-exempt from anti-hallucination read gates like
  list_dir.
- GrepTool (name 'grep', T1, FILE_READ): regex content search, returns
  path:line: text; skips gitignored, binary (NUL), and >2MB files.

Both reuse GitignoreMatcher + PathJail from the filesystem package,
share FileReadTool's jail/anchor/toggle, cap at 200 results. Registered
in ToolConfig.buildTools (fileRead block) and added to
StageConfig.ALWAYS_AVAILABLE_READ_TOOLS so every tool-granting stage can
call them. 6 tests green.

Vikunja #37.
2026-07-12 18:33:36 +04:00
kami d89d4e32a9 feat(inference): operator-tunable sampling knobs (top_k/min_p/repeat_penalty) for stage requests
GenerationConfig only carried temperature/top_p/max_tokens/stop/seed. Added nullable
topK/minP/repeatPenalty, serialized to the llama.cpp and OpenAI-compat request bodies
via @EncodeDefault(NEVER) so an unset knob is omitted (the model keeps its own default)
and behavior is unchanged unless the operator opts in.

Surfaced as a new [sampling] config section feeding the default stage GenerationConfig
(the main agentic loop) through TomlWorkflowLoader + ExecutionPlanCompiler; the former
hardcoded temperature=0.7/topP=1.0 stage defaults now come from config. Talkie
chat/narration keep their own generation settings.

Vikunja #46 (task 76) — sampling half.
2026-07-12 17:54:25 +04:00
kami b2c7bbe401 feat(config): relocate orchestration loop/threshold/budget constants to [orchestration] config
The kernel's ReAct-loop tuning constants (max tool rounds, read/rejection-loop
nudge thresholds, feedback issue cap, repo-map top-k/files-per-dir, docs catalog
cap, clarification-round cap, review-block confidence/retry cap, default
refinement, recovery/intent route budgets) were hardcoded in SessionOrchestrator/
DefaultSessionOrchestrator. Relocated to a new OrchestrationTuning value threaded
through the orchestrator constructor, mapped from CorrexConfig.orchestration in
Main.kt, parsed in ConfigLoader, written by CorrexConfigWriter. Defaults equal the
former constants so an absent [orchestration] section reproduces prior behavior.

Startup-load (not hot-reload); pure output-truncation caps left as constants.

Vikunja #46 (task 76).
2026-07-12 17:45:54 +04:00
kami 8d7c827ebb fix(server,persistence): stop slow WS client stalling kernel; log dropped emits (#53)
Two event-delivery back-pressure faults from the core audit (#7).

(a) streamGlobal forwarded globalFlow → a per-connection Channel with
buffer.send (SUSPEND). globalFlow is also SUSPEND-overflow, so one wedged
WebSocket client back-pressured globalFlow → append() suspended → the whole
kernel stalled. Now the collector uses trySend; on overflow it closes the
buffer with SlowClientException, tearing down that one connection (client
reconnects and re-syncs via replaySnapshot) instead of blocking append().

(b) Per-session subscriptions (extraBufferCapacity 64) used tryEmit with the
return ignored: a lagging in-process collector (e.g. LiveArtifactRepository)
silently diverged from the durable log. Both SqliteEventStore and
InMemoryEventStore now warnIfDropped() — the event is still persisted; only the
live SharedFlow drops, and we surface it. ponytail: log-only; bounded
rebuild-on-lag if divergence ever bites.

Added slf4j-api to :infrastructure:persistence (already the standard logging
dep across modules) for the warn.

Green: :infrastructure:persistence + :apps:server compile+detekt+test (the one
pre-existing ModelLifecycleWiringTest failure needs a real llama-server, fails
identically on clean checkout).
2026-07-12 17:11:41 +04:00
kami 3559ea67ef fix(kernel,server): evict per-session caches on workflow termination (#54)
Two unbounded per-session leaks that never released after a workflow ended:

- SessionOrchestrator.artifactContentCache (full file contents, keyed
  "<sessionId>:<path>") grew for the process lifetime. Added
  evictArtifactContentCache(sessionId) — session-prefix key removal,
  rehydrate-safe — called on both completeWorkflow and failWorkflow.
  cancellations was already evicted on both terminal paths.

- NarrationSubscriber leaked a Channel + worker coroutine + lanes map entry
  per session forever. closeLane() now closes the lane channel on
  WorkflowCompleted/WorkflowFailed (draining the terminal narration first);
  the worker self-removes from lanes when its for-loop exits on close.

Deferred: SqliteEventStore.subscriptions eviction — removing the SharedFlow
mid-life would strand LiveArtifactRepository's downstream collector (a
suspended-coroutine leak worse than the tiny empty-SharedFlow entry).

Green: :core:kernel compile+detekt, :apps:server *NarrationSubscriber* (8).
2026-07-12 17:05:34 +04:00
kami 97e56b9275 refactor(kernel): use real tokenizer for journal budgeting estimates (#58)
Real LLM Usage is already recorded (InferenceCompletedEvent.tokensUsed),
aggregated per-session (MetricsProjection), exposed via correx stats + server
MetricsInspectionService, and rendered in tui-go. The only remaining hardcoded
length/4 estimates were the journal context-entry budget and the compaction
threshold — both pre-injection (no LLM response exists for the journal text), so
estimation is legitimate, but they now use the real tokenizer estimateTokens()
for consistency with sibling context entries instead of length/4.
2026-07-12 13:24:50 +04:00
kami 530b118b67 perf(kernel): batch the artifact-lifecycle event triple via appendAll (#59)
The Created->Validating->Validated triple fires unconditionally back-to-back at
three artifact-emission sites — three single-event append transactions (each its
own commit + flow-publish pass) for one logical unit. Added emitAll(sessionId,
payloads) which routes 2+ events through EventStore.appendAll (one transaction,
one publish pass) and falls back to emit() for 0/1. Same events, same order.

Adjacent-but-conditional emits (clarification/approval pause+resume) are left on
emit(): they straddle suspension points, so batching would change observable
ordering.
2026-07-12 13:22:05 +04:00
kami 65d5e9de83 fix(persistence): assign event sequences atomically inside INSERT (#56)
nextGlobalSequence()/nextSessionSequence() computed MAX+1 with two extra
SELECT round-trips, guarded only by an in-process mutex — two processes on the
same correx.db (CLI + server) could read the same MAX and collide on the unique
index. Compute both the global sequence and session_sequence as MAX+1 subqueries
inside the INSERT and RETURNING the assigned values. SQLite serializes writers,
so the subqueries are atomic across processes; the unique index is the backstop.
Also removes the two pre-SELECTs per append.
2026-07-12 13:19:50 +04:00
kami 759828c0f5 fix(persistence): serialize SqliteEventStore reads with append transaction (#52)
Reads (read/readFrom/lastSequence/allEvents/allSessionIds/lastGlobalSequence)
shared the single JDBC Connection with append's transaction unsynchronized.
The coroutine appendMutex only excludes append-vs-append; a read on the caller
thread could hit the connection mid-transaction (setAutoCommit(false)..commit)
and corrupt tx state — SQLite JDBC is not thread-safe. Guard every connection
access with a shared JVM monitor (synchronized(connection)) via withConnection,
so reads and the IO-thread append transaction are mutually exclusive.
2026-07-12 13:17:38 +04:00
kami bb73bc9371 perf(kernel): hoist read-only check out of per-tool filter (#51)
runInference filtered the offered tool list with isReadOnlyMode(sessionId)
evaluated inside the per-tool .filter{} — a full log read+fold per offered
tool, per inference round (the audit's dominant O(events^2) hot path). The
flag is tool-independent, so read it once before the filter.

The per-tool-CALL re-check in dispatchToolCalls is left as-is: it is
semantically load-bearing (a read completing earlier in the same batch lifts
read-only mode for a later write), not redundant.
2026-07-12 13:14:58 +04:00
kami da7fe61b77 perf(talkie): fold idea board once, keep live via subscribeAll (#55)
IdeaReader folded eventStore.allEvents() on every activeIdeas()/capturedOf()
call — a full deserializing log scan per CHAT context build. Now folds once at
construction and stays current incrementally via subscribeAll(); the fold is
idempotent so seed/live overlap needs no dedupe.
2026-07-12 13:12:35 +04:00
kami 1fd878eb9b fix(approvals): a REJECTED decision must not satisfy the stage approval gate on retry 2026-07-12 13:08:42 +04:00
kami 8c45650e21 fix(artifacts): rebuild LiveArtifactRepository from event log on cold access 2026-07-12 13:05:52 +04:00
kami b93729008d fix(infra): single-read file_read (no double disk I/O for hash) + bail health poll on dead process 2026-07-12 12:55:12 +04:00
kami 363d880a69 fix(l3): persistent sidecar reader, kill-on-desync, wire persistPath save/load 2026-07-12 12:52:07 +04:00
kami 3ff9c8281a fix(inference): single ContentNegotiation config + firstOrNull on empty choices 2026-07-12 12:49:46 +04:00
kami 46fbd597c3 fix(tools): atomic file_edit writes + bound the patch subprocess 2026-07-12 12:48:30 +04:00
kami c2336ae6f7 fix(tools): don't follow redirects in web_fetch (SSRF) + drop ArrayList<Byte> boxing 2026-07-12 12:46:37 +04:00
kami ddf2c014f1 fix(shell): interruptible timeout + kill the whole process tree (#62)
withTimeout wrapped a blocking process.waitFor() that coroutine cancellation
can't interrupt, so a hung process hung the stage until it exited on its own;
and destroyForcibly() killed only the direct child, leaving sh -c grandchildren
(the real npm/tsc) as orphans. Use process.waitFor(timeout, MILLISECONDS) for
an on-the-clock deadline, and kill via toHandle().descendants() + the parent.
2026-07-12 12:42:04 +04:00
kami 44e15ea1b7 fix(shell): validate every command position against allowlist, not just argv[0] (#61)
An operator argv runs via `sh -c`, so ["ls","&&","rm","-rf","/"] passed an
argv[0]-only allowlist check with {ls} then executed rm. Now every command
position (argv[0] + the token after each &&/||/|/;/& separator) must be
allowlisted; shell builtins are implicit, redirect targets are treated as
filenames. Tests for the bypass, an all-allowed chain, and a redirect target.
2026-07-12 12:40:42 +04:00
kami 8ef957cd53 fix(sandbox): unique backup names to prevent same-basename collision (#64)
Backups were named workingDir/${fileName}.bak — two affected paths with the
same filename in different dirs overwrote each other's backup, so failure
restore wrote the wrong content. Name by full-path hash. Latent today
(single-path tools) but a correctness landmine for any multi-path tool.
2026-07-12 12:38:27 +04:00
kami cf856742b1 fix(approval): resolve preview paths against workspace root, not server CWD (#57)
computeToolPreview/readFileIfExists resolved relative file_write/file_edit
paths against the daemon CWD, so the diff shown to the operator for approval
read the wrong file (or nothing) when server CWD != workspace_root. Thread the
bound workspaceRoot (effectives.policy.workspaceRoot) through and resolve
relative paths against it, same as the tools do.
2026-07-12 12:37:04 +04:00
kami d0ab027353 fix(list_dir): file-vs-dir mismatch gives an actionable hint (#45)
The 'Not a directory' branch returned a bare message; models re-issued the
identical list_dir until cancel (session a60c54b0). Name the remedy: the path
is a FILE — file_read it or delete/convert it first. Regression test added.
2026-07-12 12:34:37 +04:00
kami 25ab4faac9 server: S5 memoize listSessionSummaries + S6 Main.kt hygiene
S5 — GET /sessions re-read + re-projected every session's full log on every
call. Cache keyed on eventStore.lastGlobalSequence(); volatile pair-swap,
no lock — any append bumps the seq so a stale read is impossible.

S6 — close research + health-probe HttpClients via shutdown hook; log the
real configured host:port (was hardcoded 8080) and bind to it; System.err
-> SLF4J; WARN at startup on non-loopback bind (unauthenticated surface).
resolveApiKey precedence item N/A — no such code exists.

Both verified green in isolated worktrees (226 pass). Full local build
currently blocked by an unrelated concurrent core:config edit.
2026-07-12 12:28:19 +04:00