# CRASH REMEDIATION ENGINE (CORE PARADIGMS) ## 0. EXPLICIT TRIGGER CONDITIONALS & PURGE DETECTION [TRIGGER_LOGIC_START] EXECUTE the [RECOVERY_PROTOCOL_START] block immediately if ANY of the following conditions are met: 1. **EXPLICIT USER TRIGGER:** User prompt contains "RECOVER", "SYNC", "STATUS", "EMERGENCY", or "EXECUTE EMERGENCY PROTOCOL". 2. **IN MEDIAS RES (PREFIX PURGE DETECTED):** Visible conversation history begins mid-stream (e.g. starts with intermediate tool outputs, compile errors, or partial turns without the original session-initiating user prompt). This is the definitive indicator of an Antigravity server-side prefix wipe. 3. **ACTIVE TRANSACTION MISMATCH / DRIFT:** The current task or target file does not match the active `[~]` milestone in `.agent-state.md`. 4. **UNINITIALIZED STATE:** `.agent-state.md` contains unspecialized generic placeholders (`[Insert ...]`, `[Rule ...]`). TRIGGER ACTION: 1. HALT all active codebase and project asset mutations instantly. 2. FORCE memory alignment to this file and `.agent-state.md`. 3. EXECUTE the [RECOVERY_PROTOCOL_START] block sequentially. CONTINUOUS INVARIANT (ALL OTHER TURNS): Never modify any project file without verifying `.agent-state.md` in the current turn and registering the target file under Section 4 with its intended mutation. [TRIGGER_LOGIC_END] ## 1. EMERGENCY ONBOARDING MANDATE [RECOVERY_PROTOCOL_START] CRITICAL ENVIRONMENT CACHE PURGE DETECTED. Execute the emergency onboarding protocol immediately: 1. Locate and read the file `.agent-state.md` in the project root directory. If the file does not exist, initialize it from the base template. 2. **ATOMIC SPECIALIZATION & PRE-FLIGHT AUDIT:** Scan the contents of `.agent-state.md`. If generic placeholder brackets (e.g., `[Insert ...]`, `[Rule ...]`, or raw examples) are detected within any block, you are authorized to self-onboard and specialize the file layout: * **Workspace Discovery:** Execute an intensive local filesystem parse using directory mapping and file reading tools. Identify the exact project identity, underlying directory architecture, target runtimes/toolchains, version control states, and foundational configuration assets. * **In-Memory Payloading:** Assemble the entire specialized `.agent-state.md` text string completely within internal memory buffers before initiating a write execution to prevent truncation loops. * **Structural Preservation Rule:** As an exempted System Management Metadata Operation, execute a single atomic write transaction to commit the payload. You MUST preserve all structural bolding, markdown headers, brackets `[...]`, and token blocks (`[CONTEXT_FENCE_START]`, etc.) exactly as written. Only replace the literal text inside the placeholder scopes with absolute workspace realities. * **Rule Extraction Mandate:** Derive concrete, non-negotiable operational rules directly matching the local repository architecture and project conventions to populate the 'Strict Operational Rules' block inside Section 1. 3. **Freeze Memory Fields:** Lock your active model short-term memory to the exact boundaries defined inside [CONTEXT_FENCE_START] and [WORKSPACE_DIFF_START] within the newly specialized version of `.agent-state.md`. 4. **Execute Workspace Audit:** Execute Step 2 of this block (Physical Workspace Audit) to check for file corruption or mutation interruptions. 5. **Telemetry Status Report:** Output this standardized telemetry status report in your response before executing any further codebase mutations: ```text [CONTEXT_GUARD_TELEMETRY] * Workspace: [Workspace Identifier] * Engine State: [SYNCHRONIZED | RECOVERY_COMPLETE | SPECIALIZED] * Active Milestone: [~] State N: [Description] * Audited Assets: [Path]: [VERIFIED_INTEGRAL | ROLLED_BACK_SAFE | PENDING_VERIFICATION] * Next Authorized Mutation: [Exact planned change] ``` Do not write, refactor, or alter any codebase source files until this specialization and physical file audit loop is completed and printed to the user. [RECOVERY_PROTOCOL_END] ## 2. SYSTEM EVALUATION ROUTINE [PHYSICAL_AUDIT_START] * **Physical Workspace Audit Execution:** Evaluate ALL target paths explicitly listed within the Section 4 `[WORKSPACE_DIFF_START]` block of `.agent-state.md` as a singular batched pass. * Initialize an internal session tracker: `ROLLBACK_TRIGGERED = false`. * **FOR EACH** path listed where `Physical Verification State` is `PENDING_VERIFICATION`: * Inspect the physical file content on disk. * **IF** the target asset does not exist on disk: - *If Intended Target State specifies NEW file creation:* Retain `Physical Verification State` as `PENDING_VERIFICATION` and proceed to Phase 2 (Codebase Mutation). - *If intended mutation was modifying an EXISTING file:* Target file is missing/deleted! Restore from backup or Git. * **ELSE IF** the code on disk is half-written, broken, or corrupted: 1. **RESTORE ASSET (Rollback Priority):** - *Priority A (Zero-Token Disk Backup):* If a backup file exists in `.agent-backup/` or under `Backup Reference`, overwrite the target asset with that backup file on disk. - *Priority B (Git Tracking):* If inside a git repository, restore clean state using git checkout/restore. - *Priority C (Inline Raw Snapshot):* If `` tags exist, extract literal text and overwrite the target asset. 2. Update the state log: As an exempted System Management Metadata Operation, rewrite that specific file's metadata block inside Section 4 of `.agent-state.md`. Change `Physical Verification State` to `ROLLED_BACK_SAFE`. 3. Set internal tracker: `ROLLBACK_TRIGGERED = true`. * **ELSE IF** the disk state perfectly matches the structural design defined in `Intended Target State`: 1. Update the file's status block to `VERIFIED_INTEGRAL`. * **ELSE IF** the disk state matches the pre-mutation baseline (mutation not yet initiated): 1. Retain `Physical Verification State` as `PENDING_VERIFICATION` and proceed to execute Phase 2 (Codebase Mutation). * **POST-AUDIT EVALUATION FENCE:** * **IF** `ROLLBACK_TRIGGERED == true`: 1. Scan the `[TRANSACTION_TRACKER_START]` block inside `.agent-state.md`. Locate any line item prepended with the active marker `[~]`. 2. Revert that active marker from `[~]` back to the unstarted state `[ ]`. Do not alter the trailing descriptive text of the state milestone. 3. Halt operations and print: `RECOVERY_ROLLBACK_COMPLETE: One or more corrupted workspace targets were detected. All affected targets have been cleanly rolled back to safe baselines, and transaction state is reset to unstarted.` * **ELSE**: 1. Allow operations to continue normally using active parameters. * **Strict Isolation Fence:** Treat all unlisted workspace vectors, directories, and files as strictly locked and inaccessible. Do not attempt to refactor anomalies outside of Section 4 (`[WORKSPACE_DIFF_START]`) in `.agent-state.md`. * **Preserve Tokens:** Retain all markdown structural headers, syntax brackets `[...]`, system notices, and block bounding tags exactly as written whenever updating either sync file. [PHYSICAL_AUDIT_END] ## 3. ATOMIC 3-PHASE MUTATION LIFECYCLE [MUTATION_LIFECYCLE_START] During all active development turns, you must execute file mutations strictly through this 3-phase atomic protocol: * **PHASE 1: PRE-MUTATION REGISTRATION (Before Touching Code)** 1. Check if the target file exists in Section 4 (`[WORKSPACE_DIFF_START]`) of `.agent-state.md` with status `PENDING_VERIFICATION`. 2. If not registered: a. Create safety backup: - *If creating a NEW file:* Set `Backup Reference: [NEW_FILE_CREATION]`. No pre-backup required. - *If modifying an EXISTING file inside a clean Git repo:* Git HEAD tracking is sufficient. - *If modifying an EXISTING file and NOT a Git repo (or working tree is dirty):* ALWAYS copy the target file to `.agent-backup/` as the physical safety baseline. b. Update `.agent-state.md`: - Ensure active milestone in Section 2 is marked `[~]`. - Add target file entry to Section 4 with `Physical Verification State: PENDING_VERIFICATION` and `Backup Reference`. - *Multi-file tasks:* Register ALL affected target files in Section 4 before executing the first code modification. 3. Do not combine this registration with the code edit in an untracked manner. * **PHASE 2: CODEBASE MUTATION** 1. Execute the code change using `replace_file_content`, `write_to_file`, or `multi_replace_file_content`. 2. Strictly adhere to the scope registered in Phase 1. Do not mutate unlisted files. * **PHASE 3: POST-MUTATION VERIFICATION & RECONCILIATION** 1. Run syntax or build verification (e.g., compile checks or test runs) if applicable. 2. Once verified functional: a. Update `.agent-state.md`: Set `Physical Verification State: VERIFIED_INTEGRAL`. b. If milestone task is finished, mark milestone `[x]` in Section 2 and set next milestone `[~]`. c. Ledger Compacting: Completed, verified file blocks can be cleared from `[WORKSPACE_DIFF_START]` to keep the ledger compact and save context tokens. 3. **IF VERIFICATION FAILS (e.g., compile/build syntax error or test failure):** - Retain `Physical Verification State: PENDING_VERIFICATION` under the active `[~]` milestone. - You are explicitly authorized to make iterative correction edits to the registered file(s) to resolve the error. - Once resolved and verified, proceed to mark `VERIFIED_INTEGRAL` and commit the milestone `[x]`. [MUTATION_LIFECYCLE_END]