The stage completion cap (e.g. 24_576) is a ceiling, not a promise. When the
rendered prompt + tool schemas fill most of the model window, sending the raw
cap makes llama.cpp truncate the prompt from the left — the traced Gemma4
32_767-token blow-up. Compute effectiveMaxTokens = min(cap, contextSize -
promptTokens - toolSchemas - templateOverhead - reserve), counting prompt/tool
tokens with the model's own tokenizer (char/4 fallback). Live-path only;
deterministic replay never calls infer, so no event recording needed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Files written by earlier stages this session aren't in the session-start
repo map and were never embedded, so semantic retrieval is structurally
blind to them. Overlay each stage's FileWrittenEvent post-images as
deterministic hits (score 1.0) leading the semantic hits, deduped by path
— no reindex, no embed. Descriptors derive via the comment-free
sourcedesc describe() so agent-written content can't inject prose.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A rejected tool call produced one generic, context-free warning per rejection
("a previous tool call was rejected — choose a different approach"), repeated
and session-scoped. With no tool, args, tier, or reason, it read to the model
as noise rather than a correction, and could not tell it which call to avoid.
Replace with a single stage-scoped entry (buildRejectionFeedbackEntry) joining
each rejected ApprovalDecisionResolvedEvent back to its ApprovalRequestedEvent
by requestId: tool name, args preview, tier, and the operator's reason. Scoped
to the stage whose calls were declined; steering notes on a decision are kept
separately. Pure (events, stageId) like buildRetryFeedbackEntry, so unit-tested
directly. Keeps sourceType "rejectionFeedback" (REQUIRED bucket) unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Stage agents were spending most of their turn budget re-discovering files
already known from prior stages/attempts. Root cause: nothing durable carries
acquired knowledge across handoffs and retries. First four slices of the fix:
- core:sourcedesc — new dependency-free module: describe(path, bytes) derives
comment-free structural navigation metadata (module, bounded symbols, bounded
imports, versioned format). Deliberately non-prose: descriptors are derived
from agent-writable files and rendered into successor-stage context, so
comments/docstrings/literals are excluded to close a prompt-injection channel.
CAS post-image hash stays authoritative; descriptor is disposable navigation.
- kernel retry-repair state (ContextFeedback): on retry, name the authoritative
CAS images of files this stage already wrote so the agent patches them instead
of re-reading to rediscover them.
- kernel file-written manifest (SessionOrchestratorArtifacts): each produced
file surfaced with its authoritative CAS image plus a comment-free structural
descriptor (via core:sourcedesc, over recorded CAS bytes — replay-safe).
- apps/server RepoMapIndexer: route the injected repo-map descriptor through the
comment-free describe(). Previously scraped leading comments, which were
embedded into L3 and surfaced verbatim to successor stages — an injection
channel from one stage into the next. Structural facts (module + imports +
symbols) remain as the retrieval signal.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Run 771c0b96 marked COMPLETE with a frontend that did not build. Two
verification holes let a broken import through:
1. A MODULE build_expectation delegates to LSP and the execution gate
returned Success trusting it — but tsserver failed to initialize every
stage, so empty diagnostics read as clean. runExecutionGate now only
trusts the MODULE->LSP short-circuit when the LSP run actually ran
(new lspDiagnosticsSkipped projection); on skip it falls through to the
real build command.
2. ExecutionPlanCompiler disabled the terminal whole-project auto build gate
whenever ANY stage declared a build_expectation — so a MODULE (typecheck-
only) declaration removed the real `npm run build` floor. Now only a real
whole-project build (PROJECT/TESTS) suppresses the auto gate; MODULE/NONE
do not. Extracted autoGateStages() helper. Two new compiler tests.
core:kernel + infrastructure:workflow tests green; no new detekt.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Session d038468a: architect's plans compiled clean (3x) but plan grounding
then rejected them. The scaffold_frontend_project stage runs `npm create vite`
(allowed_tools [file_write, shell], touches [frontend/]) to create frontend/ +
package.json at run time. PlanGrounder only credited declared writes/
expectedFiles, so the scaffolder's generated files were invisible — it
false-rejected all three: frontend/ "doesn't exist", verify stage has "no
manifest". That rejects exactly the plan the architect prompt asks for ("use
the real scaffolder, don't hand-write package.json").
Credit a file_write-capable stage's declared `touches` scope as populated by
run time: it satisfies the build-manifest prerequisite and any scope (its own
or a later stage's) that overlaps it. Keyed on file_write (create-intent), NOT
shell, so a read-only shell stage — log inspection, test runs, grep — creates
nothing and does not wrongly credit its scope. Runtime precondition handling
(#167/#170) remains the backstop for a build whose prerequisite genuinely
never appears.
Tests: scaffolder case (mirrors the session) grounds; read-only shell stage
does NOT; existing "missing prerequisite" reject still holds.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Ly2mMnt9TCZbvhcC1JfuV
Discovery-stage clarifications could only be answered over WebSocket
(ClientMessage.ClarificationResponse), so the curl-based headless QA
driver parked forever at discovery.
Add POST /sessions/{id}/clarify mirroring approveStageRoute. The server
resolves the live (stageId, requestId) from the session id via
SessionOrchestrator.pendingClarificationFor() — the newest still-live,
unanswered ClarificationRequestedEvent from the event log — so a curl
caller need not know the requestId. Empty answers = free-text skip.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Diagnosed from session 508c8d58 (frontend freestyle run, WorkflowFailed):
three independent weak-model-hostile gates, none a model-capability problem.
- shell: split a collapsed single-string command line (["npm create vite …"])
into tokens instead of rejecting it as a "collapsed array". The model
reliably re-emits this shape; rejecting looped bootstrap_frontend until
stage_loop_break. JSON-escape mangles (quotes/commas in argv[0]) stay rejected.
- recovery: a stage_loop_break route now gets a "Stuck-loop ticket", not the
"Contract arbitration ticket". The arbitration prompt told the model to read
and reconcile "the files named below" — but a tool-syntax loop names zero
files, sending the recovery agent grepping the repo for 40+ turns until the
repair ladder exhausted.
- plan lint: H3 (unreferenced_prompt_artifact) demoted from hard failure to
soft finding, and seeds excluded from it. It word-matches artifact IDs in
free prose and cannot tell a forgotten dep from a descriptive mention, so as
a hard gate it burned architect retries on words it couldn't reword away
(analysis/dod). Hard tier is now deterministic graph facts only (H1/H2).
Tests: ShellToolTest, PlanLinterTest, RecoveryRoutingTest green; detekt clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Ly2mMnt9TCZbvhcC1JfuV
Two failed web-ui freestyle runs dead-ended on the write manifest. The
scaffold_frontend stage declared writes=[frontend/package.json,
frontend/vite.config.ts], so every other file the scaffold produced
(tsconfig, src/main.tsx, index.html, App.tsx) was BLOCKED as
PATH_OUTSIDE_MANIFEST with no agent-facing escape hatch — unlike WRITE_SCOPE,
which advertises task_update. Retry exhausted -> WorkflowFailed.
- ManifestContainmentRule: a write already inside the active task's
affected_paths is allowed even when the stage manifest is narrower. The
task scope is the agent-widenable, recorded authority (see WriteScopeRule);
the stage manifest is a planner hint that defers to it. Block message now
names the remedy (widen affected_paths via task_update).
- architect_freestyle prompt: a scaffold/generator stage must declare its
`writes` as a covering directory glob (frontend/**), not enumerate files,
and use ** not * — frontend/* does not cover frontend/src/main.tsx.
core:toolintent green (78 tests), detekt clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A plan that failed grounding used to dead-end — every gate rejection in
FreestyleDriver.lockAndRun was terminal, so a legitimate grounding catch
(e.g. a stage declaring a PROJECT build with no manifest) left the run stuck
with no retry.
lockAndRun is now a gate loop: on a grounding rejection with retries left it
re-runs the planning workflow from the architect stage (rerunArchitect), which
emits a corrected plan, then re-gates. Other gate failures — and grounding once
maxGroundingRetries is spent — stay terminal.
- FreestyleDriver: gate loop + rerunArchitect/maxGroundingRetries seams;
groundPlan returns findings (String?) instead of Boolean; post-grounding
tail extracted to lockAndRunGrounded.
- DefaultSessionOrchestrator.runFrom(startStage) + emitWorkflowStarted(startStage);
run() delegates to it. Lets the re-run enter directly at architect.
- buildGroundingFeedbackEntry (ContextFeedback) injects the already-recorded
PlanGroundingEvaluatedEvent findings into the architect's L1 context on re-run;
wired in SessionOrchestratorExecution.
- Main: rerunArchitect lambda (rehydrate -> runFrom(architect) -> rehydrate).
The architect stage-entry approval gate already reuses a prior APPROVED decision
(alreadyApproved), so the re-run does not re-prompt the operator — added a
FreestyleApprovalGateTest regression guard proving runFrom(architect) with a
seeded approval emits no second request and runs straight through.
Tests: FreestyleDriverTest retry-then-lock + exhaustion->reject(source=grounding);
FreestyleApprovalGateTest reuse-approval guard.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This branch's uncommitted WIP, committed together (entangled at file level).
Distinct pieces of work:
Freestyle QA fixes (this session):
- FileEditTool: pre-validate replace anchor in validateRequest — reject a
missing/ambiguous target BEFORE the approval gate, mirroring read/write's
file-not-found / read-before-write pre-checks. Shared not-found/ambiguous
messages between validate and execute so they can't drift.
- PlanGrounder: add `scanned` flag; when no RepoMapComputedEvent was recorded,
repoMapPaths is "unknown" not "empty workspace" — skip scope grounding
(which proves a path ABSENT) so real paths (apps/server/**) aren't falsely
rejected. Build-manifest check still runs.
- FreestyleDriver: wire scanned=(repoMap!=null); on plan rejection emit a
session-terminal WorkflowFailedEvent so a rejected run reads FAILED, not the
COMPLETED-lie (last verdict was the planning-phase WorkflowCompleted).
- ServerModule: resolve project-memory workspace root from the session's bound
workspace (sessionWorkspaceRoot) instead of boot-static pm.repoRoot(), fixing
the workspace-binding divergence (correx vs empty scratch dir). Retire tracked
in Vikunja #266.
- LaunchRegistrationRaceTest: join registered jobs before asserting launchCount
— computeIfAbsent returns the Job immediately but the fire-and-forget launch
body lagged awaitAll (the 49-vs-50 flake).
ACR concept-compiler experiment (pre-existing WIP on this branch):
- ExecutionPlanCompiler/Model/PlanLinter, #264 needs-seam (sessionArtifacts),
LSP diagnostics subsystem (LspDiagnosticEvents/Runner/Lsp4j), BootWorkspace,
config surface, workflow prompts/schemas, orchestrator advance-don't-rerun.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
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>
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>
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>
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
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>
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>
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>
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>
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>
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>
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>
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>
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).
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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).
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).
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).
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.
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.
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.
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.
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.
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.