Skip to content

feat(kernel): retain reusable context and rich content facts - #2725

Merged
jbeda merged 7 commits into
mainfrom
impl/kernel-context
Nov 6, 2026
Merged

jbeda merged 7 commits into
mainfrom
impl/kernel-context

Conversation

@jbeda

@jbeda jbeda commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds passive, durable, reusable context/content facts to the isolated kernel.

  • Preserve each authored submission as UserInput{ID UserInputID, Parts} with ordered text/media parts and exact metadata, inline bytes, remote URI, or complete provider/scope/reference binding.
  • Retain run-owned incremental EffectiveInput{RunID, Inputs}. Each item references a whole earlier same-run user submission or supplies inline parts with an exact logical Actor, semantic Purpose, and Source provenance. Empty/inline-only batches and duplicates are legal; no consumption, deduplication, fallback, or per-input replacement semantics.
  • Keep independent history-scoped instruction, advertised tool-catalog, and model/API-settings replacements. Actor/source labels are descriptive, not provider roles, trust claims, or access grants.
  • Preserve shared staged admission/replay, atomic publication, exact frozen retries, bounded owned storage, pinned snapshots, and interruption reserve.

Part of #2663 and parent #2659; does not complete either issue. No production integration, model/tool lifecycle, request preparation, provider-role mapping, blob store, or execution. Kernel contracts remain provisional as higher layers develop.

Latest review batch

Implemented in b40c45289e8f7bbec8d1826f50896b8e735c2021:

  • Expand user-submission names consistently: UserInputID, UserInputView, AddUserInputRequest, and AddUserInput. Keep generic input-item/effective-input names.
  • Use InstructionBlock.Parts in domain and persistence types without changing serialized field meaning or payload version 1.
  • Add Snapshot.UserInputByID(UserInputID) (UserInputView, bool), using existing ordinal locators in O(1). Full identity and pinned membership checks reject foreign, invalid, absent, extreme, and later-than-snapshot identities without narrowing overflow. Empty inputs and interrupted historical runs remain readable. Remove positional/count user-input methods from RunView; retain chronological records.
  • Replace typed bulk Value/DTO Format/parts-slice inspection with recursive immutable, type-owned views. Compound children use views, collections use count/index navigation, and union branches expose presence. Zero handles are safe except indexed access outside bounds, which panics.
  • Copy out only requested media, argument-schema, and model-settings bytes. Normal navigation performs no payload-sized copying. Keep explicit encoded-record/history transport exports; streaming and code generation remain deferred.
  • Establish format-owned closed-vocabulary constants and document DTO/construction fields, scope restoration, media-source applicability, ownership, and harness-relative logical model routes.
  • Migrate callers/examples and retain real Submit/Apply/Load coverage. Add independent allocation/sibling-size controls, byte mutation isolation, pinned deep-handle concurrency, zero/presence/bounds, and identity-lookup regressions.

Earlier review batches flattened content/media and replaced per-input effective revisions with incremental whole-submission references. Full-scope checks precede scope omission; earlier same-batch references are legal, forward references are not. Structural validation, canonical decoding, resource limits, retry, reserve, and atomicity are preserved.

Suggested review order

  1. engine/kernel/session/format/ declarations, field contracts, and local validators; skip generated codec bulk initially.
  2. session/user_input_id.go, user_input.go, session_commit.go, and snapshot.go: naming, ownership, identity lookup, and pinned selections.
  3. content_part.go, media.go, content_source.go, input_item.go, attributed_input.go: recursive navigation and explicit branches.
  4. effective_input.go, instructions.go, tool_catalog.go, tool_definition.go, and model_binding.go: context handles and field-only byte exports.
  5. lifecycle_state.go, session.go, value_budget.go, and record.go: admission, staged publication, scope checks, and bounds.
  6. Context integration/acceptance, lookup, view-contract/allocation/concurrency, retry, and constant-time accessor tests.

Verification

Passed locally for this batch:

  • task generate, task generate:codecs:check, task api:update, task api:check
  • task test, task test:race, task test:engine-standalone
  • task lint, task docs, git diff --check
  • Offline go run ./cmd/mecademo: Read result and Write permission ask/approval/result observed.
  • Focused kernel/history/architecture race checks with workspace and GOWORK=off; session/format/architecture GOARCH=386.
  • Effective-input and tool-catalog decoder fuzzing, 10 seconds each.

Fresh final-tree review against 841f554c0392dce842604faa22e4c7035438a208 covered Spec, Standards, independent Test adequacy, and Domain architecture/security/reuse/duplication. One Standards finding (construction-field Godoc) and one Reuse advisory (redundant manual index guards) were fixed. Targeted Standards/Test/Security/Reuse rechecks are clean; unaffected axes retain their initial scoped evidence. No remaining findings or reviewer failures.

Full test/race suites began during review. After final comment/native-index cleanup, codec/API checks, focused normal/standalone race and 386 checks, and full lint passed again. Reviewers inspected the supplied current dirty/new-source candidate; ignored captures were unavailable under child workspace authority. The directing agent retained and compared exact source snapshots; no claim that children independently verified archive hashes.

API compatibility

Only isolated experimental Go/domain/persistence contracts change. Joe explicitly approved renamed/removed Go APIs and recursive navigation. There is no persisted experimental data; payload version 1 remains without compatibility-only machinery. No production/wire/protobuf/client change, major/feature bump, module-pin change, history-envelope change, or codec-runtime redesign. Structural safety remains. The early-kernel exception skips changelog bookkeeping, not regenerated API snapshots/codecs.

Full current implementation plan and review amendments, archived in the existing marked PR conversation comment with exact-body readback and plan-digest verification.

Preserve ordered authored messages separately from prepared content with
semantic purpose and provenance. Add independent session-scoped instruction,
tool catalog, and model binding replacements with immutable selected views.

Extend shared admission and replay validation, exact frozen retries, and
closeout-reserve coverage while keeping production entry points unchanged.

Publish the current implementation for review; the requested simplification
of experimental format versioning remains a separate pending review fix.

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

jbeda commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Kernel context implementation plan

Slug: kernel-context. Source: .scratch/kernel-context-plan.md (local provenance).
Updated: 2026-11-05. Branch: impl/kernel-context.
Published head: b40c45289e8f7bbec8d1826f50896b8e735c2021.
Plan-portion SHA256: ddcf78c17a7c53845f5a34b90a9cf5b57e5cef8b18b80067459513c28812dc69.

Amendment: adds the approved explicit user-input naming, pinned identity lookup, recursive immutable views, field-only byte copies, vocabulary/documentation, and completed verification. Supersedes the prior completed-batch archive; deferred streaming/codegen and all isolation boundaries remain.


Kernel context — review polish and recursive inspection

Slug: kernel-context
Plan path: .scratch/kernel-context-plan.md
Implementation branch: impl/kernel-context (resume; do not create a new branch)
Base ref: refs/heads/main
Original implementation/review start: 841f554
Next-batch starting candidate: 3e79b2f
PR: #2725 (OPEN, DRAFT)
Owning story: #2663; parent #2659; neither completed by this slice
Updated: 2026-11-05

Status and authority

Joe authorized implementation, then explicitly requested commit/push, PR update,
and marking test files reviewed for jbeda. The batch is committed and pushed as
b40c452 on impl/kernel-context. The PR stays draft.
Source/generation checks, gate receipts and independent panel review are recorded
under .scratch/kernel-context/inspection-* and run.md. No merge/reset/cleanup.

At batch start the tracked tree was clean; local HEAD, exact remote branch and PR
head matched the candidate above. The implementation is now committed and pushed;
no source changes remain uncommitted. Original plan/contract at batch start are preserved
in .scratch/kernel-context/plan-at-3e79b2fe0.md and contract-at-3e79b2fe0.md.
This plan and kernel-context-contract.md describe the approved current work.
Review notes are .scratch/kernel-context/review-notes.md (historical feedback).
Current receipts use inspection-*; older gates certify only their old candidates.
Kernel contracts remain soft as higher layers develop.

Goal and unchanged boundaries

Make public names, persisted vocabulary/documentation and accepted-state inspection
consistent. Resolve whole-user-input references from a pinned Snapshot by identity;
inspect nested content without whole-value clones. Keep handwritten, type-owned
code and views colocated with their values, with a consistent future-generatable
inspection shape. Do not build codegen now.

Preserve the existing passive isolated kernel: one UserInput submission with Parts,
flat tagged Media, run-owned incremental EffectiveInput with whole-user references
or inline attributed input, logical Actor labels, empty/duplicate contributions,
and independent history-scoped instruction/catalog/model replacements. No production
integration, legacy aggregate, request preparation, model/tool/goal lifecycle, wire
API/module pins, new identity/provenance framework, streaming bytes, blob store or
schema-policy redesign. Future tool results still need lifecycle-owned linkage.

Grounded seams at batch start (historical)

  • user_input.go combines UserInput, owned constructors and InputView; input_id.go
    defines the fully scoped one-based InputID; session_commit.go has AddInputRequest/
    AddInput. These names predate generic InputItem/EffectiveInput.
  • instructions.go and format/instructions.go still call []ContentPart Content;
    UserInput and AttributedInput call it Parts.
  • run_view.go exposes InputCount/InputAt; snapshot.go and Session.evaluate already
    maintain contiguous run ordinals and per-run input record locators. Reuse those
    for identity lookup, not a map, scan, or new index.
  • EffectiveInputView.Value and InputView.Parts clone whole subtrees. Other content
    views expose bulk Value/Format too. Decoded private acceptedRecord DTOs are owned
    and immutable after staging, suitable backing for recursive handles.
  • format has field-poor DTO comments and raw closed-vocabulary string literals.
    Public session already has ContentKind/MediaSourceKind/PromptPurpose constants.

All paths above are relative to engine/kernel/session/ unless explicitly qualified.

Approved naming and lookup contract

  • InputView -> UserInputView; InputID -> UserInputID (including owning filename),
    AddInput -> AddUserInput; AddInputRequest -> AddUserInputRequest. Expand other
    user-submission-specific shorthand consistently; do not rename generic InputItem,
    AttributedInput, EffectiveInput or their generic Inputs into user-only names.
  • InstructionBlock.Content -> Parts in BOTH public and format types. Preserve the
    ordered content, source and serialized semantics; no format bump/migration work.
  • Session/Snapshot naming stays: Session mutates; Snapshot and accepted-fact Views
    are immutable. Record/RecordView and the other View pairs remain.
func (v Snapshot) UserInputByID(id UserInputID) (UserInputView, bool)

Return zero,false for zero/invalid IDs, foreign history, absent run/input, and input
accepted only AFTER the pinned snapshot. Old completed/interrupted runs remain
lookupable: read lookup is not active-run admission. A valid empty submission is
present. Check uint64 ordinal ranges before narrowing to int/indexing; no panic on
invalid lookup. O(1), no payload copies/allocations driven by payload size. Use the
existing run/input locator arrays and snapshot/run boundaries, not live Session.
Remove public RunView.InputAt and InputCount; keep private counts/indexes needed
for lookup and RecordCount/RecordAt for chronological iteration. No second run-level
lookup until a real consumer needs it. Do not add a new persistent ID or wire shape.

Recursive read-only inspection contract

  • Scalars, strings, enums and already immutable identities return by value.
  • Nested compound content returns its associated View, recursively, including
    InputItem, AttributedInput, InstructionBlock, ContentPart, Media, ContentSource,
    WorkspaceFileSource and ToolDefinition. Keep each View beside its owning value.
    Scalar-only lifecycle facts and scoped IDs need no artificial wrapper hierarchy.
  • Collections expose conventional count/index accessors returning views, not
    []mutable-value exports or freshly allocated []View arrays. Preserve order and
    duplicates. Use conventional singular Count/At names consistently; precise method
    names are implementation details except the approved lookup above.
  • Optional/union branches return explicit presence (view/value,bool); absent/wrong
    branches and zero parents return zero,false. Required child navigation on a zero
    parent returns a zero view. Zero-view scalar fields/counts are zero/empty; indexed
    access outside [0,count) panics, consistent with existing RecordAt. Empty present
    content and explicit inline-empty source retain presence.
  • Copying a view or navigating to a child must not clone payloads or depend on
    payload size; read-only concurrent access to old handles stays safe across appends.
    Handles retain backing immutable storage; this does not promise reduced retained
    record memory. Exported constructors still accept ordinary values, detached eagerly.
  • Remove bulk Value()/Parts-slice/Format() exports from typed data views as the normal
    inspection surface. No independently mutable whole-value copy operation without
    a concrete need. Inventory genuine encoded-record/history transport boundaries
    (for example Record.Format) and retain required explicit owned DTO export there;
    do not generate one export per view just for tests or navigation convenience.
    Preserve constructor-value Clone/Equal/Validate where already useful; do not add
    a separate public copy/format framework.
  • Byte slices are the explicit exception: deep-copy out for now, clearly documented
    as owned output. Never return mutable accepted backing bytes. Apply to Media.Data,
    ToolDefinition.ArgumentSchema and ModelBinding.Settings; copy only the requested
    byte field, not sibling fields/subtrees. A future fresh bytes.NewReader stream may
    share immutable storage with independent cursor/lifetime, but is NOT in this batch.
  • No reflection/unsafe aliasing, lazy mutable caches, wrapper registry, new generator
    or interface hierarchy. A consistent API keeps future code generation possible.

Vocabulary and schema documentation

Introduce named constants for closed persisted vocabularies: ContentPart.Kind,
Media.Source and AttributedInput.Purpose. Reuse the existing inward dependency
(session may import format; format must not import session); avoid two drifting
literal sets. DTO fields can remain strings; do not redesign codec support merely
to name values. Actor remains a nonempty exact logical label with no enum/registry.

Improve member Godoc throughout session/format, including lifecycle facts as needed:
meaning, scope/referent of every ID/ordinal, context omitted and restored, required/
optional and empty/absent semantics, ordering, unions, validation ownership. Explain
payload-local validation vs aggregate earlier-membership/active-run admission.
Media documents inline Data (including empty) + required MIME, remote absolute URI,
complete Provider/Scope/ReferenceID, fields forbidden for other tags, optional
metadata and document-only Filename/Title. Retained URIs/files grant no access.

Keep ModelBinding.Route, documented as a logical provider/route name interpreted
only within the preparing harness configuration, not observed/global upstream
identity. Keep nested WorkspaceFileSource{Path}; enrichment can come later. The
ToolDefinition field set matches existing engine model-facing specs; keep explicit
valid-JSON schema validation as-is. No forensic metadata or settings-policy expansion.

Dependency-ordered tasks and checks

  1. Naming/vocabulary/docs: apply approved names and Parts consistently to domain/
    format declarations and consumers; establish closed constants in owning layer,
    document members. Generate codecs only via owning tasks. Focused format/value
    tests prove exact variant/bytes/JSON behavior unchanged. Must integrate with
    dependent API/tests before claiming the batch builds.
  2. Identity lookup: implement Snapshot.UserInputByID using existing indexes; migrate
    user-input callers, remove positional/count public API. Focused tests cover
    full scope, old/new run bounds, empty submissions, zero/foreign/extreme ordinals,
    later-than-snapshot rejection and pinned-view concurrency.
  3. Recursive views: add type-owned accessors/handles and migrate consumers/examples
    off whole-value materialization; retain only necessary transport exports. This
    task and migrated tests integrate together. Exercise actual reference-following
    from EffectiveInput item -> scoped UserInputID -> pinned lookup -> part/media.
  4. Regressions/generation: independent literal assertions through real Submit/Apply/
    Load for exact text, whitespace/Unicode Actor, purpose/provenance, union presence,
    media metadata/source binding/empty-inline and JSON bytes. Caller mutation after
    admission and byte-export mutation leave state unchanged. Preserve invalid-late-
    reference, forward/external Apply/Load atomicity, frozen retry, reserve and resource
    bounds tests; do not weaken them because bulk exports disappear.
  5. Verify/review actual integrated final tree. Prove metadata/reference traversal
    does not copy bulk data: allocation assertions scale fixture payload/collections,
    use independent negative controls, and distinguish intentional byte-copy methods
    from ordinary navigation. Preserve existing O(1) snapshot/accessor architecture
    guards or narrowly adapt them to approved API, no broad bypass.

Lead owns aggregate gates, workers focused checks only. Run task generate,
generate:codecs:check, api:update, api:check; focused kernel/history/arch race checks
normal and GOWORK=off; relevant GOARCH=386 and malformed decoding tests; engine
standalone; task test once, lint, test:race; offline mecademo ask/approval/result.
Run task docs for Markdown changes. Full suites outer timeout 1800s, other full gates
600s. All offline/isolated. Reassess scope-specific gates under engine guidance if
needed, but do not waive failures or claim old results certify this batch.

The new public inspection surface warrants fresh final-tree panel review against
original fixed point 841f554, with current approved
plan/contract as Spec and captured dirty/new files, not committed-only diff. Track
this batch delta from 3e79b2f separately. Fix concrete
findings within scope; targeted incremental rechecks use reviewed snapshot deltas.

Implemented verification results

All approved tasks are complete. Generation/codecs/API checks, full offline tests
and race suite, engine standalone, lint, docs, offline ask/approval/result demo,
focused kernel/history/arch race with and without workspace, GOARCH=386 and two
bounded decoder fuzz runs passed. Final comment/native-index review fixes passed
fresh codec/API checks, focused race/standalone/386 and full lint. Four-axis panel
is clean after targeted Standards/Test/Security/Reuse rechecks; unaffected axes
retain their original scoped evidence. Full-suite compilation began during review;
final-tree targeted rechecks certify the later small fixes. No prior-batch gate
receipt is being reused as evidence for this batch.

Compatibility, publication and resume

Experimental isolated Go API changes only; Joe explicitly approved renamed/removed
APIs and new navigation. No persisted data/version/compatibility/changelog project,
wire/protobuf/major/feature changes, module pins, history envelopes or codec runtime
changes. Regenerate public APIs/codecs rather than editing generated files.

Existing PR plan comment:
#2725 (comment)
Marker ; author jbeda. Update this same
comment in place for the authorized PR publication, preserving the full current
plan. Verify exact author/PR/marker, previous body and manual-edit conflicts,
privacy and complete readback; never duplicate/overwrite conflicts silently.
Previous plan-portion SHA256:
ac9b3920d4a58d2167d3d62479630f0178d75183c1c86b3601dfe097725de40c.
Prior receipt: .scratch/kernel-context/amendment-publication.md. Current publication
receipt: .scratch/kernel-context/inspection-publication.md.

No material open product decisions remain. Concrete accessor/constant spelling,
private representation and minimal necessary transport exports are implementation
choices within the rules above; surface any actual contradiction before changing
scope. No codegen or streaming prerequisite. Leave impl/kernel-context checked out.
On resume verify branch/HEAD/status and exact remote state; preserve unexpected user
changes. No automatic commits/push/merge/rebase/cleanup; require current authority.

jbeda and others added 6 commits November 5, 2026 14:05
Flatten authored submissions and media, retain run-owned attributed increments with whole-input references, and remove experimental version compatibility scaffolding. Preserve bounded ownership, ordered admission, replay and retry invariants.

Co-authored-by: Mecatl <[email protected]>
Use explicit user-input contracts and snapshot-pinned identity lookup. Replace bulk accepted-value exports with recursive views, retain owned byte-field copies, and document persistence vocabulary and ownership.

Co-authored-by: Mecatl <[email protected]>
Move media classification into Media, make text/media branch presence explicit, and preserve detached storage and bounded immutable inspection.

Co-authored-by: Mecatl <[email protected]>
Keep the implemented DTO, validation, ownership, and view contracts beside their code rather than duplicating them in a pending-design note.

Co-authored-by: Mecatl <[email protected]>
Retain indexed access while adding repeatable, pinned iter.Seq traversal for content, instructions, effective input, tools, records, and runs. Cover public admission seams, concurrent readers, allocation axes, and opaque consumer overhead.

Co-authored-by: Mecatl <[email protected]>
@jbeda
jbeda marked this pull request as ready for review November 6, 2026 19:55
@jbeda
jbeda enabled auto-merge (squash) November 6, 2026 19:57
@jbeda
jbeda merged commit a5322b5 into main Nov 6, 2026
75 of 77 checks passed
@jbeda
jbeda deleted the impl/kernel-context branch November 6, 2026 20:09
@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