Repository navigation
feat(kernel): retain and settle passive tool calls - #2755
Conversation
Passive tool disposition: approved scopeThis 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: 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 intentionsFinish passive tool disposition in the isolated kernelSlug: kernel-tool-disposition Goal, scope, and authorityFinish 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 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)
Material contractsAuthoring, identity, ownershipAdd 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) errorValidate 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 admissionEvery prerequisite must refer to an earlier requested call in the same response: 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.
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 endingsAdd persisted
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 collectionExpose 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. CompatibilityNo production entry point, RPC/HTTP/client/SDK semantic change, wire major/feature change, or dependency pin change. Keep Dependency-ordered implementation tasksTasks 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.
Verification ownershipIntegrating agent runs aggregate gates once per integrated change set; subagents run focused tests only. Initial focus: Generation/API: Record exact commands/results and review snapshots in Review, delivery, and remaining risksUse this plan as the Spec input. Whole-PR panel baseline is the explicit post-rebase fixed point 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: Updated: 2026-11-10T20:59:23.229361+00:00. Archived plan portion SHA-256: |
Contract rationaleIntent is not executionA 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 knowReturned 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 Prerequisites establish settlement, not successA 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 uncertaintyOrdinary run endings cannot hide unsettled tool calls. 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 jobsTyped 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 |
2660c40 to
524afe0
Compare
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]>
524afe0 to
9657389
Compare
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]>
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]>
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
RunEnded.BulkToolCloseoutdefaults 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.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 testandtask test:race(complete offline module suites)task lintwith the repository-pinned lintertask test:engine-standalonego run ./cmd/mecademo, including tool call, permission ask/approval, and resultThe 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
4a4333af0passed session/format/architecture and dtogen race tests, pinned scoped lint, API/data-generation freshness checks, andtask 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/mecatedbecause 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
omitemptysupport. Public Go API snapshots are regenerated under the kernel experiment's compatibility exception.Contract rationale · Approved scope and archived plan