Skip to content

refactor(core): add key-based session space - #5205

Open
sailist wants to merge 5 commits into
loop-refactfrom
refact-409-11-20-session-crud-core
Open

sailist wants to merge 5 commits into
loop-refactfrom
refact-409-11-20-session-crud-core

Conversation

@sailist

@sailist sailist commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

核心维护者需要在不依赖 workspace、cwd 或 v2 DI 的前提下复用 session catalog 的增删改查能力,同时保留现有 session 生命周期、state.json 格式和 KAP 行为。本 PR 在 core 提供 OSS 风格的 key-based SessionSpace,并让 v2 的权威 session 读写通过同一实现完成。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路是把“通用 session CRUD”与“workspace/cwd、live SessionScope、派生索引和 fork/copy”分开。SessionSpace 使用不透明 key 寻址,list(prefix?) 只返回 key,不隐式读取所有 record;不传 prefix 时执行全量枚举。当前磁盘布局可以直接映射为 root=sessions、key=<workspaceId>/<sessionId>,core 不解释 key 中的 workspace 含义。

flowchart TD
    Core[core SessionSpace] --> Memory[Memory backend]
    Core --> Node[Node backend]
    Lifecycle[v2 SessionLifecycle] -->|SessionScope seed| Metadata[v2 SessionMetadata]
    Lifecycle --> Adapter[HostSessionSpace adapter]
    Metadata --> Adapter
    Adapter --> Core
    Adapter --> Docs[v2 AtomicDocumentStore]
    Adapter --> HostFs[v2 HostFileSystem]
Loading

关键决策:

  • core 提供 create/get/update/delete/list、结构化错误、Memory 和 Node backend;Node 支持 canonical/legacy state.json 和整个 session 容器删除。
  • v2 的 SessionMeta 保持显式磁盘字段并结构化兼容 core SessionRecord,避免改变生成的 state manifest;现有 isCustomTitle、legacy 路径、显式 updatedAt 和 touchUpdatedAt: false 语义保留。
  • SessionSpace 在 App 初始化时注册为共享服务;SessionLifecycle 从 App accessor 获取同一实例,并通过 SessionScope seed 提供给 Metadata,独立 SessionScope 也可直接解析。
  • MiniDb 派生索引、增量 projector、锁、事件、遥测、retention 和 fork/copy 均未改变,也不迁移到 session.jsonl。

阅读顺序建议:先看 packages/core/src/session/model.ts 了解记录与接口,再看 packages/core/src/session/space.ts 的公共 CRUD 语义、packages/core/src/session/backend/node.ts 的物理布局,最后看 packages/agent-core-v2/src/session/sessionSpace/sessionSpaceService.ts 和 sessionLifecycleService.ts 的 v2 接线。Memory backend、类型迁移和测试可随后阅读。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Session catalog capability in core No core SessionSpace API Key-based CRUD plus prefix/full key listing Core library consumers Existing v2 persistence paths and formats remain supported
v2 session metadata and lifecycle persistence Direct DocumentStore/HostFs operations Same operations routed through the core SessionSpace contract and v2 adapter CLI, Desktop, SDK and KAP sessions state.json fields, legacy reads, index behavior, KAP and lifecycle semantics are unchanged; no migration is needed

现有 CLI、Desktop、SDK、ACP 和 KAP 调用方没有可感知的破坏性变化。没有修改 KAP、wire/state/config manifests、SDK、ACP 或 CLI 契约文件,也不需要数据迁移。

验证覆盖:

  • core SessionSpace、SessionMetadata 和 sessionLifecycle 共 60/60 聚焦测试通过,覆盖 prefix/full list、损坏记录、legacy 读取、递归删除、时间戳、锁和关闭路径。
  • core、agent-core-v2、kap-server、node-sdk、klient typecheck 全部通过。
  • 公开 Node 子路径在真实临时目录完成 create、prefix list、update、get、delete 和 full list 冒烟。
  • 标准 pnpm lint 以 0 退出;相对 loop-refact 的显式 base duplication 检查无新增 clone。
  • 只读公开内容审计未发现密钥、内部标识、无关文件或额外公共契约变化。
  • 最新 CI 中 L0 protected、L0 smoke、build、lint、typecheck、test (1)/(3)/(5) 已通过,stateManifest 兼容检查通过。剩余 tool.test、config 快照和 skill model-tool 三项失败与 loop-refact 自身的 LLM loop/tool 改动处于同一风险范围,但不在本 PR 的 SessionSpace diff 内,基线归属尚待确认。
未完成的验证

远程 Linux 和 Windows 环境两轮初始化均因 SSH 连接超时失败,因此远程全量回归、kap-server sessions 端到端和真实冷重启测试未执行。这些项目在本 PR 中不作为已通过验证声明。

Checklist

  • I have read the CONTRIBUTING document.
  • N/A: internal refactoring, no related issue.
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete; no existing behavior or default is removed or flipped.
  • A changeset required by CONTRIBUTING was intentionally omitted at the requester's explicit instruction.
  • No user-facing documentation update is needed because existing product behavior is unchanged.

@changeset-bot

changeset-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 1a5d06d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T09:21:49.562162Z 1a5d06d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 21, 2026 •

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

commit: 1a5d06d

@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: 06dc55dea6

ℹ️ 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 on lines +625 to +627
await this.sessionSpace.delete(
this.sessionSpace.keyFor(sessionScopeOf(this.handlerScope, sessionId)),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep deletion idempotent for indexed sessions

When a session remains in the index but its directory is already absent—for example after manual cleanup or an interrupted recovery—the new SessionSpace.delete() throws not-found, so execution never reaches index.remove() and TUI, SDK, KAP, and ACP clients cannot remove the stale session. The previous HostFileSystem.remove() used forceful recursive removal and still completed the index cleanup; treat an absent directory as already deleted at this lifecycle boundary.

AGENTS.md reference: AGENTS.md:L207-L209

Useful? React with 👍 / 👎.

this.data = { ...this.data, ...patch, updatedAt };
await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
const next: SessionMeta = { ...this.data, ...patch, updatedAt };
this.data = await this.sessionSpace.update(this.key, next, { touchUpdatedAt: false });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve normalized fields when updating legacy metadata

For an old metadata record whose id or timestamps need normalization but which already has agents, custom, and consistent title fields, load() normalizes only the in-memory value and does not rewrite it. This call then rereads the raw record through SessionSpace.update(), which preserves the raw immutable id and createdAt over the normalized next value; an untitled legacy record with ISO timestamps and no id, for example, becomes a version-2 record with a missing id and string createdAt after its first prompt, breaking live KAP/SDK summaries and index mirroring. Persist the normalized record before using the generic update path.

AGENTS.md reference: AGENTS.md:L191-L193

Useful? React with 👍 / 👎.

if (isEnoent(error)) return false;
throw error;
}
await rm(dir, { recursive: true, force: true });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Verify a record exists before deleting its directory

If a/b is a valid stored session but no record exists at a, delete('a') sees the ancestor directory, recursively removes it, and reports success, silently deleting a/b instead of returning not-found. The host adapter has the same directory-only existence check. Check for a canonical or legacy state.json belonging to the requested key before removing the container.

Useful? React with 👍 / 👎.

}
if (key !== '' && entries.some((entry) => entry.isFile() && entry.name === 'state.json')) {
keys.push(key);
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Continue traversal below parent records

Hierarchical keys permit both a and a/b, but after both are successfully created this early return stops traversal at a/state.json, so the filesystem backend's list() omits a/b while the memory backend returns both. The host adapter repeats the same early return. Record the parent key without terminating traversal so all valid descendant keys remain discoverable.

Useful? React with 👍 / 👎.

Comment on lines +57 to +58
if ((await backend.read(key)) !== undefined) {
throw new SessionSpaceError('already-exists', `session '${key}' already exists`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make duplicate creation atomic

When two callers concurrently run create() for the same key, both can await backend.read() before either write occurs, observe that the key is absent, and then both resolve successfully while the later write overwrites the first. This violates the advertised already-exists behavior and is reproducible with the asynchronous memory backend as well as possible across node-backed processes; use an exclusive backend create operation or per-key serialization so exactly one caller succeeds.

Useful? React with 👍 / 👎.

key.length === 0 ||
key.startsWith('/') ||
key.endsWith('/') ||
key.includes('\\') ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve accepted custom session IDs

Lifecycle operations now derive storage keys from externally supplied session IDs and reject backslashes here, even though the Klient lifecycle contract still accepts any string and the previous document-store path accepted a backslash as a literal filename character on Linux. A caller with an existing ID such as release\candidate can therefore no longer create, resume, or delete that session after upgrading. Encode IDs when forming keys or narrow the external contract with explicit compatibility handling.

AGENTS.md reference: AGENTS.md:L191-L193

Useful? React with 👍 / 👎.

{
seeds: [
...sessionContextSeed(ctx),
[ISessionSpace, this.sessionSpace],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Provide SessionSpace to directly created session scopes

SessionMetadata is activated for session scopes and now requires ISessionSpace, but this seed is only supplied by SessionLifecycleService. The shared TestAgent harness creates its session directly with root.createChild(LifecycleScope.Session, ...) and later resolves ISessionMetadata without providing this token, so harness-backed agent and conversation tests fail during dependency injection. Register an app-level implementation or add the same seed to every direct session-scope factory.

Useful? React with 👍 / 👎.

Comment on lines +36 to +37
(await this.storage.read(key, 'state.json')) ??
(await this.storage.read(`${key}/session-meta`, 'state.json'));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Disambiguate legacy metadata from valid child keys

Because session-meta remains a valid key component, a record stored at a/session-meta is also returned by get('a') through this legacy fallback. As a result, create('a') falsely reports already-exists, and the filesystem walker similarly reports the child under the wrong key; the host adapter duplicates this behavior. Reserve and reject the sentinel component or disambiguate legacy metadata without interpreting an otherwise opaque key.

Useful? React with 👍 / 👎.

private readonly storage: FileStorageService;

constructor(private readonly root: string) {
this.storage = new FileStorageService(root);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Protect node-backed session files with private modes

With a normal 022 umask and a caller-supplied root beneath a traversable directory, this default FileStorageService creates intermediate directories as 0755 and state.json as 0644, exposing session titles, prompts, and custom metadata to other local users. The application bootstrap explicitly configures the same storage implementation with 0700 directories and 0600 files, while nodeSessionSpace() offers no mode option. Use private defaults or expose secure mode configuration.

Useful? React with 👍 / 👎.

@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: 1a5d06deb6

ℹ️ 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".

return record;
},
update: async (key, patch, opts) => {
const current = await read(key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Serialize read-modify-write updates

When two callers update the same key concurrently, both can finish this read before either write occurs, so each merges against the same old record and the later write silently discards fields from the earlier patch. This is reproducible with memorySessionSpace() and affects core consumers that issue independent updates; serialize operations per key or provide an atomic backend mutation primitive so concurrent patches cannot lose data.

AGENTS.md reference: AGENTS.md:L211-L213

Useful? React with 👍 / 👎.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant