# TeamForge engineering change process This guide defines how TeamForge changes should be planned, implemented, validated, documented, and reviewed. The goal is not to add ceremony. The goal is to avoid a common failure mode in AI-assisted and fast-moving development: implementation begins before the important invariants, failure modes, and required evidence have been identified. For substantial changes, **plan first, then implement**. ## The change lifecycle Use this sequence for changes that affect behavior, architecture, security, release tooling, persistence, networking, Unity state, project transfer, or other non-trivial surfaces: 1. **Define the problem** — describe the observed behavior, desired outcome, or missing capability. 2. **Classify the change** — identify affected subsystems and risk level. 3. **Identify invariants** — list behavior that must remain true after the change. 4. **List failure modes** — consider how the change can fail, race, partially complete, or leave stale state. 5. **Choose required evidence** — decide what automated, Unity, chaos, release, and physical tests are needed before implementation begins. 6. **Implement the smallest coherent change** — avoid unrelated cleanup unless required for correctness. 7. **Validate** — run the planned evidence and record what actually passed, failed, or was not run. 8. **Update canonical documentation** — follow `docs/DOCUMENTATION_GUIDE.md`; do not duplicate volatile state across documents. 9. **Review release impact** — decide whether the change affects source only, compatibility, protocols, packaged bytes, field gates, or release identity. 10. **Merge only the claims supported by evidence** — a green unit test does not prove a physical two-PC workflow, and source CI does not prove an exact packaged ZIP. Use [`docs/templates/CHANGE_PLAN.md`](templates/CHANGE_PLAN.md) for a reusable planning skeleton. ## When a written change plan is expected A written plan is strongly recommended when any of the following is true: - the change modifies realtime authority, locks, revisions, replay, conflict handling, reconciliation, or reconnect behavior; - the change writes, moves, extracts, activates, trusts, or launches project files; - authentication, signatures, hashes, identities, secrets, invite handling, or path safety are involved; - the change modifies protocol/message shape or compatibility behavior; - multiple processes or runtimes must agree on the change; - the change modifies the Windows Launcher, packaged Runtime, release manifests, release workflow, or artifact verification; - the change fixes a race, lifecycle bug, shutdown bug, data-integrity problem, or physical-field failure; - a new Unity synchronization surface is introduced; - rollback or recovery behavior matters; - the implementation is large enough that a reviewer cannot easily infer intent from the diff. A typo fix, link correction, isolated comment improvement, or obvious test-only cleanup usually does not need a separate plan. ## Risk levels ### Low Examples: - documentation-only changes that do not alter release claims; - test-message wording; - isolated developer tooling with no release/runtime effect; - non-behavioral refactors with strong existing coverage. Expected evidence is usually focused validation plus documentation/workflow validation where relevant. ### Medium Examples: - normal Server or Project Peer behavior changes; - diagnostics and UX changes; - non-authority Unity Editor behavior; - build tooling changes that do not alter packaged trust or identity; - dependency/runtime updates within an already supported compatibility line. Expected evidence normally includes focused tests and the subsystem's standard CI lane. ### High Examples: - authority, locking, revision, replay, or conflict semantics; - persistent/staged/Active Project state; - path containment or filesystem mutation; - authentication, trust, signature, hash, or identity checks; - project transfer integrity and activation; - reconnect/recovery correctness; - release packaging and exact artifact identity; - arbitrary or untrusted network/project input; - a new synchronized Unity data model. High-risk changes should explicitly list invariants, negative cases, rollback/recovery behavior, and the strongest practical automated evidence. Physical field evidence remains separate when the real environment is part of the failure surface. ## Core invariants to consider Not every change touches every invariant. A change plan should name the relevant ones instead of copying this list mechanically. ### Authority and ordering - The Server remains authoritative for supported realtime collaborative state. - A stale or replayed operation must not silently become a newer authoritative mutation. - Lock/ownership state must not produce two simultaneous authoritative owners for the same protected operation. - Reconnect and late join must converge toward current authoritative state without inventing local authority. ### Identity - Saved Unity objects and session-created objects must not be silently confused. - Project, Session, Baseline, Owner, Publisher, manifest, and Active revision identities remain explicit where required. - A convenience path/alias must not become a second unverified project identity. ### Filesystem and activation - Untrusted paths cannot escape their allowed managed roots. - Failed or interrupted transfer must not destroy a previously verified Active revision. - Activation occurs only after the required integrity/trust checks succeed. - Temporary/staging state must not be mistaken for verified Active state. ### Security and secrets - Fail-closed checks must not be weakened only to make a workflow succeed. - Credentials, access codes, tokens, private keys, and private machine-local data must not enter public logs, invites, artifacts, or diagnostics. - Untrusted network/project input must be bounded and validated before use. ### Release identity - Source identity, product version, release ID, candidate tag, and byte-level artifact identity are distinct concepts. - A rebuilt/repacked ZIP is a new byte-level artifact even if the product version does not change. - Generated runtime/launcher files are not canonical public source merely because they exist in a packaged candidate. ## Test selection Do not optimize for the largest number of tests. Choose tests that can falsify the risky claim. ### Documentation / repository policy Use when documentation, workflows, repository policy, source layout, or canonical information ownership changes. Typical checks: - `npm run validate:docs` - `npm run validate:engineering` - `npm run validate:workflows` - `npm run validate` ### Server Use for session, authority, authentication, WebSocket, presence, revision, or coordinator behavior. Typical evidence: - focused unit/integration tests; - Server test suite; - malformed/replay/stale input tests when relevant; - authority/recovery chaos for authority-sensitive changes. ### Project Peer / project transfer Use for transfer, resume, manifests, chunks, trust, activation, staging, path safety, or Host/Guest orchestration. Typical evidence: - Project Peer tests; - negative path/identity/hash cases; - transfer interruption/resume E2E; - previous-Active preservation checks; - packaged/runtime validation when release behavior changes. ### Unity Editor collaboration Use for Presence, Transform, Lock, Hierarchy, Component, Inspector, selection, reconnect, Unity lifecycle, or Scene behavior. Typical evidence: - focused EditMode tests; - real TeamForge Server E2E where authority/protocol behavior matters; - late-join/reconnect checks where state convergence matters; - A/B or A/B/C contention/convergence scenarios; - physical two-PC validation only when the environment/network/OS/Unity interaction is part of the claim. ### Launcher / release Use for packaged Runtime, .NET Launcher, handoff, update, path resilience, release manifests, ZIP construction, or artifact verification. Typical evidence: - Launcher Core tests; - runtime-loader tests; - fresh staged-tree validation; - exact ZIP/hash verification; - Windows path/environment tests; - artifact provenance/attestation where available. ## Evidence classes are not interchangeable Keep these distinctions explicit: - **unit/integration tests** prove the exercised implementation logic; - **Unity automation** proves the exercised Editor/runtime path under that automation environment; - **chaos/property testing** explores ordering/state combinations but does not reproduce every physical environment; - **same-machine multi-project testing** strengthens peer/state evidence but shares one OS/hardware/network stack; - **physical field testing** proves the exact physical scenario that was run; - **release validation** proves the exact packaged artifact that was validated; - **static/security analysis** finds classes of defects but is not an independent security audit. Never upgrade one evidence class into another in release claims. ## Change-plan rules A useful plan should answer: - What exactly is wrong or missing? - What is in scope? - What is deliberately out of scope? - Which processes/modules own the affected state? - Which invariants must remain true? - What can fail halfway through? - What can race or arrive out of order? - What happens after disconnect/restart/retry? - What is the rollback/recovery behavior? - Which tests would prove the proposed fix is wrong if it is wrong? - Which claims cannot be automated and need field evidence? - Does this change alter compatibility, protocol, artifact identity, or release state? - Which canonical documents need updates? Do not turn the plan into a prediction that everything will work. The plan describes hypotheses, constraints, and required evidence. ## Pull-request expectations The PR should be understandable as the result of the plan rather than as a raw implementation dump. For substantial changes, the PR should make clear: - problem and intended outcome; - risk classification; - important invariants/failure modes; - implementation summary; - actual tests/evidence; - tests not run or evidence still missing; - security/data-integrity/recovery implications; - documentation impact; - release/field-gate impact. The repository PR template is intentionally aligned with these fields. ## Maintainability and decomposition Optimize for **clear ownership and change locality**, not for either minimum file count or minimum line count. A maintainer should be able to predict where a behavior lives without opening a monolith or traversing a maze of tiny forwarding files. Use these rules when adding or extracting production code: - split by a stable responsibility, lifecycle, dependency direction, trust boundary, protocol boundary, platform boundary, or independently testable policy — not merely because a file crossed a line-count target; - keeping tightly coupled code together is acceptable when extraction would hide control flow or create indirection without a real owner; - C# one-type-per-file is normal, especially around Unity and Launcher code, but avoid clusters of tiny `Helper`/`Util`/forwarder files that must all be opened to understand one operation; - if several small files represent one concept, either keep them under a meaningful component/subdirectory with a clear public surface or fold trivial wrappers back into the cohesive owner; - when a new responsibility moves to another file/module, update `CODEMAP.md` when that change materially affects navigation; - prefer existing subsystem boundaries — Unity Editor UI/connection/authority/sync, Server authority/coordinator, Project Peer transfer/filesystem/trust, Launcher UI/Core/recovery — over generic cross-cutting buckets such as `Helpers` or `Utils`; - prefer semantic/domain boundaries over superficial code similarity. Similar DTO shapes, state machines, retry loops, or helper logic do not by themselves justify merging concepts that carry different authority, lifecycle, invariants, or reasons to change; - before creating a shared abstraction, ask whether the participating code is actually the same concept in TeamForge product language. If not, preserve the distinction and tolerate small duplication rather than erasing meaning; - use established TeamForge terms consistently across code, tests, protocol/schema names, diagnostics, and docs. When two similar concepts are intentionally separate, record the distinction in CODEMAP.md or the owning architecture guide so future maintainers and coding agents do not simplify the boundary away; - do not expand an open PR indefinitely because adjacent cleanup is visible. Finish the stated objective and required correctness/security prerequisites, then move independent improvements to follow-up work. The automated maintainability reviewer is intentionally **warning-only**. Current review triggers are approximately **800 lines** for a cohesion check, **1,200 lines** for a strong extraction review when an already-large file grows, a broad production diff around **15 files or 1,000 added lines**, and a same-directory burst of **5+ new production code files under 100 lines**. These numbers are signals, not limits or targets. Generated/build output, tests, Unity artifacts, and XAML layout files are excluded from the fragmentation signal. Run the policy tests with: ```powershell npm run test:maintainability ``` For a branch/PR diff, run: ```powershell npm run review:maintainability -- --base --head ``` A warning requires a short architecture/scope check, not an automatic refactor. Explain a deliberate large-file choice when keeping the code together is clearer. ## Challenge the problem frame For high-impact, expensive, or hard-to-reverse design work, treat the current candidate list as incomplete by default rather than as a closed menu. Before committing to a large abstraction, ask whether the problem statement, key assumptions, or architectural boundaries are themselves causing unnecessary complexity. When it could materially change the decision, look for simpler or stronger approaches in adjacent domains, current platform capabilities, standards, and relevant external systems. A newly discovered option is not automatically better and should not bypass scope, security, licensing, or evidence requirements; record it as an alternative, test the assumptions that distinguish it, and revise the plan only when evidence justifies the change. This review is proportional to reversal cost. Routine, local, safely reversible work does not require open-ended research. ## Bounded completion blindspot review Passing the primary acceptance test is not, by itself, proof that the surrounding engineering change is complete. After a substantial implementation, incident fix, architecture change, release-flow change, or newly exposed capability works, do one **bounded second-look** for consequences the primary objective may have hidden. Scale it to the change; this is not a requirement to inspect every category or to keep polishing indefinitely. Check only plausibly affected surfaces: - **correctness and invariants** — inconsistent state, stale ownership, or hidden coupling; - **security and trust** — authority, authentication, untrusted input, path handling, secrets, or exposure; - **failure and recovery** — interruption, reconnect, crash, partial write, stale state, retry, or rollback; - **user/developer experience** — discoverability, misuse resistance, recovery clarity, and avoidable friction; - **observability** — whether a future failure would leave enough evidence to distinguish causes; - **maintainability and testability** — duplicated policy, fragile sequencing, or repeated manual steps that should become tooling; - **compatibility and performance** — whether a local improvement moved cost or assumptions onto another supported path; - **solution-space quality** — whether a current platform capability, standard, upstream mechanism, or simpler adjacent approach would materially reduce custom complexity. External research is not mandatory for every change. Check current upstream documentation, standards, issue trackers, or ecosystem evidence when the decision depends on a fast-moving API/protocol/tool, the custom approach is unusually complex, or a known platform mechanism could materially change the design. Classify adjacent findings instead of expanding scope automatically: - **fix now** when the issue affects correctness/safety, is a small coherent part of the same change, or is likely to recur immediately; - **record/propose** when useful but not justified in the current scope; - **reject/defer deliberately** when the expected value does not justify complexity or churn. A successful primary test should end the main investigation, not situational awareness. ## Optional multi-perspective surroundings scan (user opt-in) The bounded completion blindspot review above is **part of verifying substantial changes**, not an optional substitute for required correctness, security, recovery, or evidence checks. A **wider exploratory look** beyond the agreed task is different: it consumes extra context, tokens and time, so leave it to the user's choice. At a natural milestone or **after completing and reporting the primary objective**, consider whether a limited adjacent review would plausibly reveal a useful missed requirement, simpler design, or unexpected risk. If so, **offer it briefly before doing the extra work**: name the likely area, propose a small scope or deeper option, and note the additional cost/effort qualitatively. Do not interrupt a focused fix, delay its result, ask on every response, or manufacture an opportunity to explore. If the user has explicitly opted in within the **current interaction context** (the same ongoing conversation or agent execution), work within that scope without asking again, even across subsequent tasks there. Consent must be verifiable in that context; **independent conversations or separately launched agent executions do not inherit it automatically**, irrespective of provider or agent framework. Respect declines, revocation, and requests to stay focused. When authorized, sample **relevant perspectives**, not an exhaustive checklist: - **new or nontechnical user** — first-run discoverability, naming, defaults, friction, repeated input, error recovery; - **experienced user / accessibility needs** — configurability, control, keyboard access, clarity of consequences; - **developer / maintainer** — responsibility boundaries, complexity, code health, integration and future maintenance; - **tester / support / operator** — falsifiable edge cases, logs, diagnostics, setup, deployment and recovery; - **security / privacy reviewer** — trust, unintended access, secret lifecycle and misuse resistance; - **adjacent solution space** — simpler platform features, alternative approaches, assumptions or unknown unknowns. Look across the **neighboring workflow**, not only the changed function: what leads into it, what happens afterward, and what a first-time user experiences without developer knowledge. Scale the scan to likely value and the approved budget; stop when new findings are repetitive or weak. Distinguish observed defects from hypotheses. Return a few actionable findings as **fix within approved scope / propose for approval or follow-up / deliberately defer**. An optional scan never silently expands the implementation, creates a speculative Issue flood, or weakens required validation. ## Unexpected results, mistakes, and recovery Wrong assumptions and implementation mistakes are possible in real engineering work. The useful standard is how quickly and clearly the work returns to a trustworthy state. When evidence contradicts the plan, a regression appears, or the wrong thing was changed: 1. **make the state explicit** — do not hide the problem behind a generic completion claim; 2. **stop compounding it** — avoid stacking speculative fixes on unexplained state; 3. **inspect and preserve useful evidence** — keep the smallest diff/log/reproduction needed to understand what happened; 4. **separate the cause** — distinguish wrong assumption, implementation defect, stale test/policy, environment/tool failure, or unrelated pre-existing issue; 5. **contain and recover** — repair or revert the smallest affected surface while preserving unrelated work; 6. **re-verify from fresh evidence** — the corrective edit itself is not proof; 7. **make recurrence harder** — when durable, encode the lesson in a safer default, owner model, validator, generator, regression test, or automation. Do not respond to one mistake by making all future work excessively cautious or bureaucratic. Prefer small, reversible, observable changes and proportionate validation. ## Goal-driven agent iteration When an agent is asked to continue development without a specific implementation task, use a **bounded, outcome-first loop** rather than treating commits, PR count, or task volume as progress. This is work-selection guidance, not permission to run unattended, auto-merge, change credentials, or publish releases. 1. **Refresh reality.** Check the live base branch, working changes, open PRs/Issues, CI, and the canonical [current status](STATUS.md) and [roadmap](ROADMAP.md). Resume an owned in-progress fix before creating competing work. Historical checkpoints and private idea lists are candidate input, never live evidence. 2. **Locate the bottleneck.** Prefer a reproducible failure, blocked user workflow, missing falsifiable test, or concrete release-readiness gap. Compare candidate tasks by expected user benefit, severity, evidence, effort, risk, and reversibility. Do not manufacture refactors or features to keep the loop running. 3. **State the outcome before editing.** Record the user-visible or engineering outcome, baseline observation, smallest change, acceptance/negative test, affected invariants, and evidence class. Existing [change-plan rules](#change-plan-rules) still apply to high-risk work. 4. **Run one coherent change.** Implement, run focused and risk-appropriate checks, and compare the observed result against the baseline and acceptance criteria. A green CI wrapper cannot turn a skipped Unity test into a pass, source checks into packaged proof, or same-machine tests into two-PC evidence. 5. **Re-evaluate.** Record what improved, what regressed or remains untested, the relevant commit/PR/test evidence, and the next blocking condition in the existing canonical owner or task checkpoint. Then select another independent safe task, or stop with an explicit reason if remaining work needs a user decision, physical test, release approval, or new evidence. For TeamForge, **reliable Host → Guest → verified Project → Unity collaborative edit and recovery** is a more meaningful outcome than a larger synchronized feature list. Fixing an existing field blocker or proving its recovery path normally precedes broadening Component/Inspector support. Do not automatically relax locks, path identity, trust, fail-closed behavior, or release gates to satisfy a target. ## AI-assisted implementation AI assistance is welcome, but the engineering process should make it harder for plausible generated code to become an unexamined design decision. Before accepting a substantial AI-generated implementation: 1. check that it solves the stated problem rather than a nearby problem; 2. compare it with the invariants and out-of-scope list; 3. inspect any new trust, path, network, serialization, authority, or lifecycle assumptions; 4. require tests that can fail for the important wrong behavior; 5. verify that the implementation did not silently broaden scope; 6. record unresolved uncertainty instead of converting it into confident documentation. Regenerating code repeatedly is not a substitute for investigating the failure. ## Quality-gate classification `quality-gates.json` and `scripts/classify-change.mjs` provide a lightweight machine-readable mapping from changed paths to risk areas and recommended validation lanes. Run: ```powershell node scripts/classify-change.mjs path/to/changed-file another/path ``` or pipe a newline-separated changed-file list: ```powershell git diff --name-only main...HEAD | node scripts/classify-change.mjs --stdin ``` The classifier is a routing aid, not proof that the selected tests passed. A reviewer may require stronger evidence when the semantic change is riskier than its file path suggests. ## Release-tool migration rule Active release workflows should use WP-neutral entry points such as: - `scripts/build-launcher.mjs` - `scripts/verify-launcher.mjs` - `scripts/stage-release.mjs` Legacy `*-wp4-*` implementation files remain temporarily as compatibility implementations while the release internals are generalized. New release automation should not add more work-package-specific entry-point names. ## Final review question Before merge, ask one final question: > If this change is wrong, what is the most damaging believable way it could fail, and did we run evidence capable of detecting that failure? If the answer is unknown, the change is not necessarily blocked — but the uncertainty should be explicit.