The system block is now for content that does not change during a run.
Anything the run mutates renders as a user message — both because a
mutating system prefix defeats prompt caching and because models
under-weight system-folded content against the trailing user turn.
PromptRenderer: role alone decides the message type; the old
`layer == L0 ||` clause is gone. That clause was silently overriding
role on four packs (InferenceSummarizer, SemanticReviewerImpl,
CapabilityGapReflectorImpl, Talkie session-naming) which are L0+USER
prompts — they were rendering as a system-only request with no user
turn at all.
Re-roled SYSTEM -> USER, all mutable within a run:
recoveryTicket, remainingDelta, groundingFeedback, rejectionFeedback
(trailing slot), plus verifiedBaseline, promotedConcept, claimedTask,
clarificationAnswer, locked steeringNote, factSheet (inline, still
L0-pinned).
Left SYSTEM (immutable): systemPrompt, operatingGuidance,
schemaInstruction, projectProfile, operatorProfile, agentInstructions,
successfulPlanShape.
Trailing-slot scarcity guard: repairMandateSourceTypes joined ALL
matches, so a recovery stage on a retry with an unmet delta would stack
three competing mandates. Now a precedence list emits exactly one
(recoveryTicket > retryFeedback > groundingFeedback > rejectionFeedback)
with remainingDelta appended as the completion signal.
ContextClassifier keys STATIC on layer alone — L0 means pinned/never
pruned regardless of role, so the re-roled L0 entries don't fall through
to FREEFORM and get token-pruned.
Also fixes a stale ContextFeedbackTest assertion (expected a CAS hash
the producer deliberately stopped emitting) and a stale initialIntent
doc comment claiming L0/SYSTEM where the code says L1/USER.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Audits every ContextEntry producer against PromptRenderer's three real
render destinations (system fold / inline / trailing user slot). Finds
four escalation-grade entries roled SYSTEM and therefore buried in the
leading system message: recoveryTicket, remainingDelta, groundingFeedback,
rejectionFeedback. remainingDelta additionally mutates the cached system
prefix every turn.
Report only, no code changes. Re-role work filed as #313.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The kit (SKILL.md, ethos.tokens.css, ethos-icons.svg, .oxlintrc.json) lived
inside frontend/ — the exact dir freestyle runs scaffold into. vite refuses a
non-empty target, so every session improvised a stash-aside (frontend_backup/,
frontend_temp/) and left scratch dirs behind. Move the kit to a sibling
design-system/ so frontend/ starts clean, and deliver it via the L0 conventions
channel (project.toml) rather than seeding files in the scaffold target: copy
the token/icon assets in (don't read them), SKILL.md for rules only. Un-ignore
frontend/ so scaffolded output is tracked going forward.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HMbPmZZjcXhR2crU82zZ8S
A foreground long-running command (npm run dev, vite, a --watch task) hit
the 30s timeout and returned recoverable=false, giving the stage no
transition to take -> WorkflowFailed "no transition condition matched"
(killed session d734e1de). A non-zero exit right below already returns
recoverable=true; a timeout is no more fatal. Return recoverable and coach
the model to start the process detached (nohup ... &) and verify separately,
or run a one-shot that exits. No background-process registry: the model
backgrounds it itself via `&`, which already routes through `sh -c`.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HMbPmZZjcXhR2crU82zZ8S
L3 semantic retrieval does a bad job on the repo map: docs embed a terse symbol-list
descriptor while queries embed prose intent, an asymmetric comparison that collapses all
scores into a ~0.5 noise band (session 459: junk hits at 0.53/0.54, real relevance never
reached). At 0.5 the noise-winners cleared the bar and suppressed the deterministic
repo-map floor. 0.6 sits above the noise ceiling (~0.55) and below the real-signal floor
(0.68) so noise → empty → fall back to the repo map.
Band-aid, not a fix — the real remedy is a prose-shaped repo-file descriptor so query and
document share a representation space. Calibration knob, retune if the embedder changes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HMbPmZZjcXhR2crU82zZ8S
The shipped Store 1 persisted repo-file descriptors in a new SqliteObservationStore
— a second, unsynchronized SQLite writer on the event-log DB (no WAL/busy_timeout,
one shared Connection across coroutines) holding a fact the log already carries. That
violates "the event log is the only source of truth" (inv #1/#8): an Observation is
just FileWrittenEvent.path + postImageHash + describe(bytes).render(), and render is a
pure function of content-addressed CAS bytes.
Replace the whole durable apparatus with an in-process memo (descriptorMemo, keyed on
repoRoot+path+contentHash) on the orchestrator, next to the existing artifactContentCache.
Rebuilt from the log on restart, disposable, no external store. Preserves the perf win
(skip CAS read + regex on repeat describes) with none of the concurrency/lock risk.
Deletes: ObservationStore/InMemoryObservationStore/SqliteObservationStore (+ tests),
InfrastructureModule.createObservationStore, the FileReadTool priming path (which never
hit anyway — it keyed on a workspace-relative path while every consumer looks up the
absolute FileWrittenEvent.path), the FileReadConfig/SessionOrchestrator plumbing, and
five orphaned build.gradle deps.
Store 2 (soft-confidence hints) unchanged — it was correct.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HMbPmZZjcXhR2crU82zZ8S
Store 2 (Fixes): ConceptCompilerProjection already tracked the
unconfirmed(validatedFixes>=1)/falsified(contradicted)/confirmed(promoted)
lifecycle as data, but only confirmed (>=threshold) clusters were ever
delivered. unconfirmedFixEntries reactively matches the CURRENT retry's
classKey against that state and injects a soft one-shot hint (below
threshold) or steer-away (contradicted) before hard promotion — wired
into stage context build in SessionOrchestratorExecution.kt.
Store 3 (Plan-shapes): already shipped as SessionOrchestratorPlanPatterns.kt
(deterministic keyword-Jaccard over eventStore.allEvents(), no embedder
needed) — confirmed complete, no new code required.
FileReadTool hot-path extension to Store 1: a whole-file read now primes
the cross-session ObservationStore (when wired) the same way the write
path already does, so a later describeCached lookup for the same content
hash is warm even if the file was only read, not written, this session.
Adds ObservationStore (core:context) keyed on (repoRoot, path), an in-memory default and
a durable SqliteObservationStore (infrastructure:persistence), and wires it into the two
SessionOrchestratorArtifacts call sites that re-derive a SourceDescriptor from CAS bytes
on every call — a hit on matching content hash skips both the CAS read and the regex
extraction. First slice of docs/plans/2026-07-21-acr-knowledge-accretion.md (build order:
observations before fixes/plan-shapes).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HMbPmZZjcXhR2crU82zZ8S
A stage (configure_ethos_theme) looped forever re-writing an identical
postcss.config.js: file_write returned "written successfully" on a byte-
identical write, and the retry-feedback entry that says WHY it failed got
truncated out of context every turn, so the model cold-started on the same
wrong idea. CAS hashes leaked into its face from two sides too.
- SandboxedToolExecutor: a write whose result is byte-identical to disk now
returns "No change: … nothing was written" (+ noop=true) instead of a false
success signal. Uses the pre-image hashes already captured for reversibility.
- DefaultContextPackBuilder: pin "retryFeedback" in neverDropSourceTypes so the
failure reason + already-written-files list survives truncation.
- ContextFeedback: drop the opaque "— CAS <hash>" from the retry entry; path only.
- tool_output withheld until the session actually spills over-cap output to CAS
(StageConfig.ALWAYS_AVAILABLE_READ_TOOLS -> on-demand via sessionHasSpilledOutput),
so a hash-eating tool isn't advertised to every stage that never spills.
- Wrap 10 long lines in kernel to bring detekt back under maxIssues (99 -> 89).
Tests: infrastructure:tools (+2 no-op cases), core:{transitions,context,kernel} green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The #301 escalation event shipped unregistered — it would silently fail to
deserialize on replay, dropping the persisted write-scope grant and re-prompting
the same path every session restart (breaks replay invariant).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Small models frequently fail to comply with the WRITE_SCOPE/PATH_OUTSIDE_MANIFEST
remediation ("add its path via task_update affected_paths") and instead thrash the
same out-of-scope write call turn after turn, burning the session without ever
completing. After `tuning.escalateScopeAfterN` (default 3) consecutive rejections
of the SAME path for a scope/manifest reason, the orchestrator now reaches back to
the FIRST rejected invocation of that path (its pristine, pre-degraded arguments),
and routes it through the existing approval/pause flow instead of rejecting again.
On approval, a new WriteScopeGrantedEvent widens the effective write manifest for
that path for the rest of the session (mirroring how OutsidePathAccessGrantedEvent
already widens out-of-workspace reads) and the first attempt's write is executed.
On denial, the call is rejected as before. escalateScopeAfterN = 0 preserves the
old hard-block-forever behavior.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GeyGFXczJb8RUWGBKmkm6G
Live incident: "Write a web-ui for Correx" resolved to a pre-existing parent
epic (webui-8, with children webui-9..14). The old prompt only said "name a
task that covers this work" and, separately, "after decomposing, name the
single ready child" — it never said what to do when an EXISTING task found
via task_search/task_context is itself a parent. The model oscillated
between naming the epic, re-decomposing, or working a child until it burned
all 16384 reasoning tokens and emitted nothing.
Reworded analyst_freestyle.md's task-framing section so every branch
(existing leaf, existing parent, no task yet + single unit, no task yet +
needs decomposition) converges on one rule: never name a parent/epic, always
name the single ready child — removing the decision entirely rather than
asking the model to make it under ambiguity.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GeyGFXczJb8RUWGBKmkm6G
HealthMonitor's periodic poll took ~18s to notice a dead provider — long
after a retry had already re-selected it and died. Health needs to GATE
routing, not just log reactively.
- InferenceRouter.reportFailure(providerId, reason): new default-no-op
method; DefaultInferenceRouter implements it by writing Unavailable
straight into its health cache, bypassing healthCheck()/TTL entirely.
- SessionOrchestrator.runInference: on a connection-level exception
(ConnectException/SocketException/IOException or a message matching
"prematurely closed"/"connection refused"/"connection reset"), call
reportFailure immediately so the very next route() call — the retry driven
by #299 — sees the provider as down right away instead of re-selecting it
and dying again.
Pairs with #299: routing now (1) reacts to a connection drop instantly and
(2) waits/backs off for the capability to recover before declaring terminal.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GeyGFXczJb8RUWGBKmkm6G
A transient provider connection drop (e.g. OOM-killed llama.cpp mid-request)
collapsed into a hard NoEligibleProviderException that escaped runInference's
try/catch (the route() call sat outside it), propagated past the stage retry
loop, and landed in ServerModule's session-level catch — failing the WHOLE
session even though the failure was retryable and the provider recovered
seconds later.
- SessionOrchestrator.runInference: wrap router.route() in try/catch so
routing failures become InferenceResult.Failed and flow through the normal
retryable/backoff/exhaustion machinery instead of escaping.
- DefaultInferenceRouter.route: distinguish "capability never configured on
any provider" (fail fast, waiting can't help) from "configured but
currently unhealthy" (bounded wait/backoff — default 3 attempts x 2s —
re-checking health before declaring NoEligibleProvider terminal).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GeyGFXczJb8RUWGBKmkm6G
Add per-agent sprint handoff docs (Sonnet/Codex/opencode) mapping the
1-week sprint's two goals to concrete Vikunja tasks. Kept in repo root
(docs/ is gitignored). Includes hanging Lsp4jDiagnosticsRunner change +
its live-proof test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rdo9fe7SujNVeyZA8YkpkD
file_edit failed en masse for small models on two ergonomics traps:
- replace() rejected calls that sent `content` (the append param) instead of
`replacement` — intent unambiguous; now accepted as an alias.
- exact-string match died on leading-whitespace drift (model can't reproduce
indentation). Added whitespace-flexible line matching + replacement reindent,
wired into both the pre-exec validation gate and replace().
Also made the WRITE_SCOPE / PATH_OUTSIDE_MANIFEST block messages emit a literal
copy-pasteable task_update(id=..., affected_paths=[...]) call and warn against
action=block — the exact wrong turn models kept taking (18x in one session).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rdo9fe7SujNVeyZA8YkpkD
Weak models re-emit `npm -v` as ["npm,","-v"] or ["npm\",","\"-v\""] —
the JSON array separators leak into the tokens. The collapsed-array guard
rejected these, and the model re-emitted the identical mangle until
stage_loop_break killed the run (observed 6x on the web-ui QA workflow,
session 508c8d58). Strip stray leading/trailing quote/comma per token so
the call runs instead of looping the stage to death. Internal commas
(--foo=a,b) are kept; a single fully-collapsed token still rejects.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
At the terminal boundary (repair ladder spent, or a non-recoverable gate
exhaustion), run exactly one tool-free diagnostic inference per terminal
failure fingerprint over recorded facts only. A validated — materially new,
confident, recovery-stage-available — RecoveryProposal routes once into the
existing recovery stage via the ticket machinery, bypassing the spent route
budget but bounded by a one-diagnosis-per-fingerprint dedupe so no loop is
possible. Otherwise the run stays terminal FAILED (safe degrade when no
diagnoser is wired).
- New PostFailureDiagnosedEvent + nested RecoveryProposal (registered in
eventModule); every observation/proposal/decision/route recorded for replay.
- PostFailureDiagnoser seam (nullable, mirrors SalvageJudge) + DiagnosisInput
built from the event log only (no fresh workspace observation).
- diagnosisMinConfidence tuning knob.
- Hooked at both terminal boundaries: routeToRecovery ladder-exhausted and
decideGateExhaustion.
Tests: RecoveryRoutingTest (route-once-then-bounded, low-confidence stays
terminal), EventsTest serialization round-trip (proposal + null).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Move intent, repo map, docs catalog, decision journal and relevant-files
context entries to EntryRole.USER so they no longer fold into the single
leading SYSTEM block — that block stays pure policy/schema. Omit L3 repo-map
retrieval on repair retries (the transcript already carries the evidence).
Add "initialIntent" to REQUIRED_SOURCE_TYPES.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
buildRetryFeedbackEntry was L1/SYSTEM, so PromptRenderer folded it into the
leading system block — far from the assistant/tool transcript and weaker than
the original stage task. Flip it to USER role and give the renderer an explicit
trailing repair-mandate slot (a sourceType set, extensible for recovery later):
repair mandates are lifted out of the inline flow and emitted once as the final
message, after the tool evidence and the steering anchor. retryFeedback is
already in REQUIRED_SOURCE_TYPES so it stays unprunable. Golden renderer test
proves the final message is the repair USER mandate and leading system no longer
carries it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A successful file_write/file_edit echoes the whole file body (+ diff) back in
its tool result — up to ~30k chars, which pushed the traced Gemma4 request past
its context window. The write already happened and its full output is durable in
the event log/CAS; the model only needs a receipt that it landed. Replace each
exit=0 write result with a one-line receipt (path + elision marker) in the
context builder; reads, gate output, and nonzero-exit writes stay verbatim.
Derived-only pass over the transcript — authoritative events are untouched, so
it's replay-safe.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
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>