Skip to content

feat(kernel): add history-backed session lifecycle - #2687

Merged
jbeda merged 1 commit into
mainfrom
impl/kernel-session
Nov 5, 2026
Merged

jbeda merged 1 commit into
mainfrom
impl/kernel-session

Conversation

@jbeda

@jbeda jbeda commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Deliver the lifecycle inspection checkpoint for #2663: an isolated, passive history-backed session aggregate. This is not completion of #2663 or parent #2659, and production sessions do not use this package.

  • Add explicit creation, successive runs with one active owner, run-owned exact input bytes, and explicit interruption.
  • Validate ordered batches atomically and publish only accepted facts. Preserve exact frozen retry for unknown acceptance, conflict/reload barriers, and accepted-but-local-apply failure semantics.
  • Expose immutable O(1)-capture snapshots backed by owned decoded records and append-only indexes; reconstruct through the same apply path with pinned History reads.
  • Separate ordinary soft admission from hard persistence bounds. Prove the actual encoded interruption fits hard capacity before accepting an active write; replay remains hard-valid even when a reader's policy leaves no future write headroom.
  • Add generated persistence codecs/API snapshots and architecture guards without changing production entry points, History envelopes, or codec-runtime semantics.

Deliberate boundary

Only creation, run start, authored input, and interruption are implemented. No model/tool execution or lifecycle facts, normal completion, request constructor, usage accounting, pending-input service, distributed writer fencing, or production integration.

Inputs belong to active runs; loading leaves active runs active and never synthesizes an interruption. Intentional early-kernel Go/payload contracts are isolated from the legacy aggregate.

Verification

Fresh delivery gates on commit 6a7b064edaa3130b8fdb6d5c20d8b6614c6d17a4:

  • task lint — passed across configured modules.
  • task test:race — passed complete offline suite, modules, and standalone proofs.
  • go run ./cmd/mecademo — passed; actual Read call/result and Write permission ask, approval, and result observed.
  • git diff --check — passed.

Earlier implementation evidence also includes generation/API/codecs freshness, docs, full offline tests, engine standalone, focused kernel/history/architecture race, session 386/fuzz, and independent Spec/Standards/Test/Domain review. Targeted test-gap fixes and the soft/hard amendment were incrementally rechecked; remaining findings and reviewer failures were zero. This does not claim a newly repeated whole-branch panel.

API compatibility

No remote-observable API/behavior change: no production callers, protobuf/server/client changes, major bump, feature identifier, or client upgrade requirement. Experimental kernel Go APIs and session payloads are new isolated contracts with snapshots tracked; no legacy session migration or mixed-version read promise. Existing History envelopes/codec contracts remain unchanged. Early-kernel changelog bookkeeping is waived by scoped guidance.

Tracking and next work

Related to #2663; do not close it from this checkpoint. The approved design interview splits continuation into reusable context/content facts, passive model/tool lifecycle, then a separate versioned request-construction library. Concrete accounting remains a later explicit checkpoint. No future implementation is included here.

The full completed-slice plan is archived and readback-verified in one identifiable conversation comment. Humans own merge; no automatic merge is configured.

Add isolated session batching, run-owned inputs, immutable snapshots and pinned reconstruction. Separate soft write admission from hard persistence bounds while preserving explicit cleanup and uncertain-acceptance recovery.

Co-authored-by: Mecatl <[email protected]>
@jbeda

jbeda commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Completed lifecycle checkpoint — full plan archive

  • Slug: kernel-session
  • Source plan: .scratch/kernel-session-plan.md (local provenance, not a remote link)
  • Branch: impl/kernel-session; base: main
  • Recorded start: 0c7308afdf0e30296265e87aed45b61dac5543da
  • Verified PR head: 6a7b064edaa3130b8fdb6d5c20d8b6614c6d17a4
  • Archived: 2026-11-05
  • SHA-256 of the exact plan portion below: 47f6db97541643a35829354c1404c46ed4cf1415a709114704275056740293ac

Full publishable plan, with no substantive omissions. The 2026-11-05 delivery amendment supersedes historical no-push/no-PR and pending-status prose. This archives the completed lifecycle slice, not the new context/content plan or obsolete Phase B tasks. Planned verification below is distinguished from actual delivery results in the PR body. Future implementation remains separately authorized; humans merge.

Isolated session: run-owned inputs and immutable snapshots

Slug: kernel-session
Implementation branch: impl/kernel-session
Base branch: main
Plan path: .scratch/kernel-session-plan.md
Recorded implementation start: 0c7308a
Owning story: #2663; parent: #2659

Scope and authority

Joe authorized and completed the run-owned-input/immutable-snapshot revision on
2026-11-04, then approved its limits amendment and documentation cleanup. The slice
is committed as 6a7b064edaa3130b8fdb6d5c20d8b6614c6d17a4. Holistic review/gate
evidence: .scratch/kernel-session/owned-review.md; amendment and targeted-recheck
evidence: .scratch/kernel-session/limits-review.md.

Delivery amendment, 2026-11-05: Joe authorized publishing this existing slice
as a PR and preparing it for human merge. Push/PR/plan-archive publication are now
authorized; earlier no-push/no-PR statements below are historical and superseded
by this amendment. Preserve the existing commit/branch; no automatic rebase, reset,
production integration, or further implementation. This does not complete #2663
or #2659. New lint/race/demo delivery evidence is recorded separately.

The next-slice design interview is complete. Agreed direction and the three future
checkpoints are recorded in .scratch/kernel-session-next-slice-decisions.md and
#2663 (comment) . The next
plan covers reusable context/content facts only; it does not authorize implementation.
This completed plan does not authorize next-slice implementation or old Phase B tasks.
Historical grounding/task-status prose below describes earlier planning moments;
current code and the completed review receipts govern what was actually implemented.

This plan supersedes the old idle-input/consumption model and detached-copy
snapshots. .scratch/kernel-session/plan-before-run-ownership.md, batch-run.md and
batch-review.md describe older candidates, not the current implementation.
.scratch/kernel-session/review-todos.md is the review queue. The limits amendment
has precedence over the implemented baseline contracts/tasks below wherever their
admission timing, policy bounds or replay requirements conflict.

Scope remains four lifecycle record kinds only. No model/tool/accounting vocabulary
or execution, successful-run outcome, steering delivery, queues, drafts, execution
retry, run model configuration, production integration, new backend, distributed
fencing, checkpoint framework, generator expansion, borrowed bytes, generic CoW
maps or precise heap accounting. Snapshot/view-package separation was discussed:
a peer session/view is plausible but needs a shared-value and internal ownership
boundary; no package move was selected or authorized. Keep current layout.

Limits amendment: soft admission, hard bounds and error timing

Agreed behavior

  • Cumulative session size has soft ordinary-write limits and absolute hard limits.
    Soft is enforced admission, not a warning. An ordinary commit whose resulting
    accepted state would exceed a soft limit is rejected atomically before Append.
    Cleanup-only commits may exceed soft limits but never hard limits. Existing
    per-payload and per-commit codec limits remain absolute safety bounds.
  • In the current vocabulary only an interruption-only commit qualifies as cleanup.
    Other cleanup-only facts may join the same class after their semantics and
    required headroom are defined; no future settlement vocabulary or generic
    extension framework is introduced now. A mixed ordinary/cleanup batch is ordinary,
    even if its final state is idle; adding interruption is not a soft-limit bypass.
  • Keep eager per-record bounded CBOR encoding and ownership at addition. A record
    exceeding its own payload-local codec limits fails immediately, close to its
    cause. Local identity/lifecycle checks, provisional IDs and failed-addition
    atomicity remain. Successful additions do not promise aggregate admission.
  • Move aggregate rejection to submission: whole-commit record/envelope bounds,
    projected cumulative soft/hard counts/bytes/work, cleanup classification and
    required closeout headroom are checked for the complete proposal, before storage.
    Remove aggregate checks from checkAdd/add/AddInput, including per-batch count and
    cumulative session-byte checks. Retain overflow-safe arithmetic; locally collected
    counters may never wrap merely because policy admission is deferred.
  • The trusted in-process builder is not a memory sandbox against its caller. No
    speculative-memory budget, sticky/deferred builder error or deferred encoding
    mechanism. Preserve hard bounds before governed allocation when reading external
    DTOs/bytes; reject oversize output before any append so later readers are protected.
  • Load and public accepted-commit Apply perform hard admission and lifecycle/identity
    validation, not soft write admission. They must reconstruct valid history above
    soft limits, up to hard bounds. They must not require headroom for a hypothetical
    future write merely to read an otherwise hard-valid prefix. An active snapshot
    can be readable even when a tighter reader policy leaves no writable headroom.
    Keep one decoded reducer/owned publication path; separate admission context from
    shared semantic validity rather than inventing two lifecycle implementations.
  • For a newly proposed write leaving an active run, prove its actual subsequent
    interruption fits the HARD limits using the real encoding/preparation path.
    Soft < hard alone is not sufficient proof. The hypothetical closeout itself
    follows cleanup-only admission, never ordinary soft admission; avoid recursion.
    This invariant concerns writes under their policy, not a stronger guarantee for
    histories loaded under a different policy. Capacity is not backend availability.
  • Capacity rejection before Append is definitely not accepted: zero ref, no accepted
    state change, close the rejected batch/release slot, and permit replacement cleanup
    with unchanged accepted ordinal allocation. No partial commit salvage or automatic
    cleanup submission. Per-record add failure preserves earlier successful additions.
  • Cleanup retains normal lifecycle/CAS/uncertainty/conflict rules. No priority path,
    hard-limit bypass or conflict immunity. Unknown append acceptance retains the exact
    frozen proposal and existing explicit retry/reload barriers. Accepted-local failure
    still preserves the accepted ref and requires reload. Snapshots stay consistent.

Approved policy/API contract (2026-11-04)

Joe authorized implementation and approved this layout: existing MaxRetainedRecords,
MaxPayloadBytes and MaxDecodedWork remain hard bounds. Add explicit positive
SoftMaxRetainedRecords, SoftMaxPayloadBytes and SoftMaxDecodedWork, each <= its hard
counterpart, without defaults/fractions. Payload/per-commit limits stay hard-only.
Actual encoded interruption-fit reservation remains mandatory for writes. Expose
ErrAcceptanceUnknown on the existing backend-error wrapper while preserving causes,
so cause collisions cannot disguise uncertain acceptance as local rejection.
L1 is resolved; L2–L4 are authorized. No view-package move, production integration,
commit, push or PR. Earlier unapproved-status prose is historical and superseded here.

Dependency-ordered pending tasks

L1. Completed: policy contract approved. Existing Max fields are hard; explicit
SoftMax counterparts cover all three cumulative dimensions, positive <= hard,
no defaults. ErrAcceptanceUnknown marks the existing backend wrapper and
preserves causes; public source/schema compatibility remains isolated.
L2. Completed: separate admission from construction and replay. Remove
incremental aggregate rejection while retaining payload-local eager encoding,
ownership, IDs and local validation. Whole-proposal preflight classifies cleanup,
checks ordinary soft or cleanup hard limits, and actual hard-limit closeout fit
before Append. Shared decoded application/Load enforce hard validity only, not
soft admission or hypothetical future writable capacity. Keep uncertainty and
slot barriers intact. L2 and resource tests below integrate as one safe change.
L3. Completed: regression proof through real boundaries. Use real History/memory backend and
detached before/after oracles (the earlier aliased-snapshot weakness is fixed).
- Individually valid additions can cross a projected aggregate threshold without
error; submission rejects with no Append, unchanged state/counters/IDs and a
released slot. Replacement interruption-only submission succeeds in headroom.
- Payload-local codec oversize still fails during addition without mutating prior
builder facts. Whole-commit count/envelope limits fail at submission.
- Ordinary exact-soft-bound acceptance and over-soft rejection; cleanup above
soft up to hard; mixed batches cannot bypass soft, including an idle result.
- Actual interruption exact-fit/one-short hard capacity, counts/bytes/work and
sequence/ordinal/CBOR boundary cases; cleanup cannot exceed hard limits.
- Load and asserted accepted Apply succeed for hard-valid history above soft
without writes; later ordinary submission rejects but cleanup can fit when
headroom exists. Hard-invalid external history rejects before governed work.
Include readable active history with no future headroom under a tighter policy.
- Local capacity rejection versus unknown acceptance is observable even when
backend Append wraps codec.ErrLimitExceeded (or the same limit cause used by
admission). Assert slot release/replacement cleanup for the pre-Append path,
versus identical frozen proposal/replacement blocking for the backend-error
path. errors.Is on an unwrapped cause or a zero ref alone is not a verdict;
L1 must settle the minimal caller-visible outcome distinction.
- Update baseline assertions that intentionally change: in
session_sequence_test.go and session_closeout_envelope_test.go, writer
prepare/Submit still require future closeout capacity, while hard-valid
asserted Apply/replay no longer rejects solely for lacking that capacity.
Keep hard bounds, canonical identity, and semantic legality checks in both.
- Lifecycle, pinned replay, immutable snapshots, retry/late-acceptance/conflict,
error redaction and accepted-local-failure contracts remain intact. Admission
changes must not reintroduce cumulative scans/copies or mutable old snapshots.
L4. Completed: docs/API/gates and targeted review. Correct only owning Godoc/README/API
snapshots (generated via owning tasks), preserve early-kernel changelog exception.
Integrating agent runs the existing focused/race/386, standalone/full gates below.
Compare the exact amendment delta with owned-final-candidate.tar; recheck Spec,
Test and security/architecture axes affected by admission/read-boundary changes.
Prior full panel covers the unchanged baseline, not these new semantics. Stop
at Phase A for Joe; no commit/push/PR or next-phase implementation implied.

Planning critique: no blocking inconsistency. An Important error-cause-collision
regression gap and Advisory identification of intentionally changing baseline tests
were folded into L3 and text-only rechecked as resolved. Receipt:
.scratch/kernel-session/limits-plan-review.md. L1 was subsequently approved and
L2/L3 implemented; that planning receipt alone makes no runtime claim. Actual new
implementation, gate and targeted-review evidence is in limits-review.md.

Grounding

  • engine/kernel/session/session.go:101-105,206-270 and snapshot.go: current
    O(1) snapshot capture and owned append-only publication are implemented. Run/input
    locators and chronological record handles replace cumulative clones.
  • session/lifecycle_state.go:22-49: shared scalar transition rules implement
    run-owned input; no idle-input selection or consumption tracking remains.
  • session/session_commit.go:93-154: current additions still reject per-batch and
    cumulative capacity early. Move those checks to submission, not payload encoding.
  • session/session_commit.go:229-274: retain one-attempt append, frozen identical
    retry, terminal/reload and accepted-local-failure distinctions.
  • session/session.go:129-173,208-253,311-329 and
    session/lifecycle_state.go:53-77: preparation and accepted replay currently share
    admit/reserve policy. The amendment separates write admission from hard-valid
    reconstruction while preserving common semantic reduction/owned publication.
  • session/policy.go:12-39: current explicit positive policy has one cumulative
    ceiling per dimension and no defaults. The soft/hard public shape is pending.
  • session/format/{user_input,run_started}.go: mutable local-ordinal DTOs remain
    schema owners. No payload-schema or History envelope change is expected for the
    limits amendment; no second retained content model or handwritten generated code.
  • history/format/commit.go and history/history.go: History owns atomic ordered
    commits, ancestry/CID verification, bounded reads and conditional append.
  • Production engine/agent/loop.go:2658-2715 records initial input inside a run;
    steer.go:221-255 records additional input under that run. Retry at
    loop.go:1344-1368 can start a run without a new prompt. Existing production
    conversation/model does not explicitly enforce input ownership; no legacy API
    integration follows from this research.

Paths abbreviated above are under engine/kernel/ except production paths.
Code is authoritative; historical drafts are not implementation specifications.

Implemented baseline contracts

The following records the completed run-owned snapshot revision. Pending limits
admission/replay changes above override conflicting resource-check statements.

