# Minimal Context Harness Protocol

This project uses Tiny Context. The Harness maintains durable Context and workflow authority; project tests, CI, runtime evidence and human acceptance prove product quality. Its three capabilities are Minimal Context, the automatically applicable model-led default Workflow Contract for work of any complexity and the explicitly selected Single-Goal Long-Task Workflow for machine completion authority, recoverability and auditability. Complexity determines execution and verification depth; required completion authority and recoverability determine the workflow route; Long-Task-internal risk determines proof strength.

## Shared Engineering Quality Obligation

Before the first implementation edit, every delivery surfaces one externally observable, repository-bound `Architecture Deliberation`. Depth is risk-proportional, but the checkpoint always names affected owners, the current extension point/source of truth, dependency and state/lifecycle boundaries, the selected design and material alternatives, one plausible future-change challenge, touched technical debt and its disposition, forbidden shortcuts, project-owned checks and triggered engineering-quality attributes or their concrete preservation basis. Correctness/invariants and maintainability/changeability always receive at least a preservation judgment; reliability/resource lifecycle, concurrency/consistency, performance/capacity/cost, security/privacy/safety, compatibility/migration/rollout and operability/observability/testability activate only when the change or an explicit claim makes them material. Exact product/technical predicates remain owned by Semantic Facts and exact selected UI/UX values by selected-design closure. Refresh the checkpoint when scope, ownership, selected design, quality applicability or debt disposition materially changes.

When foundational machinery, a mature protocol/security boundary, a dependency/shared abstraction or a nearby extension point makes sourcing material, include a risk-triggered `Build / Reuse / Buy` judgment. Record an allowed solution set, prohibited failure modes and required rationale/evidence; do not prescribe one library or abstraction. Reusing an owner, the standard library, an installed dependency, a mature compatible external library, a bounded self-implementation and intentional non-abstraction may all be valid. Enumerate every materially supported member before selection; choosing one never removes another supported member from the allowed set or turns it into a prohibited failure. Judge the task's viable set, not one rejected proposal: when at least one supported allowed choice exists, allow and select one; block only when no supported allowed choice exists, and reserve decision-required for a genuine external choice. Reject duplicate owner-held rules, extension-point bypass, unjustified heavy dependencies, plainly incomplete security-sensitive reinvention, license/platform incompatibility, forced abstraction over merely similar semantics and a second source of truth. This adds no mandatory open-source/DRY rule, quality score, stage or Gate.

Implementation order, method and feedback cadence remain Goal-owned. Reuse the owning service/facade/adapter and one source of truth, keep the change minimal but complete, preserve explicit failure and resource-lifecycle semantics, and add abstraction only for a stable concept or evidenced change axis. These are guardrails, not a phase, per-edit mandate or proof that code is globally clean.

After implementation and project verification, perform one current-candidate `Engineering Quality Conformance` that includes `Architecture Conformance` and every triggered falsifiable invariant. Default work embeds it in Contract Conformance; an active Long-Task embeds it only in Final Gate through existing Source-backed obligations/constraints/forbidden shortcuts, owner/path/Bindings, executable Checks and independent Assertions when functional behavior could pass separately. Never schedule both carriers, and recheck after any candidate or controlling-input change. Final Gate proves only that declared project-check-bound set, not overall code quality. A performance claim additionally requires a workload, metric, baseline or budget, environment, comparator/tolerance and project-owned measurement; static shape is not runtime proof. New/worsened debt, duplicate truth, wrong dependency direction, owner bypass, silent failure, resource-lifecycle defect, scope escape, unsupported quality claim or forbidden shortcut blocks handoff unless a bounded project-owned exception records owner, rationale, tracking and removal condition. This creates no quality artifact, matrix, second Authority, Contract field/aspect/Claim/risk type, Gate, workflow state or generic analyzer.

## Default Workflow Contract

Unless a valid Long-Task binding is active or the user explicitly selects Long-Task, this prompt-level protocol applies automatically regardless of duration, complexity or file count. It guides model-led Agent execution but creates no validator result, exact Fact/Obligation ledger, Receipt, persisted phase state or machine-completion authority.

1. Read `project_context/global.md`, `project_context/architecture.md`, `project_context/context.toml` and the default area root, then collect graph/trigger candidates.
2. Before deciding `Context Delta`, run one bounded text search over `project_context/**` using a small high-signal set: explicit area/module names plus relevant API/schema/state/security/verification/deployment terms. Merge matches with manifest candidates, read relevant Context and widen whenever another Area/shared dependency becomes relevant; search supplements rather than replaces semantic judgment.
3. In a monorepo or otherwise multi-target repository, separate the expandable read scope from the task-local intended workspace(s). An optional sparse `project_context/workspaces/<workspace-id>/**` directory maps each represented Context workspace to one code root through existing manifest `root/context`; workspace-local Areas own semantic responsibilities inside it, cross-workspace Areas stay top-level, and code workspaces without durable Context need no empty mirror. Keep the monorepo default Area small and repository-common; workspace-local Context stays `on-demand` unless genuinely near-universal. This structure/default/read policy is neither a read ACL nor edit authorization. Resolve intended workspaces from explicit user/product/path/repository facts; if materially different siblings remain ambiguous, ask one concise target question before product edits. Enumerate intentional multi-workspace targets and supporting/shared scope.
4. For every material non-UI product or technical change, understand all explicit user, Context, specification and selected-constraint requirements at risk-proportional depth. Identify affected owners, material conditions, failure boundaries and real acceptance entries; do not let current code redefine Source or turn missing authority into an implementation default. This is task reasoning, not an Expected Fact Universe or proof ledger.
5. For UI/product-surface work, confirm information/action/feedback ownership and use `context_surface_contract` when durable responsibility is unclear or changes. Root `DESIGN.md` remains the current shared project Design Authority; Context workspace placement does not create independent design systems. For material UI, reconcile affected stable surface/control/target keys as Context-covered, requiring a Context update, task-local, out of scope or decision-required; traverse owning Context and `DESIGN.md`; and open every affected selected `exact-target` or `constraint`. Missing, stale, unreadable or conflicting authority fails closed for the affected claim. Local fixes and explicit non-fidelity prototypes stay lightweight.
6. Complete `Architecture Deliberation`, including applicable-quality routing or a concrete preservation basis, then decide exactly one `Context Delta: none|required`. Update owning Context before code for durable product ownership, architecture, API/schema/data, state/recovery, dependency, security, product-surface responsibility or repeatable verification/deployment change. Local fixes preserving durable semantics are `none`.
7. Use the agent/platform internal plan. Keep `Architecture Context Hit`, `Decision Rationale Hit: existing|required|none` and `Modularity Check: none|required|exception` as internal routing questions, not artifacts or extra deltas.
8. Implement precisely under the Goal-owned quality guardrails and run project-owned verification. When a check fails or exposes a missed requirement, wrong owner, design mismatch, scope escape, Context drift, stale evidence or new debt, localize it to the requirement/owner/module/check, repair it and rerun affected checks. After the last relevant code, configuration, Source or controlling-Context change, rerun every affected check on the current candidate; historical CI, pre-fix results, delegated reports and prose inspection are not current evidence. When the repository exposes a changed-path/target-scope check, run it against the intended/supporting targets and exact task-attributable paths; otherwise review the final diff against durable owners during Conformance. Do not attribute unrelated pre-existing dirty paths to the task without provenance. Perform evidence-bounded Contract Conformance including `Engineering Quality Conformance`, its `Architecture Conformance` subset and any applicable source/design checks below, then run the separate Context drift check. Report `Implemented`, `Verified`, `Unverified`, `Blocked / decision required`, engineering/architecture conformance and Context status; never fold unverified or externally pending scope into a complete claim. For material UI, use the first useful independently runnable production slice as a recommended real-entry feedback point when its expected early-localization value exceeds the run cost; it is not a prerequisite for expanding implementation. Always rerun the affected cold-start journey on the final candidate. Detached routes, specimens and deep links remain supplemental.

The default workflow never requires a plan artifact, target declaration, matrix, verdict, evidence ledger or result document. Optional scratch is not Context or proof. Bounded Context search creates no index, cache, state or second authority; it also creates no read isolation. Missing, stale, unreadable or conflicting controlling Source, a materially ambiguous target, an unsupported observation boundary or a failed/stale check blocks an unqualified handoff for the affected scope: widen reading or verification only as discovered dependencies and risk require, then report any remaining qualification. Do not make the full Context graph the default or add a required Context directory for every package-manager workspace, workspace/applicability schema, automatic topology scan, migration, target registry, generic path/import/runtime scanner or duplicate Long-Task scope classifier.

## Non-UI Source And Assurance Boundary

Both routes preserve Source authority: explicit product, business, API, data, state, failure, security, privacy, compatibility, performance, operational and architecture requirements cannot be silently omitted or redefined from current code. Genuine user/product/legal/security/commercial/safety/external choices remain decision-required. Default work identifies material requirements, conditions, owners and acceptance boundaries at risk-proportional depth, implements them through their real owners, uses attributable current-candidate project checks and reports anything not established. It does not maintain stable Fact/Obligation identities, exact set equality, a universal condition expansion, frozen Oracle/environment rows or a complete result ledger.

An active Long-Task owns the exact non-UI semantic carrier instead. Its package-managed Skill and progressive references preserve the complete Source inventory/Census, standard plus custom semantic families, atomic Fact and condition identities, Fact×required-method obligations, comparison authority, current typed results and sole Final-Gate equality. Never run a nested default semantic closure. Durable meaning still belongs in its existing owning Context; Source remains task authority, code remains implementation truth and Contract stores bindings rather than copied values. Neither route can discover unexpressed intent or prove an arbitrary Oracle semantically sound.

Every machine-closing Long-Task Claim or Fact×method obligation must compile to a package-admitted current-Actual channel. The first bounded slice is plain exact JSON only: either a static implementation/configuration carrier that existed in the pre-run snapshot and is byte/identity unchanged after the runner, or a `process` product root directly spawned and observed by Harness through one temporary `ty-context-product-observation-v1` envelope. Harness owns comparison/result identity/verdict and process-runtime derivation. Custom/named project Oracles, wrappers, project actual/pass/verdict/runtime/interaction/state rows, historical sessions, browser/native/device/layout/pixel/accessibility/motion, protected values, tolerance/mask and custom locators cannot machine-close the obligation and require blocking External Confirmation. A machine Counterfactual without admitted baseline/mutated actual fails; static structure never proves runtime reachability. Public project results remain v3, and this compiled projection adds no Contract Authority, Gate, state or Observer registry.

## Selected-Design Conformance Obligation

This obligation activates only for a selected implementation handoff. Run `ty-context design-resource preflight <handoff.md>` before UI Authority Closure. A formal Web/App target needs one completely acquired machine-readable canonical entry, its exact dependency closure and one frozen-Inspector observable-Fact manifest. Authoring derives the complete scoped `subject × target × condition × variation × atomic property` Expected Fact Universe before generation; complete Census, axis/combination/property expansion, explicit N/A/exclusions and non-sampling/non-truncation must prove `Expected Fact Universe = Canonical Resource Facts = Handoff Indexed Facts`. Product Control and eight-dimension roll-ups are not the Fact ceiling. Preserve exact located values and design-system lineage in canonical resources, every property-required Fact × method obligation, comparator/tolerance/mask, Oracle/environment and sensitive-observation policy; an exact target also needs full-target layout and pixel Facts for every condition. Deliberately partial input remains a constraint or blocking unresolved. Incomplete acquisition, aggregate labels, unreadable Census/locators, missing/extra Fact Cells or proofs, unresolved conflicts/blockers, unsupported evidence or stale digests fail closed. Preflight proves input completeness/integrity relative to the named Inspector/Oracle TCB, never production conformance.

UI symbolic V2 is explicit opt-in; V1 remains the default. A V2 target must preserve the complete extensional `subject/relation × target × reachable condition/variation × applicable atomic property × population/quantifier` denotation, with constant located Rule values, mutually exclusive exhaustive regions and distinct Fact Rule, proof-obligation and set-valued certificate identities. Applicability may retain exact physical remainder partitions or use package-owned subject property profiles plus frozen Inspector custom-property closure and explicit unique instance exceptions; every logical subject-property point still has exactly one disposition. An omitted axis requires both Source-side and production-side proof through frozen closed-world static dependency closure, restricted-IR exact equivalence or finite complete-domain exhaustive equivalence; dynamic/reflected/unfrozen/external or sampled dependencies block. One Contract may mix V1 and V2 targets; bind V1 to exact Fact results and V2 to exact Rule-method-region plus freshly recomputed certificate results in the existing sole Final Gate. V1 admission uses stat/bounded-prefix capacity checks and fails rather than truncating or silently switching. Purpose-fulfillment efficiency non-degradation is a package mechanism-change admission property, not an AcceptedDeliveryTerminal condition. Non-UI symbolic admission remains out of scope; machine-observer and verifier/runner trust-boundary closure is mandatory rather than deferred Provider/P0 work.

Every non-interference proof needs a digest-identified frozen executable Oracle with the exact `symbolic_noninterference.<side>.<method>` capability. Source proof uses one canonical package-owned restricted Source IR in the complete current Inspector inputs; the package binds its current bytes to target/certificate/Rule scope and derives the DAG, predicate or complete finite-domain evaluation itself. Submitted graph/predicate/evaluation/pass fields and the immutable artifact are cache/bindings only: preflight requires current recomputation, artifact bytes and proof cache to agree, while excluding the artifact from semantic inputs. Executable/CSS/implicit-DOM/template/dynamic/reflected/computed/unfrozen/external Source blocks. Production remains limited to the package-parsed static HTML plus inert JSON subset. Both sides bind implementation closure/version/capability, environment, exact current inputs, side snapshot, scopes, omitted axes, method result, artifact and witness; their proof digests bind the existing current Final-Gate certificate result. Extraction outside admitted representations remains an explicit TCB boundary.

Every adopted target has exactly one canonical record: `DESIGN.md` for project/system/component-family scope or the owning Screen Contract for one-screen/interaction scope. It owns interpretation, selection basis, immutable locator/digest, conditions and editable-upstream update route; other layers keep only a stable key, owner/anchor and local applicability. Use the on-demand UI/UX Skill for Design Source Projection. Never overwrite an adopted baseline; create a new immutable version and update its canonical record.

Externally authored resources remain ordinary Source. Authoring Skills do not change Context, code or Contract and do not claim acceptance.

For every external product, architecture, technical or acceptance constraint, internally classify it as Context-covered, requiring a Context update, task-local, out of scope or decision-required. Conformance confirms it reached the correct owner and verification.

Default work opens every affected selected `exact-target` or `constraint` and its declared conditions, routes it to the real production owner and cold-start journey, and runs applicable project-native visual, interaction, accessibility or runtime checks on the final candidate. It reports conditions those checks did not establish and does not claim that preflight input integrity proves production conformance. It does not rebuild the complete Fact Cell universe or retain per-Fact-by-method result rows. An active Long-Task instead projects the exact obligation into existing Source/Claims/Assertions/bindings, `fact_expectations`, `fact_results` and Final Gate and never also runs a default closure.

## Long-Task Routing

Route by required assurance, not task size. Select Long-Task when stable machine obligations, current-snapshot machine completion authority, cross-compaction/session recovery or auditability are explicitly required; its extra authoring and verification cost is not a promise of lower time or token use. A small consequential rule may use it and a complex cross-module change may remain default. Do not infer long-task mode from duration, complexity, file count or agent preference.

1. A valid Git common-dir active record plus matching worktree Git-config marker resumes with `ty-context long-task resume <workdir>` in the currently selected host execution Goal; directly load and follow the installed package-managed `long-task-workflow` Skill. This recovery path does not depend on implicit invocation.
2. An explicit selection of the logical `long-task-workflow` Skill authors or resumes exactly one complete `long-task-delivery-v2` Contract. In Codex, select it with `$long-task-workflow` or through `/skills`.
3. Otherwise remain on the default Workflow Contract.

“One native Goal” is selected and owned by the host/user and means the currently selected host execution Goal for this delivery and workspace. Harness does not create, persist or reconnect a Goal identifier. Compaction may continue inside the Goal; a later physical Goal/session restores semantic workflow state through `resume` rather than reconnecting a prior Turn.

The loaded Skill and its progressive references own Source/Contract authoring, Control/applicability closure, selected-design projection, evidence design, protected revision, rolling repair and lifecycle commands. Do not duplicate those low-frequency rules in this startup router. During Draft/proof/lifecycle work, read the applicable Skill reference and use `ty-context long-task help` for CLI syntax.

After the first Authority Lock, `execution_model_checkpoint.required: true` is an unconditional terminal-turn boundary. Stop before product implementation, edits, builds or tests even when an earlier message stated a model strategy. Tell a Chinese-speaking user exactly `处理好模型更换后，请仅回复：模型切换卡点解除，继续`; use `After handling the model change, reply exactly: model checkpoint cleared, continue` in English. A generic continuation does not satisfy the package-managed prompt protocol. Harness cannot observe the next host message or verify the host model change; later revisions do not repeat the pause and no acknowledgement, model route or checkpoint state is recorded.

Long-Task Final Gate is the sole `Engineering Quality Conformance`, `Architecture Conformance` and selected-design closure owner. It source-recompiles and reruns every declared Check on one current snapshot; targeted Progress, prose, historical tests, Receipts, compiled cache or Agent judgment never create acceptance. It proves the declared falsifiable project-check-bound invariants, not overall code quality. Exactly fresh `machine_accepted` with no pending External Confirmation is the complete declared-machine terminal; qualified/external-pending results never complete the platform-native Goal.

The `F = Implementation Freedom Boundary` keeps implementation order, methods, local feedback cadence, concrete packet decomposition and dynamic worker count Goal-owned within Source/Contract, architecture, safety, forbidden-shortcut and external-action boundaries. After the checkpoint, follow the loaded Skill's packet-first positive-default policy: a qualifying packet set requires actual calls for multiple exact fixed-profile workers; zero-start and partial-delegation outcomes use its admitted reason and integration rules. Harness creates no development method Gate, per-edit mandate, fixed agent allocation, scheduler/delegation state or proof from delegated reports; all proof-bearing output converges into the selected verification workspace.

Long-Task Anti-Degradation Assurance requires mechanism changes to preserve or strengthen coverage, false-negative resistance, fail-closed Authority and final-snapshot proof before total-cost ROI matters. Admission targets evidenced high ROI and high efficiency with a significant stable margin, not a global/local optimum; the complete formal cost theorem is unchanged and `observed_lifecycle_*` facts have no admission meaning. Once validity, relative non-degradation, must-allow behavior, structural-cost limits and applicable measured total-cost thresholds close, construction stops unless a new real counterexample, repeated material cost hot spot or significant additional-benefit evidence appears. Replacing the controlling purpose requires an explicit project-owner design-purpose decision plus replacement proof.

Tiny Context does not create or restore platform Goals, invoke models, spawn agents, call an App Server, create branches/worktrees, merge, push, open PRs, deploy or manage process trees. `ty-context enable long-task` installs the sole Long-Task Workflow Skill and package-owned lifecycle Hooks; an exact `.codex` root may also receive the optional fixed Codex worker profile. Retired standalone authoring pointers are not installed. `design-system-authoring` is explicit-only.

## Durable Facts And Generated Surfaces

- Context is intended ownership/boundary/contract truth; code is current implementation truth. Treat disagreement as drift, missing work or stale Context.
- Long-term facts live only in `project_context/**` or `DESIGN.md`. Selected targets remain Context-reachable Source/verifier inputs; generated screenshots/diffs/logs/raw evidence/runtime state/Receipts do not become Context.
- Managed `AGENTS.md` blocks, `<harnessRoot>/ty-context-managed/**` and package-managed Skills are generated and sync-overwritten.
- Explicit upgrades use `context_harness_upgrade`; package sync never imports retired orchestration or development-period authority state.

## Verification

- `make validate-context`: Context recoverability.
- `make validate-harness`: Context plus touched-source modularity.
- `ty-context doctor`: installation health plus advisory default Context footprint and Design Authority status.
- `node packages/ty-context/dist/cli.js package check-source`: managed-source/package parity in this source workspace.

Every handoff reports exactly one of `Context: updated ...` or `Context: no durable fact change`. Never claim tests, deployment or acceptance from Context alone.
