Skip to content

Implement upstream AGENTS.md hierarchy and closest-file precedence within admitted instruction sources #2090

Open

Description

@JAORMX

Problem

Mecatl reads root AGENTS.md, but does not implement the upstream's automatic nested discovery or closest-file precedence. A trusted monorepo can contain package-specific instructions that never reach the model while it edits that package. The public guide nevertheless describes applicable parent files and local refinement as working behavior.

Implement upstream AGENTS.md hierarchy within Mecatl's selected, admitted instruction sources. Preserve the separation between instruction authority and execution placement. This needs an Architectural acceptance plan before implementation: root-only discovery and per-run assembly are existing contracts, not incidental helper behavior.

Upstream contract and scope

AGENTS.md is stewarded by the Agentic AI Foundation under the Linux Foundation. Its published guidance says:

Agents automatically read the nearest file in the directory tree, so the closest one takes precedence and every subproject can ship tailored instructions.

The closest AGENTS.md to the edited file wins; explicit user chat prompts override everything.

Source snapshot: upstream commit d001185d792eb6402a58e4cbef1c228b309ec25d, usage guidance, and FAQ, inspected 2026-10-05.

Treat explicit user precedence as overriding repository guidance, never system safety or tool authorization. The public upstream materials are a lightweight behavioral specification; they do not settle activation timing, non-conflicting ancestor composition, refresh semantics, filesystem boundaries, or resource budgets. Resolve those in the acceptance plan rather than attributing invented requirements to AAIF.

Confirmed gaps

Evidence baseline: Mecatl 3222c2fb808d4140d19b2979a73dd2a6b2cc4398.

Gap Evidence Consequence
Discovery only checks the source root DiscoverInstructions reads AGENTS.md, then CLAUDE.md, and returns one nonempty contribution Nested instructions are not discovered automatically
No target-path applicability contract InstructionAssembler.Assemble(ctx) has no target path; file tools do not activate instruction scopes No harness-defined nearest-file precedence or sibling-scope isolation
No late-target activation through the current assembler buildRequest caches fragments once per run A target first encountered later in a run does not bring its local instructions into context
The existing regression pins root-only behavior RootDiscoveryCompatibility plants nested/AGENTS.md and expects no contribution Hierarchy requires an explicit contract/test change, not just additional tests
Public documentation overclaims hierarchy Owning guide promises parent discovery and local refinement Operators cannot reliably predict which instructions are active

A root instruction telling the model to manually read another AGENTS.md is a workaround, not automatic upstream support. Eagerly concatenating every nested file is also insufficient: unrelated sibling instructions would compete in one unscoped context.

Example

repo/
  AGENTS.md                 # use npm for JavaScript checks
  website/
    AGENTS.md               # this package uses pnpm; run pnpm test
    src/app.ts
  services/
    AGENTS.md               # unrelated service-specific guidance

With the source rooted at repo/, work on website/src/app.ts must automatically receive the website guidance with the correct precedence. Service guidance must not govern website work. This must work without a root-file pointer or a user explicitly asking the model to read the nested instruction file.