Identity and lifecycle

  • Session creation is explicit, first and unique. At most one run is active.
  • RunID remains {HistoryID, Ordinal}: contiguous one-based ordinals per history.
  • InputID becomes {RunID, Ordinal}: contiguous one-based ordinals per run.
    There is no parallel history-wide input ordinal. Zero IDs are invalid;
    validation and Next retain scoped meaning and overflow checks.
  • Every accepted input names exactly one owning run, which must be active at
    that record's position. No input before run start, for a foreign run/history,
    or after interruption. Drafts are not accepted inputs and have no schema here.
  • RunStarted no longer selects/consumes inputs. Its DTO retains its run ordinal;
    UserInput retains owning run ordinal, run-local input ordinal and exact bytes.
    RunInterrupted still explicitly names and closes the active run. Creation's
    payload stays empty. Verified history context supplies HistoryID; conversion
    rejects conflicting context before discarding redundant scope.
  • RunStarted and UserInput are separate facts. A normal initial prompt batches
    both atomically, start first. Input-free runs are legal; multiple input facts
    may belong to an active run. The reducer cannot require an input on every start.
  • Interruption grants no outside-world cancellation, clears active state only
    after acceptance, starts no successor and is never synthesized by Load.
  • Remove input selection, consumption flags/bitmaps/maps and their delta machinery.
    Minimal transition state is creation, run count/active identity, active-run
    input count and existing retained-record/payload counters. Reset input count
    on start; validate exact next input ordinal with overflow-safe arithmetic.

Batch and error boundaries

Keep New I/O-free, History/policy bound and operations caller-serialized. Snapshot
capture also follows that discipline; Session itself is not concurrently callable.

Public builder sketch (request/type names may follow existing conventions):

batch, err := s.BeginCommit()
// handle err; batch.Discard() remains available before submission
err = batch.Create()                   // only for a new session
runID, err := batch.StartRun()
inputID, err := batch.AddInput(AddInputRequest{RunID: runID, Content: content})
ref, err := s.SubmitCommit(ctx, batch)
// later batch: batch.Interrupt()

No empty CreateRequest, StartRunRequest or InterruptRequest. AddInputRequest is
explicitly data-bearing and carries RunID. Parameter-free start is not a promise
that future run configuration will remain parameter-free.

  • IDs are provisional until storage acceptance; accepted ordinals have no gaps.
    Earlier same-batch run IDs can own later inputs. Failed additions consume no
    slots/IDs; prior additions remain. Discarded/local-rejected batches reserve none.
  • Additions eagerly own canonical encoded payloads and only small private typed
    validation metadata. Caller byte buffers may be reused after addition returns.
    Preflight and decoded reduction use shared typed lifecycle checks.
  • Keep one open/unsettled batch. Freeze and metadata-preflight before one Append
    attempt. Local rejection releases the slot, leaves accepted state unchanged,
    and permits a replacement batch. Wrong/stale handles cannot release another slot.
  • After the storage attempt the batch cannot be cancelled into a new independent
    proposal, including after timeout/context cancellation. Unknown acceptance keeps
    identical frozen bytes/identity for explicit retry with a fresh context.
  • Conflict, retry expiry, newer observed head, or accepted-but-local-apply failure
    preserve existing reload barriers. Expiry is not rejection. Accepted-local-failure
    returns the accepted ref; never resubmit it as a new logical commit.
  • A failed update never partially publishes snapshot state. Before storage attempt,
    failure must leave the Session reusable. After the non-cancellable boundary,
    ancillary bookkeeping may be ahead/dirty only while independent writes are
    blocked until settlement/recovery. Correctness-critical validation state cannot
    be dirty when a next independent batch is allowed.
  • Make Prepare and PrepareInterruption internal, retaining real closeout preparation.
    Prepared has no demonstrated public purpose once their return paths disappear;
    make it internal too. Preserve Apply's existing verified replay/asserted-acceptance
    contract and batch/reload barrier unless a concrete implementation conflict is
    surfaced; ordinary clients use SubmitCommit and Load, not Prepare/Append/Apply.

Immutable snapshot/read surface

Snapshot is an accepted-state handle, not a mutable detached export or restore token.
Capture is O(1); copying a handle is safe. Concurrent readers need no session locks,
including while the session owner appends. No lazy mutable cache or session lookup
is permitted in snapshot/child-handle methods. Independent traversals share no
mutable cursor. An old handle never observes later inputs, runs, records or scalars.

Required public-contract sketch (review coherently before implementation consumers):

Snapshot: HistoryID, Head, Created, ActiveRun via scalar getters
          RunCount / RunAt(zero-based position)
          RecordCount / RecordAt(zero-based chronological position)
Run view: ID, InputCount / InputAt(zero-based run-local position)
          RecordCount / RecordAt(zero-based run-local chronological position)
Record view: Kind, KindVersion and concrete typed view access
Input view: scoped InputID; exact Content exported by copying
Start/interruption views: scoped RunID and their actual DTO fields

Method/type names and routine Go collection edge behavior are contract-sketch
choices to spell out in Godoc/tests, not reasons to widen the domain. Use ordinary
count-bounded indexed traversal; no callbacks, iterator framework or returned
mutable collection is needed. Preserve sensible empty behavior: New before creation
has its history scope, zero head, no runs/records and no active run. Zero Snapshot
is unscoped/empty. Wrong-kind typed access must be distinguishable from a valid
zero-field Created fact. Document index bounds, zero-handle and failure behavior.

  • Ordinal n maps to position n-1, but do not silently accept foreign IDs. Scoped
    identities are returned as small values, not preconverted retained reference arrays.
  • Global record access retains chronology; run access includes RunStarted and its
    explicit interruption, with session Created outside the run range. No commit
    grouping appears in ordinary navigation. Head still pins accepted history.
  • DTO-backed means actual private decoded DTOs, not generated mutable DTO escapes,
    parallel Inputs/Runs content projections or generic any/marker interfaces.
  • Decode newly accepted payloads once, retaining owned decoded values plus the
    encoded record/envelope data needed for faithful History correspondence. Detach
    caller-owned mutable history DTO storage at the new-commit boundary. Raw payload
    and any detached DTO exports copy mutable storage. No borrowed-byte escape hatch,
    unsafe/reflection defense, or new generator capability.
  • Capture derived scalar state at the same head. No public consumption map/query
    is necessary; ownership has eliminated that mechanism entirely.

Append-only storage and publication

Use private immutable accepted-record backing plus geometric arrays of locators:
ordered records; run entries naming identity and starting record/input positions;
a global input locator sequence referencing the same records; internal commit
metadata preserving accepted grouping, refs and envelope fields. Do not duplicate
content into indexes or expose this private layout as an API promise. The global
input locator array is a replaceable memory/runtime trade-off explicitly accepted
by Joe, not a permanent storage contract.

Never replace or mutate a published array element or DTO. Append only beyond old
captured lengths; resizing copies handles/positions, not old record payloads.
Capture all array headers/lengths and lifecycle scalars as one snapshot value/root.
Child handles retain those snapshot bounds, never the live Session or slice capacity.
An old last run's end comes from its snapshot's lengths; completed run ends derive
from the next run's start within that same snapshot. No mutable end pointer,
parent pointer, cached counts or retroactive patching of old run entries.

Validate admission, canonical envelope identity, decode/own new records, all ordered
transitions and actual interruption reserve before publishing. Stage only the new
batch's records/index entries/scalars; discard on rejection. Publication must have
no remaining ordinary error-returning step once accepted arrays/state begin changing.
OOM is not a recoverable transaction target. Preserve decoded application/replay
as one path; metadata preflight must not become the source of retained content.

Cost contract: O(1) snapshot capture and run/input/record positional access;
linear traversal in visited records/references, with no full-history startup copy;
linear new-data processing and amortized O(1) append per locator/record, allowing
occasional geometric O(N) growth. Total prefix-copy work over N small appends must
be O(N), not O(N^2). Check every accepted/preflight/index path, not only payloads.
No tree, read-side locks, persistent map, whole-state clone, or cumulative scan
per commit. Byte exports cost their requested size.

GC owns lifetimes; snapshots/individual handles can retain extra backing capacity
and later suffix entries. No Close, lease or reclamation protocol. Policy bounds
remain logical retained-fact/payload/decoded-work admission, not exact process-heap
limits under retained snapshots and detached exports. Index counts must derive
from bounded facts; validate counts/conversions before governed allocations and
use overflow-safe arithmetic. Avoid a new policy dimension without demonstrated need.

Load, closeout and compatibility

Load pins Head once, reads bounded verified pages from genesis and uses common
decoded application; verify the final pin was reached. No partial successful load,
implicit creation/interruption, execution, storage writes or repair of old objects.
A late old append can still finish after reload; no distributed writer fencing.

Every active accepted candidate reserves its actual one-record interruption,
including sequence/CBOR-width/retained-count/payload/work limits, using the real
internal preparation path rather than guessed constants. This guarantees policy
capacity, not backend availability. Stricter reader policy may reject replay.

API compatibility: isolated unpublished Go and session payload schemas change:
InputID becomes run-relative; UserInput gains run ownership; RunStarted loses
input references; snapshot shape and preparation/request APIs change. Existing
uncommitted experimental bytes are not promised readable; no migration reader or
new compatibility facade. Do not change History envelope or codec runtime.
No legacy/wire clients, server behavior, module pins or remote feature/major change.
Keep API snapshots current; skip early-kernel changelog bookkeeping per scoped rule.

Completed baseline implementation tasks

Tasks 1–5 below are completed; they are retained to explain the existing candidate,
not instructions to rebuild it. Next work is pending L1–L4 above.

  1. Review/update independent contracts. Present the coherent public ID/DTO/read
    handle/builder slice. Change owning ID/value/format declarations and local
    validators; generate codecs via task generate, never hand-edit generated code.
    Preserve the strict inward import guards and per-owner file/Godoc conventions.
    Done: contract tests show scoped conversion, contiguous per-run numbering,
    owned round trips and rejection of malformed/mixed scope/overflow. No aggregate
    consumer is expanded into model/tool vocabulary. Contract and reducer edits
    integrate together; do not deliver an intermediate broken package.
  2. Correct builder and shared lifecycle rules. RunStarted allocates a run without
    input selection; AddInput requires owner, allocates per-run ordinal; remove empty
    requests/consumption logic and internalize preparation/Prepared. Keep one-slot,
    discard, freeze/retry and interruption reserve behavior. Done: batch legality
    is shared by metadata/decoded paths; local rejection is reusable and no ordinal
    leaks. Same-batch create/start/input and interrupt/start/input work atomically.
  3. Publish owned records and positional indexes. Implement append-only arrays,
    per-snapshot bounds and immutable DTO-backed access. Stage only new data, fully
    validate/reserve, then publish. Route Submit/Apply/Load through it; no shadow
    content projection/full-history clone. Done: old snapshots/child handles remain
    stable across same-capacity appends and growth; semantic navigation is O(1).
    Tasks 2-3 are one integration unit before a runnable candidate is delivered.
  4. Real-boundary regressions and example. Update external-package tests and the
    straight-line example using actual History/memory backend. Cover crashes after
    accepted append/before local publication, pinned replay and deterministic backend
    faults. Add ownership/concurrency/complexity tests below. Done: example shows
    create/start/input -> snapshot/load active -> interrupt -> successor/start/input
    -> load, with identical semantic facts regardless of commit batching.
  5. Generate/document/verify and stop. Refresh owning doc.go/comments and minimal
    kernel README corrections (tech-writer for substantive prose), generated codecs
    and API snapshots through owning tasks. Preserve architecture allowlists/API
    filename disambiguation. Integrating agent runs gates and panel-review, fixes
    findings with targeted rechecks, then presents the public slice/evidence and
    stops for Joe. No commit/push/PR/Phase B continuation implied.

Observable verification

  • Run-owned input: exact bytes, explicit owner, zero/multiple inputs, run-local
    numbering resets, same-batch IDs, foreign/nonexistent/closed/wrong active owner,
    ordinal gaps/duplicates/overflow, input-before-start and duplicate start reject.
  • Whole-batch failure: a valid prefix plus invalid last record leaves old head,
    scalar state, chronological records and every run/input locator unchanged;
    local preflight rejection makes no Append and permits another batch with reused IDs.
  • Pending/uncertain batches never appear in snapshots. Fault wrappers prove exact
    proposal retry, no hidden attempt, timeout/late acceptance safety, slot barriers,
    conflicts/expiry/newer head, accepted-local-failure ref and required recovery.
  • Existing handles before append remain stable after append within spare capacity,
    after growth, after another run starts and after failed candidate work. Test run
    and input handles independently, including old last-run bounds and zero-input runs.
  • Multiple goroutines read snapshots/child handles while the sole owner appends;
    no shared iteration state, races or consults of mutable session state. Snapshot
    capture itself remains owner-serialized. Exercise both growth and non-growth.
  • Mutate caller Content and imported mutable DTOs after calls; mutate every returned
    byte/DTO export. Retained content, earlier handles, metadata and retry bytes stay
    unchanged. Distinguish kind mismatch from valid Created. Test empty/index edges.
  • Compare identical facts accepted under different commit groupings via public run,
    input and record navigation. Retain explicit interruptions and exact chronology;
    same grouping reloaded preserves head/ref as well. No consumers need commit loops.
  • Deterministic structural/accounting tests, not timing-only assertions: snapshots
    allocate no history-sized copies; unchanged records keep backing identity; across
    growing workloads aggregate locator growth/copy is linear and no per-commit
    preflight/reducer path scans/copies the accepted prefix. Use white-box evidence
    and allocation benchmarks as appropriate, not production telemetry/frameworks or
    brittle exact Go runtime growth factors. Benchmarks alone do not prove the bound.
  • Real Load/History: pinned endpoint, incomplete prefix, wrong parent/scope/CID,
    unsupported kind/version and tighter policy fail; active runs remain active;
    replay makes no Append/execution calls. Actual interruption reserve still fits
    at CBOR-width/sequence/count/payload/work edges. Include bounded 386/fuzz checks.

Focused gates from root: engine kernel/history adapter/architecture race tests;
root internal/apicheck and internal/cborgen tests; generated-code/API freshness;
focused malformed/fuzz smokes. Use actual Taskfile targets for generation and
snapshots, including task generate, task api:update and task api:check.

This revision changes engine state, format and root checks/docs: integrating agent
runs task lint, task docs, task test once per integrated set, task test:race,
task test:engine-standalone, and offline go run ./cmd/mecademo proving tool call,
permission ask/approval/result. Full suites get 1800-second outer timeouts; other
full gates 600 seconds. No paid/live e2e. No module-pin changes expected.

Completed-code panel review starts at the recorded implementation start OID above,
not moving main; previously reviewed candidate receipts support targeted fixes,
not approval of this new design. Keep Spec/Standards/Test/Domain axis results.
Implementation results for this baseline are in owned-review.md: generation/API,
docs/lint, full offline/race/standalone, focused race/386/fuzz and offline demo passed.
The final two test-only fixes received targeted rechecks. None of that evidence
claims the pending limits amendment is implemented or verified.

Review and delivery

Fresh-context plan critique found no correctness/security/requirement gaps:
0 blockers, 0 important findings, 0 advisories. Receipt:
.scratch/kernel-session/run-owned-snapshot-plan-review.md. The reviewer received
this exact full plan inline because ignored files were absent in its isolated
checkout and checked current session/history sources. This is design review only,
not implementation, concurrency/complexity proof or executed-test evidence.

Material baseline and limits-amendment choices are settled; L1's approved contract
is recorded above. Routine private helper layout remains an
implementation choice. Surface inability to meet immutable bounds, atomic publication
or hard-limit cleanup capacity rather than weakening them or expanding scope silently.

PR delivery and plan-comment synchronization for this existing slice were authorized
on 2026-11-05. Link #2663 without claiming completion of parent #2659; preserve the
full latest publishable plan in one identifiable PR conversation comment with
identity/privacy, conflict/digest/completeness and readback checks. Keep comment
metadata ignored and refresh the same comment on revisions. Merge remains human-owned.

Stop after publishing this completed checkpoint, the separately requested next-slice
plan, and HANDOFF. No next-slice implementation or obsolete Phase B continuation.

@jbeda
jbeda enabled auto-merge (squash) November 5, 2026 18:25
@jbeda
jbeda merged commit 841f554 into main Nov 5, 2026
45 checks passed
@jbeda
jbeda deleted the impl/kernel-session branch November 5, 2026 18:33
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Nov 18, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant