> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase20-session06-file-mutation-core/spec.md).

# Session Specification

**Session ID**: `phase20-session06-file-mutation-core` **Phase**: 20 - Orchestration Actionability Execution **Status**: Not Started **Created**: 2026-06-28 **Package**: null **Package Stack**: mixed TypeScript across `packages/protocol` and `apps/server`

***

## 1. Session Overview

This session creates the core file mutation contract and server manager needed to preview, apply, audit, and roll back real workspace file changes. It turns the current file-intent coordination layer into a safe executable foundation by adding request/result types, strict repo-relative path handling, preflight hashes, backups, rollback metadata, conflict checks, and compact execution-run records.

It is next because Phase 20 sessions 01-05 have made capability labels truthful and have delivered terminal, Git, and campaign execution behavior. File capabilities still remain approved-not-executing until a real mutation path exists. Session 06 builds that path at the protocol and server-manager layer so Session 07 can wire guarded actions, queue tasks, campaigns, and web controls to it without inventing filesystem behavior in route handlers or UI code.

The session is intentionally backend-focused. It must prove write, edit, delete, move, rename, rollback, stale hash, conflict, backup failure, and path rejection behavior with temp-directory server tests. It must not promote file executors to `executor_ready` or add broad UI apply controls; those are Session 07 integration responsibilities.

***

## 2. Objectives

1. Define protocol-owned file mutation request, result, backup, rollback, and safe execution metadata for read, write, edit, delete, move, and rename operations.
2. Implement `FileMutationManager` with repo-relative validation, symlink escape rejection, traversal rejection, absolute path rejection, URL-like input rejection, NUL rejection, and generated or ignored directory policy checks.
3. Apply mutating operations only after expected hash validation, conflict checks, and successful backup creation, with duplicate-trigger prevention and compensation on failure.
4. Record compact file execution evidence and provide rollback for supported write, edit, delete, move, and rename operations without leaking file contents or patch bodies into broad rows, events, logs, docs, or diagnostics.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase20-session01-truthful-capability-baseline` - Keeps file executor capability labels truthful until real mutation and integration are proven.
* [x] `phase20-session05-campaign-dag-recovery` - Confirms the current phase sequence is complete through the campaign DAG slice before file mutation begins.

### Required Tools Or Knowledge

* Node 26.2.0 and npm 11.16.0 from `.spec_system/CONVENTIONS.md`.
* Existing `CommandCenterExecutionRun`, file intent contracts, `FileIntentManager`, `OrchestrationCommandCenterManager`, and command-center redaction patterns.
* Node filesystem APIs, `crypto` SHA-256 hashing, `diff` package availability, Vitest temp-directory testing, and current protocol parser style.

### Environment Requirements

* Local repo checkout with npm workspaces installed.
* Writable temp directories for server tests.
* No hosted credentials, provider credentials, analytics, Worker proxy, remote execution, Docker runtime, browser UI server, or new native dependency is required.

***

## 4. Scope

### In Scope (MVP)

* Operators and later orchestrators can request bounded file mutation previews - Add protocol parser coverage for safe request/result metadata and blocked raw-field rejection.
* The server can safely resolve workspace paths - Enforce repo-relative paths under an approved root with symlink, traversal, absolute path, URL-like input, NUL, and policy-directory rejection.
* The server can mutate real files through guarded manager calls - Implement read, write, edit, delete, move, and rename behavior with expected hash guards and no mutation on preflight failure.
* The server can recover supported mutations - Create backups before mutating, retain backup ids and metadata, and roll back write, edit, delete, move, and rename when a backup exists.
* The server can coordinate with active file intents - Block mutating operations when active conflicting file intents exist unless an explicit override or cleared intent path is supplied.
* The server can audit file mutations compactly - Record execution runs and result metadata with path labels, operation, hashes, changed byte count, backup id, and rollback state only.

### Out Of Scope (Deferred)

* Guarded file approval execution - Reason: Session 07 owns replacing metadata-only guarded file behavior with `FileMutationManager` adapters.
* Queue or campaign file executable dispatch - Reason: Session 07 owns task and campaign integration through `TaskExecutionCoordinator`.
* Web file preview, apply, conflict, result, and rollback UI - Reason: Session 07 owns product-surface wiring after the manager is proven.
* Rich editor or Monaco workflows - Reason: The MVP needs safe filesystem mutation and rollback, not an editor surface.
* Remote, hosted, Worker, or container-backed file mutation - Reason: Phase 20 remains local-first and no-claim for hosted or remote execution.
* Database, persistence schema, or migration work - Reason: Current command-center state is manager-owned in local runtime memory.

***

## 5. Technical Approach

### Architecture

Protocol remains the shared contract boundary. File mutation request and result types should live with command-center contracts in `packages/protocol/src/orchestrationCommandCenter.ts`, because they are command-center execution metadata and must use the same parser, safe id, relative path, blocked-field, and compact error patterns as existing execution runs and file intents.

Server behavior belongs in a new `apps/server/src/managers/fileMutationManager.ts`. The manager should accept an approved workspace root and FactionOS state root, normalize and realpath-check all targets, run conflict checks through `FileIntentManager`, create backups under local FactionOS state before any write path, mutate the filesystem, and record compact execution evidence through `OrchestrationCommandCenterManager`. Route handlers and UI components should not own file mutation rules.

Mutating operations should use a preflight-first flow: validate request, resolve source and destination paths, reject blocked paths, compute current hashes, require `expectedSha256`, check file-intent conflicts, create backup metadata, perform the mutation, compute after metadata, save an execution run, and return safe result fields. Rollback should use stored backup metadata and should itself be idempotent, audited, and failure-explicit.

### Design Patterns

* Protocol-first contracts: Shared request, result, rollback, and safe metadata parsing lands before server manager behavior.
* Manager-owned runtime boundary: Path validation, hashing, backup, mutation, rollback, idempotency, and execution evidence stay in `FileMutationManager`.
* Broad-summary plus scoped-detail split: File contents and patch bodies remain request-scoped only; broad execution records expose operation, labels, hashes, counts, backup id, and rollback state.
* Fail closed before mutation: Validation, conflicts, stale hashes, blocked paths, and backup failures return explicit errors without touching workspace files.
* Existing file-intent coordination: Active write-path conflicts are checked through `FileIntentManager` instead of duplicating coordination state.

***

## 6. Deliverables

### Files To Create

| File                                              | Purpose                                                                                                                            | Est. Lines |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/managers/fileMutationManager.ts` | Core file mutation, validation, backup, execution evidence, and rollback manager.                                                  | \~560      |
| `apps/server/tests/fileMutationManager.test.ts`   | Temp-directory acceptance coverage for mutations, rollback, conflict, path rejection, stale hashes, backup failure, and redaction. | \~520      |
| `packages/protocol/tests/fileMutation.test.ts`    | Focused protocol coverage for file mutation request/result parsing and blocked raw-field rejection.                                | \~180      |

### Files To Modify

| File                                                         | Changes                                                                                                                  | Est. Lines |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `packages/protocol/src/orchestrationCommandCenter.ts`        | Add file mutation operation, request, result, backup, rollback, safe execution metadata, and parser helpers.             | \~260      |
| `packages/protocol/tests/orchestrationCommandCenter.test.ts` | Cover any shared executor vocabulary or execution-run attachment changes needed for file metadata.                       | \~60       |
| `apps/server/src/managers/orchestrationCommandCenter.ts`     | Preserve compact file execution metadata in event entries if execution attachments are extended for file runs.           | \~40       |
| `apps/server/tests/commandCenterManager.test.ts`             | Prove command-center execution records keep file metadata compact and exclude content or patch bodies.                   | \~70       |
| `apps/server/README_server.md`                               | Document the manager-level file mutation boundary, backup location, redaction rules, and Session 07 integration handoff. | \~35       |
| `docs/api/README_api.md`                                     | Document that file mutation contracts are manager-level until guarded/queue/campaign integration ships.                  | \~35       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Write, edit, delete, move, and rename operations mutate real files in temp-directory tests.
* [ ] Read and preview/preflight operations return safe metadata without mutating files.
* [ ] Rollback restores prior content or prior path for write, edit, delete, move, and rename when a backup exists.
* [ ] Conflict, stale hash, backup failure, path escape, symlink escape, absolute path, traversal, URL-like input, NUL input, generated directory, and ignored directory cases do not mutate files.
* [ ] Execution runs record compact before/after metadata without file contents, patch bodies, broad absolute paths, tokens, secrets, provider payloads, or raw diagnostics.

### Testing Requirements

* [ ] Protocol tests cover file mutation request/result parsing, path validation, rollback metadata, and blocked raw-field rejection.
* [ ] Server manager tests cover successful mutations, rollback, stale hashes, active file-intent conflicts, backup failure, path rejection, symlink escape, idempotency, compensation on partial failure, and redaction.
* [ ] Focused protocol and server typechecks pass.
* [ ] Focused Vitest tests for file mutation pass before broader gates.

### Non-Functional Requirements

* [ ] All filesystem operations stay under the approved workspace root or FactionOS state backup root.
* [ ] Mutating operations are duplicate-trigger protected by idempotency keys or stable operation keys.
* [ ] Backup and rollback metadata is local-only and does not imply trusted unified erasure.
* [ ] Existing terminal, Git, queue, campaign, guarded-action, and file-intent behavior remains compatible.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] No product claim promotes file executors to `executor_ready` before Session 07
* [ ] Focused protocol, server, root quality, and `git diff --check` commands pass

***

## 8. Implementation Notes

### Working Assumptions

* Cross-package scope is intentional: The analyzer reports `package: null`, the selected stub lists `packages/protocol` and `apps/server`, and the work spans shared contracts plus a server manager. Planning can proceed with `Package: null` because all task paths are repo-root-relative and the affected packages are explicit.
* Session 06 is the manager and contract core, not executor integration: The session stub excludes queue, campaign, and guarded-action file executor integration, while Session 07 explicitly owns those product paths. Planning can proceed by proving manager behavior and keeping file capabilities approved-not-executing until integration.
* Backups are local recovery artifacts, not erasure evidence: Security and considerations documents keep trusted unified erasure as no-claim, so this session may create local backup metadata only with explicit redaction and documentation.

### Conflict Resolutions

* The Phase 20 appendix Slice 3 includes replacing file executor registry entries with real adapters, while the Session 07 stub owns registry, guarded action, queue, campaign, and web integration. The chosen interpretation is to implement `FileMutationManager` and safe protocol metadata in Session 06, then leave registry promotion and adapter wiring for Session 07.
* Existing command-center executor vocabulary has `file_move` but no separate `file_rename`, while the Session 06 stub requires both move and rename operations. The chosen interpretation is to distinguish `move` and `rename` in file mutation request/result metadata while preserving broad execution summaries as file-family compact metadata unless implementation proves an additional executor kind is required.

### Key Considerations

* \[P19] Executor claims are family-scoped: File executor readiness must remain unavailable or approved-not-executing until Session 07 proves guarded/queue/campaign execution.
* \[P19] Scoped detail stays separate from broad rows: File contents, patch bodies, diffs, absolute paths, tokens, secrets, provider payloads, and raw diagnostics must not enter broad execution rows, WebSocket events, docs, or logs.
* \[P03-packages/protocol] Protocol leads cross-package work: Shared mutation contracts and parser helpers should land before the server manager consumes them.
* \[P19] Command-center state is manager-owned: Idempotency, execution-run updates, redaction, and bounded snapshots should remain in managers.
* \[P07] Redaction is boundary-specific: Backup metadata, file paths, execution records, route responses, events, logs, and docs each need explicit minimization.

### Potential Challenges

* Symlink escapes can bypass string-only path checks: Resolve real paths for existing source, destination parent, and backups before mutation and reject anything outside the approved roots.
* Backup creation can fail after preflight: Treat backup failure as a hard no-mutation result and test that file contents remain unchanged.
* Mutation failure after backup can leave partial state: Record failure and offer rollback where possible, with compensation for move/rename partial outcomes.
* Conflict checks can drift from file-intent semantics: Reuse `FileIntentManager.checkConflicts` and document explicit override behavior rather than adding a second conflict model.
* Broad metadata can accidentally include raw paths or patch content: Keep result summaries compact and assert serialized broad responses do not contain synthetic secret, content, patch, or absolute path markers.

### Relevant Considerations

* \[P19] **Executor claims are family-scoped**: This session creates the proof foundation but must not mark the file family ready.
* \[P19] **Scoped detail stays separate from broad rows**: File content and patch detail stays out of execution rows and event entries.
* \[P03-packages/protocol] **Protocol leads cross-package work**: File mutation contracts land in protocol before server behavior relies on them.
* \[P19] **Command-center state is manager-owned**: File mutation execution evidence stays manager-owned.
* \[P06-S07-ERASURE] **Trusted unified erasure remains no-claim**: Backups and rollback metadata do not close trusted erasure.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* State-mutating file operations running twice or running after stale preflight data.
* Files changing after conflict, backup failure, path escape, stale hash, or malformed input errors.
* File contents, patch bodies, absolute paths, tokens, secrets, provider payloads, or raw diagnostics leaking into broad execution records, events, docs, logs, or test snapshots.

***

## 9. Testing Strategy

### Unit Tests

* Protocol parser tests for read, write, edit, delete, move, rename, rollback request/result metadata, safe path labels, expected hash requirements, and blocked raw fields.
* Server manager tests for repo-relative resolution, symlink escape rejection, traversal rejection, URL-like rejection, NUL rejection, generated/ignored policy rejection, and stale hash handling.
* Server manager tests for backup creation, backup failure, write/edit/delete/move/rename mutation, rollback restore, idempotent duplicate responses, and failure compensation.

### Integration Tests

* `FileMutationManager` tests with injected `FileIntentManager` and `OrchestrationCommandCenterManager` to prove conflict blocking, execution-run creation, compact event metadata, and no raw content leakage.
* Command-center manager tests for any new file execution attachment or event metadata shape.

### Runtime Verification

* Temp-directory Vitest scenarios create a workspace, mutate actual files through the manager, verify on-disk results, roll back, and assert blocked cases leave files unchanged.

### Edge Cases

* Existing file write with matching and stale `expectedSha256`.
* New file write with expected empty or missing revision semantics.
* Edit operation whose search/patch target is missing.
* Delete of an already missing file.
* Move or rename where the destination exists.
* Source path is a symlink pointing outside the workspace.
* Destination parent is a symlink pointing outside the workspace.
* Path includes absolute prefix, `..`, URL-like scheme, backslash where disallowed, or NUL.
* Backup directory cannot be created or written.
* Rollback is requested twice for the same backup id.
* Active file intent conflict exists for the target path.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase20-session01-truthful-capability-baseline`
* Depended by: `phase20-session07-file-executor-integration`

***

## Next Steps

Run the `implement` workflow step to begin implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase20-session06-file-mutation-core/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
