Skip to content

feat(kernel): retain and settle passive tool calls - #2755

Merged
jbeda merged 7 commits into
mainfrom
impl/kernel-tool-disposition
Nov 10, 2026
Merged

jbeda merged 7 commits into
mainfrom
impl/kernel-tool-disposition

Conversation

@jbeda

@jbeda jbeda commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Why

The isolated kernel needs to distinguish a model asking for a tool, the intent committed for that call, and what is actually known about its outcome. Collapsing those into one “tool result” loses the difference between a rejected call, a returned error, and an execution whose outcome was never captured. That distinction matters for faithful replay and for avoiding unsafe assumptions about retry or side effects.

This PR makes those facts part of the kernel's retained lifecycle. It does not execute tools or integrate the experimental kernel into the production agent.

Contract

  • Original request and effective intent remain separate. Requested argument bytes stay exact; invocation retains the effective tool name, structured arguments, and prerequisites. Retaining intent is not proof of dispatch, and loading history grants no execution authority.
  • Settlement records knowledge, not just success. Returned, NotInvoked, and Indeterminate are distinct. A tool-level error is a normal Returned outcome; output capture completeness is independent of that outcome. Rich output retains ordered content, exact JSON, resource references and embedded bodies. Diagnostics remain bounded, producer-sanitized human context—not authorization or automatic model content.
  • Prerequisites are settlement barriers. They reference earlier requested calls in the same response. Any explicit disposition settles a barrier; success is not required. Accepted-history prerequisites cannot be manufactured by putting dependent facts in the same batch.
  • Ordinary endings require individual settlement. RunEnded.BulkToolCloseout defaults to false and is omitted when false. Exceptional Limit/CaptureFailed endings can explicitly set it true to close outstanding calls in bulk: uncommitted calls derive NotInvoked; committed calls without an outcome derive Indeterminate. Existing explicit outcomes win. The ending is the provenance, with no fabricated per-call records, reasons, or output.
  • Capacity exhaustion must still permit an honest ending. Ordinary admission reserves a minimal exceptional ending under both Session and History hard limits. Only that lone minimal bulk ending bypasses soft limits; richer or mixed batches do not. This reserves capacity, not backend availability.
  • Inspection preserves those distinctions. Raw records expose retained facts. A caller-retained run collection joins calls with their facts and effective settlement by composing public view types and APIs, borrowing pinned immutable payloads. Old views keep their old answers after later writes.

The core deliberately omits speculative evidence bags and execution-state machinery. Scheduling, permissions, automatic retry/recovery, richer execution provenance, partial output bodies, and accounting remain later work. This completes this PR's isolated lifecycle slice, not all of #2663.

Verification

Local verification covers typed Submit and storage-backed Load, every retained output branch, exact arguments/JSON, ownership and selected-leaf copying, source-versus-candidate admission, all settlement categories, ordinary/bulk endings, exact/one-short capacity boundaries, failed capture, frozen uncertain-acceptance retry, and pinned concurrent readers. Collection construction is measured separately from traversal and leaf copies.

The integrated lifecycle passed these local gates:

  • task test and task test:race (complete offline module suites)
  • task lint with the repository-pinned linter
  • task test:engine-standalone
  • Data generation/freshness and public API snapshot/freshness checks
  • Offline go run ./cmd/mecademo, including tool call, permission ask/approval, and result

The follow-up retaining format version 1 passed session/format/architecture race tests, pinned scoped lint, and API/generation freshness checks. The full repository gates above were not repeated for that version-only correction.

The final review fixes in 4a4333af0 passed session/format/architecture and dtogen race tests, pinned scoped lint, API/data-generation freshness checks, and task docs. The focused fix review found no remaining findings. The full repository suites were not repeated for this isolated delta. Projection benchmarks confirm borrowed traversal remains allocation-free; retaining complete public views increases locator storage without adding construction allocations.

The earlier CI race job failed in cmd/mecated because its recovery test's daemon did not become ready, with no reported data race. A local CI-like package race run and 10 repetitions of that exact test passed; its CI timeout remains unexplained rather than claimed fixed. New-head CI is separate from this local evidence.

Whole-PR Spec, Standards, Tests, Security, Architecture, Reuse, and Duplication review found no outstanding findings after targeted fixes and rechecks. Detailed receipts remain local rather than becoming a PR work diary.

API compatibility

No production entry point, RPC/HTTP/client/SDK semantics, wire major/feature identifiers, or dependency pins change. Session format remains version 1: the isolated kernel currently has only an in-memory backend, so there is no persisted-session migration to manage. The bulk-closeout flag is optional with a false default; explicit true retains its reason constraints. Required identity/payload fields and strict validation remain. This does not add migration or compatibility readers. History, codec-runtime, and identity schemas are unchanged; dtogen gains narrowly scoped Boolean omitempty support. Public Go API snapshots are regenerated under the kernel experiment's compatibility exception.

Contract rationale · Approved scope and archived plan

@jbeda

jbeda commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Passive tool disposition: approved scope

This PR now completes the isolated lifecycle slice. The kernel must retain what was requested, what intent was committed, and what is known about the outcome without equating commitment with execution or uncertainty with failure. Replay and inspection need those same distinctions; loading retained facts must never grant authority to execute them again.

Ordinary endings require individual settlement. Explicit exceptional bulk closeout preserves uncertainty when an outcome cannot be retained, with capacity reserved under both owning policies. Raw records stay faithful to history; the run collection derives convenient settlement with its actual provenance rather than inventing per-call facts.

Scope amendment: the earlier DTO-only checkpoint has been replaced by integrated authoring, per-call admission, ordinary/bulk closeout, pinned inspection, and typed Submit/Load proofs. Prerequisites are backward-only same-response settlement barriers, not success dependencies. No readiness API, production execution, scheduler, permissions, automatic retries/recovery, new tool-capture evidence, or partial-body/accounting schema is included. Session format stays at version 1 because the isolated kernel currently has only an in-memory backend, with no persisted sessions to migrate. Required identity/payload fields and strict validation remain; the bulk-closeout flag is optional and defaults to false. No migration or compatibility reader is added. #2663 remains open.

Final review amendment: 4a4333af0 omits false BulkToolCloseout values through narrow Boolean omitempty generation, while explicit true remains restricted to Limit/CaptureFailed. The tool-call projection now retains public view handles and composes public APIs only, preserving one-pass association, pinned payload borrowing and actual settlement provenance. The per-call slice-copy strategy stays unchanged, with its possible O(n²) cumulative cost documented at the clone; ownership optimization and new RunView helpers remain deferred. Scoped regression/race, generation/API, lint, documentation and incremental review evidence is summarized in the PR description.

Joe authorized verified commit/push and ready-for-review delivery. Detailed execution logs and review-fix receipts remain local; the PR description summarizes completed verification. The approved design and verification intentions are archived below for provenance, not as an implementation walkthrough or a claim that every planned check ran.

Full approved plan and verification intentions

Finish passive tool disposition in the isolated kernel

Slug: kernel-tool-disposition
Implementation branch: impl/kernel-tool-disposition
Base branch: main
PR: #2755
Issue: #2663 (this slice does not close the larger issue)
Verified execution-start local/remote/PR head: 007bf6b
Whole-PR post-rebase review baseline: 7e791b1
Historical branch start: e726fdb

Goal, scope, and authority

Finish this PR by making isolated Session admit, retain, inspect, and replay tool invocation/disposition facts, with per-call pairing, backward-only prerequisites, ordinary settlement, and exceptional bulk closeout. No tool executes. This is the single current remaining-work plan; it replaces historical speculative sections and folds in the scratch-only session-contracts detour. Source and the settled decisions below take precedence over older notes.

Joe authorized executing this approved plan, committing/pushing verified work to the existing PR, updating its description and existing comments, and taking it out of draft after verification. Implementation-start HEAD is 007bf6b58bb7ed1b7217971f635b7d9ff9ba611b; preserve the explicit whole-PR review baseline above. Keep the branch in this checkout. Do not rebase, change module pins, merge, or update HANDOFF.md. Detailed execution receipts remain separate from this plan.

Non-goals/approved deferrals: production entry points, tool execution, scheduling, permission/approval evaluation, preparation/authorization ancillary records, execution provenance, retry/attempt hierarchy, automatic crash recovery, late observations, asynchronous-job lifecycle, new tool-capture evidence, interrupted-body representation, spillover storage, finalized accounting, and model request construction. No public Ready/Eligible API: actual execution may have constraints not represented in Session facts. No incremental RunView changes API, mutable consumer aggregate, hidden cache, persistent index framework, or graph-work policy knob.

Starting checkpoint and reuse (historical context)

  • engine/kernel/session/format/tool_invocation.go and tool_disposition.go already define bounded passive facts and generated codecs. Reuse effective Name/value.Map Arguments, prerequisites, Returned/NotInvoked/Indeterminate, bounded Diagnostic, ordered rich output, and exact JSON. Do not restore removed evidence/provenance/extension bags or output totals.
  • model_request_id.go provides full RequestedCallID, scoped via request/run/history. model_response.go derives call identity from requested-call order, not interleaved content-item order. Reconstruction proves no membership.
  • lifecycle_state.go currently stores only a scalar outstanding-call count. Only Completed checks unresolved calls. Shared admission distinguishes pinned accepted source from ordered candidate.
  • SessionCommit.add copies admissionContext before every addition (session_commit.go:103-119); mutable maps/slices added to that context must not leak through this shallow copy. Failed additions must leave even the original candidate unchanged.
  • session.go stages complete records and compact append-only indexes, then publishes immutable backing. snapshot.go promises O(1) capture and pinned concurrent readers; RunView currently retains a pinned chronological record span.
  • run_ended.go currently recognizes any evidence-free ending as minimal escape. reserveEnding currently reserves error/limit/interrupted/capture-failed shapes. Replace these assumptions, not merely add a field.
  • format/run_ended.go Capture is existing MODEL-request capture evidence; preserve it separately. Resource reservation is a capacity guarantee, not backend availability.
  • policy.go already bounds payload/commit codec work and retained records/bytes/decoded work. MaxDecodedWork is not graph CPU accounting. Tool arrays/maps use these shared budgets, without per-field operational settings.
  • Read internal/dtogen/README.md before changing generation declarations/tags/accessors. Reuse value.MapView/value.View, views.Bytes and existing lazy collection adapters. Final review authorizes narrowly scoped Boolean omitempty support; no general optional-scalar or generator framework extension.

Material contracts

Authoring, identity, ownership

Add session aliases and concrete immutable views, following neighboring model-request/response ownership patterns:

func (*SessionCommit) AddToolInvocation(call RequestedCallID, value ToolInvocation) error
func (*SessionCommit) AddToolDisposition(call RequestedCallID, value ToolDisposition) error

Validate live handle, full destination identity/scope, and zero incoming RunID/RequestID/CallID before sizing/materialization. Use existing invalid-data/identity/transition error conventions. Populate only a local DTO copy. Reject absent/foreign/wrong-run calls and duplicate invocation/disposition facts; no invocation after disposition or facts after run ending. One invocation at most and one explicit disposition at most per requested call; NotInvoked does not require an invocation and may follow one, including earlier in the same batch.

Shared codec limits validate before governed allocation/clone/conversion; detach caller-owned mutable backing. Original RequestedCall argument bytes stay exact and separate from effective semantic value.Map arguments. Nil/empty effective maps mean empty object. Preserve primitive depth/cycle rules, exact integers and canonical CBOR; JSON output bytes stay exact, not normalized. Producers own safe diagnostic retention and higher-layer preparation/authorization assertions; Session grants no execution/disclosure authority.

Prerequisites and source/candidate admission

Every prerequisite must refer to an earlier requested call in the same response: 1 <= prerequisite position < current call position. Reject self, duplicates, absent/foreign references, and forward references. Use requested-call membership/position; do not create a general public ordering contract for opaque IDs. Preserve prerequisite-list order in equality/canonical bytes. This is a deliberate restriction of the former arbitrary-DAG design; no cycle detector is needed. B may be committed before A even when B depends on earlier requested A.

A prerequisite is a settlement barrier, not a success dependency. Every disposition category, including Returned error, NotInvoked and Indeterminate, settles it. Kernel admission checks the facts needed by its lifecycle contract, not real dispatch or all external execution constraints.

Action Pinned accepted source Ordered candidate
Invocation Call belongs to an earlier accepted response Matching active run, no invocation/disposition; valid backward-only prerequisites
Returned Invocation and every prerequisite disposition already accepted Matching active run, no disposition
Indeterminate Invocation already accepted; prerequisites may remain unsettled Matching active run, no disposition
NotInvoked Call membership in earlier accepted response; invocation optional Matching active run, no disposition; may follow same-batch invocation
Ordinary ending Preserve existing model-capture membership checks All tool calls individually settled; Completed also preserves existing pending-model/input-coverage checks
Next model request Preserve source binding, active-run, no pending model request/calls, and frontier checks Must also be eligible; same-batch settlement cannot manufacture source eligibility
User/effective input Preserve existing identity/reference checks, without adding a new source-eligibility rule Existing candidate eligibility applies; earlier same-batch settlement may unblock input

Response plus its tool facts in one commit rejects. Invocation plus Returned/Indeterminate in one commit rejects. A's disposition plus dependent B's Returned in one commit rejects if A was unsettled at the accepted source. Multiple independent invocations/dispositions may batch; all final dispositions and an ordinary ending may share a batch. No artificial per-call flush rule.

Maintain only the bounded active-response bookkeeping needed for admission, using immutable replacement or candidate-owned storage so copied contexts and old snapshots cannot be mutated. Document call/edge/scratch bounds under existing limits; avoid needless repeated whole-session scans. Private data layout is an implementation choice, not a separate data-structure project.

Ordinary and exceptional endings

Add persisted BulkToolCloseout bool to RunEnded with omitempty: false is omitted on encoding and a missing flag decodes to false. True must be explicit; bulk semantics are never inferred from reason or outstanding count.

Reason Flag false Flag true
Completed Ordinary; all tool calls settled plus existing clean model/input checks Reject
Error Ordinary; all tool calls settled Reject
Interrupted Ordinary; all tool calls settled Reject
Limit Ordinary; all tool calls settled Explicit bulk closeout
CaptureFailed Ordinary; all tool calls settled Explicit bulk closeout

EndRun(reason) remains an ordinary convenience method. Exceptional callers use AddRunEnded(run, RunEnded{Reason: RunEndedLimit or RunEndedCaptureFailed, BulkToolCloseout: true}). No additional helper. Preserve existing model-pending semantics for noncompleted endings; bulk tool settlement does not fabricate a model outcome or assert stopped external effects.

A bulk ending derives settlement for outstanding calls: no invocation -> NotInvoked; invocation without disposition -> Indeterminate. Preserve explicit dispositions unchanged. Invocation/disposition facts earlier in the ending's accepted commit count according to ordered candidate state. Do not eagerly rewrite every call, emit synthetic individual records, invent tool reason labels/output, or encode per-call closeout lists. Ending encoding is constant-shape independent of call count. No late tool facts after ending, including when a successor run is active.

Only one exact minimal exceptional ending (flag true, allowed reason, no Explanation/Capture) in an otherwise empty batch may bypass soft limits. Rich bulk endings and mixed batches remain ordinary resource admission, though their bulk semantics are valid. Reserve the actual maximal supported minimal exceptional shapes under BOTH Session and History hard limits after every ordinary candidate with an active run, including largest identity/envelope widths, unequal label lengths, and record/payload/work/codec dimensions. Replay uses hard limits without future reserve. Existing error/interrupted evidence-free endings no longer qualify as emergency escape.

Capture failure means inability to retain an admissible model response/tool outcome; it may be caused by one result, not only a huge session. Truncated/omitted output is not automatically capture failure, and tool error is a normal Returned outcome. Reject oversized dispositions whole, leaving the call outstanding; no silent truncation/downgrade. Defer new tool-correlated capture evidence, preserve model Capture and safe optional Explanation. Capacity reserve cannot ensure success during backend failure.

Fact inspection and derived ToolCallView collection

Expose typed RecordView.ToolInvocation/ToolDisposition and complete concrete DTO-backed views for retained payload fields. Raw fact inspection remains separate from derived call state.

RunView exposes a just-in-time, caller-retained collection of ToolCallViews representing ALL requested calls across its responses, in response order then requested-call order. Construct it by a single bounded pass/association over pinned records/items: expected O(run records + response items + requested calls) work and O(requested calls) locator memory. Do not scan the whole run once per call. The collection retains immutable public RequestedCallView, ToolInvocationView and ToolDispositionView handles and composes their public APIs, not extracted DTO pointers or cloned payloads. This is an API-usability proof point and keeps later extraction possible; do not move the projection now. Repeated traversal of a retained collection reuses those references; asking RunView to construct another collection rebuilds it. No hidden cache or continuously maintained historical join index.

Each ToolCallView exposes full ID, original RequestedCallView, optional invocation/disposition, scoped prerequisites through the invocation, and effective settlement/provenance. Collection lookup by full ID returns zero,false for invalid/foreign/absent calls; do not invent zero-value identity matches. No separate Snapshot-wide joining API unless existing navigation requires it; Snapshot -> RunView -> tool-call collection is sufficient.

Effective settlement is a small immutable derived value, distinct from ToolDisposition DTO: optional presence means unsettled; category is Returned/NotInvoked/Indeterminate; provenance gives either the actual explicit disposition or the actual bulk RunEnded view. An explicit disposition always wins. Bulk-derived categories have no fabricated disposition, per-tool reason, output, or diagnostic. Add only the concrete discriminator/accessors needed by this consumer, not a generic status framework. Exact method/type spelling follows neighboring conventions and is routine implementation, not a separate contract-only work phase.

Old RunViews/collections/call handles retain their earlier answers after later appends, bulk ending and successor runs. Loaded historical runs produce equivalent derived state. Snapshot capture and RunView creation remain O(1); collection construction cost is explicit and measured separately from traversal. Scalar/presence/direct-child reads do not copy siblings; byte Copy detaches only its selected leaf. Preserve present-empty children and safe zero views. The collection may allocate locator storage; do not claim the whole derived aggregate is zero-allocation/zero-copy. Payload navigation remains borrowed and immutable.

No public Ready/Eligible method or execution-state taxonomy. Execution call graph, scheduling, and authority may involve constraints beyond these logs. Consumers may layer that later; no incremental/delta API is added here.

Compatibility

No production entry point, RPC/HTTP/client/SDK semantic change, wire major/feature change, or dependency pin change. Keep format.Version = 1: the isolated kernel currently has only an in-memory backend, with no persisted sessions requiring migration. This operator-approved amendment removes the version bump. Final review makes the bulk flag optional with a false default and adds only Boolean omitempty support to dtogen; explicit true reason constraints and strict payload validation remain. No migration/dual reader is added. Keep History/codec-runtime/identity schemas unchanged. Regenerate public API snapshots; skip kernel compatibility/changelog bookkeeping under scoped guidance. Record this assessment in PR delivery.

Dependency-ordered implementation tasks

Tasks 1-5 form ONE integrated behavior change. Temporary development states must not be pushed as completed settlement support. Keep each task focused and run only its local checks while iterating.

  1. Integrate bounded tool facts and schema. Update format kinds while retaining version 1, optional false-default bulk flag and its reason validation; tighten prerequisites to earlier positions where payload-local; add materialization, type-specific sizing, session aliases, scoped fact views, typed record access and two authoring methods. Read generator guide; regenerate, never hand-edit outputs. Likely files: format/tool_invocation.go, format/run_ended.go, format/doc.go, record.go, tool_invocation.go/tool_disposition.go, record_view.go, session_commit.go and generated files. Local proof: codec roundtrips, zero-destination/error precedence, scope checks, validation before allocation, ownership, exact arguments/output, wrong-kind/zero views and unsupported-version/missing-field rejection. Preserve existing primitive tests rather than reimplement Value.
  2. Implement per-call admission. Replace scalar-only handling with bounded active-call state and shared admission for builder, preflight and replay. Enforce source/candidate matrix, response membership, one fact per kind, backward-only dependencies and settlement. Make failed-add candidate ownership explicit; preserve frozen exact-proposal retry semantics. Local proof: response/fact batching rejection, same-batch commitment outcome rejection, out-of-order commitments/results, every prerequisite category, source-vs-candidate gate, duplicate/post-settlement rejection, candidate-copy alias negative controls, all calls settling then input/model advancement.
  3. Integrate ordinary/bulk closeout and reserve. Update EndRun comments/behavior, ordinary all-settled gate, bulk reason/flag matrix, terminal state, exact escape classifier and reserve construction under Session+History. Preserve separate model capture behavior. Local proof: ordinary rejection, disposition+end batch, minimal versus rich/mixed admission, explicit outcomes preserved, candidate-invocation plus bulk end, no late facts, many-call constant-size end, exact/one-short hard budgets at maximum widths, replay without reserve, next run without inherited tool obligations. Update obsolete tests that permitted unresolved ordinary interruption rather than maintaining legacy behavior.
  4. Implement the lazy RunView tool-call collection. One association pass, immutable locators, ordered repeatable traversal and scoped lookup. Add ToolCallView and small effective-settlement/provenance value; reuse raw payload views. Local proof: active/ordinary-ended/bulk-ended/past runs, noncall content interleaving, multiple model responses, unresolved absence, explicit-versus-derived categories/provenance, zero/foreign/absent identities, repeated traversal, pinned old and concurrent readers. No readiness/delta/cache API. Measure construction/scaling separately from traversal and leaf-copy costs.
  5. Prove real Submit/Load and failure seams. Use existing memory History/backend fault and retry fixtures, with offline/test-owned stores. Traverse every retained field through real typed Submit and storage-backed Load using nonempty structured argument/output siblings. Test caller mutations, selected-leaf Copy detachment, exact IDs/JSON, present-empty/omitted, historical bulk provenance and later runs. Reject oversized outcome then accept minimal bulk ending; cover failed add/append/decode and uncertain acceptance without state leak or duplicate writes. A copied DTO or History-only roundtrip does not satisfy Session ownership/replay proof.
  6. Integrate, review, and deliver. Update owning Godoc and only current architectural claims materially changed; no historical work diary or speculative user docs. Finish generation/API freshness; run focused then aggregate gates below. Full final-tree panel-review uses explicit whole-PR baseline above and includes uncommitted/new owned files; incremental fixes use captured reviewed-tree deltas. Stop on material unapproved contract changes. After checks/review, commit explicit paths with required trailer, normal push to existing branch, update existing PR description/plan comment in place and read back. Mark ready for review after verified delivery as Joe requested; humans merge. Completion: whole isolated lifecycle inspectable/replayable with clean evidence, current remote PR, no unresolved material findings.

Verification ownership

Integrating agent runs aggregate gates once per integrated change set; subagents run focused tests only. Initial focus: cd engine && go test ./kernel/session/...; broaden to race and direct boundaries ./kernel/value ./kernel/views ./kernel/codec ./arch ./adapter/history/... as touched. Use meaningful negative controls and accepted-source-versus-candidate tests, not source-text assertions. No live models/tools, Kubernetes, ambient operator stores, or URI fetching.

Generation/API: task generate:data, task generate:data:check, task api:update, task api:check. Focused lint uses repository-pinned tool where ambient tooling is incompatible. Engine standalone check is task test:engine-standalone. Follow current scoped guidance to avoid re-running broad prerequisite suites per amendment. For this integrated change, run task test once; before PR-ready run task lint, task test:race, and go run ./cmd/mecademo proving tool call, permission ask/approval, result. Markdown edits to tracked docs require task docs; ignored planning notes do not. Full test/race suites need 1800-second outer timeout, other full gates 600 seconds. No dependency pin/workspace integration changes are planned.

Record exact commands/results and review snapshots in .scratch/kernel-tool-disposition/run.md; prior DTO evidence does not certify lifecycle changes. Never report a failed/unrun gate as passed. Preserve complete receipts locally rather than dumping them in PR comments.

Review, delivery, and remaining risks

Use this plan as the Spec input. Whole-PR panel baseline is the explicit post-rebase fixed point 7e791b195fdc459f7a6f4edb69f5e30cd4cb82d9, not moving main. Record execution-start OID and incremental reviewed candidates separately. No automatic rebase/restack, no speculative framework, no restoring removed metadata.

Existing plan comment: #2755 (comment) . At authorized delivery, verify repo/PR/head/comment marker+author, read existing content and reconcile manual changes; refresh the same comment with the full publishable current plan, stable marker, timestamp and digest, then verify exact readback. Do not publish arbitrary run notes/local paths as working links. Keep a concise rationale-focused PR body and distinguish planned checks from actual results. Until synchronized, report the remote plan as stale. Do not create a duplicate comment. Push authorization does not permit force-push, merge, deployment, or issue closure.

Main risks: copied admission contexts sharing mutable storage; accidentally weakening accepted-source rules; retaining emergency classification for ordinary endings; under-reserving History envelopes; conflating capture loss with tool failure; synthesizing stored dispositions for bulk outcomes; mutable collection locators breaking pinned views; accidental O(calls * run records) inspection. Test these directly. Existing limits bound the inputs; avoid speculative CPU budgeting. No semantic scope questions remain; private layouts and exact accessor spelling are implementation choices. If a concrete correctness problem requires changing agreed behavior, bring that specific issue back rather than silently weakening the contract.

This is the complete remaining scope for PR #2755. Production execution and other approved deferrals belong to later PRs.

Slug: kernel-tool-disposition; source: .scratch/kernel-tool-disposition-plan.md (local provenance, not a remote link). Branch: impl/kernel-tool-disposition; whole-PR baseline: 7e791b195fdc459f7a6f4edb69f5e30cd4cb82d9; implementation-start: 007bf6b58bb7ed1b7217971f635b7d9ff9ba611b. Verified pushed PR head: 4a4333af0957698004e4c4ad98f3e8c045d120f9.

Updated: 2026-11-10T20:59:23.229361+00:00. Archived plan portion SHA-256: 65cd875b21de5e057f5bc4d85e0177b16467ad415042e2d4e0e90276815ce3ef.

@jbeda

jbeda commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Contract rationale

Intent is not execution

A requested call preserves what the model supplied, including exact opaque argument bytes. An invocation separately preserves the effective name and structured argument object that higher layers commit to. Keeping both avoids rewriting the original request or pretending that preparation, authorization, dispatch, and execution are the same event. Session records facts; it does not evaluate permission or grant a recovery lease on Load.

Settlement is about what we know

Returned means an observed terminal outcome, including tool-level errors. NotInvoked means known non-invocation and may follow committed intent. Indeterminate means execution outcome is uncertain—not permission to retry. Diagnostics are optional bounded human context whose safe retention and release remain the producer's responsibility.

Capture completeness is separate from outcome. Truncated or omitted output does not automatically mean capture failure or tool failure. Failure to retain even one admissible outcome can justify CaptureFailed. Its existing Capture field remains model-request evidence; this PR invents no tool-correlated capture evidence.

Prerequisites establish settlement, not success

A call may name earlier calls in the same response as barriers. All disposition categories settle them. Restricting references to earlier requested calls gives an unambiguous bounded relationship without a general execution-graph framework. Invocation facts may arrive in a different order. The accepted-history boundary still matters: a candidate batch cannot supply the invocation or prerequisite settlement needed to admit a dependent Returned fact.

Bulk closeout preserves uncertainty

Ordinary run endings cannot hide unsettled tool calls. BulkToolCloseout defaults to false; encoding omits false and decoding a missing flag supplies false. Only an explicit true flag on a Limit/CaptureFailed ending closes calls without individual outcomes: no invocation means derived NotInvoked; committed intent without disposition means derived Indeterminate. Explicit outcomes remain authoritative. Derived settlement points to the actual ending rather than masquerading as a stored disposition with invented per-tool reasons or output.

Reserving the minimal exceptional ending under both Session and History policies prevents normal admission from consuming its capacity. It cannot promise backend availability or prove external work has stopped. Rich endings and mixed batches remain subject to soft limits.

Raw history and convenient inspection have different jobs

Typed RecordViews preserve the recorded facts. The run's caller-retained tool-call collection associates them only when requested; it does not maintain a second historical aggregate or hidden cache. The projection retains public view handles and inspects them through public APIs, making it an API-usability proof point that can move outside the package later. Its payloads remain borrowed and pinned, so later writes do not revise an earlier reader's answer. Construction cost is explicit; selected-leaf copying does not copy unrelated siblings.

The format declarations own payload meaning; session admission owns cross-record legality. Session format stays at version 1: the isolated kernel has only an in-memory backend, not persisted sessions requiring migration. Optional-false bulk closeout uses narrowly scoped Boolean omitempty support in dtogen; required identity/payload fields and validation remain strict. No migration or compatibility reader is added. No production execution behavior changes. Scheduling, permission evaluation, retries/recovery, new ancillary evidence, interrupted bodies, and accounting are outside this PR.

jbeda and others added 2 commits November 9, 2026 16:05
Draft the DTO-only public contract checkpoint for #2663 before integrating session consumers, admission, replay, or closeout.

Co-authored-by: Mecatl <[email protected]>
Use the value.Map primitive for object-root effective arguments, preserving exact nested values and shared codec bounds instead of opaque JSON or byte storage. Keep raw model-request arguments separate and mark provisional evidence and provenance choices beside their declarations.

Co-authored-by: Mecatl <[email protected]>
@jbeda
jbeda force-pushed the impl/kernel-tool-disposition branch from 524afe0 to 9657389 Compare November 10, 2026 00:05
jbeda and others added 3 commits November 9, 2026 19:33
Remove speculative evidence, provenance, metadata and capture accounting. Defer supporting observations to typed ancillary contracts once higher-layer needs establish their shape.

Co-authored-by: Mecatl <[email protected]>
Keep demonstrated resource fields and optional bounded diagnostic text on dispositions. Document preparation-failure and uncertain-execution examples, and exercise diagnostics through the owning payload.

Co-authored-by: Mecatl <[email protected]>
Distinguish requested calls, committed effective intent, and observed outcomes
so replay preserves uncertainty without implying execution or retry authority.
Require individual settlement for ordinary endings; allow explicit bounded bulk
closeout when capture or capacity fails, with emergency space reserved under
both Session and History policies.

Expose pinned raw facts and caller-retained derived call inspection without
maintaining a second historical aggregate. Prove ownership, admission ordering,
closeout capacity, storage replay, and uncertain-acceptance retry at the typed
Session boundary.

The experimental Session schema advances to v2; older experimental sessions
must be recreated. Production execution and wire contracts are unchanged.

Co-authored-by: Mecatl <[email protected]>
@jbeda jbeda changed the title feat(kernel): draft passive tool disposition contracts feat(kernel): retain and settle passive tool calls Nov 10, 2026
@jbeda
jbeda marked this pull request as ready for review November 10, 2026 17:17
jbeda and others added 2 commits November 10, 2026 09:30
The isolated kernel has only an in-memory backend, so this lifecycle addition does not need a storage version bump or migration claims. Keep required payload validation unchanged and restore version-one fixtures and the public API snapshot.

Co-authored-by: Mecatl <[email protected]>
Omit false bulk-closeout flags with generated optional bool support, and compose tool-call projections through public views. Retain the copy-scaling note and refresh canonical fixtures and generated contracts.

Co-authored-by: Mecatl <[email protected]>
@jbeda
jbeda enabled auto-merge (squash) November 10, 2026 20:55
@jbeda
jbeda merged commit 56c38b5 into main Nov 10, 2026
46 checks passed
@jbeda
jbeda deleted the impl/kernel-tool-disposition branch November 10, 2026 21:17
@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