Production map-first reasoning kernel. Source of packages/opencode/src/session/prompt/reasoning_prompt.txt.
Before changing anything here, read docs/kernel-quality-doctrine.md. The kernel states rules; that file states why, and its § Craft is what keeps an improvement from making the prefix worse — a rule's position sets its price, a slot beats an imperative, constants are derived and never invented, and a red pin is a spec to move rather than noise.
flowchart LR
G0["G0 Understand"] --> G1["G1 Ground"] --> G2["G2 Decompose"] --> G3["G3 Master plan"] --> G4["G4 Authorize"]
G4 -->|ALLOW| G6["G6 Ground plan"] --> G7["G7 Implement"] --> G8["G8 Oracle"] --> G9["G9 Closure"] --> SUCCESS
G4 -->|CONCERN| G5["G5 Concern loop"] --> G2
G4 -->|ASK| WAITING_APPROVAL
G8 -->|repair| G6
G8 -->|invalid plan| G2
G9 -->|residual evidence| G1
G9 -->|invalid geometry| G2
G0 -->|ambiguous intention| WAITING_APPROVAL
G1 -->|ownership unresolved: ticket, observe, follow-up| G2
G2 & G3 & G5 & G6 & G7 & G8 & G9 -.->|INTENTION_RESET| G0
G1 & G2 & G6 & G7 & G8 -.->|DELEGATION| SUB["sub-agent / AICall falsifier"]
WORKFLOW: gates,gated_workflowsuccess path,forward_move/CONCERN/back_move/terminaledges.ABI_AND_VOCABULARY: precedence, reference grammar,INFORMATION_STATUS,SV_CONTRACT,SOURCE_ROUTING, state, and action classes.SHARED_RULES: definitions needed by multiple gates.GATE_REFINEMENT:G0..G9, with each gate's local rule definitions beside their use.- Advisory protocols: semantic attention, delegation, intention reset, evolution.
- Identity contracts.
source.py is the only semantic owner. validate.py rejects incomplete topology, duplicate rule ownership, broken state flow, unresolved identities/references, authorizing optional loops, and unsafe size budgets before rendering.
migration.py gives every legacy runtime rule an explicit disposition: preserved, merged into a named canonical owner, or delegated to a named host/runtime boundary. No legacy rule is silently dropped or retired.
dedup.py keeps schema and behavior distinct:
- state descriptions are compact data shapes; rules describe transitions and enforcement;
- unapproved state/rule similarity at or above
0.58fails validation; - reviewed overlap requires a pair-specific rationale in
SEMANTIC_OVERLAP_ALLOWLIST; - repeated five-token boilerplate, repeated ownership lines, duplicated edge serialization, and repeated identity authority clauses are regression-tested;
- the declared UTF-8 byte ceiling is 66,000; normalized-word ceilings are 8,700 for product and 8,800 for Claude, Codex and Cursor;
SV_FORMATandSOURCE_ROUTINGare typed IR contracts; compatibility fails if they or the digest/discipline coverage disappear.
evidence.py — read-only consumer predicates Rule/FSM на G6/G9. G1 выдаёт
STRUCTURAL_EVIDENCE; G3 — PLAN_STRATEGY и PORTFOLIO_AUDIT. G6 требует
релевантного структурного запроса со свидетельством свежести от parent/tool и
поддержанной стратегии относительно неизменной цели мастера. SUCCESS на G9
требует полного текущего аудита: каждый active root plan является стратегией,
каждый [x] имеет source/oracle pins, отдельный explorer report проверен родителем.
Присутствие имени файла, заявленные счётчики и текст DONE контракт не выполняют.
Consumers перечитывают SHA256 pins, секцию цели мастера и полный active inventory. Изменение, пропущенный план, устаревший отчёт, отсутствие проверки или неподчинённая стратегия запрещают SUCCESS. Открытая согласованная работа может оставаться; законный ограниченный stop сохраняется. Filesystem fixtures и mutation tests проверяют настоящие переходы Rule/FSM. Эти consumers и нормативный prompt сами по себе не являются runtime ACL каждого вызова модели; живые tool paths проверяются отдельно.
Codex bindings используют обнаруженные node_repl/apply_patch/exec_command/write_stdin, collaboration и cua_repl APIs. LSP/AST требуют отдельной привязки и квалификации. Во всех вариантах структурный CodeGraph предшествует scanners; read-only explorer получает refresh evidence, без shell authority. MCP pack сохраняет существующие Python/Delphi/Unicode paths вне фиксированных prefixes.
Измерение 2026-10-12: максимум 63 553 UTF-8 bytes / 8 571 normalized tokens. После восстановления награды и дополнения завершения задач (2026-10-15): product 65 381 B / 8 700 words, Claude 65 253 / 8 777, Codex 65 172 / 8 723, Cursor body 65 214 / 8 799. Конечный byte cap — 66 000; word caps указаны выше. Normalized tokens не являются измерением model tokenizer или FLOPs.
python -m pytest prompt_kernel/tests/ -q
python -m prompt_kernelAssembly writes only timestamped files under prompt_kernel/dist/:
YYYY-MM-DD_HH-MM-SS_reasoning_prompt.txtYYYY-MM-DD_HH-MM-SS_reasoning_prompt.mdcYYYY-MM-DD_HH-MM-SS_manifest.jsonYYYY-MM-DD_HH-MM-SS_migration_report.json
The stamp is local time, Windows-safe (2026-09-01_19-27-54). Tests write to a temp directory so pytest does not pollute dist/.
Install into production:
python -m prompt_kernel --installOrdinary python -m prompt_kernel (no --install) only stamps dist/ and leaves the working copy unchanged. build.py step_kernel runs --install.
cutover.py remains the hash-gated promote API (approve=True + current SHA-256).
GATE_ADDONS (addons.py) binds each gate to opencode's own tools
(codegraph, cmd_runner, applypatch, checkstate, messagesearch, nssm,
…). Everything else — WORKFLOW, ABI_AND_VOCABULARY, SHARED_RULES,
GATE_REFINEMENT's local rules, the protocols, the identity contracts — is
host-agnostic.
addons_claude.py swaps that binding for the Claude Code CLI's own tools
(Read/Edit/Write/Glob/Grep, a Bash tool and a PowerShell tool side by side,
Agent, AskUserQuestion, run_in_background + Monitor for long-lived
processes, the Browser tool for visual oracles) while keeping the same
kernel core. render_kernel, render_review, kernel_digest, and
write_artifacts all take an optional addons argument so any tuple of
GateAddons can be rendered without touching source.py.
python -m prompt_kernel --claudewrites stamped artifacts under prompt_kernel/dist_claude/ (same file
shapes as dist/: ..._reasoning_prompt.txt, .mdc, _manifest.json,
_migration_report.json).
python -m prompt_kernel --claude --installadditionally refreshes .claude/reasoning_kernel.md — a stable,
git-tracked, renderer-only file (never hand-edit it). .claude/CLAUDE.md
pulls it in with Claude Code's @reasoning_kernel.md import syntax, so it
loads automatically into every Claude Code session in this repo. Unlike
install_production/cutover (which hash-gate writes to the opencode
runtime prompt other code depends on), install_claude_kernel has no gate:
.claude/reasoning_kernel.md never carries hand-written content to protect,
only prior renderer output. Re-run --claude --install after any change to
source.py or addons_claude.py to keep it in sync — nothing does this
automatically yet.
Before wiring this in, note the size trade-off: the installed file is the
full kernel render (60 133 B as of 2026-10-05), so every session in this repo
spends that many tokens up front. If that is not wanted, remove the
@reasoning_kernel.md line from .claude/CLAUDE.md (the generator and
dist_claude/ builds stay unaffected either way).
addons_codex.py binds the same graph to this Codex harness: Read, Glob,
Grep, Edit, Write, LSP, AST Edit, Hub, Eval Browser access,
Todo, Task, and the mounted codegraph_explore device. It renders with:
python -m prompt_kernel --codexArtifacts are stamped under prompt_kernel/dist_codex/. Codex receives the
kernel ONLY as $CODEX_HOME/AGENTS.md (t64, owner 2026-10-16: «developer_instructions
писать не надо просто AGENTS.md в ~.codex и все» — reverses t54; the global file is
read whole, with no project_doc_max_bytes cap). Install it with:
python -m prompt_kernel --codex-global install--codex --install writes no receiver: the single writer is --codex-global install.
A running Codex task keeps the prefix it started with; the
installed variant becomes active for the next task.
Re-render it in the same motion as product --install and Claude
--claude --install, and check addons_codex.py whenever a sibling registry
gains a host binding — a shared mechanism with no instrument named on this host
is the defect the reverse-reachability check catches inside the graph and
nothing catches across variants.
addons_cursor.py binds the same graph to Cursor. Cursor publishes its agent
tools as capabilities rather than stable function names — Read File, List
Directory, Codebase, Grep, Search Files, Web, Fetch Rules; Edit & Reapply,
Delete File; Terminal; plus MCP servers — so this registry names the
capability the way the host presents it and makes the LADDER the binding. It
has no LSP tool, no background/daemon control and no session-history search;
each of those gates says so instead of naming a tool it does not have.
python -m prompt_kernel --cursorArtifacts are stamped under prompt_kernel/dist_cursor/. Install into the
always-apply rule receiver with:
python -m prompt_kernel --cursor --installwhich refreshes .cursor/rules/reasoning-kernel.mdc: the rendered body plus
the description/alwaysApply: true frontmatter Cursor's .mdc reader
requires, written atomically after kernel and migration validation plus a
stamped-artifact equality check. The returned digest is the BODY's digest, so
it compares with a dist_cursor/*_reasoning_prompt.txt stamp. ADID ships this
generated file to the projects its installer serves; before that host existed,
artefacts/rules/reasoning-kernel.mdc was a hand-copied fork and drifted a
whole kernel generation behind — test_variant_parity.py now fails if the
host-agnostic bindings are retyped instead of copied.