Skip to content

Kode — Player Data Clone (KBEngine Player Persistent Data Cloning) Detailed Implementation Plan ​

Source: the full ChatGPT plan provided by the user (share link https://chatgpt.com/s/t_6aec9e508bf88191b5ccf25ebb51b412); the user supplied the complete .md file (422 lines) on 2026-11-05. Scope: v0.2.1. Nature statement: an external plan, not a fact of this repository — every comparison conclusion in §2 "Fact baseline and source-code verification boundary" must be re-checked against this repo's code before execution (Phase 0 exists for exactly this). Task baseline discipline: the 51 checkboxes in §9 are the sole fine-grained task baseline for the CLONE series; the repo-root todo.md keeps only stage-level entries (CLONE-P0~P6); dual ledgers are forbidden.

Kode — Player Data Clone (KBEngine Player Persistent Data Cloning) Detailed Implementation Plan ​

Version: v1.0 (technical plan / Code Agent execution baseline) Date: 2026-11-05 Target repo: cuihairu/kode Status: design proposal; not a description of implemented features. This document relies on Kode's published README, the Cargo Workspace, kode-types source, and KBEngine documentation. Any specific database column name, child-table parent-child relation, and engine version behavior must be verified in Phase 0 against the target engine's source and real database-creation samples — never hard-coded from examples.

0. One-sentence conclusion ​

Build a Rust-led Player Data Clone subsystem inside Kode: use the persistent database structure derived from the existing .def/types.xml/entities.xml to read-only export a specified player's persisted Entities and their engine-generated child-table records from an authorized source MySQL database; produce an auditable, redactable, verifiable offline archive; in a stopped local test environment preview the impact, allocate new IDs, remap per known reference rules, import in a transaction, and verify with a local engine load test.

Explicitly not promised: online authoritative memory snapshots, automatic recognition of all business foreign keys, automatic cloning of an entire game world, or automatic proof of reproduction of any live issue.

1. Requirements and non-goals ​

1.1 Core user stories ​

  • The developer picks a project/Source Profile, an Entity type, a database interface, and a Player DBID, and sees the main and child tables that will be included.
  • Clicking "one-click export": read-only, bounded copying of the character already persisted in the current database plus determinable child records, producing a re-importable package.
  • Pick a local target environment: rehearse conflicts, unique-key problems, data redaction, account mapping, and ID rewriting.
  • Clicking "one-click import": write only to targets explicitly marked local/test, generate new DBIDs and repair relations, run a local transaction; finally verify for real using KBEngine's native loading path.
  • The mapping of original source DBIDs, types, and source version to new DBIDs is visible only in the authorized offline audit report, avoiding copying sensitive identity data.

1.2 Non-goals (v1) ​

  • No reading transient in-memory objects from online BaseApp / CellApp; no calling writeToDB() to force online saves.
  • No automatic copying of shared business entities such as guilds, friends, mail, leaderboards, or payment orders.
  • No MySQL → PostgreSQL/MongoDB migration; no automatic migration of incompatible schemas.
  • No direct online modification of a locally running, already loaded character; writes to online databases are not allowed.
  • No universal SQL editor or production-account impersonation in the tool.

1.3 Export scope allowed for the MVP ​

  1. A single Persistent Entity main table.
  2. The ARRAY, component, and nested-container child tables determined by the engine's database mapper (the actual level the recursive parentID points at needs verification).
  3. FIXED_DICT expanded fields within the same Entity and binary values exactly restorable.
  4. Custom business associations do not follow by default; they extend only when the user explicitly specifies rules.
  5. Exported objects must be persisted entities with stable database IDs; temporary entities are out of scope for this feature.

2. Fact baseline and source-code verification boundary ​

Kode's published README describes: a Rust Core (kode-parser, kode-types, kode-server, etc.); database table-structure derivation, read-only table preview, Schema Drift checks, isolated Profile connections, and table-name prefix handling. The Cargo Workspace uses Rust 2021, minimum Rust 1.82, unsafe_code = forbid. The existing kode-types provides an XML/def type graph and container/alias/entity reference models.

Still to verify: whether the database table IR is provided directly by Rust, whether the existing DB connector currently sits in TypeScript or Rust, the actual SQL construction path, the engine branch and table-name mapping, and the level-by-level linkage of parentID in real databases. The README's listed features must not be treated as already covering export/import.

KBEngine documentation confirms Persistent=true fields are archived, tbl_ is the common prefix for tables generated for business Entities/components/ custom types, sm_ marks engine-managed fields; internal tables like kbe_ should not be copied by default. The documentation also warns that reading the database directly is not equivalent to an online Entity's current values, and a later online save may overwrite the database value.

3. Solution architecture ​

text
VSCode Kode UI (TypeScript)
  ├── Source Profile / Player Picker / Export Plan Preview
  ├── Archive Preview / Target Profile / Import Plan Preview
  └── only handles interaction, cancellation, audit display; holds no write business rules
              │ versioned, limited-capability command protocol
              ▼
Rust Core (existing schema/type layer reused)
  ├── kode-db-clone (new crate)
  │    ├── SchemaResolver        structure mapping, source/target drift checks
  │    ├── RelationGraph         engine child-table relations / explicit business relations
  │    ├── ExportPlanner         exportable scope, SQL query plan
  │    ├── ExportExecutor        source read-only consistent snapshot / streaming reads
  │    ├── ArchiveCodec          archive, checksum, encryption, redaction
  │    ├── ImportPlanner         target diffs, unique-key conflicts, ID remap plan
  │    ├── ImportExecutor        target transactional writes
  │    └── ImportValidator       data-relation verification and load results
  ├── kode-parser / kode-types  (existing)
  └── kode-server                 (keep the existing LSP; ordinary LSP queries never gain write access)
              │
     SourceReader (forced read-only)      TargetWriter (local/test only)
              │                           │
      source MySQL / read replica           local MySQL

3.1 Reducing duplicate implementation ​

  • Reuse Kode's existing EntityDef and type graph; do not rewrite an XML parser.
  • Use the existing Schema Drift capability to find mismatches between real and derived tables; data cloning must fail closed on unconfirmed mappings.
  • If the existing database connection layer can be safely reused, reuse the connection configuration and TLS parsing; but create separate Export Read Sessions and Import Write Sessions.
  • Do not lift Kode's current database panel's read-only restriction; writes go only through a dedicated local ImportExecutor and an explicit target permission boundary.

4. Schema / relation identification design ​

4.1 Two-level schema: derived + on-site verification ​

DefDerivedSchema comes from .def, types.xml, component definitions, inheritance, and Persistent markers. PhysicalSchema reads actual databases, columns, indexes, storage engines, primary keys, and auto-increment info from MySQL information_schema. ResolvedCloneSchema contains only the fields/relations matched on both sides and explicitly approved by rules.

  • Table names, prefixes, component child tables, and container nesting paths must never be guessed by pure string splitting.
  • Verify field data types, charsets, nullability, defaults, primary keys, and unique constraints.
  • Original values are stored in typed encodings: unsigned integers, DECIMAL, DATETIME, BLOB, NULL, TEXT; converting all values to float64 / bare JSON numbers and back is forbidden.
  • Explicit allow/deny policies are built separately for kbe_ internal management tables and critical sm_* fields such as auto-login; whole- database scans are forbidden.

4.2 Relation classification (determines the degree of automation) ​

Relation classExamplev1 behavior
A engine-determined relationsentity main table → ARRAY/component child tables, parentID verified against the real engineauto-discovered and copied
B real database constraintsFK present in INFORMATION_SCHEMAshown in preview, copied when whitelisted
C explicit business relationsAccount holds Avatar DBIDs, friend referencesfollowed or rewritten only when the user declares rules
D unknown structureIDs embedded in JSON/BLOB/Python custom objectsuntouched by default, marked risky; plugin codecs if necessary
E external resourcesRedis/payments/guilds/shared public-server stateout of MVP scope; a missing-report is provided

Key point: if a nested child table's parentID points at the parent ARRAY row's auto-increment ID rather than the player DBID, remapping must recurse along a per-level relation graph. All primary keys and ID references form typed mappings keyed by {entityType, table, column, oldValue}; global 1001→5001 substitution is forbidden.

4.3 Relation-rule extension file (illustrative; not directly runnable) ​

yaml
apiVersion: kode.dev/player-clone/v1alpha1
root:
  entity: Avatar
  lookup: dbid
relations:
  - name: account-avatar
    from: {entity: Account, property: characters}
    to: {entity: Avatar, key: databaseID}
    action: remap-if-present
    provenance: project-declared
  - name: guild-reference
    from: {entity: Avatar, property: guildDBID}
    action: detach-or-map-existing
    provenance: project-declared
identities:
  account: bind-existing-local-account
  loginCredentials: redact
  playerName: generate-unique-local
  autoLoad: disable
limits:
  maxRows: 50000
  maxBytes: 67108864

This is only the direction of a product DSL. Reference rules must compile, verify fields really exist and have correct types; automatic callbacks executing arbitrary SQL/Python scripts are forbidden.

5. Export design ​

5.1 Connections and authorization ​

  • The Source Profile must explicitly set source, environment=production|staging; purpose is inferred from the database credential configuration, not the hostname.
  • The source account is granted only SELECT on the needed schemas; UPDATE/INSERT/DELETE/DDL and any state repair against the source database are forbidden.
  • Connection information goes in VS Code SecretStorage/the system credential service — never into the project's .vscode/settings.json, logs, or the archive.
  • Prefer TLS, an SSH tunnel, or an intranet proxy to reach the read replica; automatically exposing the database port is forbidden.
  • Use pre-approved Query Plans and parameterized DBID queries; physical identifiers must come from a verified schema allowlist.

5.2 Read-only consistency ​

  • MySQL InnoDB, REPEATABLE READ + READ ONLY CONSISTENT SNAPSHOT, reading the main table and all child tables within the same connection/transaction; avoid reading the main table from version A and child tables from version B.
  • START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY is used where supported; the actual transaction API must be checked against the driver's behavior.
  • Only consistency of the committed database view can be guaranteed — not the latest state of Base/Cell online memory.
  • Multiple DB interfaces, cross-instance, or non-transactional tables cannot get a globally consistent snapshot automatically; v1 should refuse to promise "fully consistent export" and annotate the limitation.
  • Set timeouts, per-run row and size caps, and connection concurrency caps; end read transactions promptly to avoid InnoDB undo pressure; for oversized exports, run from a read replica or a test snapshot.

5.3 Export steps ​

  1. Parse the project/engine version, entity type, and source database.
  2. Check the user's authorization and purpose for exporting player data; collect operational audit metadata.
  3. Build the main-child table relation plan from the DBID, identifying unknown business references and redacted fields.
  4. Show a Dry Run: table list, estimated rows and size, sensitive fields, items that cannot be auto-copied.
  5. In a read-only consistent transaction, run parameterized SELECTs and stream into a temporary archive; accumulating unbounded full results is forbidden.
  6. Apply the specified redaction/exclusion policies to protected identity, credential, device-ID, social, and similar fields.
  7. Generate the manifest, schema fingerprint, per-table record counts, and content checksums; encrypt the archive if needed.
  8. Atomically rename after the archive completes; on interruption clean up the incomplete archive and audit the failure.

5.4 The Archive format ​

text
avatar-<local-uuid>.kdpclone   # controlled archive container (zip-like or framed archive recommended)
├── manifest.json
├── data/
│   ├── tbl_Avatar.rows.cbor
│   └── tbl_Avatar_*.rows.cbor
├── relations.json
├── redaction-report.json
└── checksums.json

Prefer CBOR/MessagePack-style typed record encodings (or per-column fixed-shape binary encodings), not a pure SQL dump — avoiding SQL injection, type loss, and running unknown scripts at import. The manifest must contain at least: archiveVersion, engineVariant/version, projectRevision, Entity/ typeDefs hashes, DB schema fingerprint, database interface, capture time/ consistency mode, protected identifiers of the root Entity/DBID, included and excluded tables, redaction policy version, original type metadata, and file SHA-256. Archives are encrypted by default, with the key never stored alongside the archive; syncing to cloud drives or Git by default is forbidden.

6. Import and ID remapping ​

6.1 Safety gates ​

  • The target connection must explicitly declare environment=local|test; prod/staging targets are forbidden. Judging safety by 127.0.0.1 alone is unreliable.
  • Require first that the KBEngine local target instance is stopped / the target Entity is not checked out; detecting local processes and DBMgr state may be added.
  • Support both "empty target database + keep original DBIDs" and "existing test database + new DBIDs", but recommend new-ID mode by default to reduce collision risk.
  • Force a rehearsal of unique-key/account conflicts, charset and data-type compatibility, engine version differences, auto-load switches, and external associations.
  • No automatic table creation/DDL on the target. The target's table structure should first be created by the corresponding KBEngine engine version.

6.2 Two-phase commit-style planning (not a distributed two-phase commit) ​

Prepare: load and verify the Archive → compare target schemas → sort the relation DAG → generate a typed IDMap → unique-key strategy/account binding/sensitive-field handling → output a fully auditable SQL plan (parameter placeholders, not raw sensitive values).

Apply: within a single transaction on local MySQL InnoDB: insert each Entity's main row → get the new primary key → insert child tables per dependency order → get intermediate row keys and update parentIDs level by level → handle explicit business references → disable online autoLoad → check row counts, main-child relations, and constraints → COMMIT; ROLLBACK on failure. Sequence gaps from MySQL AUTO_INCREMENT cannot be rolled back, which does not affect the transactional atomicity of data rows. With multiple DBs/non-transactional tables, v1 must not claim atomic import.

Verify: after import, read-only checks of target row counts/hashes/ reference relations; optionally start local KBEngine and load with the standard createEntityFromDBID, verifying login or Entity properties. A load failure must not casually delete committed data — return a cleanable local import inventory and wait for the user.

6.3 Concrete IDMap requirements ​

  • Distinguish runtime entity.id, Entity.databaseID, child-table row IDs, custom business IDs, and third-party account IDs.
  • The oldID → newID key includes the database interface, Entity type, physical table, and primary-key column, so repeated numbers in different tables are never cross-contaminated.
  • New primary keys come from the database after the target insert; all related fields use mapping results, never arithmetic offsets.
  • Business-permanently-stable item template IDs, skill config IDs, and map IDs are not rewritten.
  • Unique fields such as usernames, nicknames, and account names get locally unique generated values per configuration, with uniqueness checks.
  • The Account↔Avatar relation depends on the project's real implementation: without a mapping rule, importing an Avatar will not automatically make a local account see the character — the UI must state this explicitly.
  • Old player data carries no real tokens, password hashes, or payment/device identity; account binding happens within the local security policy.

6.4 Re-import and rollback ​

  • Use the archive hash + importRun ID to check for duplicate operations; by default show the already-imported mapping and do not create the character again; allow the user to explicitly choose "create another copy".
  • Before-commit failures roll back the transaction; after-commit failures provide a local-only controlled cleanup inventory, never implicitly replaying deletions.
  • Cleanup must detect whether the entity was already loaded by the local game server and whether other test data references it.
  • Cancellation support: Prepare can be cancelled anytime; cancelling Apply rolls back; Verify can be aborted without erasing import results.

7. VSCode product design ​

A new Explorer group Player Data Clone:

  1. Connections: two Profiles — Source (read-only) and Target (locally writable) — TLS/SecretStorage, connection testing and version info.
  2. Export Player Data: Entity type selection, DBID entry/search (authorized search only), export scope selection, relation explanations.
  3. Export Preview: estimated data volume, table/row counts, schema drift, sensitive information, business relations to be skipped, and the consistency level.
  4. Archive Browser: open .kdpclone, showing anonymized player refs, included fields, hashes, source version, redaction status; passwords/ tokens not shown by default.
  5. Import Preview: target environment, account binding policy, keep/new IDs, unique-key conflicts, possibly unreproducible issues, Dry Run.
  6. Import Results: new DBIDs, table-level record counts, relation verification, error location and one-click copy of non-sensitive logs; optional Open Entity in Local KBEngine.

Suggested command names:

  • KBEngine: Export Persistent Entity
  • KBEngine: Preview Player Clone
  • KBEngine: Import Player Clone
  • KBEngine: Verify Imported Entity
  • KBEngine: Show Clone Audit

Interaction constraints: the UI says "a copy of the database's persisted data", never "the complete online current state"; if business reference mappings are missing, the export can continue but the import must first explain which parts will be missing.

8. CLI and Rust API contract draft ​

bash
kode-db-clone inspect --project ./server_assets --entity Avatar
kode-db-clone plan-export --source source-profile --entity Avatar --dbid 1234 --out plan.json
kode-db-clone export --plan plan.json --out avatar.kdpclone
kode-db-clone inspect-archive avatar.kdpclone
kode-db-clone plan-import --archive avatar.kdpclone --target local-profile --policy ./clone-policy.yaml
kode-db-clone import --plan import-plan.json --confirm-local
kode-db-clone verify --run <import-run-id> --target local-profile

CLI examples are not commands that exist today; the real implementation should avoid passing passwords on the command line, supporting stdin/ SecretStorage/environment credentials and structured JSON output. Experimental or scripted output must not contain raw player privacy data.

Rust type interface sketch:

rust
struct CloneContext { source_schema: ResolvedSchema, target_schema: ResolvedSchema }
struct ExportPlan { root: EntityKey, table_queries: Vec<ApprovedSelect>, limits: Limits }
struct ImportPlan { table_inserts: Vec<TypedInsert>, remap_policy: RemapPolicy }
struct CloneArchive { manifest: Manifest, records: Vec<TypedRecord> } // actual import needs streaming reads

trait SourceReader { /* read-only snapshot + parameterized SELECT only */ }
trait TargetWriter { /* local-only transaction/insert/rollback */ }

Interfaces should have hard resource budgets and explicit error types (UnsupportedMapping, SchemaMismatch, SourceNotReadOnly, TargetNotLocal, DuplicateIdentity, UnresolvedReference, ExportTruncated, ImportFailed, VerificationFailed).

9. Development phases and Code Agent todos ​

Phase 0 — Fact forensics and sample fixation (blocks later development) ​

  • [x] PDC-0001 Review Kode's existing DB Schema IR, MySQL connection implementation, read-only checks, and profile code; record reuse points and file locations. (fcfbe2c; docs/player-clone/source-evidence.md §2 — pure derivation core databaseSchemaCore.ts + Rust mirror database_schema.rs
    • RPC bridge; the sole mysql2 contact surface databaseDrift.ts with a read-only double-line defense (whitelist + SET SESSION TRANSACTION READ ONLY); the Profile connection registry; the query lifecycle gate; 41 existing test files; gaps stated honestly: no FK/relation code, no information_schema physical layer, no archive/import)
  • [x] PDC-0002 Pin the two target engine versions (at least official KBE and the actually used branch); record version, dbInterface, tablePrefix. (fcfbe2c; source-evidence.md §1/§3/§4 — official baseline 2.5.10; actual branch cuihairu/kbengine b6fd2ce also 2.5.10; dbInterface defaults mysql + databaseName kbe (kbengine_defaults.xml:333/357); the Redis backend does not persist entities; the engine has no tablePrefix config key — the prefix is the compile-time constant tbl (entity_table.h:38); kode's kbengine.db.tablePrefix is a kode-side override pointing at prefix-changing projects)
  • [ ] PDC-0003 In a real test MySQL, let the engine auto-create tables; build a Fixture with ordinary Persistent fields, ARRAY, nested ARRAY, FIXED_DICT, components, and Account/Avatar relations. (Blocked: no Linux-compiled engine server locally (kbe/bin holds only Windows artifacts; kbengine-build has no compiled binary); compiling the server is a user-level environment decision (same discipline as IDE-LIV-003..007); local MariaDB 11.8.6 is running but has no usable credentials; to be added when the environment is ready)
  • [x] PDC-0004 Against KBEngine's real persistence sources such as entity_table_mysql.cpp, confirm the parentID linkage, child-table primary keys, insert/read order, and autoLoad. (fcfbe2c; source-evidence.md §3 — parentID = bigint unsigned, no FK, INDEX only, pointing at the parent table's id; child tables own an id primary key; parent INSERT first → LAST_INSERT_ID → recursive child tables; reads: main table first → child tables recursively by parentID in(...); autoLoad set after writing; deletion: children first, parent last)
  • [x] PDC-0005 Verify binary representations of different columns (UINT64/DECIMAL/BLOB/Unicode etc.) and the actual query driver conversions. (fcfbe2c; source-evidence.md §4 — a 21-type→column-type full table with file:line; no prepared statements/MYSQL_BIND — values are always string literals inlined (snprintf + mysql_real_escape_string); the Pickler lives at the entity def serialization layer, not the db layer; charset via mysql_set_character_set)
  • [x] PDC-0006 Fix the samples of business references that cannot be auto-recognized, privacy fields, and the security whitelist. (fcfbe2c; source-evidence.md §5 — classes A–E delimited by source: A = engine- determined (ARRAY/component child tables + parentID); B is empty since the engine DDL has no FK; C business references (Account.characters/guildDBID) need user declaration; D pickle blobs are not introspectable; E kbe_ internal tables excluded; privacy has no engine concept — it is an engineering declaration)
  • [ ] PDC-0007 Produce docs/player-clone/source-evidence.md, fixtures/, and a Golden Schema; add a regression gate. (Partial: source-evidence.md produced (fcfbe2c, §6 mapping verification = 13 rules, item-by-item match); fixtures/ + Golden Schema depend on PDC-0003's real table creation — unfinished; the regression gate follows)

Acceptance gate: able to list accurately, from a real table-creation sample, all of an Avatar's "engine-determined child tables"; explicitly refuse automation for uncertain associations; never guess relations from table-name prefixes alone. (Half-open: at source level an Avatar's full set of engine-determined child tables can already be listed precisely (§3 child-table naming rules + §6 item-by-item match), uncertain associations are explicitly refused automation (§5 classes B/C/D); but the "real table-creation sample" part depends on PDC-0003 (engine auto table creation), awaiting environment readiness — the gate stays half-open and Phase 1 must not dress document inference up as real-sample verification)

Phase 1 — Relation graph and Export Planner ​

  • [x] PDC-0101 Add the kode-db-clone crate, unsafe-free, compiling at the existing Rust MSRV. (fa770fe: workspace unsafe_code = "forbid" inherited, rust-version.workspace = 1.97, cargo build --workspace passes.)
  • [x] PDC-0102 Wire into the existing Rust type graph and table-structure derivation. (fa770fe: wire.rs deserializes kode-server's $/kode/databaseSchema/build camelCase output (the same serde contract) → CloneSchema, with root tables kind:"entity" normalized to root; what is consumed is the same-source derivation as the RPC output — no duplicate derivation in this crate. def property collection still goes through the TS collection surface (consistent with the engine derivation boundary; see source-evidence §2).)
  • [x] PDC-0103 Implement PhysicalSchema reads from information_schema and drift checks. (fa770fe: information_schema.rs generates read-only TABLES/COLUMNS/STATISTICS queries (identifier backtick escaping) and assembles PhysicalTable via the RowSource abstraction, fail-closed on row misalignment; drift check in SchemaResolver::resolve (type normalization comparison + engine verification + unknown-column/unknown-table rejection). Real-database direct-connection acceptance awaits the PDC-0003 environment; row assembly already tested with synthetic rows.)
  • [x] PDC-0104 Implement the relation graph: EngineGenerated / ForeignKey / ProjectDeclared / Unresolved. (fa770fe: RelationKind{EngineGenerated,ForeignKey,ProjectDeclared,Unresolved,External} aligned to §4.2 A–E; engine-generated relations edge directly from the child-table parentID structure; kbe_ → External; explicit declarations go through rules::RelationRule (ProjectDeclared); pickle-embedded goes to Unresolved, untouched. DFS three-color cycle detection.)
  • [x] PDC-0105 Implement a deterministic hierarchical query plan (with duplicate/cycle detection and a row budget). (fa770fe: ExportPlanner::plan emits the SELECT sequence pre-order (parents before children), the root table bound by id and child tables by parentID; duplicate table names rejected in CloneSchema::new; cycles raise CycleDetected; row estimates over budget → an honest BudgetExceeded error, never silent truncation.)
  • [x] PDC-0106 Implement the Export Dry Run result, error/gap explanations, and the source-data redaction policy. (fa770fe: the DryRun summary is generated on the same path as the plan (no drift), with denied/missing per table with reasons; redact.rs classifies column sensitivity (Credential/Personal/Public) + masking + log redaction. Archive encryption and key storage are planned as PDC-0205.)
  • [x] PDC-0107 Give understandable errors for unsupported DB interfaces, non-transactional tables, and unknown columns. (fa770fe: error.rs's eight variants all carry displayable English copy (no SQL/credential details): UnsupportedDbInterface/UnknownTable/UnknownColumn/ NonTransactionalTable/InvalidRule/CycleDetected/BudgetExceeded/ DriftMismatch.)

Acceptance gate: with a virtual Fixture, generate table/SQL plans matching the golden results, including row limits and every excluded relation. (fa770fe achieved: tests/golden_plan.rs on a representative Avatar (root + second-level ARRAY + component) → golden table order/column list/SQL asserted string by string; row budget with within/exceeded cases; denied (kbe_ + physically unique) asserted per table with reasons; cargo test -p kode-db-clone 33 unit tests + 2 golden, all green.)

Phase 2 — Source read-only export and Archive ​

  • [ ] PDC-0201 Implement compile-time/interface-level read-write isolation in SourceReader, rejecting all DML.
  • [ ] PDC-0202 Implement MySQL REPEATABLE READ consistent read-only transactions with timeout cancellation and resource budgets.
  • [ ] PDC-0203 Implement typed row encoding covering NULL/BLOB/64-bit/ DECIMAL/UTF-8 times and timezones.
  • [ ] PDC-0204 Implement streaming archive writes, manifest, SHA-256, and atomic temp-file commit.
  • [ ] PDC-0205 Implement default sensitive-data redaction and archive encryption; keys stored independently.
  • [ ] PDC-0206 Implement archive inspect, corruption checks, size caps, and a format-version migration entry.
  • [ ] PDC-0207 Export log redaction, error auditing, and read-only account permission tests.

Acceptance gate: export test cases complete, readable, verifiable; the source database's read/write counters prove no updates. No misusable half-products left behind after interruption.

Phase 3 — Target import planning and IDMap ​

  • [x] PDC-0301 TargetProfile forces local/test marking and a write-permission check allowing only local write targets. (94d3613: target.rsTargetEnvironment accepts only local/test (prod/staging etc. all raise ImportRejected); validate_for_import rejects non-mysql interfaces/read-only targets; a host declaration grants no safety.)
  • [x] PDC-0302 Verify target tables, columns, indexes, data-type compatibility, and the engine version. (94d3613: archive tables ⊆ target resolved tables or UnknownTable; row width = the target's projected column count; per-value type_fits compatibility (stripping width/unsigned rules) or DriftMismatch; engine version — the archive format does not record the source engine version, and schema_notes states this honestly without inventing a comparison.)
  • [x] PDC-0303 Implement previews for both the preserve-id-if-empty and allocate-new-ids modes. (94d3613: ImportMode{PreserveIfEmpty,AllocateNewIds} — both modes plan on the same path; preserve passes original values through + ledger registration; allocate puts placeholders on all primary keys; each mode has a locking unit test.)
  • [x] PDC-0304 Implement level-by-level mapping of Entity primary keys, child-table row IDs, and parentID. (94d3613: idmap.rs key = physical table + primary-key column + old value triple (same values in different tables never cross-contaminate, §6.3); monotonic placeholders; the seed pass lands the full ledger before the render pass reads it read-only — forward references from the root table to child-table rows no longer leak; parentID shares the placeholder with its parent row's id, fail-closed when referencing an uncloned parent row.)
  • [x] PDC-0305 Implement unique-key conflict detection and the local nickname/login-name rebuild policy. (94d3613: UniquePolicy{Reject,RebuildSuffix}; detection = three-way placeholders over target existing values ∪ same-column values inside the archive ∪ already-rebuilt values, incrementing {original}_{seed}{n} until free; conflicts enter the conflicts audit surface; the Reject policy fails closed with ImportConflict.)
  • [x] PDC-0306 Implement the local Account binding plugin (blocking a "login-ready" claim when no rule exists). (94d3613: AccountBindingPlan with no declared rule sets login_ready=false with a note explicitly saying "will not automatically be visible to any local account"; only a Follow declaration pointing at this clone's root table sets it true, with the declaration path. Binding write-side actions belong to Apply (Phase 4) per §6.2.)
  • [x] PDC-0307 Implement project-declared typed business reference rules and validators. (94d3613: Follow rule → (declaring-side table, join column) → referenced-table mapping; a hit on a row inside the clone set → shares a placeholder with that row's new key (BusinessReference category in the ledger); a referenced table outside the clone set → the audit surface notes kept-as-is, no rewrite; a value not in the clone set → original value passed through + warning. Skip/Error follow the existing rules semantics.)
  • [x] PDC-0308 Implement an explicit policy for sm_autoLoad and other engine-managed fields. (94d3613: AutoLoadPolicy{PreserveArchive,ForceDisabled} (default ForceDisabled, aligned with §6.2 Apply's "disable online autoLoad" recommendation), rendered as a PolicyOverride bound to the policy value rather than the archive value.)

Acceptance gate: the import rehearsal shows every table, every changed ID category, the account binding method, and unresolved reference risks; unknown references never get default global substitution. (94d3613 achieved: ImportSummary.statements_per_table per-table statement counts / id_categories five-category counts (root/child/parent-reference/ business-reference/rebuilt) / account_binding binding method / unresolved_reference_risks + per-declaration references destinations; unknown references are not substituted on three fronts — ledger misses return None, business-reference misses pass original values through with a warning, undeclared columns are always Literal; tests/golden_import.rs on a representative Avatar archive → golden plan assertions (execution order / placeholder sharing / unique-key rebuild / binding warning / serialized audit) + 11 import.rs unit tests; crate 90 unit tests all green, clippy -D warnings 0, workspace 102 blocks 0 failures.)

Phase 4 — Transactional import and verification ​

  • [x] PDC-0401 Implement local transactional import limited to MySQL/InnoDB and a single DB interface. (apply.rs ImportApplier::apply: re-checks TargetProfile::validate_for_import at entry (mysql + local/test + writable only), strict begin → statement by statement → rollback on failure → commit only on full success; a real MySQL connection does not enter the crate (same discipline as reader/information_schema — carried by the WriteExecutor abstraction); driver assembly belongs to Phase 5 UI.)
  • [x] PDC-0402 Complete main-table→child-table topological execution and new primary-key return. (Executed per plan.order, parents before children; NewKey binds NULL and lets the target AUTO_INCREMENT allocate; the real primary key returned by execute_insert backfills resolved_ids, and later KeyReferences bind real values; tests/golden_apply.rs asserts items/gold's parentID landed value = the root row's new primary key 1000.)
  • [x] PDC-0403 Execute all explicit relation remappings, detecting orphan rows and unique-key errors. (Remap execution = KeyReference placeholder backfill + unique-key rebuilt values (Remapped takes the idmap's Rebuilt); orphan rows already fail closed at planning (P3 "not part of this clone"); at Apply the executor raises unique-key errors as-is and rolls back first (executor_constraint_error_midway_rolls_back).)
  • [x] PDC-0404 Implement Import Run auditing, the archive fingerprint, and duplicate-import checks. (ImportRun full audit (run number / per-table counts / placeholder→real primary key mapping / root handle / binding / verification / cleanup / load verification); archive_fingerprint = manifest bytes SHA-256 (the manifest covers all data-frame checksums; content-sensitive, tested); the ImportRunStore registry answers the same fingerprint with DuplicateRejected echoing the existing run's mapping; "create another copy" requires explicit allow_duplicate.)
  • [x] PDC-0405 Failure injection: a failure at any Nth row must roll back, and retries are never silently duplicated. (ApplyControl::fail_at_statement injection surface + the executor's error path both roll back before reporting; injected_failure_at_any_row_rolls_back_and_retry_is_clean asserts a failure at the injection point → zero commits, zero ledger entries, and a retry as a fresh transaction with exactly one copy of the data; the duplicate fingerprint gate is the second line of defense.)
  • [x] PDC-0406 After commit, re-query target records per the relation graph, verifying the data is readable. (After commit, per-table SELECT COUNT(*) … WHERE id IN (new primary key set) read-only checks; VerifyReport per-table expected/found, honest errors on failure, never silent; AUTO_INCREMENT sequence gaps are not rollable, noted per §6.2 (data-row atomicity unaffected).)
  • [x] PDC-0407 Local KBEngine load verification, recording wasActive, load success, and major persisted-field consistency. (Shape landed; real engine load verification awaits Phase 5 assembly: same PDC-0003 environment block — LoadVerification{attempted,was_active,load_success, field_checks,note} records the shape + a consistency spot-check structure (FieldConsistency archive value vs read-back value); within the crate it honestly reports attempted=false, noting the wiring belongs to the UI phase — never claiming verified.)
  • [x] PDC-0408 Implement a local controlled cleanup plan, but no automatic deletion. (CleanupPlan generates parameterized DELETEs in reverse topological order (children before parents, parameters = real new primary keys); execution preconditions include "confirm the entity is not loaded by the local KBEngine server"; the applier never executes cleanup; golden_apply asserts zero DELETEs in the execution log.)

Acceptance gate: after import, KBE can load the Entity with the new database ID; duplicate operations are controlled; a mid-transaction failure leaves no half a character. (1c0c12a transactional surface achieved: tests/golden_apply.rs 4 cases — single-transaction shape (begin×1/ commit×1/rollback path with zero commits) + placeholder backfill + per-table post-commit checks + duplicate-fingerprint rejection/explicit-copy allow + failure injection and constraint errors fully rolling back with clean retries; crate 92 unit tests + 5 integration files all green, clippy -D warnings 0. The real MySQL/KBEngine load half awaits Phase 5 environment assembly for the same reason as PDC-0407 — not claimed.)

Phase 5 — Kode UI and the end-to-end workflow ​

  • [x] PDC-0501 Add Source / Target connection UI, SecretStorage credentials, and configuration checks. (kbengine.clone.configureSource|configureTarget| testSource|testTarget: CloneProfileStore keeps configuration in workspaceState, passwords only in SecretStorage (key includes the role; clearing the configuration deletes the secret; never in the profile); the target environment picker accepts only local/test, with prod/staging rejected at the configuration gate (re-checked fail-closed by Rust's planImport side TargetEnvironment::validate_for_import); the connection test SELECT VERSION() reports its two states honestly.)
  • [x] PDC-0502 Add Entity/DBID selection and an export-scope preview. (kbengine.clone.export: registered-entity QuickPick (all workspace roots)
    • DBID numeric validation → a read-only session probes physical tables via information_schema (identifier whitelist) → Rust $/kode/dbClone/planExport produces a read-only SELECT plan → previews the table list / row budget / missing tables → executes only after confirmation.)
  • [x] PDC-0503 Add archive browsing, sensitive-field masking, and version and hash display. (kbengine.clone.inspectArchive (Explorer .kdpclone right-click + panel): the manifest returns only entity/format version/row counts/encryption bit/per-table row counts/checksums.json and redaction-report.json existence — no row values are ever echoed; redaction defaults on at the archive write side (P3 redactSensitive=true; a column without a classification plan is rejected — no fake protection).)
  • [x] PDC-0504 Add Import Preview / conflict explanations / a local environment double confirmation. (kbengine.clone.import plans in two passes: pass-1 with an empty snapshot for column order → bounded WHERE IN probing of the archive's actual unique values → pass-2 conflict rehearsal; the preview shows per-table statements / ID change categories / unique conflicts (local rebuild with an _imported suffix) / account binding / unresolved reference risks / warnings; two explicit gates — the first "continue to confirmation" + the second "confirm writing to the local database…".)
  • [x] PDC-0505 Add progress, cancellation, timeouts, audit logs, and non-sensitive issue reports. (withProgress cancellable — cancelling during Apply rolls back (CloneApplyCancelledError, no half transaction), cancelling during export stops; Rust RPC surfaces a 120s timeout; audit JSON lands in .kode/clone-runs/ (echoed by kbengine.clone.showAudit), containing only counts/new keys/verification/cleanup plans — no secrets, no row values.)
  • [x] PDC-0506 Provide a "local verification load" entry, compatible with the existing Rust/TS backend modes. (Shape landed; the engine-native load verification is honestly not wired: the wired surface = per-table COUNT re-checks after commit (success is reported only when verify fully passes; otherwise it honestly reports "committed but re-checks not all passed"); the audit's load_verification.attempted=false notes that engine-side load verification needs a local KBEngine runtime (same cause as PDC-0003) — not claimed as verified. Compatibility surface = Rust planning/archiving all in kode-server RPC ($/kode/dbClone/* ×5, the same gate pattern as databaseSchema/messageTable); transactional execution in the TS mysql2 driver (an explicit trade-off — Rust has no MySQL client), with semantics locked on both sides by tests/playerDataClone.test.ts and crates/kode-db-clone golden_apply.rs; a missing gate is honestly no-gate — no TS fake fallback.)
  • [x] PDC-0507 Documentation and bilingual UI copy: Persisted ≠ Live, made explicit. (UI copy zh-primary + English in parentheses; PERSISTED_NOT_LIVE "a copy of the database's persisted data (Persisted copy) ≠ the online current state (Live state)" appears in five places — archive browse / export preview / export done / import preview / import done; docs = docs/features.md en+zh CLONE-P5 entries + this plan reconciled, writing only real paths.)

Acceptance gate: without hand-written SQL, the full loop export → offline package → target rehearsal → import → locally loadable completes from the UI. (The UI loop is landed: configure/test → export (plan preview + confirmation) → archive browse → two-pass rehearsal + double confirmation → single-transaction import (cancel rolls back) → COUNT re-checks → audit; the "locally loadable" half = engine-native load verification not wired (PDC-0003 environment constraint, attempted=false recorded honestly); the wired surfaces are count re-checks and the audit — not claimed. TS side tests/playerDataClone.test.ts 14 cases + Rust side kode-server db_clone 5 cases + the full kode-db-clone suite; clippy -D warnings 0. Real MySQL end-to-end belongs to Phase 6 PDC-0601 testcontainers.)

Phase 5 leftover (real-environment assembly, with Phase 6) ​

  • [ ] Wire engine-side native load verification (once a local KBEngine runtime is ready, upgrade load_verification from attempted=false to real wasActive/load_success/field_checks; the audit currently honestly records not attempted. PDC-0607 honestly lists it as a known limitation in docs/player-clone/ops-and-security.md §4.2 — this line stays unchecked because the real environment is not assembled; unimplemented is never written as implemented).

Phase 6 — Security / performance / compatibility and release ​

  • [x] PDC-0601 Real integration tests with testcontainers/MySQL across differing version combinations. (2c0fb00 crates/kode-db-clone/tests/mysql_real.rs: real MySQL 8.0 + 5.7 dual-version export→archive→import→verify round-trip loop; a custom MysqlImage (testcontainers-modules' mysql module's "X Plugin ready" and /usr/sbin/mysqld: ready for connections both fail to match 5.7, switched to message_on_stderr("ready for connections") substring waiting) + connect_with_retry (on an empty datadir's first start, the temporary init server reports readiness before the real server listens on TCP 3306 → retry until connectable); export uses a read-only src connection, import/re-check use a writable dst connection (separation avoids READ ONLY transaction 1792); URLs use mysql://root@127.0.0.1:{port}/test (get_host() returning localhost is unreliable). Gated behind KODE_DB_CLONE_MYSQL=1 with 2 cases green (26.1s); cargo test workspace 0 failures + clippy --all-targets -D warnings 0 + fmt 0; without the env var the 2 cases are #[ignore] and never false-fail.)
  • [x] PDC-0602 Fuzz: archives, rule parsing, malformed BLOBs, extremely deep nesting and cyclic references. (3138ecb crates/kode-db-clone/tests/fuzz.rs: 10 catch_unwind cases asserting never-panic — archive byte streams 300 random + 8 large buffers + byte-flip of the first 64 bytes + point-wise truncation 32 + random truncation 40 + appended garbage 20 + bad magic/bad version/encrypted flag without key; malformed BLOBs (TypedValue::Bytes odd hex/non-hex/empty) + negative BigUInt/Int overflow/unknown tag/DateTime missing offset; rules (empty entity/unknown table/self-reference/Error action/include-exclude overlap/empty include) → validate/apply_relation/ project/identity_column; nested relations (2000-level deep chains + 5000 fan-out + a cycle at a deep chain's end) → build + topological_order terminate. Cycle detection = the a↔b double-ring asserting CycleDetected (the first-version fixture accidentally formed a DAG and never cycled — turned green after prove-red by fixing to the relations.rs rejects_cycle discipline). Deterministic xorshift64 with no third-party dependency — cargo test runs it; clippy --all-targets -D warnings 0 + fmt 0 + workspace tests 0 failures.)
  • [x] PDC-0603 Performance: large ARRAYs, hundred-thousand-scale child rows / large packets, batched reads, memory peaks, and timeouts. (f7c1be0 crates/kode-db-clone/tests/perf.rs: 4 cases — a large ARRAY child table of 300k rows counted accurately (large_array_subtable_300k_streams_and_counts)
    • a 4MiB large-packet blob kept untruncated in one row's hex (large_blob_packet_reads_in_one_row) + a 300-column wide row (wide_row_many_columns_exports) + a mid-stream cancel stopping at 1000 rows and reporting cancelled honestly (mid_stream_cancel_stops_export); the reader hands off row by row without accumulating whole tables (a discard-style counting sink: a single row's encoding is far smaller than the total); assertions set only loose upper bounds (catching hangs/quadratic degradation, not load jitter — the PDC-0601/0602 lesson); measured timings/sizes go to eprintln logs, not strict timing assertions; 300k rows measured at 8.7s. Mid-stream cancel/timeout complements hardening's zero-timeout/pre-cancel without duplicating it. clippy --all-targets -D warnings 0 + fmt 0 + workspace tests 0 failures.)
  • [x] PDC-0604 Security: prod→prod rejection, source write-permission rejection, SQL injection, secret-leak prevention. (ae3ba40 crates/kode-db-clone/tests/security.rs: 4 cases proving fail-closed from the public API boundary — prod_and_staging_import_targets_fail_closed (prod/staging/PROD/ Production/pRoD rejected at the parse layer with ImportRejected; TargetEnvironment has no prod variant so a prod target cannot even form, making prod→prod impossible) + source_write_statements_fail_closed (validate_readonly rejects INSERT/UPDATE/DELETE/DROP/ALTER/REPLACE/CREATE/TRUNCATE/GRANT/SET autocommit while allowing SELECT/SHOW/DESCRIBE/EXPLAIN/SET SESSION READ ONLY/START...READ ONLY/COMMIT/ROLLBACK) + sql_injection_identifiers_neutralized (; DROP TABLE/--/backtick payloads embedded in table/column names go through planner→render_select backtick escaping, assert_no_breakout proves no ;/--/quotes/newlines outside backticks, predicates ? parameterized) + sensitive_values_do_not_leak_into_export (reader→RedactingSink end to end: captured rows carry no password/email originals; the report records credential/personal and contains no public columns). The mechanisms are proven in target/reader/planner/redact unit tests; this file adds integration-level proof + broader injection payloads; clippy --all-targets -D warnings 0 + fmt 0 + workspace tests 0 failures.)
  • [x] PDC-0605 Windows/Linux/macOS file paths, key storage, and CLI packaging compatibility. (b614946 crates/kode-db-clone/tests/platform.rs: 3 cross-platform boundary cases — key_id_windows_separators_and_drive_are_sanitized (..\escape/ ..\..\x/C:\Users\player/spaces/..\..\..\etc\passwd all flattened; no out-of-bounds file under the key root; defensive traversal covering Windows backslashes/drive letters) + key_root_with_spaces_and_unicode_works (key root with spaces + Unicode) + archive_roundtrip_on_space_and_unicode_path (write_archive + Archive::inspect round-trip identical on "玩家 克隆 归档 😀.kdp"; file non-empty). Path handling goes entirely through PathBuf/.join; no hard-coded / string concatenation in source (verified); key storage forces 0600 on Unix, Windows relies on user-directory ACLs (the non-Unix branch honestly noted); the CLI binary of §8 explicitly states "examples are not commands that exist" and is unimplemented — the current delivery surface = command palette entries + Rust RPC, CLI deferred, not claimed; clippy --all-targets -D warnings 0 + fmt 0 + workspace tests 0 failures.)
  • [x] PDC-0606 Rust cargo test/clippy, TS vitest, VSCode Extension Host, and Nightly distribution gates. (567a653 ci.yml's rust-coverage job gains a clippy gate — clippy previously lived in no workflow (only local manual runs caught it) and the test gate only covered cargo test; cargo clippy --workspace --all-targets -- -D warnings placed after coverage upload (a clippy failure still reds the job; uploaded coverage is not lost); the clippy component is installed automatically by rustup per rust-toolchain.toml; locally measured clippy 0 warnings + workspace tests 0 failures. The four gates verified: cargo test ✓ (ci.yml rust-coverage's cargo llvm-cov --workspace --all-targets --no-fail-fast, existing) + TS vitest ✓ (ci.yml build's vitest run --coverage, existing) + Nightly distribution ✓ (nightly.yml existing: the 48h-staleness gate + the rolling nightly tag release + verify-no-version-tags with no version-tag leakage)
    • VSCode Extension Host ⚠️ — the gate = the "fake-vscode assembly mocha suite" pnpm test full chain (run by nightly+publish), pure node with no display, but main is currently red by 2 cases, unrelated to CLONE-P6 drift: manifest.test asserts every command has an onCommand activation event — kbengine.python.selectInterpreter has had none since 1a95f5e (the venv/QuickPick commit; pre-existing) + activationSmoke status bar 3→5 (the interpreter entry 1a95f5e + the channel light 5347782 hotreload commit, both other sessions' domains); therefore the mocha step was not added to per-push ci.yml (red would break everyone's pushes), recorded honestly pending the venv/hotreload sessions updating their tests; the real @vscode/test-electron host (VS Code download + display) stays a local xvfb gate, not in CI. PDC-0606's own delivery surface is green: clippy 0 / vitest green / cargo test 0 failures.)
  • [x] PDC-0607 Write operations documentation, sensitive-data handling, archive retention/destruction policy, and known limitations. (2099354 adds docs/player-clone/ops-and-security.md (Chinese, alongside source-evidence.md) + reconciles docs/features.md en/zh (the CLONE-P5 line gains the honest "archive redacted but not encrypted" annotation + a documentation pointer). Four blocks: ① operations = an 8-command flow table (configureSource/Target/testSource/Target/export/inspectArchive/ import/showAudit) + landing (.kdpclone defaults to {entity}-{dbid}.kdpclone, audit in .kode/clone-runs/ under the first workspace root) + RPC $/kode/dbClone/* ×5 (inspectArchive/planExport/ export/planImport/readArchiveRows) + the import safety flow (target accepts only local/test, source read-only validate_readonly, two explicit confirmations, single-transaction rollback, COUNT re-checks + reverse- topology cleanup plan + audit, a Persisted Copy notice on every screen); ② sensitive data = the SensitivityPolicy column classification (credential/personal) + RedactingSink redaction defaulting on (redactSensitive:true) + redact_log + passwords only in SecretStorage, never in profiles; ③ archive retention/destruction = honestly: no automatic retention policy / no archive delete command / no key destruction API (archive.rs's public surface has no delete/destroy/purge, keystore.rs has no key deletion interface, the command surface has no deleteArchive/purge) — persisted until manual cleanup; the only automatic cleanup = deleting the temp file on a failed archive write (atomic write); ④ a 14-item honest known-limitations list (CLI unimplemented §8 "examples ≠ commands" / engine load verification attempted=false PDC-0003 / persisted copy only, not memory state / V1 structure-exact compatibility only / business references need explicit declaration / prod-staging rejection / the target's local service should be stopped / long transactions controlled / account binding not fully automatic / Redis ZSET leaderboards unsupported (a separate data domain) / archive cap 4GiB / 300k rows ~8.7s / the extension host mocha gate red on main (1a95f5e + 5****82 outside CLONE-P6's domain, not added per-push) / archive export unencrypted). Major honest finding (§2.2): archive encryption was implemented and tested (chacha20poly1305 AEAD + FileKeyStore 0600), but the production export path writeCloneArchive passes no keyHex ({path,entity,rows,plan,redactSensitive:true}) → ExportParams.key_hex=None → write_archive(key:None) → encrypted:false; FileKeyStore is unwired and test-only — the current delivery surface's export = redacted but unencrypted, a known security gap, honestly written into the docs and features.md en/zh, never claimed as encrypted; wiring (generating/passing keys) belongs to later work (PDC-0608 wired it). clippy --all-targets -D warnings 0 + fmt 0 (the doc change touches no Rust/TS; the docs gate = no markdown lint; ci.yml paths-ignore docs/**).)
  • [x] PDC-0608 Archive encryption wiring: closing the "redacted but unencrypted" security gap found in PDC-0607 §2.2; export encrypted by default. (7b3f0b4 key management converged server-side: TS passes only the keyRoot directory path; key material never crosses RPC — extension assembly getKeyRoot: () => globalStorageUri/clone-keys (machine domain, not in the workspace/VCS) → Rust write_key_from_root = ensure_key_outside_archive (structurally rejecting a key directory inside the archive path) + key_id_for_archive (new: the archive absolute path's SHA-256 hex, avoiding sanitize path collisions; same-location archives stably share a key) + FileKeyStore::get_or_create (getrandom generation, Unix 0600) → ArchiveWriter carries the key, writing encrypted:true; the read side resolve_read_key (inspectArchive/readArchiveRows/planImport) first probes the encryption bit via the new archive::is_encrypted header — plaintext archives fetch no key (backward compatible; old archives still open), encrypted archives fetch by the same id, and a missing key raises an honest error naming the key root and id, never silently generating a new key (that would only mint a wrong key that can never decrypt the archive); explicit keyHex still takes priority (test/tool old paths retained). Export/Inspect/ ReadRows/PlanImport Params gain #[serde(default)] key_root; the TS bridge's four wrappers gain keyRoot parameters, and playerDataCloneCommands' six call sites pass deps.getKeyRoot(). Tests: Rust db_clone.rs +3 (export_with_key_root_encrypts_and_reads_back_through_all_handlers end-to-end = archive bytes carry no plaintext row value b"hero" + exactly 1 .key file + meta.encrypted + all handlers read back with the key; frame names in plaintext do not assert encryption — the header is AEAD associated data, authenticated but not encrypted; frames must be located by name before decryption — a format design choice, not a gap; missing_key_reports_honest_error_naming_store = deleting the key directory → an error naming clone-keys and the id without rebuilding the directory; key_root_inside_archive_path_is_rejected); a new TS tests/playerDataCloneRust.test.ts with 3 cases locking the payload contract (export always carries redactSensitive:true + keyRoot; the three read surfaces all pass it; keyRoot absent = the field is not sent, serde None, backward compatible for plaintext archives). Prove-red: sabotaging Some(_root) => None reds the 3 new cases; restoring greens them. Gates: kode-server db_clone 8/8 + kode-db-clone 134/0 + clippy -D warnings 0 + fmt 0 + workspace cargo test 776/0 + vitest full exit 0 + compile/lint 0. Reconciliation: ops-and-security.md §2.2 unwired → wired (plaintext frame names = the design discipline, documented) + §3's retention discipline + §4-14 changed to the key lifecycle limitation + features.md en/zh synced; the key id binding the absolute path means moving the archive/changing machines = an honest missing-key report (copy the key or re-export), added to known limitations.)
  • [x] PDC-0609 Export encryption can be turned off: a settings default + per-run toggle on the export confirmation page (user directive "default on when exporting, but also cancellable"; AskUserQuestion fixed the shape = a settings default + changeable at export time). (dd9096a ① the setting kbengine.clone.archiveEncryption (enum encrypted|plain, default encrypted, window scope, package.json en/zh descriptions); ② a new command layer pickExportEncryption(pick,queryCount,defaultEncrypt) three-item loop — the confirm item's copy carries the current state ("Export, encrypted (machine key) / plaintext (transferable across machines)") + "toggle encryption → …" flipping repeatedly + cancel; runExportCloneCommand's confirmation page goes through this loop with the initial state = deps.getArchiveEncryptionDefault?.() ?? 'encrypted'; ③ writeCloneArchive's fifth parameter = encrypt ? deps.getKeyRoot() : undefined — plaintext = the payload carries no keyRoot (serde None); the completion message honestly states "archive encrypted / archive is plaintext (unencrypted)"; the read side is untouched (inspect/readRows/ planImport still always pass keyRoot; the encryption bit is probed, so both plaintext and encrypted archives read; the setting affects only the write side). Tests: a new tests/playerDataCloneExportEncryption.test.ts with 4 command-level full-flow cases (vi.mock at the mysql session layer + setKodeCoreShadowGate on the real path) — default encryption exports directly → the export payload carries keyRoot='/keys' and the confirm copy includes the encrypted state; toggling once → the payload's keyRoot undefined and the second screen's copy flips to plaintext; the settings default plain → plaintext with no toggle; cancelling on the confirmation page → no export RPC sent and executeExportPlan not called. Prove-red: sabotage (ignoring the choice, always passing deps.getKeyRoot()) reds 2 cases (toggle / default plain); restoring greens them. Lesson = never git checkout uncommitted changes when restoring from a sabotage (the first batch of command-layer edits got rolled back and had to be redone from hand-held content — no loss; commit before prove-red from now on). Gates: targeted 21/21 (the playerDataClone trio) + compile 0 + lint 0 + vitest full exit 0; Rust untouched since PDC-0608 (no .rs changes) so the workspace's 776/0 carries over. Shared-tree record: package.json and features.md en/zh also carried another session's in-flight changes (the description→markdownDescription batch upgrade + HOT-102/HOT-QUICK blocks); the first committed version accidentally swallowed package.json's +152/-128 — reset and re-landed cleanly before push (dd9096a package.json only +7), with the other session's changes fully restored via backup + checkout + apply, zero loss; features.md isolated the same way. Reconciliation: ops-and-security.md §2.2 gains the "encryption can be turned off (PDC-0609)" section + features.md en/zh add the setting/toggle clauses.)

Acceptance gate: CI fully green, no known sensitive-information leaks, and all blocking security scenarios proven fail-closed in real tests.

10. The minimal test matrix ​

CaseExpected
A single Avatar with only scalar fieldsone-click export → import → KBE loads
ARRAY empty / with valuesempty collections and array order not lost
Nested ARRAY/component child tablesparentID remapped correctly level by level
FIXED_DICT/custom typesbyte-identical against the engine's read/write formats
BLOB/Unicode/UInt64bytes identical, no precision loss
The same DBID appearing in different tablesno mistaken rewrite
Account→Avatar custom referencewithout a rule, prompted that binding cannot be automatic; with a rule, bound correctly
Importing the same package twiceby default never silently produces a second copy
Target has a same-name character/accountrejected, or generated per declared local-unique rules
An online player keeps writing during exportreads one database snapshot, clearly not the latest memory value
Non-transactional tables or a different DB interfacerefuses to promise full consistency
Mid-import failure/cancelrollback, no partial character on the target
The local service still has this DBID loadedsafely blocked
A production source carrying write permissionthe program still forces read-only and recommends a least-privilege account
A target marked productionwrite refused unconditionally
The archive tampered / missing fileschecksum failure blocks import
A business-relevant table missingwarned, explicitly not a complete business clone

10.1 Coverage reconciliation (CLONE-P6 closure, 2026-11-06) ​

Row-by-row reconciliation of the §10 matrix against §11's DoD; "evidenced" rows carry evidence anchors, and "honestly unwired" rows share one source with the known limitations (docs/player-clone/ops-and-security.md §4) — nothing is claimed beyond reality.

#Matrix rowVerdictEvidence / honest note
1Single Avatar scalar one-click export → importexport → import evidenced; KBE load honestly unwiredround-trip: tests/mysql_real.rs (real MySQL 8.0/5.7, PDC-0601) + P5 UI end-to-end; engine-native load attempted=false (PDC-0003, ops §4-2)
2ARRAY empty/values, order keptevidencedTypedValue order-preserving array serialization (archive.rs unit tests) + 300k-row ARRAY counting (tests/perf.rs, PDC-0603) + malformed input never panics (tests/fuzz.rs, PDC-0602)
3Nested ARRAY/component child tables, parentID level-by-level remapevidencedtests/golden_apply.rs (placeholder backfill parentID=1000) + fuzz nesting 2000-level deep chains / 5000 fan-out terminating
4FIXED_DICT/custom types vs engine read/writehonestly not engine-comparedcloning preserves physical column types faithfully (decimal/text/integer families exact; wire typing tests); FIXED_DICT has no by-name special-casing; comparison against the engine's real read/write formats is blocked by the same PDC-0003 environment — unwired
5BLOB/Unicode/UInt64evidencedfuzz malformed BLOBs + perf 4MiB blob untruncated + platform Unicode path round-trip + tvBigUInt exact (wire tests)
6Same DBID in different tables, no mistaken rewriteevidencedthe parent-child tree is itself same-root cross-table; the planner remaps only KeyReference/new primary keys (identity_column/planner unit tests + golden_apply backfill semantics)
7Account→Avatar custom referenceevidenced (declaration surface)no rule = literal pass-through + warning (known limitation 5); rules are explicit declarations; PDC-0407 account binding only registers, never writes credentials
8Importing the same package twiceevidencedthe manifest-bytes SHA-256 fingerprint gate DuplicateRejected/explicit copy (tests/golden_apply.rs)
9Target same-name character/accountevidencedP5's two-pass plan unique-value probing + conflict rehearsal (local _imported-suffix rebuild)
10Online players writing during exportevidenced (honest discipline)source session READ ONLY + row-budget batching (PDC-0604); snapshot semantics = the InnoDB consistent-read assumption; a Persisted≠Live notice on every screen
11Non-transactional tables or a different DB interfaceinterface rejection evidenced; non-transactional table surface honestly by assumptiontarget.rs UnsupportedDbInterface accepts only mysql; the engine always creates InnoDB databases — no separate table-type gate
12Mid-import failure/cancelevidencedtests/golden_apply.rs failure injection with full rollback + P5 cancel-means-rollback
13Local service still has this DBID loadednot enforced in code (honest)the operations discipline requires the target's local service be stopped (ops §1.2-4/§4-7); no process-detection gate — a known limitation
14Production source with write permissionevidencedvalidate_readonly forces read-only, fail-closed at the statement layer (PDC-0604 tests/security.rs)
15Target marked productionevidencedTargetEnvironment has no prod variant; ImportRejected at the parse layer (PDC-0604)
16Archive tampered / missing filesevidencedSHA-256 checks + fuzz byte-flip/truncation/appended garbage/bad magic all rejected (PDC-0602)
17Business-relevant table missingevidencedthe export preview's missing-table warning (the P5 preview surface) + the explicit not-a-complete-business-clone statement

§11's six DoD items judged: #2/#3/#5/#6 hold (evidence as above + ops-and-security.md's tutorial + features/ops honest clauses); #1 mostly holds — real MySQL end-to-end evidenced (PDC-0601), while "tables actually auto-generated by KBEngine" were constructed per the engine's table-creation shape, with real engine-run generation not done (same as PDC-0003); #4 honestly does not hold — engine-native load attempted=false, with account binding explicitly disclosed. The two engine-side items share a cause with the IDE-LIV family: they close once the user provides a connectable, verifiable engine instance, at which point §10-1/§11-1/§11-4 are updated.

11. Definition of Done ​

The MVP counts as done only when all of the following hold:

  1. An end-to-end demonstration of a single Avatar (including ARRAY/ components) export and local import, using test MySQL tables actually auto-generated by KBEngine, not hand-written fakes.
  2. The source database read-only; exporting multiple related tables with InnoDB consistent reads; the archive carries type info, hashes, versions, and a redaction report.
  3. The target is a defined local environment; a Dry Run is shown before import; new IDs, recursive parentID mapping, unique-key conflicts, and transaction rollback supported.
  4. The imported Avatar can be loaded via the target KBEngine's native API; if account binding is unsupported, it is explicitly disclosed.
  5. The open-source repo carries complete golden/integration/failure-injection/ security tests and a reproducible tutorial.
  6. No exaggerated claims like "automatically copying the complete online current state" or "automatically understanding all player business relations".

12. Technical risks and trade-offs ​

  • Highest risk: misjudging engine mappings. Lock relations with actual engine C++ source and real table-creation samples; never infer from naming.
  • High risk: business IDs. Automatic handling limited to engine- determinable parent-child relations; business references must be explicit declarations.
  • High risk: privacy and accounts. Copying credentials/payment info is forbidden by default; archives redacted + encrypted; accounts bound locally.
  • High risk: source database vs live memory divergence. The UI always marks Persisted Clone; for the latest memory state, design a separate controlled server export — out of the current project.
  • High risk: target engine version differences. V1 supports only structure-exact compatibility; schema migration is a separate capability.
  • Medium risk: target writes affecting the online game. The local service must be stopped by default; online hot injection refused.
  • Medium risk: long transactions crushing the production database. Budget limits, batched reads, short timeouts; prefer read replicas.
  • Medium risk: account/character identity binding. Most business logic is project-custom; .def cannot automatically reveal all ownership rules.

13. Priority and iteration advice ​

v0.1 the verifiable core (first) ​

  • Precise export of the real main table and one level of ARRAY/component tables, offline archive, restore into an empty local database.
  • Read-only safety, schema verification, level-by-level parentID rewriting, transactional import, native Entity load verification.
  • One complete CLI test chain; a command-palette entry inside Kode first.

v0.2 daily usable ​

  • Full nested relations, project business reference rules, local account binding, ID remapping into an existing test database.
  • Visual previews, conflict and permission controls, data redaction/ encryption, regression tests.

v0.3 later extensions (per actual need) ​

  • Multiple anonymized test copies from one archive, relation templates, post-import diff diagnostics.
  • Differential adaptation across KBEngine branches/projects; more database backends need separate evaluation.

Do not do: whole-server/whole-database migration from the start, automatically tracking all EntityCalls and arbitrary Python objects, or turning Kode into a game GM platform.

14. References ​

Kode documentation