[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KG11GVFJR4RGDDE0HCX3NT":3,"skill-same:01M6KG11GVFJR4RGDDE0HCX3NT":103},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":67,"commitSha":68,"skillDirectory":69,"forksCount":70,"repositoryHtmlUrl":71,"repositoryHomepageUrl":6,"ownerHtmlUrl":72,"ownerBlogUrl":6,"ownerDescription":73,"updatedAt":74,"install":75,"resources":88},"01M6KG11GVFJR4RGDDE0HCX3NT","unity-dots-ecb-lifecycle-debugger",null,"ECB playback failure debugger for Unity DOTS\u002FECS. Load when you see: \"EntityCommandBuffer playback failed\", \"entityExists=False\", \"Buffer does not exist on entity\", \"Component does not exist on entity\", \"AppendDestroyedEntityRecordError\", \"Invalid deferred entity\", \"Duplicate AddComponent during playback\", \"SetComponent on missing component\", or \"DestroyEntity executed before another ECB command\". Do NOT load for: MonoBehaviour optimization, ECS architecture design, NavMesh, Addressables, UI event listeners, or generic DOTS implementation.","dyCuong03\u002Funity-agent-team","dyCuong03","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F137050365?v=4","01M6KFXC85HQHXZJC2VC1KY6EZ","CuongND","01M6KFXCCHP6CD5MTA8NECJC36",8,"MIT","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"unity dots ecb lifecycle debugger","unity","debugger","lifecycle","log","static","you","invalid","windsurf","architecture design","files","bug","design","read","command","Safety","run","architecture","component","safe","2026-11-10 10:12:30",false,"---\nname: unity-dots-ecb-lifecycle-debugger\ndescription: >-\n  ECB playback failure debugger for Unity DOTS\u002FECS. Load when you see: \"EntityCommandBuffer playback\n  failed\", \"entityExists=False\", \"Buffer does not exist on entity\", \"Component does not exist on\n  entity\", \"AppendDestroyedEntityRecordError\", \"Invalid deferred entity\", \"Duplicate AddComponent\n  during playback\", \"SetComponent on missing component\", or \"DestroyEntity executed before another\n  ECB command\". Do NOT load for: MonoBehaviour optimization, ECS architecture design, NavMesh,\n  Addressables, UI event listeners, or generic DOTS implementation.\nmetadata:\n  user-invocable: false\n  platform-compat:\n    - \"Unity Entities 1.0+\"\n    - \"Entities 1.3.x (tested)\"\n    - \"Entities 1.4.x (tested)\"\n  security: >-\n    All helper scripts in scripts\u002F are static syntax-pattern scanners only. They read .cs files\n    via regex — no code execution, no writes, no network calls. Safe to run on any DOTS codebase.\nuse-when: |\n  Load for unity-dots-dev and bug-investigation when a Unity console log contains:\n  \"EntityCommandBuffer playback failed\", \"entityExists=False\", \"AppendDestroyedEntityRecordError\",\n  \"Buffer does not exist on entity\", \"Component does not exist on entity\",\n  \"Invalid deferred entity\", \"Duplicate AddComponent during playback\",\n  \"SetComponent on missing component\", or \"DestroyEntity executed before another ECB command\".\n  Load when debugging ECB command ordering across multiple systems sharing a playback phase.\ndo-not-use-when: |\n  Do not load for MonoBehaviour optimization, ECS architecture design, NavMesh, Addressables,\n  UI event listeners, timeline, or generic DOTS implementation. Do not load for tester, verifier,\n  qa-tester, or architect roles. Not needed for Burst compilation errors (use burst-safety).\n  Not needed for NativeContainer leaks (use memory-safety). Not needed for general ECB usage\n  without playback failures (use ecs-job-patterns).\nplatforms: [claude-code, codex, copilot, cursor, windsurf]\n---\n\n# Unity DOTS ECB Lifecycle Debugger\n\n**When to load this skill:**\n- Runtime exception contains: `EntityCommandBuffer playback failed`, `entityExists=False`,\n  `AppendDestroyedEntityRecordError`, `Buffer does not exist on entity`,\n  `Component does not exist on entity`, `Invalid deferred entity`,\n  `Duplicate AddComponent during playback`, `SetComponent on missing component`,\n  `DestroyEntity executed before another ECB command`\n- Question is about ordering of ECB commands across multiple systems targeting the same playback phase\n- Entity is valid at record time but invalid at playback time\n\n**When NOT to load this skill:**\n- MonoBehaviour performance optimization\n- ECS architecture design \u002F component layout planning\n- NavMesh, Addressables, UI events, Timeline, Animator\n- Generic NullReferenceException without ECB stack trace\n- Burst compilation errors (use `burst-safety`)\n- NativeContainer leaks (use `memory-safety`)\n- General ECS job implementation (use `ecs-job-patterns`)\n\n> **NOT THIS SKILL** — If ECB is being used correctly and you want guidance on patterns\n> (when to use which singleton, how to schedule jobs with ECB, ParallelWriter usage),\n> load `ecs-job-patterns` instead. This skill starts where `ecs-job-patterns` ends:\n> at playback failure. It does not teach correct ECB usage — it diagnoses why playback\n> threw an exception.\n\n---\n\n## Core Mental Model\n\nThe fundamental ECB trap: **an entity is valid at record time but invalid at playback time.**\n\n```\nFrame N:\n  ProducerSystem.OnUpdate():\n    ecb.AppendToBuffer(TargetEntity, new TargetBufferElement{...})  \u002F\u002F entity valid here ✓\n\n  CleanupSystem.OnUpdate():\n    ecb.DestroyEntity(TargetEntity)                                  \u002F\u002F also valid here ✓\n\n  \u002F\u002F Both write to the SAME ECB singleton (same playback point)\n\nPlayback at BeginSimulationECBSystem:\n  [1] ecb command from CleanupSystem executes first  → TargetEntity destroyed\n  [2] ecb command from ProducerSystem executes next  → entityExists=False ✗\n```\n\nThe guard `if (entityManager.Exists(entity))` before recording is **always wrong** — the entity\nexists at record time. The problem is what happens *between record and playback*.\n\n---\n\n## Investigation Flow\n\nFollow these steps in order. Do not skip to a fix before completing Step 5 (root-cause proof).\n\n### Step 1 — Failure Classification\n\nExtract from the exception \u002F console log:\n\n| Field | How to extract |\n|-------|----------------|\n| Exception type | First line of stack trace |\n| Failing ECB operation | The command that threw (AppendToBuffer, SetComponent, AddComponent, DestroyEntity…) |\n| Target entity index+version | Shown as `Entity(X:Y)` in error text |\n| `entityExists` state | Stated in error: `entityExists=False` means destroyed; `True` = wrong component\u002Fbuffer |\n| Recording system | System name in the stack trace **above** the playback point — NOT the playback ECB system |\n| Playback ECB system | The `XxxEntityCommandBufferSystem` shown at the top of the stack |\n| ECB phase | Derived from playback system name (Begin\u002FEnd + group) |\n| Job \u002F Burst context | Look for `BurstCompile` attribute or `IJobEntity` in recording system |\n| Primary error vs secondary | Primary = first exception; secondary = cascade from destroyed components |\n\n**Do not assume the system named in the stack trace IS the destructive producer.** The playback\nsystem executes commands from *all* producers that wrote to that ECB. The stack trace identifies\nthe failing command's *recording* origin, not the destroyer.\n\n---\n\n### Step 2 — ECB Producer Inventory\n\nRun the helper script from this skill directory:\n```sh\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_ecb_producers.py \u003Crepo-root>\n```\n\nManually verify output. Build a table — use DISCOVERED names from the repo:\n\n| System | File | Update Group | Ordering Attrs | ECB Phase | Operation | Target Expression | Risk |\n|--------|------|-------------|---------------|-----------|-----------|------------------|------|\n| (discovered) | (file:line) | (group) | ([UpdateAfter...]) | (Begin\u002FEnd+Group) | AppendToBuffer\u002FDestroy\u002F… | (entity field\u002Fvar) | high\u002Fmed\u002Flow |\n\nFill every cell from actual code evidence. A cell cannot be \"unknown\" — if you cannot determine\nit, note \"undetermined — read \u003Cfile>:\u003Cline>\".\n\nKey patterns to locate (see `find_ecb_producers.py` for full list):\n- `BeginSimulationEntityCommandBufferSystem.Singleton`\n- `EndSimulationEntityCommandBufferSystem.Singleton`\n- `BeginInitializationEntityCommandBufferSystem.Singleton`\n- `EndInitializationEntityCommandBufferSystem.Singleton`\n- `BeginPresentationEntityCommandBufferSystem.Singleton`\n- `.CreateCommandBuffer(state.WorldUnmanaged)`\n- `.AsParallelWriter()`\n- `ecb.DestroyEntity`, `ecb.AppendToBuffer`, `ecb.AddBuffer`, `ecb.SetBuffer`\n- `ecb.AddComponent`, `ecb.SetComponent`, `ecb.RemoveComponent`\n\n**Focus on producers that target the same ECB phase as the failing command's playback system.**\n\n---\n\n### Step 3 — Entity Lifetime Tracing\n\nFor the target entity identified in Step 1, trace:\n\n1. **Creation site** — which system\u002Fbaker creates this entity? (`EntityManager.CreateEntity`,\n   `ecb.CreateEntity`, baker `GetEntity()`, prefab instantiation via `ecb.Instantiate`)\n2. **Owner** — which system or component \"owns\" this entity? (stores the entity ref in a component\n   or buffer on another entity)\n3. **Reference storage** — where is the `Entity` value stored? (field on IComponentData, DynamicBuffer,\n   NativeArray, singleton component)\n4. **LinkedEntityGroup membership** — is the entity part of a linked group? If so, destroying the\n   root also destroys it.\n5. **Lifetime states** — does the entity have lifecycle marker components?\n   Generic lifecycle: `Created → Initialized → Referenced → Activated → Consumed → MarkedForCleanup → Destroyed`\n6. **All destruction paths** — collect EVERY code path that could destroy or remove key components:\n   - Direct `ecb.DestroyEntity` \u002F `EntityManager.DestroyEntity`\n   - `ecb.RemoveComponent\u003CT>` \u002F `EntityManager.RemoveComponent\u003CT>` (if T is needed by failing op)\n   - Cascaded destruction (LinkedEntityGroup, child entities)\n   - Pooled return disguised as cleanup\n   - State-driven cleanup (tag added → system destroys)\n   - Scene-driven cleanup (unload triggers destruction)\n7. **Stale reference check** — any system that caches the entity ref in a field and doesn't clear\n   it after destruction is a stale-reference source.\n\n---\n\n### Step 4 — Ordering Reconstruction\n\nRun the helper script:\n```sh\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_system_ordering.py \u003Crepo-root>\n```\n\nThen manually reconstruct the actual execution order for the relevant frame.\n\n**Frame timeline template (10-step minimum):**\n\n```\nFrame N execution timeline\n──────────────────────────────────────────────────────────────────────────────\nStep  | World time | System               | Entity state | Recorded op  | ECB phase\n──────┼────────────┼──────────────────────┼──────────────┼──────────────┼──────────\n  1   | t=0.000    | [group start]        | alive v=3    | —            | —\n  2   | t=0.001    | ProducerSystem       | alive v=3    | AppendToBuffer(E:3) | BeginSim\n  3   | t=0.002    | CleanupSystem        | alive v=3    | DestroyEntity(E:3) | BeginSim\n  4   | t=0.003    | [group end]          | alive v=3    | —            | —\n  5   | t=0.004    | BeginSimECBSystem    | alive v=3    | [playback begins] | —\n  6   | t=0.004    | BeginSimECBSystem    | alive→dead   | DestroyEntity executes | —\n  7   | t=0.004    | BeginSimECBSystem    | dead         | AppendToBuffer executes → FAIL | —\n──────────────────────────────────────────────────────────────────────────────\nROOT CAUSE: CleanupSystem recorded DestroyEntity(E:3) to BeginSimECBSystem; \nProducerSystem recorded AppendToBuffer(E:3) to same ECB; cleanup command executed \nfirst; entity version incremented; subsequent AppendToBuffer fails (entityExists=False).\n```\n\nFill with DISCOVERED system names. Use placeholders only when actual system names are not yet known.\n\n**Ordering factors to evaluate:**\n\n1. `[UpdateInGroup]`, `[UpdateBefore]`, `[UpdateAfter]`, `[CreateBefore]`, `[CreateAfter]` on all\n   relevant systems\n2. Nested group execution order (outer group → inner groups → systems within inner)\n3. Systems without explicit ordering attributes: they execute in creation\u002Fregistration order\n   (non-deterministic relative to each other — flag this as a risk)\n4. When two separate ECBs both target `BeginSimulationEntityCommandBufferSystem`:\n   - Commands from different `CreateCommandBuffer()` calls within the same phase\n   - Order is registration order of the ECB singleton, NOT system execution order\n5. `AsParallelWriter` sort keys: they control order *within one CB* only, not across CBs\n6. Main-thread vs job-recorded commands: both land in same ECB; job commands arrive at\n   `AddJobHandleForProducer` time\n7. Frame of origin: a command recorded in frame N-1 via a persistent ECB plays in frame N\n\n---\n\n### Step 5 — Root-Cause Proof\n\nBefore proposing any fix, prove all of the following:\n\n- [ ] **Exact failing op identified** — `ecb.\u003Cop>(Entity(X:Y), ...)` with recording system\n- [ ] **Target entity source traced** — where it was created, who owns the ref\n- [ ] **All candidate destructive producers listed** — every system that calls DestroyEntity or\n      removes a component required by the failing op\n- [ ] **Actual producer proven** — not just \"probably CleanupSystem\" — show the execution order\n      evidence that puts its destroy command *before* the failing command in playback\n- [ ] **Playback phase confirmed** — both recording and playback ECB singleton match\n- [ ] **Record-time guard is insufficient** — document why `if (ecb.Exists(entity))` fails\n- [ ] **Ordering is the root cause** — not a race condition, not a missing dependency, not a\n      ref-counting error\n\n**Template — Root-Cause Proof Statement:**\n```\nPROVEN ROOT CAUSE:\n  Failing op:         ecb.\u003Cop>(Entity(X:Y), \u003Cargs>)\n  Recording system:   \u003CSystemName> at \u003CFile>:\u003CLine>\n  ECB phase:          \u003CBeginXxx \u002F EndXxx>EntityCommandBufferSystem\n  Destructive producer: \u003CSystemName> — ecb.DestroyEntity(Entity(X:Y)) at \u003CFile>:\u003CLine>\n  Ordering evidence:  \u003CSystemName>[UpdateAfter(X)] executes before recording system [UpdateBefore(Y)]\n                      OR: both write to same ECB singleton; cleanup CB registered first\n  Why guard fails:    Entity exists at record time (frame N step A); destroyed at playback\n                      (frame N step B, B > A); guard at record time cannot see playback-time state\n  Rejected causes:    [list any hypotheses considered and ruled out with evidence]\n```\n\n---\n\n### Step 6 — Fix Decision Tree\n\nApply the FIRST applicable fix. Do not apply multiple fixes simultaneously.\n\n```\nIs the entity destroyed by a system that MUST run in the same frame as dependents?\n  YES →\n    Can cleanup be split into two phases?\n      YES → Preferred Lifecycle Fix (see below)\n      NO  → Can cleanup be delayed one frame via a pending-cleanup tag?\n              YES → Pending-Cleanup Tag Fix\n              NO  → Consolidate Ownership Fix\n\nDoes the failing system record to a DIFFERENT ECB than the destroyer?\n  YES →\n    Are both ECBs targeting the same playback point?\n      YES → Same-ECB Fix (merge to one ECB if local determinism is sufficient)\n      NO  → ECB Phase Fix (change one system's ECB to a later playback point)\n\nIs the problem a stale entity reference (entity destroyed but ref not cleared)?\n  YES → Stale Reference Fix\n\nIs the problem a deferred entity used across two separate ECBs?\n  YES → Deferred Entity Fix (deferred entities are only valid within their origin ECB)\n\nIs the problem ParallelWriter sort keys assumed to order across separate CBs?\n  YES → Sort Key Scope Fix (educate: sort keys scope to one CB only)\n```\n\n---\n\n#### Preferred Lifecycle Fix — Pending-Cleanup Pattern\n\nUse whatever naming convention the target repo already uses (e.g., the existing marker component\nname for \"entity is being torn down\"). If none exists, introduce a generic marker. The concept:\n\n```\nPhase 1 — Request cleanup:\n  ProducerSystem detects entity should be cleaned up → adds a PendingCleanup marker component\n  (structural change via ECB to an early playback point)\n\nPhase 2 — Dependents finish:\n  All systems that reference this entity check for the PendingCleanup marker\n  → they complete their last writes (buffers, components) via ECB\n  → playback of dependent commands happens BEFORE final destruction\n\nPhase 3 — Final destruction:\n  CleanupSystem runs AFTER dependents (explicit [UpdateAfter] or separate ECB phase)\n  → reads PendingCleanup entities\n  → ecb.DestroyEntity (later playback point than Phase 2)\n```\n\n**Implementation constraints:**\n- Do NOT introduce a project-specific component name here — use target repo's existing convention\n  or propose it in workspace\u002Fdesign.md for architect approval\n- Do NOT change `[UpdateBefore\u002FAfter]` attributes without architect approval\n  ([BLOCK: architecture risk] per escalation-policy.md)\n- If a new ECB phase is needed, route through architect — changing ECB singletons changes\n  system execution contracts\n\n---\n\n#### Pending-Cleanup Tag Fix\n\nWhen full 3-phase lifecycle is too heavy:\n1. Recording system checks: `if (SystemAPI.HasComponent\u003CPendingCleanupTag>(entity)) return;`\n2. CleanupSystem adds `PendingCleanupTag` via ECB to an EARLY phase\n3. Final DestroyEntity uses a LATER phase ECB\n4. Dependents run between early and late phases\n\n---\n\n#### Same-ECB Fix\n\nWhen destructive producer and dependent producer can deterministically share one ECB:\n1. Consolidate to one `CreateCommandBuffer` call → one `ecb` instance\n2. Record dependent commands first (lower in OnUpdate), destroy command last\n3. Valid ONLY when ordering is local and explicit — not when scheduling is parallel\n\n---\n\n#### ECB Phase Fix\n\nChange the failing system's ECB singleton to a later playback point:\n- From `BeginSimulationEntityCommandBufferSystem` → `EndSimulationEntityCommandBufferSystem`\n- Verify this does not break OTHER dependencies of the failing system\n- Document the new semantic in workspace\u002Fdesign.md (what \"end of simulation\" means for this system)\n- Route through architect if the change affects system group contracts\n\n---\n\n#### Stale Reference Fix\n\n1. Identify the field\u002Fbuffer that stores the stale entity ref\n2. On the cleanup path, add `ecb.SetComponent(ownerEntity, new ComponentWithEntityRef { ref = Entity.Null })`\n3. Consumers guard: `if (ref == Entity.Null || !SystemAPI.Exists(ref)) continue;`\n4. This is a SECONDARY protection — fix the lifecycle first, then add the guard\n\n---\n\n#### Deferred Entity Fix\n\nDeferred entities (created via `ecb.CreateEntity()` returning a temporary negative index) are\nonly valid within the ECB that created them. They cannot be stored and reused in a different ECB.\n\nFix: ensure the entity ref used in all commands originates from the same `ecb.CreateEntity()` call\nwithin the same `CreateCommandBuffer()` scope. If the entity needs to outlive the ECB, bake it\nor use a two-step pattern (create + set singleton → other system reads singleton next frame).\n\n---\n\n## Anti-Patterns — Reject These Fixes\n\n| Anti-pattern | Why it fails |\n|---|---|\n| `if (entityManager.Exists(entity))` guard before recording | Entity exists at record time; guard passes; destroyed before playback |\n| `if (!ecb.HasBuffer(entity))` early return | Same timing issue — HasBuffer is main-thread, recorded state is deferred |\n| `try { ecb.AppendToBuffer(...) } catch { }` | Swallows the exception; underlying lifecycle bug remains; entity version incremented silently |\n| Add `yield return null` or one-frame delay | Arbitrary delay; breaks when frame rate drops; creates new ordering ambiguity |\n| Move ALL systems to `EndSimulationEntityCommandBufferSystem` | Shifts the problem; may create new ordering conflicts; breaks systems that need early playback |\n| Add `state.Dependency.Complete()` before ECB recording | Sync point that blocks all jobs; expensive; does not fix the recording\u002Fplayback ordering |\n| Disable `[BurstCompile]` on the recording system | Does not affect ECB playback ordering; `[BLOCK: performance]` — never remove Burst from hot-path ISystem |\n| Remove the CleanupSystem to \"fix\" the crash | Hides the symptom; entity memory leaks; cleanup requirements remain |\n| Hardcode `[UpdateAfter(CleanupSystem)]` on every dependent | Brittle; creates circular dependency risk; couples unrelated systems; architecture risk |\n| Treat `ParallelWriter` sort keys as ordering between separate CBs | Sort keys scope to one CB only; two different CBs registered to the same playback system have their own independent ordering |\n| Assume the stack-trace system IS the destructive producer | Stack trace shows the recording origin of the *failing command*, not who destroyed the entity |\n\n---\n\n## Templates\n\n### Template A — Investigation Report\n\n```markdown\n## ECB Playback Failure Investigation\n\n### Failure Classification\n- Exception type:          [e.g. InvalidOperationException]\n- Failing ECB operation:   ecb.\u003Cop>(Entity(X:Y), \u003Ctype>)\n- Target entity:           Entity(X:Y)\n- entityExists:            [False = destroyed | True = wrong component\u002Fbuffer]\n- Recording system:        \u003CSystemName> at \u003CFile>:\u003CLine>\n- Playback ECB system:     \u003CXxxEntityCommandBufferSystem>\n- ECB phase:               \u003CBegin\u002FEnd>\u003CGroup>EntityCommandBufferSystem\n- Job\u002FBurst context:       [IJobEntity | main-thread | IJobChunk]\n- Primary error:           [exception message]\n- Secondary errors:        [cascade exceptions from missing component\u002Fbuffer]\n\n### ECB Producer Inventory\n[Paste table from Step 2]\n\n### Entity Lifetime Trace\n- Creation site:           \u003CSystem> at \u003CFile>:\u003CLine>\n- Owner:                   \u003Ccomponent field on OwnerEntity>\n- Reference storage:       \u003CIComponentData field | DynamicBuffer entry | NativeArray>\n- LinkedEntityGroup:       [yes\u002Fno — root entity]\n- Lifecycle states:        Created → … → MarkedForCleanup → Destroyed\n- All destruction paths:   [list with file:line]\n- Stale refs after cleanup: [list]\n\n### Ordering Reconstruction\n[Paste frame timeline from Step 4]\n\n### Root-Cause Proof\n[Paste proof statement from Step 5]\n\n### Rejected Fix Candidates\n- Guard-only (`Exists` check): [reason it fails in this case]\n- [other rejected candidates]\n\n### Selected Fix\n- Fix type: [Preferred Lifecycle | Pending-Cleanup Tag | Same-ECB | ECB Phase | Stale Ref | Deferred Entity]\n- Change: [what changes, file:line]\n- New lifecycle contract: [describe the phases]\n\n### Validation Results\n- [ ] Compilation clean\n- [ ] Exception no longer thrown\n- [ ] Dependent behavior preserved (describe)\n- [ ] Final cleanup still executes (describe)\n- [ ] No new ECB ordering warnings in console\n- [ ] Remaining uncertainty: [any unresolved questions]\n```\n\n---\n\n### Template B — ECB Producer Inventory\n\n```markdown\n## ECB Producer Inventory\n\nRepo root: \u003Cpath>\nScan date: \u003Cdate>\nScanned with: scripts\u002Ffind_ecb_producers.py + manual verification\n\n| System | File | Update Group | Ordering Attrs | ECB Phase | CB Creation Site | Operation | Target Expression | Component\u002FBuffer Type | Job Type | Parallel Writer | Sort Key | Dep Registration | Risk |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n| \u003Cname> | \u003Cfile:line> | \u003Cgroup> | [UpdateAfter(...)] | BeginSim | \u003Cline> | AppendToBuffer | \u003Cvar>\u002F\u003Cfield> | \u003CBufferType> | IJobEntity | yes\u002Fno | \u003Cexpr> | AddJobHandleForProducer | high |\n```\n\n---\n\n### Template C — Lifecycle Timeline\n\n```markdown\n## ECB Lifecycle Timeline — Frame N\n\n| Step | World time | System | Entity(X:Y) state | Recorded operation | ECB phase | CB identity | Expected | Observed |\n|---|---|---|---|---|---|---|---|---|\n| 1 | t=N.000 | [SimGroup start] | alive v=Y | — | — | — | alive | alive |\n| 2 | t=N.001 | \u003CProducerSystem> | alive v=Y | AppendToBuffer(E:X:Y, elem) | BeginSim | CB#1 | queued | queued |\n| 3 | t=N.002 | \u003CCleanupSystem> | alive v=Y | DestroyEntity(E:X:Y) | BeginSim | CB#2 | queued | queued |\n| 4 | t=N.003 | [SimGroup end] | alive v=Y | — | — | — | — | — |\n| 5 | t=N.004 | BeginSimECBSystem | alive v=Y | [CB#2 plays] DestroyEntity | — | CB#2 | after CB#1 | BEFORE CB#1 |\n| 6 | t=N.004 | BeginSimECBSystem | dead v=Y+1 | [CB#1 plays] AppendToBuffer → FAIL | — | CB#1 | entity alive | entityExists=False |\n```\n\n---\n\n## Helper Scripts\n\nThree read-only Python 3 scripts in `scripts\u002F`. Each outputs `file:line` evidence.\n\nRun from repo root:\n```sh\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_ecb_producers.py \u003Crepo-root>\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_destroy_paths.py \u003Crepo-root>\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_system_ordering.py \u003Crepo-root>\n```\n\nAll scripts:\n- Read `.cs` files recursively from `\u003Crepo-root>`\n- Use regex pattern matching only (no compilation, no execution)\n- Are read-only — no writes to the target repo\n- Have no network calls\n- Output structured tables to stdout\n\n---\n\n## Self-Check Before Proposing a Fix\n\n- [ ] Root-cause proof complete (all 7 checkboxes in Step 5 checked)\n- [ ] Frame timeline shows the actual ordering with discovered system names\n- [ ] Destructive producer identified with file:line evidence (not just \"probably\")\n- [ ] Guard-only fix explicitly considered and rejected with explanation\n- [ ] Fix type selected from decision tree\n- [ ] Fix does not require changing `[UpdateBefore\u002FAfter]` without architect approval\n- [ ] Fix does not add `state.Dependency.Complete()` without performance review\n- [ ] Fix does not remove `[BurstCompile]` (automatic [BLOCK: performance])\n- [ ] Validation plan covers: compilation + exception gone + dependent behavior preserved + cleanup still works\n","# Unity DOTS ECB Lifecycle Debugger\n\n**When to load this skill:**\n- Runtime exception contains: `EntityCommandBuffer playback failed`, `entityExists=False`,\n  `AppendDestroyedEntityRecordError`, `Buffer does not exist on entity`,\n  `Component does not exist on entity`, `Invalid deferred entity`,\n  `Duplicate AddComponent during playback`, `SetComponent on missing component`,\n  `DestroyEntity executed before another ECB command`\n- Question is about ordering of ECB commands across multiple systems targeting the same playback phase\n- Entity is valid at record time but invalid at playback time\n\n**When NOT to load this skill:**\n- MonoBehaviour performance optimization\n- ECS architecture design \u002F component layout planning\n- NavMesh, Addressables, UI events, Timeline, Animator\n- Generic NullReferenceException without ECB stack trace\n- Burst compilation errors (use `burst-safety`)\n- NativeContainer leaks (use `memory-safety`)\n- General ECS job implementation (use `ecs-job-patterns`)\n\n> **NOT THIS SKILL** — If ECB is being used correctly and you want guidance on patterns\n> (when to use which singleton, how to schedule jobs with ECB, ParallelWriter usage),\n> load `ecs-job-patterns` instead. This skill starts where `ecs-job-patterns` ends:\n> at playback failure. It does not teach correct ECB usage — it diagnoses why playback\n> threw an exception.\n\n---\n\n## Core Mental Model\n\nThe fundamental ECB trap: **an entity is valid at record time but invalid at playback time.**\n\n```\nFrame N:\n  ProducerSystem.OnUpdate():\n    ecb.AppendToBuffer(TargetEntity, new TargetBufferElement{...})  \u002F\u002F entity valid here ✓\n\n  CleanupSystem.OnUpdate():\n    ecb.DestroyEntity(TargetEntity)                                  \u002F\u002F also valid here ✓\n\n  \u002F\u002F Both write to the SAME ECB singleton (same playback point)\n\nPlayback at BeginSimulationECBSystem:\n  [1] ecb command from CleanupSystem executes first  → TargetEntity destroyed\n  [2] ecb command from ProducerSystem executes next  → entityExists=False ✗\n```\n\nThe guard `if (entityManager.Exists(entity))` before recording is **always wrong** — the entity\nexists at record time. The problem is what happens *between record and playback*.\n\n---\n\n## Investigation Flow\n\nFollow these steps in order. Do not skip to a fix before completing Step 5 (root-cause proof).\n\n### Step 1 — Failure Classification\n\nExtract from the exception \u002F console log:\n\n| Field | How to extract |\n|-------|----------------|\n| Exception type | First line of stack trace |\n| Failing ECB operation | The command that threw (AppendToBuffer, SetComponent, AddComponent, DestroyEntity…) |\n| Target entity index+version | Shown as `Entity(X:Y)` in error text |\n| `entityExists` state | Stated in error: `entityExists=False` means destroyed; `True` = wrong component\u002Fbuffer |\n| Recording system | System name in the stack trace **above** the playback point — NOT the playback ECB system |\n| Playback ECB system | The `XxxEntityCommandBufferSystem` shown at the top of the stack |\n| ECB phase | Derived from playback system name (Begin\u002FEnd + group) |\n| Job \u002F Burst context | Look for `BurstCompile` attribute or `IJobEntity` in recording system |\n| Primary error vs secondary | Primary = first exception; secondary = cascade from destroyed components |\n\n**Do not assume the system named in the stack trace IS the destructive producer.** The playback\nsystem executes commands from *all* producers that wrote to that ECB. The stack trace identifies\nthe failing command's *recording* origin, not the destroyer.\n\n---\n\n### Step 2 — ECB Producer Inventory\n\nRun the helper script from this skill directory:\n```sh\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_ecb_producers.py \u003Crepo-root>\n```\n\nManually verify output. Build a table — use DISCOVERED names from the repo:\n\n| System | File | Update Group | Ordering Attrs | ECB Phase | Operation | Target Expression | Risk |\n|--------|------|-------------|---------------|-----------|-----------|------------------|------|\n| (discovered) | (file:line) | (group) | ([UpdateAfter...]) | (Begin\u002FEnd+Group) | AppendToBuffer\u002FDestroy\u002F… | (entity field\u002Fvar) | high\u002Fmed\u002Flow |\n\nFill every cell from actual code evidence. A cell cannot be \"unknown\" — if you cannot determine\nit, note \"undetermined — read \u003Cfile>:\u003Cline>\".\n\nKey patterns to locate (see `find_ecb_producers.py` for full list):\n- `BeginSimulationEntityCommandBufferSystem.Singleton`\n- `EndSimulationEntityCommandBufferSystem.Singleton`\n- `BeginInitializationEntityCommandBufferSystem.Singleton`\n- `EndInitializationEntityCommandBufferSystem.Singleton`\n- `BeginPresentationEntityCommandBufferSystem.Singleton`\n- `.CreateCommandBuffer(state.WorldUnmanaged)`\n- `.AsParallelWriter()`\n- `ecb.DestroyEntity`, `ecb.AppendToBuffer`, `ecb.AddBuffer`, `ecb.SetBuffer`\n- `ecb.AddComponent`, `ecb.SetComponent`, `ecb.RemoveComponent`\n\n**Focus on producers that target the same ECB phase as the failing command's playback system.**\n\n---\n\n### Step 3 — Entity Lifetime Tracing\n\nFor the target entity identified in Step 1, trace:\n\n1. **Creation site** — which system\u002Fbaker creates this entity? (`EntityManager.CreateEntity`,\n   `ecb.CreateEntity`, baker `GetEntity()`, prefab instantiation via `ecb.Instantiate`)\n2. **Owner** — which system or component \"owns\" this entity? (stores the entity ref in a component\n   or buffer on another entity)\n3. **Reference storage** — where is the `Entity` value stored? (field on IComponentData, DynamicBuffer,\n   NativeArray, singleton component)\n4. **LinkedEntityGroup membership** — is the entity part of a linked group? If so, destroying the\n   root also destroys it.\n5. **Lifetime states** — does the entity have lifecycle marker components?\n   Generic lifecycle: `Created → Initialized → Referenced → Activated → Consumed → MarkedForCleanup → Destroyed`\n6. **All destruction paths** — collect EVERY code path that could destroy or remove key components:\n   - Direct `ecb.DestroyEntity` \u002F `EntityManager.DestroyEntity`\n   - `ecb.RemoveComponent\u003CT>` \u002F `EntityManager.RemoveComponent\u003CT>` (if T is needed by failing op)\n   - Cascaded destruction (LinkedEntityGroup, child entities)\n   - Pooled return disguised as cleanup\n   - State-driven cleanup (tag added → system destroys)\n   - Scene-driven cleanup (unload triggers destruction)\n7. **Stale reference check** — any system that caches the entity ref in a field and doesn't clear\n   it after destruction is a stale-reference source.\n\n---\n\n### Step 4 — Ordering Reconstruction\n\nRun the helper script:\n```sh\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_system_ordering.py \u003Crepo-root>\n```\n\nThen manually reconstruct the actual execution order for the relevant frame.\n\n**Frame timeline template (10-step minimum):**\n\n```\nFrame N execution timeline\n──────────────────────────────────────────────────────────────────────────────\nStep  | World time | System               | Entity state | Recorded op  | ECB phase\n──────┼────────────┼──────────────────────┼──────────────┼──────────────┼──────────\n  1   | t=0.000    | [group start]        | alive v=3    | —            | —\n  2   | t=0.001    | ProducerSystem       | alive v=3    | AppendToBuffer(E:3) | BeginSim\n  3   | t=0.002    | CleanupSystem        | alive v=3    | DestroyEntity(E:3) | BeginSim\n  4   | t=0.003    | [group end]          | alive v=3    | —            | —\n  5   | t=0.004    | BeginSimECBSystem    | alive v=3    | [playback begins] | —\n  6   | t=0.004    | BeginSimECBSystem    | alive→dead   | DestroyEntity executes | —\n  7   | t=0.004    | BeginSimECBSystem    | dead         | AppendToBuffer executes → FAIL | —\n──────────────────────────────────────────────────────────────────────────────\nROOT CAUSE: CleanupSystem recorded DestroyEntity(E:3) to BeginSimECBSystem; \nProducerSystem recorded AppendToBuffer(E:3) to same ECB; cleanup command executed \nfirst; entity version incremented; subsequent AppendToBuffer fails (entityExists=False).\n```\n\nFill with DISCOVERED system names. Use placeholders only when actual system names are not yet known.\n\n**Ordering factors to evaluate:**\n\n1. `[UpdateInGroup]`, `[UpdateBefore]`, `[UpdateAfter]`, `[CreateBefore]`, `[CreateAfter]` on all\n   relevant systems\n2. Nested group execution order (outer group → inner groups → systems within inner)\n3. Systems without explicit ordering attributes: they execute in creation\u002Fregistration order\n   (non-deterministic relative to each other — flag this as a risk)\n4. When two separate ECBs both target `BeginSimulationEntityCommandBufferSystem`:\n   - Commands from different `CreateCommandBuffer()` calls within the same phase\n   - Order is registration order of the ECB singleton, NOT system execution order\n5. `AsParallelWriter` sort keys: they control order *within one CB* only, not across CBs\n6. Main-thread vs job-recorded commands: both land in same ECB; job commands arrive at\n   `AddJobHandleForProducer` time\n7. Frame of origin: a command recorded in frame N-1 via a persistent ECB plays in frame N\n\n---\n\n### Step 5 — Root-Cause Proof\n\nBefore proposing any fix, prove all of the following:\n\n- [ ] **Exact failing op identified** — `ecb.\u003Cop>(Entity(X:Y), ...)` with recording system\n- [ ] **Target entity source traced** — where it was created, who owns the ref\n- [ ] **All candidate destructive producers listed** — every system that calls DestroyEntity or\n      removes a component required by the failing op\n- [ ] **Actual producer proven** — not just \"probably CleanupSystem\" — show the execution order\n      evidence that puts its destroy command *before* the failing command in playback\n- [ ] **Playback phase confirmed** — both recording and playback ECB singleton match\n- [ ] **Record-time guard is insufficient** — document why `if (ecb.Exists(entity))` fails\n- [ ] **Ordering is the root cause** — not a race condition, not a missing dependency, not a\n      ref-counting error\n\n**Template — Root-Cause Proof Statement:**\n```\nPROVEN ROOT CAUSE:\n  Failing op:         ecb.\u003Cop>(Entity(X:Y), \u003Cargs>)\n  Recording system:   \u003CSystemName> at \u003CFile>:\u003CLine>\n  ECB phase:          \u003CBeginXxx \u002F EndXxx>EntityCommandBufferSystem\n  Destructive producer: \u003CSystemName> — ecb.DestroyEntity(Entity(X:Y)) at \u003CFile>:\u003CLine>\n  Ordering evidence:  \u003CSystemName>[UpdateAfter(X)] executes before recording system [UpdateBefore(Y)]\n                      OR: both write to same ECB singleton; cleanup CB registered first\n  Why guard fails:    Entity exists at record time (frame N step A); destroyed at playback\n                      (frame N step B, B > A); guard at record time cannot see playback-time state\n  Rejected causes:    [list any hypotheses considered and ruled out with evidence]\n```\n\n---\n\n### Step 6 — Fix Decision Tree\n\nApply the FIRST applicable fix. Do not apply multiple fixes simultaneously.\n\n```\nIs the entity destroyed by a system that MUST run in the same frame as dependents?\n  YES →\n    Can cleanup be split into two phases?\n      YES → Preferred Lifecycle Fix (see below)\n      NO  → Can cleanup be delayed one frame via a pending-cleanup tag?\n              YES → Pending-Cleanup Tag Fix\n              NO  → Consolidate Ownership Fix\n\nDoes the failing system record to a DIFFERENT ECB than the destroyer?\n  YES →\n    Are both ECBs targeting the same playback point?\n      YES → Same-ECB Fix (merge to one ECB if local determinism is sufficient)\n      NO  → ECB Phase Fix (change one system's ECB to a later playback point)\n\nIs the problem a stale entity reference (entity destroyed but ref not cleared)?\n  YES → Stale Reference Fix\n\nIs the problem a deferred entity used across two separate ECBs?\n  YES → Deferred Entity Fix (deferred entities are only valid within their origin ECB)\n\nIs the problem ParallelWriter sort keys assumed to order across separate CBs?\n  YES → Sort Key Scope Fix (educate: sort keys scope to one CB only)\n```\n\n---\n\n#### Preferred Lifecycle Fix — Pending-Cleanup Pattern\n\nUse whatever naming convention the target repo already uses (e.g., the existing marker component\nname for \"entity is being torn down\"). If none exists, introduce a generic marker. The concept:\n\n```\nPhase 1 — Request cleanup:\n  ProducerSystem detects entity should be cleaned up → adds a PendingCleanup marker component\n  (structural change via ECB to an early playback point)\n\nPhase 2 — Dependents finish:\n  All systems that reference this entity check for the PendingCleanup marker\n  → they complete their last writes (buffers, components) via ECB\n  → playback of dependent commands happens BEFORE final destruction\n\nPhase 3 — Final destruction:\n  CleanupSystem runs AFTER dependents (explicit [UpdateAfter] or separate ECB phase)\n  → reads PendingCleanup entities\n  → ecb.DestroyEntity (later playback point than Phase 2)\n```\n\n**Implementation constraints:**\n- Do NOT introduce a project-specific component name here — use target repo's existing convention\n  or propose it in workspace\u002Fdesign.md for architect approval\n- Do NOT change `[UpdateBefore\u002FAfter]` attributes without architect approval\n  ([BLOCK: architecture risk] per escalation-policy.md)\n- If a new ECB phase is needed, route through architect — changing ECB singletons changes\n  system execution contracts\n\n---\n\n#### Pending-Cleanup Tag Fix\n\nWhen full 3-phase lifecycle is too heavy:\n1. Recording system checks: `if (SystemAPI.HasComponent\u003CPendingCleanupTag>(entity)) return;`\n2. CleanupSystem adds `PendingCleanupTag` via ECB to an EARLY phase\n3. Final DestroyEntity uses a LATER phase ECB\n4. Dependents run between early and late phases\n\n---\n\n#### Same-ECB Fix\n\nWhen destructive producer and dependent producer can deterministically share one ECB:\n1. Consolidate to one `CreateCommandBuffer` call → one `ecb` instance\n2. Record dependent commands first (lower in OnUpdate), destroy command last\n3. Valid ONLY when ordering is local and explicit — not when scheduling is parallel\n\n---\n\n#### ECB Phase Fix\n\nChange the failing system's ECB singleton to a later playback point:\n- From `BeginSimulationEntityCommandBufferSystem` → `EndSimulationEntityCommandBufferSystem`\n- Verify this does not break OTHER dependencies of the failing system\n- Document the new semantic in workspace\u002Fdesign.md (what \"end of simulation\" means for this system)\n- Route through architect if the change affects system group contracts\n\n---\n\n#### Stale Reference Fix\n\n1. Identify the field\u002Fbuffer that stores the stale entity ref\n2. On the cleanup path, add `ecb.SetComponent(ownerEntity, new ComponentWithEntityRef { ref = Entity.Null })`\n3. Consumers guard: `if (ref == Entity.Null || !SystemAPI.Exists(ref)) continue;`\n4. This is a SECONDARY protection — fix the lifecycle first, then add the guard\n\n---\n\n#### Deferred Entity Fix\n\nDeferred entities (created via `ecb.CreateEntity()` returning a temporary negative index) are\nonly valid within the ECB that created them. They cannot be stored and reused in a different ECB.\n\nFix: ensure the entity ref used in all commands originates from the same `ecb.CreateEntity()` call\nwithin the same `CreateCommandBuffer()` scope. If the entity needs to outlive the ECB, bake it\nor use a two-step pattern (create + set singleton → other system reads singleton next frame).\n\n---\n\n## Anti-Patterns — Reject These Fixes\n\n| Anti-pattern | Why it fails |\n|---|---|\n| `if (entityManager.Exists(entity))` guard before recording | Entity exists at record time; guard passes; destroyed before playback |\n| `if (!ecb.HasBuffer(entity))` early return | Same timing issue — HasBuffer is main-thread, recorded state is deferred |\n| `try { ecb.AppendToBuffer(...) } catch { }` | Swallows the exception; underlying lifecycle bug remains; entity version incremented silently |\n| Add `yield return null` or one-frame delay | Arbitrary delay; breaks when frame rate drops; creates new ordering ambiguity |\n| Move ALL systems to `EndSimulationEntityCommandBufferSystem` | Shifts the problem; may create new ordering conflicts; breaks systems that need early playback |\n| Add `state.Dependency.Complete()` before ECB recording | Sync point that blocks all jobs; expensive; does not fix the recording\u002Fplayback ordering |\n| Disable `[BurstCompile]` on the recording system | Does not affect ECB playback ordering; `[BLOCK: performance]` — never remove Burst from hot-path ISystem |\n| Remove the CleanupSystem to \"fix\" the crash | Hides the symptom; entity memory leaks; cleanup requirements remain |\n| Hardcode `[UpdateAfter(CleanupSystem)]` on every dependent | Brittle; creates circular dependency risk; couples unrelated systems; architecture risk |\n| Treat `ParallelWriter` sort keys as ordering between separate CBs | Sort keys scope to one CB only; two different CBs registered to the same playback system have their own independent ordering |\n| Assume the stack-trace system IS the destructive producer | Stack trace shows the recording origin of the *failing command*, not who destroyed the entity |\n\n---\n\n## Templates\n\n### Template A — Investigation Report\n\n```markdown\n## ECB Playback Failure Investigation\n\n### Failure Classification\n- Exception type:          [e.g. InvalidOperationException]\n- Failing ECB operation:   ecb.\u003Cop>(Entity(X:Y), \u003Ctype>)\n- Target entity:           Entity(X:Y)\n- entityExists:            [False = destroyed | True = wrong component\u002Fbuffer]\n- Recording system:        \u003CSystemName> at \u003CFile>:\u003CLine>\n- Playback ECB system:     \u003CXxxEntityCommandBufferSystem>\n- ECB phase:               \u003CBegin\u002FEnd>\u003CGroup>EntityCommandBufferSystem\n- Job\u002FBurst context:       [IJobEntity | main-thread | IJobChunk]\n- Primary error:           [exception message]\n- Secondary errors:        [cascade exceptions from missing component\u002Fbuffer]\n\n### ECB Producer Inventory\n[Paste table from Step 2]\n\n### Entity Lifetime Trace\n- Creation site:           \u003CSystem> at \u003CFile>:\u003CLine>\n- Owner:                   \u003Ccomponent field on OwnerEntity>\n- Reference storage:       \u003CIComponentData field | DynamicBuffer entry | NativeArray>\n- LinkedEntityGroup:       [yes\u002Fno — root entity]\n- Lifecycle states:        Created → … → MarkedForCleanup → Destroyed\n- All destruction paths:   [list with file:line]\n- Stale refs after cleanup: [list]\n\n### Ordering Reconstruction\n[Paste frame timeline from Step 4]\n\n### Root-Cause Proof\n[Paste proof statement from Step 5]\n\n### Rejected Fix Candidates\n- Guard-only (`Exists` check): [reason it fails in this case]\n- [other rejected candidates]\n\n### Selected Fix\n- Fix type: [Preferred Lifecycle | Pending-Cleanup Tag | Same-ECB | ECB Phase | Stale Ref | Deferred Entity]\n- Change: [what changes, file:line]\n- New lifecycle contract: [describe the phases]\n\n### Validation Results\n- [ ] Compilation clean\n- [ ] Exception no longer thrown\n- [ ] Dependent behavior preserved (describe)\n- [ ] Final cleanup still executes (describe)\n- [ ] No new ECB ordering warnings in console\n- [ ] Remaining uncertainty: [any unresolved questions]\n```\n\n---\n\n### Template B — ECB Producer Inventory\n\n```markdown\n## ECB Producer Inventory\n\nRepo root: \u003Cpath>\nScan date: \u003Cdate>\nScanned with: scripts\u002Ffind_ecb_producers.py + manual verification\n\n| System | File | Update Group | Ordering Attrs | ECB Phase | CB Creation Site | Operation | Target Expression | Component\u002FBuffer Type | Job Type | Parallel Writer | Sort Key | Dep Registration | Risk |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n| \u003Cname> | \u003Cfile:line> | \u003Cgroup> | [UpdateAfter(...)] | BeginSim | \u003Cline> | AppendToBuffer | \u003Cvar>\u002F\u003Cfield> | \u003CBufferType> | IJobEntity | yes\u002Fno | \u003Cexpr> | AddJobHandleForProducer | high |\n```\n\n---\n\n### Template C — Lifecycle Timeline\n\n```markdown\n## ECB Lifecycle Timeline — Frame N\n\n| Step | World time | System | Entity(X:Y) state | Recorded operation | ECB phase | CB identity | Expected | Observed |\n|---|---|---|---|---|---|---|---|---|\n| 1 | t=N.000 | [SimGroup start] | alive v=Y | — | — | — | alive | alive |\n| 2 | t=N.001 | \u003CProducerSystem> | alive v=Y | AppendToBuffer(E:X:Y, elem) | BeginSim | CB#1 | queued | queued |\n| 3 | t=N.002 | \u003CCleanupSystem> | alive v=Y | DestroyEntity(E:X:Y) | BeginSim | CB#2 | queued | queued |\n| 4 | t=N.003 | [SimGroup end] | alive v=Y | — | — | — | — | — |\n| 5 | t=N.004 | BeginSimECBSystem | alive v=Y | [CB#2 plays] DestroyEntity | — | CB#2 | after CB#1 | BEFORE CB#1 |\n| 6 | t=N.004 | BeginSimECBSystem | dead v=Y+1 | [CB#1 plays] AppendToBuffer → FAIL | — | CB#1 | entity alive | entityExists=False |\n```\n\n---\n\n## Helper Scripts\n\nThree read-only Python 3 scripts in `scripts\u002F`. Each outputs `file:line` evidence.\n\nRun from repo root:\n```sh\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_ecb_producers.py \u003Crepo-root>\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_destroy_paths.py \u003Crepo-root>\npython3 .claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_system_ordering.py \u003Crepo-root>\n```\n\nAll scripts:\n- Read `.cs` files recursively from `\u003Crepo-root>`\n- Use regex pattern matching only (no compilation, no execution)\n- Are read-only — no writes to the target repo\n- Have no network calls\n- Output structured tables to stdout\n\n---\n\n## Self-Check Before Proposing a Fix\n\n- [ ] Root-cause proof complete (all 7 checkboxes in Step 5 checked)\n- [ ] Frame timeline shows the actual ordering with discovered system names\n- [ ] Destructive producer identified with file:line evidence (not just \"probably\")\n- [ ] Guard-only fix explicitly considered and rejected with explanation\n- [ ] Fix type selected from decision tree\n- [ ] Fix does not require changing `[UpdateBefore\u002FAfter]` without architect approval\n- [ ] Fix does not add `state.Dependency.Complete()` without performance review\n- [ ] Fix does not remove `[BurstCompile]` (automatic [BLOCK: performance])\n- [ ] Validation plan covers: compilation + exception gone + dependent behavior preserved + cleanup still works\n",{"name":5,"metadata":54,"use-when":60,"platforms":61,"description":7,"do-not-use-when":66},{"security":55,"user-invocable":50,"platform-compat":56},"All helper scripts in scripts\u002F are static syntax-pattern scanners only. They read .cs files via regex — no code execution, no writes, no network calls. Safe to run on any DOTS codebase.",[57,58,59],"Unity Entities 1.0+","Entities 1.3.x (tested)","Entities 1.4.x (tested)","Load for unity-dots-dev and bug-investigation when a Unity console log contains:\n\"EntityCommandBuffer playback failed\", \"entityExists=False\", \"AppendDestroyedEntityRecordError\",\n\"Buffer does not exist on entity\", \"Component does not exist on entity\",\n\"Invalid deferred entity\", \"Duplicate AddComponent during playback\",\n\"SetComponent on missing component\", or \"DestroyEntity executed before another ECB command\".\nLoad when debugging ECB command ordering across multiple systems sharing a playback phase.\n",[62,63,64,65,37],"claude-code","codex","copilot","cursor","Do not load for MonoBehaviour optimization, ECS architecture design, NavMesh, Addressables,\nUI event listeners, timeline, or generic DOTS implementation. Do not load for tester, verifier,\nqa-tester, or architect roles. Not needed for Burst compilation errors (use burst-safety).\nNot needed for NativeContainer leaks (use memory-safety). Not needed for general ECB usage\nwithout playback failures (use ecs-job-patterns).\n","main","fe4746b9f07e6c7c2b6d3932002183af9b9f6fa2",".claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger",0,"https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team","https:\u002F\u002Fgithub.com\u002FdyCuong03","Game developer","2026-07-25 22:22:25",{"source":8,"skillName":5,"commands":76,"prompt":86,"zipAvailable":87},[77,80,83],{"tool":78,"command":79},"npx","npx skills add dyCuong03\u002Funity-agent-team --skill unity-dots-ecb-lifecycle-debugger",{"tool":81,"command":82},"bunx","bunx skills add dyCuong03\u002Funity-agent-team --skill unity-dots-ecb-lifecycle-debugger",{"tool":84,"command":85},"pnpm","pnpm dlx skills add dyCuong03\u002Funity-agent-team --skill unity-dots-ecb-lifecycle-debugger","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002FSKILL.md",true,[89,95,99],{"path":90,"resourceType":91,"resourceTypeDesc":92,"sizeBytes":93,"sourceHtmlUrl":94},"scripts\u002Ffind_destroy_paths.py","SCRIPT","脚本",11679,"https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_destroy_paths.py",{"path":96,"resourceType":91,"resourceTypeDesc":92,"sizeBytes":97,"sourceHtmlUrl":98},"scripts\u002Ffind_ecb_producers.py",13737,"https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_ecb_producers.py",{"path":100,"resourceType":91,"resourceTypeDesc":92,"sizeBytes":101,"sourceHtmlUrl":102},"scripts\u002Ffind_system_ordering.py",17707,"https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Funity-dots-ecb-lifecycle-debugger\u002Fscripts\u002Ffind_system_ordering.py",[104,129,153,175,193,212],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":49},"01M6KH55FFS00ET877QSMRYGX4","dots-update-groups","How to choose the right ECS system group and ordering so per-frame and per-fixed-step work is deterministic and never races its own readers. Covers InitializationSystemGroup \u002F SimulationSystemGroup \u002F PresentationSystemGroup \u002F FixedStepSimulationSystemGroup \u002F VariableRateSimulationSystemGroup, UpdateBefore \u002F UpdateAfter peer ordering, OrderFirst \u002F OrderLast group-boundary placement, RateManager, and the cross-group ordering trap. Use when adding an ISystem, fixing \"value visible one frame late\" bugs, or coupling simulation to a fixed timestep.","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fdots-program\u002Fscratch\u002Fwave-2-orchestrator-drafts\u002Fdots-update-groups\u002FSKILL.md",[],[111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128],"update","dots update groups","boundary","simulation","how","system","choose","work","use","never","peer","deterministic","how to","coupling","ecs","bugs","frame","value",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":49},"01M6KH50PWYEFQDCGYBZ0326F1","dots-transform-patterns","The Entities 1.x transform model — LocalTransform (writable input) vs LocalToWorld (system-owned matrix), Parent\u002FChild hierarchy, reparenting cost, uniform vs non-uniform scale (PostTransformMatrix), and when to opt out with custom transform systems. Use when designing parent\u002Fchild hierarchies, runtime reparenting (mount\u002Fdismount\u002Fsocket), or choosing transform components at the Baker boundary.","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fdots-program\u002Fscratch\u002Fwave-2-orchestrator-drafts\u002Fdots-transform-patterns\u002FSKILL.md",[],[136,137,138,139,113,116,140,141,119,142,143,144,145,146,147,148,149,150,151,152],"patterns","transform","dots transform patterns","components","mount","model","cost","runtime","systems","input","with","matrix","socket","at","child","custom","hierarchy",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":162,"publishedAt":49},"01M6KH4VW4MA14DQW4KQYPFT0S","dots-singleton-patterns","Model cross-system shared configuration and game state as a single-entity component with a strict single-writer contract. Covers RequireForUpdate gating, SystemAPI.GetSingleton \u002F GetSingletonRW \u002F HasSingleton \u002F TryGetSingleton, bake-time vs runtime-created vs ECB-system singletons, the \"exactly one entity\" runtime invariant, and the single-writer rule. Use when designing frame-stable global config, shared mutable state, or any component intended to exist on exactly one entity.","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fdots-program\u002Fscratch\u002Fwave-2-orchestrator-drafts\u002Fdots-singleton-patterns\u002FSKILL.md",[159],{"categoryNo":160,"categoryName":161,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000037","律师与法务",[136,163,164,47,165,166,167,116,141,119,168,169,170,143,171,172,146,127,173,174],"singleton","dots singleton patterns","config","state","game","writer","time","shared","contract","as","ecb","gating",{"skillNo":176,"name":177,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":181,"publishedAt":49},"01M6KH4PR076AYNDZHD63HHWX6","dots-hybrid-bridge","The one-way bridge between DOTS-owned runtime state and Unity-owned presentation. Covers UnityObjectRef for managed asset refs in components, the DOTS-writes \u002F Unity-reads ownership rule, when to use managed IComponentData vs UnityObjectRef vs CompanionComponent, baker-bridge vs runtime-bridge, and SubScene boundary rules. Use when an entity must reference Unity assets (Mesh, Material, AudioClip, ScriptableObject), a MonoBehaviour view must read entity state, or input\u002FUI must trigger ECS work.","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fdots-program\u002Fscratch\u002Fwave-2-orchestrator-drafts\u002Fdots-hybrid-bridge\u002FSKILL.md",[],[182,183,184,185,139,166,113,186,187,118,42,188,119,143,189,30,145,190,191,192],"bridge","hybrid","dots hybrid bridge","mesh","assets","Rules","view","trigger","material","for","managed",{"skillNo":194,"name":195,"nameZh":6,"description":196,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":197,"categories":198,"keywords":199,"publishedAt":49},"01M6KH4FGRQ9AP2ND5H5HX4D83","dots-event-driven-ecs","Model one-frame events and external requests in ECS without dual ownership, polling, or persistent state leaks. Covers request-tag pattern with ECB, enableable command components (no structural change), event buffers (IBufferElementData), explicit consumer ownership, one-frame latency rules, and the banned C# event \u002F UnityEvent \u002F static bus anti-patterns. Use when input\u002FUI\u002Fnetwork must trigger ECS work, when a one-frame signal fans out to N consumers (damage, hit, collision), or when state changes must be processed exactly once.","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002Fworkspace\u002Fdots-program\u002Fscratch\u002Fwave-2-orchestrator-drafts\u002Fdots-event-driven-ecs\u002FSKILL.md",[],[200,201,125,202,203,139,204,205,206,141,118,43,207,136,208,209,145,210,34,211],"event driven","driven","event","dots event driven ecs","change","ui","network","anti-patterns","pattern","structural","events","request",{"skillNo":213,"name":214,"nameZh":6,"description":215,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":216,"categories":217,"keywords":227,"publishedAt":49},"01M6KH4BWRGCEBJ8PKCKCSGT33","valid_skill","A complete, well-formed test fixture skill for SkillHub validation testing. Covers basic task routing and code review for Unity projects.","https:\u002F\u002Fgithub.com\u002FdyCuong03\u002Funity-agent-team\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fvalid_skill\u002FSKILL.md",[218,221,224],{"categoryNo":219,"categoryName":220,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":222,"categoryName":223,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":225,"categoryName":226,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[228,229,230,231,232,233,234,235,236,237,238,239,240,241,30,242,191],"valid skill","valid","code review","testing","review","test","routing","code","validation","projects","fixture skill","task","fixture","basic","complete"]