Skip to content

fix(agent-core-v2): harden wire restore and background task lifecycle - #1635

Merged
sailist merged 12 commits into
MoonshotAI:mainfrom
sailist:fix/agent-core-v2-task-lifecycle
Jul 14, 2026
Merged

fix(agent-core-v2): harden wire restore and background task lifecycle#1635
sailist merged 12 commits into
MoonshotAI:mainfrom
sailist:fix/agent-core-v2-task-lifecycle

Conversation

@sailist

@sailist sailist commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Related Issue

No linked issue. This fixes three related agent-core-v2 durability, restore-compatibility, and task-lifecycle problems described below.

Problem

  1. Wire-log replacement could lose or silently fail live records. Restore did not await migration rewrites, live appends could be overwritten by a stale replacement snapshot, and an auto-drain failure let a later flush() report success. Non-empty unversioned logs were also stamped as current instead of being rejected.
  2. Session close did not stop task-owned processes. Agent removal aborted the turn/activity kernel but did not apply the task manager's graceful TERM → configured grace → force-stop policy. Disposal paths that bypassed normal removal could leave a process that ignored SIGTERM alive.
  3. Per-agent task persistence broke previous v2 restores. Moving task records to the owning agent fixed v1 layout compatibility and cross-agent isolation, but the main agent could no longer see records written by the previous v2 session-level root.

What changed

1. Wire and AppendLog durability

  • AgentWireRecordService.restore() awaits migration rewrites and propagates rewrite failures. Agent create and session fork reject non-empty logs without a protocol metadata envelope; empty logs still receive normal metadata.
  • AppendLogStore.rewrite(records) now has an explicit cutover contract: records replaces history already durable before the call, while queued or in-flight appends remain an ordered live tail after the atomic replacement.
  • A cutover epoch prevents an old in-flight drain from deleting or repeatedly draining the tail after rewrite ownership changes. flush() remains pending through the post-rewrite durable append.
  • Ambiguous append and atomic-rewrite failures are sticky for that acquired buffer generation. Later flush, read, or rewrite calls return the same error instead of guessing whether storage committed and risking duplicates.
  • Releasing the final acquired owner retires the keyed buffer only after in-flight work settles. A replacement owner waits for that retirement, and identity checks prevent an old owner from deleting the replacement state.

2. Background process teardown

  • AgentLifecycleService.remove() awaits AgentTaskService.stopAllOnExit() before activity drain and scope disposal.
  • Normal stop sends SIGTERM/cancel, waits killGracePeriodMs, then calls the task's force-stop callback when needed. The keepAliveOnExit opt-out skips task-manager teardown for independently living work such as processes.
  • Scope disposal is a synchronous safety net: it cancels/aborts active work and immediately starts best-effort force-stop, covering bootstrap failure, rollback, and root-scope disposal paths that cannot await graceful shutdown.
  • Legacy [background] values are merged beneath [task]; the environment-only keepAliveOnExit overlay no longer hides maxRunningTasks or killGracePeriodMs.

3. Task persistence compatibility

  • New writes remain rooted at the owning agent, matching v1's runtime <sessionDir>/agents/<id>/tasks/ layout.
  • The main agent reads the previous v2 session-level task root only when its local record/output is absent. Local empty, corrupt, or unrecognized entries remain authoritative; output snapshots report the path of the root actually used.
  • Subagents never read the shared fallback, so they cannot claim another agent's legacy task.

Review follow-up

  • Added controlled rewrite gates for snapshot → pending append, old drain already in flight, post-rewrite flush durability, ambiguous append failure, atomic rewrite failure, and acquired-owner retirement.
  • Added an ignore-SIGTERM disposal contract that observes SIGTERM followed by immediate SIGKILL, plus a real process keep-alive contract.
  • Added persistence and public restore contracts for local-first main-agent fallback, real legacy output paths, corrupt/empty boundaries, and subagent isolation.
  • Moved implementation rationale into domain headers and documented background.kill_grace_period_ms in the mirrored English and Chinese configuration references.
  • Session materialization rollback and same-ID initialization admission are handled separately in PR fix(agent-core-v2): roll back failed session initialization #1642.

keepAliveOnExit in this fix is intentionally scoped to task-owned work that can live independently of the Session scope, such as a detached process. Session-scoped subagents still end with their Session lifecycle; this PR does not claim to detach a DI child scope from its owner.

Verification

  • agent-core-v2: 236 files / 3288 tests passed with one worker.
  • Targeted lifecycle/durability/restore suite: 6 files / 110 tests passed.
  • agent-core-v2 build, typecheck, and domain lint passed (848 files).
  • kap-server typecheck passed.
  • Targeted type-aware lint completed with 0 errors (existing warnings remain).
  • VitePress docs build, changeset status, and git diff --check passed.
  • Independent fixed-diff review reported no actionable findings for cutover, concurrent rewrite, sticky recovery, retirement handoff, and multi-key close.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue, or explained the problem above.
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill. (3 focused patch changesets)
  • Ran gen-docs skill. (Updated mirrored EN/ZH config references)

sailist added 3 commits July 14, 2026 00:03
…ioned logs (8 files)

- await the migration rewrite in wireRecordService.restore() so restore only resolves once the migrated log is durable and rewrite failures surface
- serialize AppendLogStore.rewrite() behind the log flush so appends arriving during the whole-file replace land after the new content
- reject wire logs missing the metadata envelope (missingWireMetadataError) in restore, session fork, and agent create instead of fabricating a current-version envelope over legacy records
- add IAgentTaskService.stopAllOnExit: suppress terminal notifications, then SIGTERM → grace → SIGKILL for every active task (v1 stopBackgroundTasksOnExit parity, gated by keepAliveOnExit)
- call stopAllOnExit from agentLifecycle.remove before scope disposal, and abort live tasks in AgentTaskService.dispose as a last resort for disposal paths that bypass the graceful close
- honor [task] killGracePeriodMs in the stop grace window and bind the v1 KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT env override for keepAliveOnExit
- persist task records under <sessionScope>/agents/<agentId>/tasks/ (v1's
  per-agent layout) so tasks written by older versions are found on resume
- stop one agent's restore from loading, marking lost, or re-notifying
  another agent's tasks
- add a per-agent isolation test covering loadFromDisk + reconcile
@changeset-bot

changeset-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9fcca23

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Jul 13, 2026

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@9fcca23
npx https://pkg.pr.new/@moonshot-ai/kimi-code@9fcca23

commit: 9fcca23

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 942ad7c0f8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/agent-core-v2/src/agent/task/configSection.ts
Comment thread packages/agent-core-v2/src/persistence/backends/node-fs/appendLogStore.ts Outdated
Comment thread packages/agent-core-v2/src/persistence/backends/node-fs/appendLogStore.ts Outdated
@wbxl2000

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ddbc96d52f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/agent-core-v2/src/persistence/backends/node-fs/appendLogStore.ts Outdated
@wbxl2000

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 96cc1e4cde

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/agent-core-v2/src/agent/task/taskService.ts
@wbxl2000

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9bee9d83e8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/agent-core-v2/src/agent/task/taskService.ts Outdated
@wbxl2000

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 9fcca23f28

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@sailist
sailist merged commit e49b3b8 into MoonshotAI:main Jul 14, 2026
15 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 14, 2026
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.

2 participants