Skip to content

feat(assistant): integrate discovery intake, memory and scheduling - #6633

Open
sunrioa wants to merge 37 commits into
apache:mainfrom
sunrioa:codex/feat-discovery-memory-pr
Open

sunrioa wants to merge 37 commits into
apache:mainfrom
sunrioa:codex/feat-discovery-memory-pr

Conversation

@sunrioa

@sunrioa sunrioa commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This Draft combines event intake from #6510 with shared discovery memory and one execution manager, so the proposed architecture can be reviewed and tested as a runnable whole. It retains the original #6510 history through df86958cc41638e6313a86801e9d5909f5c897f7.

Broad exploration and judgement remain one cycle. Quick investigation waits in the same FIFO. Source receipt continues while the slot is occupied; screening can run alongside broad discovery, but waits during quick investigation and its completion cooldown.

  • One Runner: DiscoveryRunner owns requests, admission, exact-message observation, recovery and settlement. The former coordinator and separate controller recovery loops are removed.
  • One scheduling authority: coalesced requests and logical investigations live in discovery_requests and discovery_jobs. Controller working fields are projections of jobs. Their broad/quick payloads and fixed submissions now have explicit types, and key controller/store writes document the projection boundary. Quick configuration shares the scheduler transaction; source receipts stay in their existing database.
  • Message contract: use the existing Host query type. pending and inbox wait for owned; an unsupported completed reply cannot settle a job. Execution completion is checked separately.
  • Recover the original execution: queued or owned messages retain their fixed identity and body. Unknown ownership appears in recovery status. After five continuous minutes without resolving recovery, the investigation is abandoned, its slot is released, and its lane waits for the normal cadence. Recovery age survives restart; healthy long investigations, queued admission and user interaction are not execution timeouts. Confirmed failures preserve captured work and the existing retry cadence.
  • Abandoned outputs: cancellation is best-effort and cannot block scheduling or shutdown. Later cycles use fresh workers in both context modes. Late memory commits, final drafts and unsent reports from an abandoned investigation are discarded; committed knowledge, history and unconsumed source hints remain.
  • Separate commit boundaries: notebook operations and Bot handoffs retain stable identities. If intake acknowledgement succeeds before scheduler settlement, recovery finishes settlement without another model call. Business completion followed by lease expiry is also reconciled.
  • Shared memory and continuation: immutable events support versioned current entries, corrections, search and bounded pagination. Both paths can save knowledge and research progress without notifying the user. Fresh contexts receive up to three short progress previews with links to the originals. Very long topic identifiers no longer produce an empty page with a non-advancing cursor.
  • Measured follow-up: automatic quick investigations share a completion-based minimum gap (default 15 minutes). Source conversations merge after 3 quiet minutes or 30 minutes of continuous activity; successful empty screening decisions also observe the per-conversation gap. Waiting periods preserve receipts, and restart preserves their timing. Screening uses the selected model’s least supported reasoning through the existing Host path, plus bounded same-source screening and investigation context. Event investigations focus on their trigger and necessary related evidence; broad discovery retains global exploration.
  • Memory and delivery ergonomics: existing-topic notes use the stored title; only new topics require one. Reads return a complete nextRead request for snapshot-safe pagination. ReplyDiscovery requires source Inbox IDs and shares the existing transactional Bot delivery path; ordinary messages and unlinked historical records retain their current meaning.
  • Preserved controls: source authorization, worker tool restrictions, permissions, provider retry policy, enablement and broad cadence remain in place. Configured quick intervals are retained and now also bound event wakes and per-conversation screening. Existing legacy context reuse remains the default; opt-in scoped workers normally rotate after success. Both modes rotate after recovery-timeout abandonment.

Source events are not semantically discarded by request coalescing. Moderate repeat investigation is acceptable; progress is not a coverage certificate, and Bot acceptance is not proof of user delivery. This change adds no distributed scheduler, investigation priorities or automatic risk-based actions.

Refs #6504 and #6360. Implementation and upgrade boundaries are documented in Discovery execution.

Cutover and review focus

Use a fresh profile, or finish pending discovery work in the previous version before switching. The Runner starts from idle settings. When an idle old quick configuration references a scoped worker, its durable worker identity is imported before the binding becomes visible, preventing a false legacy/scoped identity conflict at startup. It does not import old in-flight jobs, queue order or previous handoff records, and does not reconstruct missing submission identities from old conversation history.

Unfinished old work is rejected without being deleted; scheduler status exposes coordination.initializationError. Existing notebook events, source receipts, settings and restricted worker roles remain available. Old coordinator tables remain untouched and unused. Normal triggers create new requests from the current cadence and hints. Jobs created by this Runner still recover across restart and Host handoff. Rollback to an older binary requires the pre-upgrade data.

The main tradeoff remains one non-preemptive investigation slot for valid work. Long healthy broad investigation can delay quick investigation. An abandoned worker may continue running if cancellation is unavailable, but its late writes and reports are rejected. The five-minute limit applies to unresolved recovery, not ordinary execution or provider retries.

Validation

Validated locally on macOS with Node 24.19.0. Current follow-up commit: 0b2cd3254771b15d8be4679bd78264e231bc19c4.

Check Result
Workspace build and typecheck Passed
Lint, formatting, ASF headers and staged whitespace Passed
Protocol compatibility guard Passed; epoch remains 238
Assistant memory / discovery / persistent-task suites 102 / 229 / 88 passed; 419 total
Runtime LLM service and model thinking contracts 67 passed
Complete compiled Runtime Host coverage 3,102 applicable cases covered, with 13 conditional skips; see the rerun note below
Cadence and pressure Continuous updates, resolved events in the same batch, empty-decision cooldown, independent threads, maximum merge wait, persisted cooldown, manual checks, long-record continuation, retry fairness, source revocation, broad/quick FIFO and 1,000-hint bounded batches
Memory and delivery Canonical existing-topic titles, new-topic title validation, unchanged operation identity, complete pagination requests, required valid discovery references, idempotent delivery and linked feedback
Existing-profile macOS development app Restarted successfully on this commit; saved enablement/model selection and workspace retained

The initial full Host run passed 3,101 cases and skipped 13. Its one failure was a handoff fixture that still waited 1.6 seconds for event screening. After advancing that fixture’s clock through the new three-minute merge window, the entire affected execution-composition file passed 64/64. No production behavior or handoff assertion was relaxed. The model request test confirms least-supported reasoning for screening and unchanged Session reasoning for ordinary auxiliary calls.

Host tests use an isolated home outside /tmp, synthetic inputs and local provider fixtures. They do not establish a token-saving percentage or recommendation quality. Windows execution and packaged Desktop smoke were not run locally for this follow-up.

AI use

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

OpenAI Codex assisted with implementation, review, tests and documentation. New commits include Generated-by: OpenAI Codex; imported #6510 commits retain their original history. Human review of the combined proposal is pending.

Checklist

  • Relevant regression and integration tests cover the change
  • Build, typecheck, lint and formatting pass locally
  • Behavior and upgrade boundaries are described above
简体中文

变更内容

这个 Draft 将 #6510 的事件接入、共享发现记忆和统一执行管理放在同一条可运行分支中,供整体审阅。保留 #6510 截至 df86958cc41638e6313a86801e9d5909f5c897f7 的原始提交历史。

广域探索与判断仍属于同一轮;快速调查进入同一个 FIFO 等待。调查运行时持续接收来源事件;筛选可与广域调查并行,但在快速调查运行期间及其结束后的冷却期等待。

  • **统一 Runner:**由 DiscoveryRunner 管理请求、接纳、精确消息观察、恢复和收尾,删除旧 coordinator 和两条路径分别维护的恢复循环。
  • **统一调度状态:**待运行请求和逻辑调查分别保存在 discovery_requests、discovery_jobs;控制器中的工作字段由 job 投影;广域、快速发现的工作数据及固定提交均有显式类型,并在控制器与 store 的关键写入点说明投影边界。快速发现配置与调度状态共用事务,来源接收记录保留在原数据库。
  • **消息契约:**使用现有 Host 查询类型,pending 和 inbox 等待 owned;不支持的 completed 响应不能使调查结算。实际执行是否结束另行检查。
  • **接续原执行:**排队或已接纳的消息保持原身份和正文。归属未知时显示恢复状态;连续五分钟无法完成恢复,就放弃本次调查、释放调查位,并让该路径等待原周期。恢复计时跨重启保留;正常长调查、排队和等待用户输入不受五分钟执行时限影响。确认失败后保留捕获范围和原重试节奏。
  • **放弃后的输出:**尽力停止旧执行,但不因取消无响应而阻塞调度或退出。后续轮次在两种上下文模式下都使用新 worker。旧调查迟到的记事本写入、最终草稿及尚未发出的报告直接舍弃;已提交知识、历史及尚未消费的来源线索保留。
  • **区分提交边界:**记事本操作与 Bot 投递使用稳定身份。来源回执先成功、调度收尾后中断时,只补做收尾,不再次调用模型;业务完成后租约到期也能正确恢复。
  • **共享记忆与接续:**保留不可变事件、当前知识版本、修正、搜索和有界分页。两种发现均可在不通知用户时记录认识与调查进展。新上下文获得最多三条简短进展及原记录入口。修复超长主题 ID 导致空页、游标无法前进的问题。
  • **实测后的优化:**自动快速调查统一遵守完成后的最小间隔,默认 15 分钟;来源线程连续 3 分钟无更新或持续活跃满 30 分钟后允许合并筛选,空筛选结果也遵守同线程间隔。等待时保留原事件,重启保留时间状态。筛选通过现有 Host 链路使用当前模型支持的最低思考档,并获得有限的同来源筛选与调查记录。事件调查围绕触发线索和必要关联证据进行,全局探索交给广域主动发现。
  • **记忆与投递接口:**向已有事项追加笔记时使用存储中的标题,仅新建事项需要标题;分页返回完整的 nextRead 请求。ReplyDiscovery 强制引用发现的 Inbox ID,并复用原有事务投递链路;普通消息和没有关联的历史记录保持原含义。
  • **保留已有控制:**来源授权、Worker 工具限制、权限、供应商重试、启用状态及广域周期保持原有规则;保留快速发现配置的间隔数值,并将其应用于事件触发和同线程筛选。默认继续 legacy 复用;可选 scoped 模式通常在成功后轮换 Session。恢复超时放弃时,两种模式都改用新 worker。

合并请求不会按语义相似度丢弃来源事件。允许适度重复调查;进展记录不证明完整覆盖,Bot 接受也不等于已经向用户送达。本次没有引入分布式调度、调查优先级或风险自动执行机制。

关联 #6504、#6360。实现和升级边界见上方文档链接。

切换方式与审阅重点

使用干净配置,或先在旧版本完成待处理调查,再切换到新版。Runner 只从空闲配置开始;对于引用 scoped worker 的旧快速发现配置,先载入持久角色身份,再暴露会话绑定,避免启动时误判为 legacy 身份并产生冲突。不再导入旧版在途任务、排队次序和上一轮交接记录,也不再从旧会话历史反查缺失的提交身份。

遇到未完成的旧任务时明确拒绝,不删除旧数据;调度状态通过 coordination.initializationError 显示原因。记事本事件、来源回执、设置和 Worker 权限绑定继续保留。旧 coordinator 表不删除、不再使用;正常触发器根据当前周期和线索创建新请求。新版 Runner 自身的重启和 Host 交接恢复仍然保留。回滚旧二进制需要使用升级前数据。

有效调查仍共用一个不抢占的调查位,正常长时间广域调查可能延迟快速调查。如果取消不可用,被放弃的旧 worker 仍可能运行,但它的迟到写入与报告不会被接收。五分钟限制针对恢复不明,不限制正常执行,也不改变供应商重试策略。

验证

本地环境为 macOS、Node 24.19.0,本次优化提交为 0b2cd3254771b15d8be4679bd78264e231bc19c4。

检查 结果
全工作区构建、类型检查 通过
lint、格式、ASF、暂存差异空白检查 通过
协议兼容性检查 通过,epoch 保持 238
助手记忆 / 发现 / 持久任务套件 102 / 229 / 88 通过,共 419 项
Runtime LLM 服务与模型思考契约 67 通过
完整 Runtime Host 覆盖 3,102 个适用用例完成验证,13 个条件跳过;复测情况见下文
调度与压力覆盖 连续更新合并、同批次中的解决信息、空结果冷却、独立线程、最长合并等待、重启保留冷却、手动检查、长记录接续、重试公平性、来源撤权、广域/快速 FIFO、千条线索分批
记忆与投递 已有事项标题解析、新事项标题校验、操作幂等性、完整分页请求、必填且有效的发现来源、幂等投递及反馈关联
macOS 开发版沿用原工作区 已用本提交重启,原启用状态、模型选择和工作区保留

完整 Host 首轮为 3,101 通过、13 跳过,唯一失败是一个仍按 1.6 秒等待事件筛选的旧交接夹具。按新的三分钟合并窗口推进该夹具的模拟时间后,整个 execution-composition 文件复跑 64/64 通过;没有放宽生产行为或交接断言。实际请求契约测试确认筛选使用模型支持的最低思考档,普通辅助调用继续使用 Session 原有思考设置。

Host 测试使用位于 /tmp 之外的隔离用户目录、合成输入和本地供应商夹具。这些结果不证明某个 token 节省比例或推荐质量提升。本次未在本地执行 Windows 和 Desktop 打包烟雾测试。

AI 使用说明

OpenAI Codex 协助实现、审查、测试和文档。新增提交包含 Generated-by: OpenAI Codex,#6510 保留原始历史;整合方案仍待人工审阅。

xxhZs and others added 8 commits November 1, 2026 01:36
Persist source changes, screen conversation groups fairly, and wake the existing
quick worker with permission-checked, paginated evidence instead of large prompts.
Include optional read-only Codex history, memory and activity source adapters.

Generated-by: OpenAI Codex
…wakes

Replace per-event investigation checklists with concise durable wake hints and size screening batches against the selected model capacity.

Generated-by: OpenAI Codex
Keep immutable notebook events and derive versioned current entries, searchable
snapshot pages and explicit research checkpoints. Share the bounded read and
execution-bound incremental write interfaces across both discovery paths.

Add opt-in scoped worker contexts that rotate only after successful completion,
preserving failure recovery, user feedback authority and existing tool boundaries.

Generated-by: OpenAI Codex
@github-actions github-actions Bot added the effort/XL Under 2500 readable lines label Nov 4, 2026
…view

Merge apache/maka PR apache#6510 at df86958. Preserve its source intake, screening and durable wake hints alongside versioned memory and scoped-context recovery. Add the required ASF header to the imported adapter README.

Generated-by: OpenAI Codex
Schedule broad and quick investigations through a durable non-preemptive FIFO while event intake continues independently. Preserve pending hints and retry identities, fence replaced owners, and hand the previous committed memory interval to the next worker. Recover releases delayed by lease expiry without granting expired owners write authority.

Add integration coverage for fairness, intake during long runs, queued activity, restart, interruption, pause and bounded history handoff. Keep investigation coverage and actual user delivery separate.

Generated-by: OpenAI Codex
@sunrioa sunrioa changed the title feat(assistant): add versioned discovery memory feat(assistant): integrate discovery intake, memory and scheduling Nov 4, 2026
Read owner quote comments as feedback, ignore empty contextual quotes, and preserve already imported feedback. Cover restart and later feedback delivery.

Generated-by: OpenAI Codex
`next()` authorizes a wake, then `directions()` authorizes the same wake
again while building the prompt. A transient source failure between the two
made `directions()` return an empty list, but `complete()` still marked the
wake delivered on the successful activation, so the hint was lost forever and
never retried.

Treat a requested wake that is still pending but cannot be read as a failed
activation: it is not settled, the run is retried, and the hint is read again.
Revoked or already discarded wakes keep disappearing as before.

Add a regression test that fails authorization between admission and
directions, then checks the wake stays pending with nothing delivered and that
the retry actually renders the hint.
`query()` failed the whole source as soon as one in-scope thread used legacy
rollout history, while `changes()` never looked at `history_mode`. Such a
thread has no rows in `thread_items`, so a thread update only moved the
activity token and the incremental call returned an empty page: a silent
"nothing changed".

Both methods now use the same policy and skip legacy threads instead of
failing the source. Querying such a thread by threadId fails with a targeted
error, and `changes()` emits a `legacyThreadNotice` item for an in-scope
legacy thread update, stating that its turns are not representable
incrementally and how to read them. The notice is authoritative and readable,
and its revision follows the thread's `updated_at`, so it is reported once
per update instead of every poll.

Add changes-side coverage: the notice appears next to paginated items, does
not repeat, and an unscoped query still returns paginated items when a legacy
thread exists.
Fence receipt, screening, progress and revocation writes inside transactions. Let captured wakes recover after intake is disabled and defer execution while captured hints are temporarily unreadable. Reject unsupported Codex history before advancing change state, including legacy scanner caches.

Generated-by: OpenAI Codex
Keep the remote wake retry and legacy-thread notice policies. Retain the tested lease fencing and disabled-intake recovery fixes, avoid duplicate outage coverage, and invalidate old scanner tokens so omitted legacy updates are checked on upgrade.

Generated-by: OpenAI Codex
@github-actions github-actions Bot added effort/XXL Over 2500 readable lines and removed effort/XL Under 2500 readable lines labels Nov 5, 2026
Persist captured hints independently of activation retries. Prepare authorized FIFO batches using the actual worker model capacity and Host message limits, and acknowledge only hints passed to the worker. Preserve deferred captures across restart and disabled intake; recover old oversized captures on a fresh worker while retaining their history.

Generated-by: OpenAI Codex
intake_wakes carries the capture time in its at column, but
EventIntake.directions()/prepare() read back only the direction string.
quick.ts then joined those strings into one line, so a hint captured three
hours ago and one captured a minute ago were indistinguishable: the worker
treated an already-handled lead as the discovery of the moment, which is
how a 13:02 fixed lead woke it again and it nearly re-reported two fixed P2s.

Carry at with each hint, order the prompt oldest first, and label every hint
with its coarse age ("[3h ago] ..."), plus one sentence telling the worker
that an old hint may already be handled. Keeping every hint (rather than
dropping old ones) preserves the bounded-FIFO behavior from 6096991: only
hints that actually fit the measured request are confirmed.
A restart or lost lease demoted an active activation to pending but kept
only its messageId, while the body is composed per attempt with the
current UTC time and each hint's age. The retry resubmitted that
identity with a different payload, the Host rejected it as a durable
receipt conflict, and the failure path minted a fresh identity -- so a
wake the Host had already admitted started a second investigation of
the same content.

Persist the composed body (prompt version, worker Session, captured
hints and text) with the activation and resend it byte for byte; only a
body that genuinely changed earns a new identity. Observe the identity
before submitting, so an admission that outlived the restart is awaited
instead of resubmitted, and keep a terminal admission out of the retry
loop. A receipt that holds another payload (state written before bodies
were persisted) is abandoned once with a freshly composed body.

The tests mirror the Host's per-identity execution state, and the new
redelivery suite asserts one turn per messageId across a restart, no
payload conflict, and no recomposed body.
Keep immutable prepared submissions while using durable Host ownership to recover accepted messages. Align terminal-failure fixtures with the real Host contract.

Generated-by: OpenAI Codex
A paused quick discovery kept reporting "Event intake disabled" and never
reached the worker. dispatch() reads pending wakes through EventIntake.next(),
which used the write guard ready(): that requires intakeEnabled && enabled, so
pausing threw before activation even though intake itself was on. The throw
landed in state.lastError while checkRequested stayed true, because the success
cleanup was never reached; every later tick retried the same message. The
panel's "check once" is not gated on enabled, so that path always failed.

Reads now use a read-only guard that requires intakeEnabled plus the lease.
Being paused is not a closed intake. Intake writes keep the stricter guard, so
a paused discovery still cannot collect or judge new events.

Test: pause with intake on, check once, and assert one worker call, no
lastError, a cleared checkRequested, and that later ticks stay clean.
…take

judgeLong() threw on capacity failure before any backoff was written, so every
five-second tick retried the same event at the queue head and the short
messages behind it never screened. A retained earlierContext summarized under
a previously larger model made that failure permanent after a model shrink.

- record a per-event retry_at (30s) and skip the event on capacity failure, so
  judge() keeps scanning and the event's short neighbours stay eligible;
- restart the event from offset 0 when its retained summary no longer fits the
  current context budget, instead of truncating it.

Reset over truncation: the summary is only meaningful for the offset it was
written at, so cutting it would silently drop facts while still claiming that
prefix was summarized - exactly the kind of loss that causes a missed wake.
Re-reading costs a few more chunks under the smaller model but keeps offset and
summary consistent, and terminates because chunk size now adapts to the
smaller budget.

Regression tests: a model shrink no longer retries forever and drops no text;
a queue head that can never fit is backed off on its own row while following
short events still screen and retry only after the backoff expires.
Record the existing group backoff before rejecting an oversized saved context, so healthy groups keep making progress after a screening model change. Preserve the original event and checkpoint for later recovery.

Generated-by: OpenAI Codex
Rotate deferred events behind other groups when their retry deadline has elapsed, without delaying healthy neighbours in the same group. Preserve the concurrent full-text restart and per-event deferral changes.

Generated-by: OpenAI Codex
A reply to an excerpt carries an empty message body: the owner's words live in
quotes[].comment. Event intake projected only displayText/text, stored an empty
text, and still advanced the session receipt, so screening marked the empty
event as screened and the original was never read again. With intake enabled the
activity token is constant, so no later activity check could recover it either.

Project the body plus every quote comment, as BotStore already does for
feedback, and treat a frame with nothing to project as not received: it is not
queued and its session keeps the previous receipt position so the next
collection retries it.

Generated-by: Maka
…ed recovery

A wake can be admitted by the Host before its completion state is stored. After a
restart that activation becomes pending, and the scheduler returned as soon as it
saw the worker still running, releasing the shared investigation slot on the way
out. Broad discovery could then start while the accepted worker was unfinished,
and that worker's DiscoveryNotebookRemember was rejected because no active
activation carried its identity.

Hold the reservation while a sealed handoff's admitted turn is still running, and
carry its token in durable state so the resumed activation settles the same slot
instead of taking a second one. Resolve the worker's write identity from the
activation, including the sealed pending handoff, so recovery keeps the identity
the accepted turn was given.

Generated-by: Maka
Reattach an unfinished quick investigation through its durable Host receipt
before admitting broad work. Preserve its execution identity through Root
recovery, retain the slot while awaiting input, and keep uncertain admissions
fenced without resubmitting. A saved request body alone grants no write identity.

Keep quote comments in event screening while advancing past genuinely empty
frames; later edits still trigger a new read. Integrate the concurrent quote
and recovery fixes without retaining a second slot-token mechanism.

Validation: build, typecheck, lint, format, ASF and protocol guards, Desktop/UI
Knip, 395 assistant tests, 208 affected Host tests, and four separate-process
crash/restart cases. The Host suite includes a real sealed Root handoff and
successful memory write after recovery. Tests use synthetic models and data.

Generated-by: OpenAI Codex
Preserve the active broad phase until Host admission is reconciled, including
paused one-off checks. Persist each submission's identity and feedback revision,
recover older submissions through canonical history and durable receipts, and
observe the original execution before committing its output or starting judgement.

Keep the shared reservation and complete memory interval across both discovery
lanes. Unknown ownership continues to block new work; confirmed absence retains
the existing retry cadence. Root snapshots remain reserved during startup recovery.

Validation: build, typecheck, lint, format, ASF and protocol guards, Desktop/UI
Knip, 400 assistant tests, 212 affected Host tests, 14 Runtime service tests and
four process-recovery cases. Four native broad regressions cover discovery and
judgement with current and legacy submissions. One unchanged Matter integration
case timed out during the initial parallel run; its complete 9-test file and
88-test suite then passed without source or timeout changes.

Generated-by: OpenAI Codex
A restored investigation waits for `messageExecution` before it submits anything,
which is correct. What was missing is a bound: `restoreExecution()` returned
early on an unknown answer and left the lane "recovering" forever. Because
`acquire()` withholds the other lane while either one recovers, an answer that
never came stopped both investigations, and neither `QuickDiscoveryStatus` nor
`coordinator.status()` showed anything but an idle schedule.

- Count unresolved reconciliations per lane and stop waiting after a bound
  (60s or 120 attempts). The saved submission is kept and never resubmitted on
  uncertainty: the wake stays pending, `lastError` says it is unconfirmed, and a
  later scheduled cycle retries the same identity.
- The quick lane releases the shared reservation it kept for a crashed window,
  reclaiming it while the lane still reports recovering.
- Treat the protocol's `inbox` resolution like `pending`/`owned` on the quick
  lane: the Host already holds the message, so it is reattached, never resent.
- Report the withheld lane through `coordinator.status().recovering` (since,
  attempts, and why the bound was exceeded), so a stuck reconciliation is
  visible instead of looking healthy.

Validation: typecheck, biome, sync:model-metadata, 401 assistant tests
(102/211/88) and the Host dist suite (3101/3115; the remaining failure,
"two real managed activations converge on one Host and exit at true idle",
also fails on the parent commit).
…proved absent

Broad discovery reconciles a restored wake with `messageExecution` before it
submits anything, but a proved-absent wake was still retried as a new cycle:
`claim()` always minted a fresh activation id, so the retry of the same
conversation looked like a second investigation in the journal and in cost rows.

- `store.retry(id)` records the cycle the Host proved absent; `claim()` reuses
  that identity (and its start time) for the retry and drops the record.
- `restoreExecution` records it on the positive-absence path only. Uncertainty
  still keeps the activation and never resubmits.

The `broad-recovery.test.ts` regression covers both answers for a wake that a
restart found still queued in the Host:

- queued/not started: the wake is reattached, the original message id is never
  submitted twice, and the run finishes under the interrupted activation id;
- proved absent: it is retired, and the next scheduled window resubmits it
  exactly once, under the same activation id.

Evidence on the parent commits: 13c91a9 drops the activation, so the window
after the restart reports `lastRun 8eea7c5d...` for a wake submitted as
`dac1f3df...` (two investigations); with the reconciliation but without this
commit the retry still minted `d935f7fe...` instead of reusing `cycle-3`.
Fence Plugin Agent admission, snapshots and idle waits when the Host commits
to detaching its Roots. Physical completion in the retiring Host no longer
settles the observer; owner cancellation preserves the unfinished activation,
shared reservation and event receipts for recovery in the successor.

Exercise natural handoff with live observers in both broad phases and quick
discovery, including event receipts and a cancelled sealed handoff. All six
independent R7 preservation reproductions now pass.

Validation: build, typecheck, lint, format, ASF and protocol guards, Desktop/UI
Knip, 402 assistant tests, 14 Runtime service tests and final per-file results
of 214 affected Host tests. One unchanged hosted-environment case exceeded its
wait during the first suite run; parent/fixed isolated checks and its complete
66-test file passed without changing the test or its timeout.

Generated-by: OpenAI Codex
Centralize discovery admission and settlement in one durable Runner, preserve source receipts and permissions, and provide bounded investigation continuation across scoped Sessions.

Generated-by: OpenAI Codex
Require idle legacy settings instead of converting old jobs, queues and handoff records. Keep current Runner restart recovery and consolidate its regression coverage.

Generated-by: OpenAI Codex
Use the Host message execution contract, reject unsupported completion replies, and document the typed job-work projection at controller writes.

Generated-by: OpenAI Codex
Bound continuous recovery uncertainty to five minutes, discard late outputs, and preserve committed knowledge and pending hints for a fresh worker on the next normal cycle.

Generated-by: OpenAI Codex
Import durable worker identities before exposing the old quick discovery configuration, so scoped bindings are not mistaken for legacy workers during startup.

Generated-by: OpenAI Codex
@sunrioa
sunrioa requested a review from xxhZs November 7, 2026 08:04
@sunrioa

sunrioa commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Recording follow-up optimization ideas from a 24-hour local run on 0b2cd3254771b15d8be4679bd78264e231bc19c4. This is a discussion note: none of the changes proposed below has been implemented, and this is not a commitment to expand the current PR.

The observations include existing Bot and delegated-task behavior as well as discovery. They should not all be interpreted as regressions introduced by this PR.

Observed baseline

Window: 2026-11-08 10:53:50 to 2026-11-09 10:53:50, UTC+8, one local profile using Command Code → DeepSeek V4.1 Flash, with scoped discovery workers.

  • 6,358 recorded model calls: 6,355 with usage, two network failures and one aborted auxiliary call without usage.
  • Known input: 496,955,219 tokens; output: 3,269,231; total: 500,224,450.
  • Input cache hits: 471,123,840; misses: 25,831,379; token-weighted hit rate: 94.80%.
  • Canonical and auxiliary accounting were checked for duplicate call identities. Unknown usage is not treated as free. Cached input is included in input; reasoning is included in output.
  • These are cumulative request tokens, not the size of newly produced content or a controlled comparison against main. Only aggregate data is included here.
Area Model calls Total tokens Token share Relative cost weight using official price ratios*
Broad exploration + judgement 3,237 153,625,825 30.71% 31.52%
Quick investigation 834 31,493,166 6.30% 8.94%
Event screening 8 73,119 0.015% 0.17%
Bot 331 206,166,020 41.21% 27.05%
Delegated execution + auxiliary settlement review 1,948 108,866,320 21.76% 32.32%

*The current official DeepSeek prices distinguish cache hits, misses and output. Applying one common time-of-day tariff gives the relative weights above; this is not the Command Code invoice. A reduction in raw tokens will not necessarily produce the same percentage reduction in cost.

1. Try an earlier Bot-specific compaction threshold

The current Bot fallback is 80% of the configured context capacity: approximately 800,000 tokens for this 1M configuration. Bot input averaged 622,534 tokens per request, ending at 720,898.

Compaction is working: on November 6 at 03:57 UTC+8, a persisted compaction was applied and the surrounding main requests went from 797,960 input tokens to 14,555. The context subsequently grew again.

A reasonable first experiment is a Bot-specific threshold of 128,000 tokens, bounded by model capacity and still subordinate to an explicit user threshold. Keep the same Session and existing compactor; preserve current requests, standing authorizations and restrictions, unfinished tasks, exact IDs and feedback relationships. Full records remain available for lookup.

For scale only: holding 331 calls fixed and assuming average input of 100,000 would reduce Bot input from 206.1M to 33.1M, a static difference equal to about 34.6% of the observed total. This is not a measured saving: compaction calls, additional lookups, behavioral changes and cache rebuilding are excluded.

2. Make recent context cheap to read

Quick workers called DiscoveryContext 310 times, with up to 50 tool calls in one investigation Session. Its serialized return values totaled about 171 million characters, approximately 96.3% of which was the attached task data.

These are raw tool-result characters, not model tokens. Code Mode filtered some results before returning them to the model.

The current implementation pages messages by offset from the beginning and attaches the full task listing on every page. The recorded calls include repeated offset probing to find recent messages.

Proposed direction:

  • Add bounded recent-message and stable-cursor incremental reads.
  • Avoid attaching every task's full details to every message page.
  • Reuse compact task summaries and ID-based detail reads, such as the existing MatterOverview / MatterTasks(id) capabilities.
  • Keep older history available on demand and retain owner/permission checks.

This targets avoidable retrieval, serialization and model navigation work without introducing another memory subsystem.

3. Remove fixed Bot control round trips where safe

The 331 Bot model steps consisted of 94 InboxCheck steps, 48 delegation steps, 93 send steps, 94 Sleep steps and two other combinations. All 92 observed Bot Turns began with an Inbox check; there were 93 send-then-Sleep pairs.

Two possible interface changes:

  • Include the first bounded unread batch in the admitted wake, retaining InboxCheck for additional pages and newly arriving messages.
  • Allow the final publication and sleep request to be submitted together.

Preserve durable admission identity, idempotent publication, delivery acknowledgement and the final check for newly arrived mail. A failed admission must not acknowledge unseen input; a new message during publication must prevent sleeping.

Sleep currently finishes the Turn and is direct-only, so this needs a real contract change, not just a prompt telling the model to nest it in Code Mode.

The inbox and sleep steps carried about 117.24M tokens, but that is not an immediately removable cost total. In particular, first-request cache misses can move to the next request after combining steps.

4. Avoid back-to-back idle checks after broad discovery

Of 22 quick investigations, seven began within one minute of a broad completion, and 12 within 15 minutes. This timing alone does not prove that the investigations were redundant.

Consider deferring only a purely periodic/idle quick check after a recent broad completion when there is no new event and no observed activity change. Explicit event wakes, manual checks and recovery should retain their rules. An unavailable source must not be treated as unchanged, and postponement must not acknowledge source events as processed.

The existing completion time and trigger information should be enough to explore this, without adding a new scheduler.

5. Consider combining broad exploration and judgement as a later experiment

Exploration used 1,472 model calls / 65.32M tokens; judgement used 1,765 / 88.30M. The current prompts make judgement another substantial investigation phase, rather than a small final filter.

A later alternative worth evaluating is one investigation Session that explores, verifies, updates the notebook and decides whether to submit a discovery. This may reduce handoff and rereading, but the independent second phase may also catch mistakes. Its entire 88.30M-token usage cannot be counted as removable: necessary investigation would move into the combined flow.

This should be evaluated separately from the first three interface/context changes.

What to preserve and how to evaluate

Event screening is already small: 68 captured events across seven source conversations, eight screening calls and one event wake. Tightening it further is not the first priority. Useful long investigations are not inherently a problem, and task settlement review, feedback handling, permissions and delivery records should remain intact.

If these ideas are taken forward, the first candidate batch would be Bot compaction, recent-context reads and Bot control round trips. Replay the same inputs separately for each change before combining them. Measure cache hits/misses, output, compaction and lookup overhead, latency, useful discoveries and task outcomes. Check that quotes, task associations, authorizations and feedback survive compaction; that concurrent arrivals cannot be lost; and that retries cannot duplicate publication. Savings from overlapping changes must not be added together.

AI assistance: OpenAI Codex assisted with local record/source inspection and drafting this note. Posted at the author's request.

简体中文

记录基于 0b2cd3254771b15d8be4679bd78264e231bc19c4 的最近 24 小时本地运行观察与后续优化想法。以下仅供讨论,尚未实现,也不表示承诺将这些改动全部加入当前 PR。

观察涉及原有 Bot、委派任务及发现链路,不能全部归因于本 PR 引入的回归。

实测基线

时间:北京时间 2026-11-08 10:53:50 至 2026-11-09 10:53:50。单个本地工作区,使用 Command Code → DeepSeek V4.1 Flash,发现使用 scoped worker。

  • 记录到 6,358 次模型调用,其中 6,355 次有用量回报;2 次网络失败、1 次辅助调用中止没有用量。
  • 已知输入 496,955,219,输出 3,269,231,总计 500,224,450 token。
  • 输入缓存命中 471,123,840,未命中 25,831,379,按 token 计算的命中率 94.80%。
  • 主调用与辅助调用已核对身份,避免重复计算。未知消耗不视为免费;命中输入已包含在输入中,推理已包含在输出中。
  • 这是多次请求累计的 token,不是新增内容体积,也不是与 main 的受控对照。这里仅提供汇总数据。
环节 模型调用 总 token token 占比 按官方单价比例折算的费用权重*
广域探索+判断 3,237 153,625,825 30.71% 31.52%
快速调查 834 31,493,166 6.30% 8.94%
事件筛选 8 73,119 0.015% 0.17%
Bot 331 206,166,020 41.21% 27.05%
委派执行+辅助结算复核 1,948 108,866,320 21.76% 32.32%

*当前 DeepSeek 官方价格区分命中输入、未命中输入和输出。这里统一按同一时段单价比例比较,不是 Command Code 实际账单。token 下降不等于费用同比例下降。

1. 试验提前压缩 Bot

当前 Bot 默认在配置容量的 80% 附近压缩,本地 1M 配置对应约 80 万 token。Bot 平均每次输入 622,534,最新一次达到 720,898。

压缩机制已经实际工作:北京时间 11 月 6 日 03:57 有已应用的压缩记录,相邻主请求输入由 797,960 降至 14,555,之后又逐渐积累。

可以先试验 Bot 专用的 128,000 token 阈值,受模型容量约束,用户显式配置仍优先。继续使用同一个 Session 和现有压缩机制,保留当前要求、持续授权与限制、未完成事项、准确 ID 和反馈关联;完整记录按需回查。

仅作静态量级说明:假设调用仍为 331 次,平均输入降到 10 万,Bot 输入会从约 2.061 亿降到 3310 万,差额约占本次全部 token 的 34.6%。这不是实测节省率,尚未计入压缩调用、补充回查、行为变化和缓存重建。

2. 让近期上下文更容易读取

快速调查调用 DiscoveryContext 310 次,单个调查 Session 最多调用 50 次。原始工具返回累计约 1.71 亿字符,其中约 96.3% 是附带的任务数据。

这是原始工具返回字符数,不是模型 token;Code Mode 在向模型返回前已经筛掉部分内容。

当前接口从旧消息开始按 offset 分页,每页再次附带完整任务列表。实际记录存在反复试探 offset、寻找近期消息的行为。

建议:

  • 增加有界的最近消息读取及稳定游标增量读取。
  • 翻消息页时不再默认重复附带全部任务详情。
  • 复用简短任务目录和按 ID 查询详情的能力,例如现有 MatterOverview、MatterTasks(id)。
  • 保留旧历史回查和原有归属、权限检查。

目标是减少读取、序列化及模型寻找入口的工作,不增加新的记忆子系统。

3. 减少 Bot 固定的控制调用

331 次 Bot 模型步骤包括:94 次收件、48 次委派、93 次发送、94 次休眠,以及 2 次其他组合。观察到的 92 轮 Bot Turn 都先读取 Inbox,93 次发送之后紧接着调用 Sleep。

可考虑:

  • 在已接纳的唤醒中直接携带第一批有界未读消息;追加分页和执行中新来的消息仍由 InboxCheck 读取。
  • 允许最终发送和休眠申请一起提交。

必须保留持久提交身份、幂等发送、投递确认和最后的新消息检查。接纳失败不能确认尚未看到的输入;发送期间有新消息到达,就不能休眠。

当前 Sleep 是结束 Turn 的 direct-only 工具,需要真正调整契约,不能只靠提示词要求放进 Code Mode。

收件和休眠步骤累计携带约 1.1724 亿 token,但不能全部视为可直接削减的费用。例如合并调用后,首次请求的缓存未命中可能转移到下一次请求。

4. 错开紧挨着广域完成的空闲检查

22 轮快速调查中,7 轮在广域完成后不到一分钟启动,12 轮在十五分钟内启动。时间接近本身不证明调查重复。

可以考虑:广域刚完成且没有新事件、没有观察到活动变化时,适当推迟纯定时或空闲快速检查。明确事件、手动检查和恢复继续遵守各自规则。来源不可用不能视为没有变化;延后检查不能把来源事件确认成已处理。

先利用已有完成时间和触发信息,不增加另一套调度器。

5. 后续单独评估合并广域探索与判断

探索消耗 1472 次调用、6532 万 token;判断消耗 1765 次调用、8830 万 token。当前判断阶段本身也负责深入调查,不是一个很轻的最终过滤器。

可以后续试验由同一个调查 Session 完成探索、核实、记事本更新和是否提交发现的判断,减少交接与重新读取。但独立第二阶段也可能发现错误,不能把其 8830 万 token 全部当作可消除开销:必要调查仍需要在合并后的流程中完成。

这项应与前三项上下文和接口优化分别评估。

保留的能力与验证方式

事件入口已较轻:本窗口捕获 7 个来源会话的 68 条事件,进行 8 次筛选,产生 1 个事件唤醒。继续收紧它不是首要方向。有价值的长调查本身不是问题;任务结算复核、反馈、权限与送达记录应保留。

如果后续推进,优先考虑 Bot 压缩、近期上下文读取、Bot 控制调用。每项先单独回放相同输入,再测试组合效果。统计缓存命中/未命中、输出、压缩与回查开销、响应时间、有效发现和任务结果;验证压缩后引用、任务关联、授权和反馈不丢失,并发新消息不漏处理,重试不重复发送。相互重叠的节省幅度不能直接相加。

AI 使用说明:OpenAI Codex 协助检查本地记录、源码及起草本评论,按作者要求发布。

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/XXL Over 2500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants