In this article

Give a coding assistant the evidence needed to make the requested decision: the contract, relevant code, failing input, runtime, and behavior to preserve. This original Node.js example repairs an eight-byte label limit without changing the submitted text or the caller's error format.

Explain what the limit measures before requesting code

An instruction such as “fix Unicode support in the label validator” leaves the central decision unstated. Does the product limit visible characters, JavaScript string units, or encoded bytes? Each interpretation can produce a different patch that looks reasonable in isolation. Resolve that unit before asking the assistant to choose an API.

In this illustrative service, a label must be a primitive string whose UTF-8 representation occupies between one and eight bytes. Exactly eight is allowed. Success returns the original text; nonstrings return INVALID_LABEL and empty or oversized strings return LABEL_SIZE. Whitespace is meaningful. The eight-byte number belongs to this exercise, not a general recommendation for user-facing labels.

The existing validator uses value.length. JavaScript defines string length in UTF-16 code units, so it does not measure the quantity named in this contract. MDN: JavaScript string length The mismatch is a specific input-validation defect, not evidence that all string length checks are wrong.

    Attach an input that separates the two interpretations

    Five copies of the precomposed letter é occupy ten UTF-8 bytes but have JavaScript length five. The flawed function accepts them under an eight-unit check. That example isolates the measurement error while avoiding uncertainty about the maximum. It also gives you a stable result to reproduce before reviewing any proposed replacement.

    The short assertion below is deliberately failing. Run it in a Node .mjs file to establish that the current result disagrees with the contract. Keep the same expected error after the repair. Changing the fixture to an ASCII label would remove the evidence that distinguishes bytes from string units.

    Include one accepted boundary too: four copies of é occupy exactly eight bytes. A prompt containing only a rejected long label can encourage a repair that rejects every non-ASCII input. A useful context packet shows both the behavior that must change and a nearby result that must remain valid.

    Deliberately failing multilingual label example
    Codejavascript
    import assert from 'node:assert/strict';
    
    function labelResultProposed(value) {
      if (typeof value !== 'string') return { ok: false, error: 'INVALID_LABEL' };
      if (value.length === 0 || value.length > 8) {
        return { ok: false, error: 'LABEL_SIZE' };
      }
      return { ok: true, value };
    }
    
    assert.deepEqual(labelResultProposed('ééééé'), {
      ok: false, error: 'LABEL_SIZE',
    });
    

      Supply the caller boundary and the relevant files

      For a real repository, identify the validator file, the caller that maps its result, and the focused test file. Include their actual paths and the few surrounding lines that establish the contract. If you cannot find the specification for bytes, say that the requirement needs clarification instead of presenting a guess as existing behavior.

      The caller matters because returning false, throwing an exception, and returning an error object are different interfaces. Here the caller displays the error field from the returned object. A generated function that throws for oversized input may measure bytes correctly and still break the application. Make the successful shape equally explicit.

      Include the runtime as evidence: this example executes in Node.js 24, where Buffer.byteLength accepts a string and an encoding and reports its encoded byte length. Node.js 24: Buffer.byteLength A browser-only module has a different available API surface, so omitting the runtime can send the assistant toward an incompatible implementation.

        Replace a vague prompt with a checkable assignment

        A weak prompt asks the assistant to “make labels Unicode safe and improve validation.” It invites decisions about trimming, normalization, character counting, and error handling that the user never requested. A more useful request gives the existing function and says: “Repair labelResult for Node.js 24. Enforce one through eight UTF-8 bytes, inclusive, while preserving its result objects.”

        Continue with evidence: “Five precomposed é characters currently succeed and must return LABEL_SIZE. Four must succeed unchanged. Keep INVALID_LABEL for nonstrings. Do not trim, normalize, truncate, add dependencies, or modify the caller. Explain the changed measurement and add literal success and error expectations.” Attach the relevant code and the command that reproduced the failure.

        Those exclusions prevent accidental changes to the agreed behavior; they are not a reason to ignore a real contradiction in the code. Ask the assistant to report conflicting requirements before broadening the patch. Remove unrelated logs and private data from the context packet so the behavior under discussion remains easy to inspect.

          Review the chosen API and the unchanged return values

          The repaired function below checks type before measuring bytes, names UTF-8 explicitly, and returns the input unchanged. The measurement API supplies the number required by this contract. It does not decide whether the application should have chosen a byte limit in the first place. Node.js 24: Buffer.byteLength Keep that product decision separate from whether the implementation follows it.

          Inspect alternatives against the same examples. Counting code points can still accept five é characters even though they exceed the byte limit. Truncating a string silently changes a label the caller asked to validate. Trimming can turn a permitted space into an empty value. None follows from the specified behavior.

          A compact prompt cannot guarantee a correct patch. Read the diff and connect each changed line to the assignment. If the assistant modifies error constants or introduces normalization, require a reason supported by the caller contract before accepting those changes. The useful result is an inspectable implementation, not confidence in the wording of the prompt.

          Focused Node.js repair preserving the label contract
          Codejavascript
          import { Buffer } from 'node:buffer';
          
          function labelResult(value) {
            if (typeof value !== 'string') return { ok: false, error: 'INVALID_LABEL' };
            const bytes = Buffer.byteLength(value, 'utf8');
            if (bytes === 0 || bytes > 8) return { ok: false, error: 'LABEL_SIZE' };
            return { ok: true, value };
          }
          

            Verify boundaries, error objects, and preserved text

            Paste the repaired function above the following assertions in a Node .mjs file. The accepted and rejected lists supply literal decisions instead of calling the measurement API to calculate expected validity. ASCII and multilingual boundaries test different ways to reach the limit. Two smiling faces use eight UTF-8 bytes; appending an ASCII letter takes the label beyond it.

            The decomposed accent example is intentionally preserved as supplied. The exercise does not require Unicode normalization, and a byte validator should not silently add it. Likewise, a single space remains valid. Invalid primitive types protect the established error path. These details make the original prompt exclusions observable rather than ceremonial.

            These checks passed during preparation. Replacing the byte measurement with string length makes the multilingual rejection cases fail. Changing the maximum comparison to reject equality makes accepted eight-byte cases fail. Those experiments show that the suite distinguishes two plausible wrong patches without relying on the assistant's explanation.

            Executable label checks with independently chosen expectations
            Codejavascript
            import assert from 'node:assert/strict';
            
            for (const value of ['a', '12345678', 'éééé', '🙂🙂', ' ', 'é']) {
              assert.deepEqual(labelResult(value), { ok: true, value });
            }
            for (const value of ['', '123456789', 'ééééé', '🙂🙂a']) {
              assert.deepEqual(labelResult(value), { ok: false, error: 'LABEL_SIZE' });
            }
            for (const value of [null, undefined, 0, false, {}, []]) {
              assert.deepEqual(labelResult(value), { ok: false, error: 'INVALID_LABEL' });
            }
            console.log('16 label contract cases passed');
            

              Carry the result back to the application boundary

              After the focused suite passes, run the repository checks that exercise the caller. Verify that the same error codes reach the UI or API response and that a valid label is stored without alteration. The standalone example establishes function behavior; it cannot demonstrate storage constraints, request parsing, or agreement with a separate client validator.

              For a service that receives arbitrary strings, malformed Unicode and replacement behavior deserve an explicit policy and dedicated fixtures. This guide uses well-formed examples. Do not claim exhaustive Unicode handling or database compatibility from these sixteen checks. A visible-character limit would also need a different requirement and verification plan.

              Record the prompt together with the requirement, changed files, executed command, and remaining boundary. That packet helps another reviewer understand why the patch exists. There is no measured productivity claim here: the benefit being demonstrated is that the proposed change can be evaluated against a concrete assignment.

                Common questions about context for AI coding

                How much code should I include? Include enough to establish the failing operation, its inputs, and the interface its caller relies on. Add surrounding files when they resolve a specific uncertainty. An entire repository dump does not replace a missing unit or a missing expected result.

                Should I prescribe the exact fix? You can name a relevant API, but keep acceptance tied to behavior. The tests should still challenge an incorrect implementation using that API, including a wrong maximum comparison or changed error response.

                What if the assistant asks whether to normalize? Answer from the product contract. Here the label must return unchanged, so normalization is outside scope. If the requirement is actually unclear, resolve it before treating a generated implementation as the specification.

                  Sources & editorial notes

                  This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.

                  1. MDN: JavaScript string length

                    Establishes that JavaScript string length counts UTF-16 code units, supporting the unit mismatch in the reproduction. Retrieved October 27, 2026; evergreen documentation, not an announcement.

                  2. Node.js 24: Buffer.byteLength

                    Documents the Node.js encoded-byte measurement used in the repair; examples specify UTF-8 explicitly. Retrieved October 27, 2026; evergreen documentation, not an announcement.

                  Put the reading into practice

                  Work through an existing repository, review AI suggestions, and test the decisions behind your changes.

                  Explore practice problems