Files
aji/docs/rfcs/0038-bounded-diagnostic-edits.md

23 KiB

RFC 0038: Bounded source edits in diagnostic repair candidates

Status: Proposed
Scope: Optional source edit candidates for E3101 and selected E7006 diagnostics
Language version: 0.1
Supersedes: —

Work recommendation: defer pending evidence and application-workflow validation. This is not a new RFC lifecycle status: formal status remains Proposed, and only the owner decides adoption. The design below is retained for discussion, not recommended for implementation as it stands. It narrows C1 in the design review following its assessment.

Evidence and conditions for resumption

The published native smoke, P6A-9 and P5-0 reports do not report E3101. P6A-9 reports E7006 but not its reason; that does not establish a Copy-move error eligible for this RFC. An unreported code is not a verified zero in a complete per-run dataset. Synthetic examples establish feasibility, not observed repair cost or expected payoff.

Reconsider the proposal only after the following evidence is available:

  1. Incidence with an explicit denominator. Publish aggregate counts for an independently chosen Aji/source cohort: runs with at least one eligible E3101 or classified Copy-move E7006, divided by all source runs, failures included, with sample size and agent/toolchain strata. Count affected runs separately from repeated diagnostic occurrences. Report unknown E7006 reasons as unknown, not eligible or zero. ajieval summary, profile and checkpoint now classify structured code/reason counts (DD-017), retaining unknown reasons and log availability; they cover the entire recorded transcript, without a pre-acceptance cutoff. Specify that cutoff and missing-data treatment before collecting a new cohort.
  2. Material repair cost. Show that the eligible cases cause location/transcription work, failed patches, retries or meaningful tool cost, and compare the proposed workflow against today's suggested_effects plus ordinary editing on independent public fixtures/tasks. Frequency alone is insufficient; a syntactically exact edit may cost more to apply than the existing repair.
  3. A usable application path. Resolve the byte-offset workflow objection below and validate the chosen path with the actual editor/tool interface. Application must remain explicit, stale-input checks must hold, and edited source must be rechecked.

The independent instrumentation prerequisite is implemented by DD-017/spec 15 §10: E7006 carries a stable reason, move_copy excludes borrowed and non-materializable operands, and ajieval counts occurrences and affected runs by code/reason without parsing message. These changes implement no edits or application workflow. The assessment records the baseline gap and subsequent follow-up. Missing reasons in old records remain unknown; no historical data is relabeled and no new incidence experiment is supplied. E3101 remains countable by code. This instrumentation does not satisfy the repair-cost/workflow conditions above or change this RFC's Proposed status and recommendation to defer.

No numeric N% or minimum sample size is justified by the current reports. If the owner chooses an incidence threshold and sample-size gate, record them before evaluating a new cohort rather than selecting them to match observed results. These conditions reopen design review; they do not automatically accept the RFC. Do not change frozen B1 instrumentation or inputs, inspect private held-out material, or use M/C to select or tune the eligible transformations. An authorized independent operator may publish aggregate metadata under the evaluation protocol.

Application workflow gap

The retained schema is exact for a programmatic byte-range applicator. It is not yet demonstrated to help an agent using contextual or string replacement: expected: "[]" is not unique in a file, and the primary E3101 position points to the operation, not necessarily the declaration. A file hash protects the input version but supplies no surrounding edit context. Requiring an agent to write an offset-application script may erase the intended saving.

Two alternatives remain open for a revised RFC:

  • Add the edit's line/column plus enough original context to identify a unique replacement in that file, including a rule for multiline/ambiguous cases and stale input. Keep byte offsets as optional precise metadata if useful. One line alone is not guaranteed unique.
  • Specify a separately invoked aji apply-candidate <id> workflow, including candidate identity/lifetime, exact source snapshot, file scope, stale-input handling and explicit application. An agent-invoked command would not be automatic application during checking or a compiler flag changing language semantics; it would add a tool protocol and implementation cost that need evaluation.

Neither alternative is adopted or implemented here. If a future revision adds an explicit application command, it must revise the invariant and scope below, which currently prohibit compiler application and exclude such a command. Until the workflow and payoff are supported, the byte-offset design is a retained candidate rather than a resolved interface.

Motivation

E3101 already supplies suggested_effects, but an agent still locates the declaration and copies the list. E7006 rejects some unnecessary move expressions on Copy bindings, but also covers many unrelated source restrictions. A small eligible subset can expose exact edits without inferring effects into the public contract or making an automatic repair.

The objective is machine repairability: reduce source-location and transcription work. An exact candidate is not a unique correct response to an error. The agent may instead change the operation, alter the API or reject the candidate. Candidates also do not promise that the whole program will verify after application.

Precise invariant

The compiler MUST check the submitted source unchanged and MUST NOT apply a candidate to that source, emitted AIR or the program being executed. Acceptance, rejection, existing diagnostic codes and runtime behavior MUST remain unchanged until an external agent explicitly edits and rechecks the source.

Each emitted candidate MUST describe a single specified local transformation against the exact parsed file bytes. It MUST NOT insert move, choose a missing match arm's behavior, add a capability/grant, discharge unsafe obligations, or alter ownership/lifetime rules.

Normative rule changes

Proposed addition to spec 10 §3, “Bounded source edit candidates”:

A repair_candidates object MAY contain edits, a nonempty ordered array describing one candidate applied as a unit. A candidate is non-binding and MUST NOT be applied by the compiler. Consumers MUST NOT interpret a candidate as proof of programmer intent or whole-program acceptance.

Each edit MUST contain file, source_hash, range, expected and replacement. file MUST identify the original source input as reported by source diagnostics. source_hash MUST be sha256: followed by 64 lowercase hexadecimal digits of the complete original file bytes, without newline or Unicode normalization. range MUST be [start,end], zero-based UTF-8 byte offsets with an exclusive end, within that file and on UTF-8 boundaries. expected MUST equal those original bytes as UTF-8 text. replacement MUST be UTF-8 text.

A consumer applying a candidate MUST check the complete file hash and every expected range before writing, and MUST NOT apply a stale or partial candidate. The language toolchain MUST continue to require an ordinary check of the edited program. Edit arrays MUST be ordered by file identity and increasing original start offset, with no overlapping edits. Multiple diagnostic candidates remain independent alternatives; the compiler MUST NOT implicitly compose them.

In this RFC each candidate has exactly one edit. The array shape supports the existing repair-candidate grouping, not additional multi-edit transformations in this release. New candidate kinds or eligibility rules require a specified extension.

Object serialization order: candidate kind, then edits; edit file, source_hash, range, expected, replacement. The existing diagnostic envelope order is retained. Existing kind-only candidates remain valid. The edited file is never read again merely to create a candidate: the hash and text come from the bytes that were parsed.

Proposed addition to spec 15 §10: source edit candidates are optional, source-only metadata governed by spec 10 §3. The following two kinds and eligibility conditions are exhaustive for this RFC.

replace_effects — E3101

An implementation MAY emit this candidate only when all conditions hold:

  1. The diagnostic is E3101 and has the verifier's complete suggested_effects for that function under the current submitted callee contracts.
  2. The checked AIR function maps unambiguously to exactly one original, non-generic .aji function declaration and one explicit effects [...] clause. The source file and exact token range are retained from parsing/lowering; they are not reconstructed by parsing messages or demangling a name.
  3. The function is not a generic specialization, template, compiler-generated wrapper, compiler-pinned std function or trusted boundary. The suggested list does not add/discharge unsafe. Static function-parameter/template contracts are outside this initial subset.
  4. The edit replaces only the bracketed effect list, preserving effects, the signature, body, capability parameters, annotations and surrounding tokens. Effects are distinct and canonically sorted, exactly matching suggested_effects. Comments inside that replaced range are omitted from the replacement; expected exposes their removal explicitly.

Repeated E3101 diagnostics for the same function MAY repeat the identical candidate. They MUST NOT describe inconsistent effect lists or ranges. An agent must deduplicate identical candidates or choose one; applying the first makes duplicates stale.

Changing a callee may expose a new missing caller effect on the next check. This is not a fixed-point inference or a promise of a one-pass global repair. Alternative reductions of effects and authority remain the agent's decision.

remove_copy_move — E7006

An implementation MAY emit this candidate only when all conditions hold:

  1. The compiler has identified the specific source error move of a complete runtime Copy binding, not merely the code E7006 or a matching human message. Name resolution and the binding's concrete type are available and valid.
  2. The type is Copy under the normative type properties, excluding borrows, linear values and internal storage/scope/guard/shield handles. A Copy binding represented in frame storage remains eligible only when ordinary name use is a complete Copy read; an internal storage handle is not eligible.
  3. The expression is exactly the parsed move name form in an ordinary monomorphic body, mapped to the original user-provided program source. It is not inside a generic template/specialized body where move name can intentionally transfer a Copy specialization (spec 15 §17), or compiler-pinned library/generated source. File permissions do not authorize the compiler to write; application remains an external agent's explicit action.
  4. The edit deletes exactly the four bytes of the move keyword, leaving the identifier, comments and whitespace unchanged. Removing those bytes must leave the parsed expression as an ordinary use of that same resolved binding, with no token concatenation or changed name resolution.

No candidate is emitted for a borrowed value, an owner, an unknown name, an unsupported move shape or any other E7006 reason. No new diagnostic code is needed; the compiler's explicit internal error classification determines eligibility. The candidate kind makes the proposed transformation machine-readable without relying on prose.

Verifier implications

No new abstract state, rejection rule or transfer function. Existing effect verification and Copy properties supply facts. Edit provenance is frontend/diagnostic metadata, never evidence used to accept a program.

Effects candidates are attached only after the verifier has finished collecting suggested_effects for the original function. Eligibility does not broaden its contract. Copy candidates use the already resolved source binding and type; they do not substitute not linear for the stronger Copy condition.

Hash each relevant parsed file at most once; retain token offsets and declaration identity through lowering. Extra work is linear in input bytes plus emitted edit text. Do not run a speculative solver, infer new effects or recursively recheck candidate combinations to generate this initial subset. Failed or ambiguous provenance simply suppresses the optional candidate.

Interpreter / runtime implications

No runtime changes, implicit moves, cleanup or authority. Deterministic checking emits deterministic candidates for the same input. Hashing and candidate serialization occur outside Aji execution and consume no program fuel. An unchanged rejected program remains rejected; an unchanged accepted program has the same run record.

AIR changes

No new or changed instruction, operand/result type, ownership/memory/concurrency effect, capability requirement, trap or transfer function. AIR format 0 retains its meaning and feature headers are unchanged. Direct AIR inputs keep current effect suggestions and do not receive source edits from this RFC.

Valid example

module edits.valid
fn echo(out: cap<io.write>, x: u64) -> u64 effects [io.write] {
    io.stdout_write(out, b"ok") or trap;
    return x;
}
fn main(out: cap<io.write>) -> u64 effects [io.write] {
    return echo(out, 42u64);
}

The effect list is explicit and the Copy return needs no move. This ordinary function remains accepted; the compiler applies no edits or grants.

Rejected examples

module edits.effects
fn echo(out: cap<io.write>) -> void effects [] {
    io.stdout_write(out, b"ok") or trap;
}
fn main(out: cap<io.write>) -> void effects [io.write] { echo(out); }

This remains E3101. An eligible replace_effects candidate replaces [] with [io.write]; it does not introduce out, grant authority or run the program. Applying that candidate explicitly and rechecking resolves this example's missing effect.

module edits.copy
fn identity(x: u64) -> u64 effects [] { return move x; }
fn main() -> u64 effects [] { return identity(42u64); }

This remains E7006. An eligible remove_copy_move candidate deletes only move. After explicit application and recheck, returning x is accepted. The generic version's permitted Copy transfer must not receive this candidate.

Proposed candidate for the exact UTF-8 effects example above, with LF line endings and its final newline. The hash and offsets must be computed again for any different file bytes; this is not current compiler output:

{"kind":"replace_effects","edits":[{"file":"effects.aji","source_hash":"sha256:fbd3a536e427c7d573a4508e9e0378d65d82b4a73394da0a9c433f3ddcd5569f","range":[65,67],"expected":"[]","replacement":"[io.write]"}]}

Diagnostics impact

No new codes/kinds in the error registry. Two new non-binding repair candidate kinds, each available only under its explicit source conditions. Existing suggested_effects, messages, fields, primary locations, ordering, counts and deduplication remain intact. Existing clients may ignore the extra member of a repair candidate.

The compiler must serialize typed edit objects in src/diag.zig; neither raw JSON strings in ordinary fields nor parsing message is an implementation of this contract. Source identity must be preserved across package files. A diagnostic about a compiler-pinned std module must never suggest editing the agent's similarly named local file.

Spec integration

If resumed, revised and accepted, integrate spec 10 §3 (edit schema, stale-input protection, candidates never applied automatically), spec 15 §10 (the two eligibility sets and original-file provenance) and short references from spec 15 §9/§17 where relevant. reference/error-codes.md links existing codes to those conditions. Quick Reference receives one short note that candidates are optional and require an explicit patch and recheck. Keep schema/eligibility in a compact table with only necessary invariants and cross-references; RFC rationale and validation checklists must not become repeated normative prose.

Spec 10 §3 already enters the AIR bundle. It must also enter diagnostics/errors.md through docs/agent/source-bundle.txt, because the current source bundle includes spec 10 §2/§5 but not §3. Keep the source-specific eligibility rules in spec 15 §10, already included in that page. Do not add RFC rationale or every example to the bundle.

Compatibility and migration

No accepted/rejected set or runtime outcome changes and no AIR/language format increment is required. Kind-only candidates and current diagnostics stay valid. Exact-JSON goldens must be updated for eligible source cases. File paths preserve existing source identity conventions rather than silently canonicalizing them differently. Hashes/offsets refer to original bytes, including CRLF and comments.

This extension does not expose a CLI flag that repairs programs or changes semantics. Whether an external editor offers explicit candidate application is outside scope; it must honor the stale-input and complete-candidate requirements if it does.

Agent complexity impact

  • New concepts: an optional, version-bound text edit candidate; no new Aji programming construct.
  • Verifier state: none; frontend retains exact token offsets and file/declaration identity, plus file hashes for diagnostics.
  • Syntax/instructions: none; source syntax and lowering semantics remain unchanged.
  • Interactions: effect propagation, Copy versus linear/borrow types, generic Copy-transfer exceptions, comments/UTF-8/CRLF, package paths, repeated diagnostics and compiler-pinned modules.
  • Repairability: reduces location/transcription work for two transformations; cannot establish programmer intent or prevent all follow-up errors.
  • Existing primitives: already sufficient for correct source; the richer diagnostic API makes existing facts actionable.
  • New diagnostics: no codes, two candidate kinds.
  • Current documentation baseline: AIR 46,300 cl100k tokens; following the floating-point clarification, Quick 8,688, other source 64,160, full source 72,848. Draft RFC text is outside the bundles. Measure before/after normative integration in all supported tokenizers, including adding spec 10 §3 to source diagnostics; no token estimate is claimed as measured growth.

As a diagnostic extension this needs no new .aji syntax. Delivery still covers spec, diagnostic API, frontend provenance, verifier attachment, Quick Reference and AIR/source CLI tests together. Neither this document nor its proposed convenience establishes MCC or lower economic cost.

Validation plan

  1. Check valid/rejected examples before and after explicit external application; the compiler must leave the rejected original unchanged. Validate original run/check exit codes and unchanged accepted records.
  2. E3101: multiple missing effects in one function, repeated diagnostics, unrelated declared effects, multiline lists, imported user functions, changed callee contracts, and no candidates for generic/static-policy functions, trusted/unsafe boundaries or compiler-pinned std.
  3. E7006: Copy scalars/aggregates/frame values, unknown names, borrows, linear/internal values, unrelated restrictions and generic Copy transfers. Only the specified error emits an edit; owners never get implicit move insertion.
  4. Validate hash, exact expected bytes, half-open offsets, UTF-8 boundaries, CRLF, comments and lexical separation; reject stale input and modified prefix/suffix bytes even when the range text still matches.
  5. Cover deterministic serialization, retained old fields, original package file identity, optional suppression under ambiguous/missing provenance, and duplicate candidates becoming stale after one application.
  6. Direct AIR diagnostics keep existing behavior; existing verifier conformance codes/counts and source/AIR ratios remain stable. Run unit/conformance/targeted CLI tests and bundle measurements before marking implemented.
  7. Measure repair success, retries, follow-up diagnostics, tool calls and total cost including failed attempts on independent public fixtures/tasks. M/C provide regression only and must not select or tune the eligible transformations.

Alternatives considered

  • Top-level ungrouped edits: obscures whether edits belong to one alternative or several; use the existing repair_candidates API.
  • Only suggestions as today: smallest API, but repeats location/transcription work.
  • Automatic application / inferred public effects: violates the explicit proposal/verification boundary.
  • Move insertion: consumes an owner and can invalidate later uses; outside scope.
  • Missing arms with trap: selects failure behavior; outside scope.
  • Generic template effect edits: individual specialization feedback is insufficient to choose a universal public contract; outside scope.
  • Context plus line/column: supports ordinary contextual editing better than an isolated short expected string; uniqueness, multiline behavior and encoding conventions remain to be specified and tested.
  • Explicit application command: potentially avoids offset scripts without automatic checking-time repair; candidate storage/identity, source scope and stale-input behavior introduce additional tooling work. This alternative is unresolved, not rejected by the current narrow scope.

Unresolved questions

Resumption requires the evidence and workflow review above; the owner must decide adoption. Contextual edit metadata or an explicit application command must be specified in a revised or separate proposal before implementation. Multi-edit candidates, edits for AIR, generic contracts and other diagnostic codes remain outside the retained design. No implicit expansion of eligibility is delegated to implementation.

Draft validation

The three .aji blocks were extracted and checked against the current compiler: the valid example accepts, and the two negative examples reject with E3101 and E7006 respectively. Explicitly replacing the first effect list or deleting the Copy move in separate temporary files makes those examples accept. The compiler applied no edit, and the proposed edit schema/eligibility implementation remains pending.