Decisions required before implementation

  1. Scope and composition. Define root-to-target resolution within the admitted source, closest-file conflict precedence, and treatment of non-conflicting ancestors. Recommended: preserve applicable ancestor guidance and give the most local instructions precedence on conflicts. Specify multi-file tasks, sibling transitions, and absolute versus relative target paths. Separate within-source directory precedence from operator-configured source combine/replace precedence.
  2. Activation before action. Decide how applicable instructions reach the model before it decides a mutation. Cover new-file Write without an earlier Read, Read and mutation in the same model-produced batch, and multi-path Copy/Move/Remove. Define the policy for Shell and other tools whose affected paths cannot be inferred reliably. Attaching instructions after an edit does not guide that edit; arbitrary shell parsing must not be presented as complete target discovery.
  3. Source-to-target mapping. Define logical target mapping when instruction and execution namespaces differ, including a session rooted below the repository root and non-filesystem sources. A target path cannot select a new source or authorize a host ancestor walk. Traversal stops at the admitted source boundary.
  4. Freshness and lifecycle. Specify whether newly encountered scopes and changes to already loaded instruction files refresh within a run, including the agent editing AGENTS.md itself. Cover new runs, approval continuation, compaction, reopen/restart, and children. Preserve ephemeral context without stale active scopes or repeated fragment accumulation.
  5. Failure and resource limits. Define missing, whitespace-only, unreadable, removed, oversized, or context-budget-exhausting instruction behavior. Preserve genuine read errors as errors rather than filename fallback. Do not silently advertise complete guidance after applicable content has been omitted. Bound discovery and resolve symlink containment, alias scope, and cycles through the source abstraction.
  6. Compatibility and trust UX. Retain or explicitly amend root AGENTS-first/CLAUDE-fallback behavior; decide nested CLAUDE interaction separately from upstream requirements. AGENTS files are admitted by project trust, but are not currently part of the remembered-trust anchor or authority-presence probe (internal/adapter/workspacetrust/{anchor,authority}.go). Decide whether to retain that policy; test an AGENTS-only repository's admission/diagnostic path. This is not evidence of an authorization bypass.
  7. Explainability. Define a content-safe way to tell which logical instruction scopes were selected or omitted. Existing request manifests record kind/provenance/byte counts, not directory applicability, and transcripts omit ephemeral fragments. Reuse existing diagnostics/evidence where possible; a new public inspection API is not assumed.

Boundaries to preserve

  • Discovery uses only selected, authorized context sources. Never reopen virtual /workspace through host osfs, infer authority from cwd, or fall back to unselected execution files when a selected source fails.
  • Project provenance remains project provenance. Headless posture alone grants no project trust; deny/ask policy and tool capabilities remain unchanged.
  • Ordinary Subagent, Parallel, and parented Team workers already inherit the parent's source binding. Resolve child target scopes against that authority; do not substitute a child checkout. Preserve specialist/internal-reviewer exclusions and binding lifetime through cancellation and parent retirement. Inheritance is not necessarily a frozen copy of the parent's assembled bytes.
  • No-FS sessions can retain independent admitted context without gaining file tools. Required execution-backed sources cannot invent storage for no-FS.
  • Automatic instruction reads must not populate the execution ReadLedger or authorize Edit/overwrite. Preserve explicit same-session read evidence, CAS, and create-only writes.
  • New caches or retained resources need owner, cleanup, and restart decisions under ADR 0027. Do not introduce watchers or persisted scope state without a demonstrated need.

Existing proofs to retain include internal/app/harness_context_execution_test.go (source/execution independence and ledger separation), harness_context_regression_test.go (worker inheritance/attenuation), harness_context_generation_test.go (lifetime), and microvm_harness_context_test.go (real backend, no-FS, conflicting child content, restart, and ledger behavior).

Proposed acceptance scenarios

These are planning inputs, not an approved interface contract.

  • Automatic hierarchy: root, package, and deeper AGENTS markers reach actual provider requests in the documented order for a nested target. Conflicting local guidance has explicit nearest-file precedence; user task overrides remain distinguishable. No manual instruction-file read or root-file pointer is required.
  • Scoped multi-file work: switching between sibling targets and working on both in one task preserves each scope's applicability. Stale sibling guidance is not presented as governing a new target. Deduplication does not erase scope or precedence.
  • Before mutation: applicable guidance is model-visible before the decision that executes an edit or new-file creation, including same-turn read/mutation batches. Namespace operations and opaque Shell writes follow the explicitly documented policy rather than bypassing it accidentally.
  • Admitted-source isolation: poisoned unselected execution/host/child instruction files never enter automatic context; selected local and virtual sources behave consistently. Traversal cannot escape the admitted root through .., absolute paths, or symlinks.
  • Workers and no-FS: normal isolated/direct-write/Parallel/Team workers retain source authority and resolve applicable scopes under existing restrictions. Excluded reviewer roles remain excluded. Independent no-FS context works without granting filesystem capabilities.
  • Lifecycle and evidence: scope changes, instruction updates, compaction, next-run refresh, approval continuation, reopen, and binding retirement follow the chosen contract. Persisted history does not accumulate injected instructions; automatic discovery creates no mutation-read evidence.
  • Failure visibility: missing/blank candidates, genuine I/O faults, bounded traversal, and request-budget exhaustion have tested operator-visible outcomes with safe provenance and no silent fallback to unauthorized sources.
  • Documentation and compatibility: correct the owning user guide, document the actual loading/precedence/refresh policy, and update identified contracts deliberately. Include an offline end-to-end conformance fixture through real factory/request construction. Structural mock-provider assertions prove delivery and framing; do not claim they prove arbitrary live-model obedience.

Existing contracts and related work

Recommended classification: Architectural; Split plan/interface approval before implementation. ADR 0359 and the harness-context acceptance contract explicitly preserve root-only discovery and source-authority inheritance. ADR 0043 owns per-run ephemeral assembly. Record which decisions need a new/superseding ADR; do not silently rewrite frozen rationale. Follow engine API compatibility if the scope-aware integration changes exported contracts.

Out of scope: AGENTS.override.md, @imports, new global/home instruction conventions, vendor-wide configuration migration, or executing instruction prose as shell commands. These are not established requirements of the upstream guidance cited here.

Investigation verification

At baseline 3222c2fb808d4140d19b2979a73dd2a6b2cc4398, both focused commands passed:

cd engine && go test ./prompt -run 'Test(DiscoverInstructions|RootAssembler)' -count=1
go test ./internal/app -run '^TestADR_0359_HarnessContext_Scenario3_(RootDiscoveryCompatibility|ProjectInstructionsPerRun)$' -count=1

These confirm the existing root-only and per-run behavior, not hierarchy support. No implementation changes or full-suite qualification were performed for this issue.

Activity

  1. JAORMX commented on Oct 5, 2026

    @JAORMX
    ContributorAuthor

    Implementation analysis: keep hierarchy behind the instruction-source boundary

    Two independent code investigations, followed by a review of composition and execution edge cases, point to a scope-aware extension of the existing source architecture. The filename walk is the small part. The difficult parts are source-to-target mapping, request composition, and ensuring guidance reaches the model before the mutation decision it governs.

    Evidence below is from 3222c2fb808d4140d19b2979a73dd2a6b2cc4398. This is design analysis for the acceptance plan, not an approved interface contract or implementation claim. No code was changed during the investigation.

    Recommended separation

    Component Responsibility
    File-backed instruction adapter AGENTS.md names, ancestor traversal, directory scope, and any approved CLAUDE.md fallback
    Existing source binding/composition Selected sources, provenance/admission, principal, target mapping, ordering, and lifetime
    Engine Current effective instruction view, the view that generated a tool call, and whether replanning is required
    Tool implementation Validated target/effect description based on its actual argument semantics

    The engine should not inspect AGENTS.md filenames, reopen host directories, or infer instruction storage from execution cwd. An API-backed source should be able to provide scoped guidance without pretending to contain files.

    1. Source-to-target mapping is the cloud-native boundary

    An executor path such as /workspace/website/src/app.ts is neither a source identity nor a host path. Different principals and environment revisions can expose the same virtual root.

    The server-owned binding must establish how an execution target maps to a logical target such as website/src/app.ts within an already selected instruction source:

    • An explicitly execution-backed source uses its authorized backend workspace.
    • An independent file/API source needs an explicit trusted mapping or source-native logical targets.
    • Without a mapping, retain its unscoped contribution and report the limit on scoped coverage. Do not search execution files as fallback.
    • No-FS can retain independent context without acquiring file tools or execution storage.
    • Children retain the parent's source authority, while their current focus remains run-local. Do not retarget instructions to a child checkout.

    Existing seams: HarnessSourceRegistration, registerRepositorySources, and selector-free acquisition in internal/adapter/server/placement.go:211.

    Concrete native Kubernetes follow-through: the generic source acquirer calls Reattach without BindingID (internal/adapter/server/placement.go:219), while the native provider rejects an empty binding ID (internal/adapter/executionclient/client.go:776). PlacementBinder.Reattach does not supply one. Enabling execution-backed instruction acquisition through that path needs the server-authorized binding identity captured internally. This does not mean independent Kubernetes context is broken: the existing integration test uses independent context and expressly expects the execution-file registration not to be admitted (internal/adapter/executionclient/harness_context_integration_test.go:138-156).

    2. Use an optional run-local instruction view

    Keep InstructionAssembler.Assemble(ctx) as the once-per-run compatibility path. Do not force soul, memory, and every custom assembler to accept repository paths.

    The proposed additional capability is conceptually:

    open instruction view for this run
      → resolve complete effective contributions for logical target focus
      → return messages and matching scope/provenance metadata together
      → close the view when the run ends
    

    Keep these states separate:

    • Source selection/mapping/backend lifetime: existing binding and generation.
    • Fetched bodies and missing-file observations: source-specific run view.
    • Current focus and the snapshot actually sent to the model: agent.Run.

    Lazy first-observation caching within a run is a reasonable initial freshness policy, with a new run refreshing observations. It avoids watchers and distributed cache invalidation, but is not a transactional repository snapshot. Instruction-file edits during a run need an explicit policy.

    Wrapper propagation is mandatory. The effective chain includes fixedInstructionAssembler, policyInstructionAssembler, generationInstructions, MultiAssembler, and childGenerationInstructions. Each concrete wrapper must preserve the capability and its existing admission, provenance, ordering, or lifetime responsibility. A second raw-provider pointer in the engine would bypass those protections.

    Relevant code: internal/app/harness_context.go:1252-1367, internal/app/harness_context_binding.go:201-216, internal/app/harness_context_generation.go:67-101, and internal/app/build.go:7018-7027. In particular, acquire one run hold for repeated scoped lookup; do not repeatedly register the child hold currently established during once-per-run assembly. Protect in-flight reads during cancellation.

    3. Resolve complete views; do not append scoped text indefinitely

    For each source, resolve its root/unconditional plus applicable scoped contribution, then apply the existing source policy.

    For combined sources A and B, preserve:

    A root + A applicable nested guidance
    B root + B applicable nested guidance
    

    Do not produce all roots followed by all nested guidance. Under replace, an earlier source with only an applicable nested contribution can become the winner; a cached lower-source root cannot remain in the active prefix. Whole-view versus per-target replacement must be decided explicitly.

    A run-long observation cache is useful; a run-long set of universally active instructions is not. Frontend → backend → frontend should reuse cached observations while changing the effective instruction view. Multi-target views need trusted scope framing so sibling guidance does not become overriding merely because it appears later.

    Deduplicate by source-local contribution identity within the binding, not body text, basename, or /workspace. Preserve historical tool messages; replace the ephemeral effective view instead. Compaction and manifests must describe that same view (engine/agent/loop.go:3176, engine/agent/request_manifest.go:23).

    4. Describe targets at the tool boundary and replan unseen-context mutations

    tool.LocalFileOperands already recognizes some built-in operands, but it is not a complete effect declaration (engine/tool/tool.go:341). A shell-script operand does not describe the files the script changes, and a custom/MCP argument named path does not establish workspace semantics.

    Prefer a small optional typed capability on tool implementations for known targets and their read/mutation/subtree relevance, with an honest unknown-effects classification. Reuse actual argument validation. Do not add another engine switch over tool names and JSON keys, or infer semantics from model-facing schemas. Target metadata does not grant authority; mapping and authorization still apply.

    The ordering problem is concrete: a model can emit Read("website/a.ts") and Edit("website/a.ts", ...) in one turn. Read-parallel/mutate-serial dispatch does not insert another model decision between them.

    If a mutation requires instructions absent from the request that generated it:

    1. Resolve the required scoped view.
    2. Do not execute the stale proposal.
    3. Publish a normal CallID-matched result explaining that execution did not occur and reconsideration is required.
    4. Include the effective view in the next request and let the model issue a fresh call.

    Use existing result pairing and the normal loop, rather than a new parked-mutation scheduler. Conservatively suppress remaining mutations/unknown-effect calls in a stale batch; different paths do not prove semantic independence. Preserve actual results from calls already executed and existing failure/turn limits.

    Preflight is not sufficient by itself. Recheck effective arguments after hook rewrites and approval waits, including external-authorization continuation paths. References: engine/agent/dispatch.go:65, :805, :991, and engine/agent/loop.go:1500.

    Fetched is not delivered. Freeze the context snapshot used by each model turn after request construction/compaction and before runTurn (engine/agent/loop.go:1863). A cache hit, fresh assembly on resume, or human permission does not establish that an old proposal was generated with those instructions. Without trustworthy generating-request evidence on continuation, replan the context-sensitive mutation. Transparent cross-process continuation would need a larger durable-evidence contract. Correctness cannot depend on optional request-manifest logging.

    5. Contextual review must use the appropriate effective context

    Action review currently captures instruction facts once (engine/agent/actionreview.go:209, :318). Changing the main request alone would leave reviews with stale facts.

    Separate invariant principal/root facts from target-qualified action-local instruction context. Do not let a child replace the shared review root with its active package scope. Bind reviews and repeat grants to the relevant effective-view identity. Existing revision checks and grant machinery can be reused, but revision increments and digest invalidation are different: grant digests hash principal facts, not principalRevision (internal/app/guardrails.go:270). The plan must specify context changes during approval and content-addressed A→B→A reuse.

    6. Keep opaque-tool policy explicit

    Arbitrary Shell, background commands, and opaque remote tools cannot have complete affected-path discovery through argument parsing. Three honest choices exist:

    • Strong coverage for trustworthy target-aware tools, documented best-effort guidance for opaque tools.
    • Require declared scope for opaque mutations, while acknowledging that a declaration alone does not confine actual effects.
    • Enforce scope through the execution facility, which is substantially larger sandbox/execution work.

    Recommendation: do not silently disable Shell or add a sandbox as part of this issue. Scope the first deterministic guarantee to structured target-aware operations, and obtain an explicit decision on opaque-tool behavior. Upstream AGENTS.md guidance does not settle this policy.

    Suggested implementation sequence and proofs

    1. Approve mapping, composition, activation, freshness, failure, and continuation semantics under the architectural acceptance route.
    2. Implement the run-local view and wrapper forwarding, then one file-backed hierarchy adapter.
    3. Add typed targets, generating-request snapshots, and replanning integration.
    4. Align review evidence and binding lifetime, then qualify actual cloud adapters.

    Prioritize tests for wrapper admission/provenance preservation; source grouping and replace winner changes; sibling scope transitions; fetched-but-not-published context; same-turn Read→Edit; new-file writes; hook retargeting; approval/restart without delivery evidence; child-local scope isolation; generation cleanup; no-FS independent context; and discovery leaving the execution read ledger untouched.

    Resolve only ancestor candidates rather than recursively scanning repositories. Keep caches run-local and source-bound. Validate targets using actual backend semantics: Redis code is in adapters/redisstore/workspace.go and rejects any .. component before normalization. The protected source-workspace wrapper also does not automatically forward optional backend capabilities; expose only what mapping actually needs, rather than unwrapping it. Reference-adapter tests do not qualify Redis, MicroVM, or native Kubernetes production integration.

    Coordinate the generic target-activation/request-lifecycle work with #1974, while keeping AGENTS hierarchy and rule-format parsing in their respective adapters.

    The governing invariant: execution identifies what is being worked on; the admitted source binding determines where instructions may come from; the generating model request establishes which instructions were available to inform the proposed action.

  2. self-assigned this
    on Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions