Skip to content

core: new sessions reuse stale AGENTS.md from the per-location instruction cache #51936

Open

Description

@depler

Description

Instruction files are not read per session. Their contents live in a per-location, in-memory cache (InstructionDiscovery), and a brand-new session only snapshots that cache into its durable instruction state. The cache is invalidated exclusively by a filesystem watcher: there is no read-on-session-start and no mtime/hash check when a session is initialized. So whenever the watcher misses an edit, every new session in that location keeps the previous contents of AGENTS.md until the location is rebuilt (explicit config reload, restart, or location TTL expiry).

This is not limited to symlinked files; the symlink case is simply a deterministic reproduction, because the watcher subscribes to the unresolved path while the reader resolves it with fs.resolve (realpath).

Where in the code

  1. packages/core/src/config/plugin/instruction.ts

    The only invalidation path is the watcher, subscribed once when the location activates, with a debounce before the rescan:

    const updates = yield* PubSub.subscribe(changes)
    yield* Stream.fromSubscription(updates).pipe(
      Stream.debounce("100 millis"),
      Stream.runForEach((file) => refresh(file).pipe(Effect.andThen(discovery.reload()))),
      Effect.forkScoped({ startImmediately: true }),
    )
    yield* refresh()

    Nothing else re-reads the files afterwards. The watcher candidates for project files are not realpath-resolved:

    ...(project
      ? ancestorDirectories(start, stop)
          .map((directory) => join(directory, "AGENTS.md"))
          .filter((file) => discovery.global || file !== globalFile)
      : []),

    while projectSource() / read() read through fs.resolve / fs.readFileStringSafe. With a symlinked AGENTS.md, Watcher.subscribe({ path, type: "file" }) watches the symlink's directory instead of the target's directory, so edits to the real file produce no event and refresh() never runs. (The global candidate is resolved via fs.resolve and is watched correctly; only project candidates are affected.)

  2. packages/core/src/instruction-discovery.ts

    load() returns a snapshot of the in-memory state:

    load: Effect.fn("InstructionDiscovery.load")(function* () {
      const files = yield* list()
      if (!Array.isArray(files)) return source(files)
      return source(files.length === 0 ? Instructions.removed : files)
    }),

    with source(...) using read: Effect.succeed(value). The cached value only changes through transform / reload, i.e. only when the watcher fires.

  3. packages/core/src/session/instruction-state.ts

    A new session's baseline is taken from that snapshot: observe() → Instructions.read(instructions) → commit() persists initial_values, and initial() renders the per-request epoch baseline from initial_values. There is no re-read of the files at session creation, so the session inherits whatever the location cached — including a value that is no longer on disk.

Steps to reproduce (deterministic)

  1. At the project root, make the instruction file a symlink: ln -s real/AGENTS.md AGENTS.md.
  2. Start OpenCode in that project (the location activates and discovers AGENTS.md).
  3. Edit the real file real/AGENTS.md, not the symlink.
  4. Create a brand-new session in the same project.
  5. Ask the model to repeat the instructions it was given from that file.

General case (no symlink): any edit the watcher does not deliver — made before the subscription is ready, or on a filesystem where events are unreliable — leaves new sessions with the old contents. There is no fallback re-read that corrects it.

Expected Behavior

A new session uses the current contents of AGENTS.md.

Actual Behavior

The new session keeps the previous contents. The change only appears after the location is rebuilt (config reload or restart), because the per-location cache is stale and nothing re-reads the file when a new session starts.

Workaround

Force the watcher to deliver an event for the instruction file by bumping the metadata of the watched (unresolved) path itself:

touch -h AGENTS.md

Why this works:

  • touch -h is touch --no-dereference: it updates the timestamps of the symlink itself instead of its target (the lutimes(2) syscall). Plain touch AGENTS.md follows the link and touches the real file — precisely the write that the watcher never observes here, so it changes nothing about the cache.
  • The project candidates are registered through the unresolved path (join(directory, "AGENTS.md")), while projectSource() / read() resolve the path with fs.resolve (realpath). As a result the watcher is attached to the symlink's own directory and only reports events for the symlink inode. Rewriting the target changes neither the link nor its directory entry, so no event is produced and refresh() / discovery.reload() never run (see "Where in the code").
  • touch -h produces a metadata change on the link inode that the watcher does report. That drives the existing invalidation path — Stream.debounce("100 millis") → refresh(file) → discovery.reload() — standing in for the missing event, so the location cache is refilled with the current contents of the target.
  • For a regular (non-symlinked) AGENTS.md the same trick applies with a plain touch AGENTS.md: on filesystems where events are unreliable, an explicit metadata event for the watched file forces the rescan that a missed notification would otherwise skip.

In other words, the manual touch is a deterministic substitute for the watcher event the stale cache depends on. It is a workaround, not a fix: it has to be repeated after every edit until instruction files are re-read at session start (or the cache is invalidated by some other means).

Environment

  • opencode version: 2.0.18
  • OS: Linux (Ubuntu, x64)
  • Terminal: unavailable
  • Shell: /usr/bin/bash

Activity

  1. github-actions commented on Sep 28, 2026

    @github-actions
    Contributor

    This issue might be a duplicate of or overlap with existing issues. Please check:

    • #11532: reports AGENTS.md not being present in a newly created /new session; this issue identifies a symlink-specific cause for stale instructions.
    • #34341: tracks how edits to path-scoped AGENTS.md files are re-observed and delivered through durable Instructions, which may overlap with the stale-update behavior here.
  2. changed the title [-]core: new sessions keep stale AGENTS.md when the project instruction file is a symlink[/-] [+]core: new sessions reuse stale AGENTS.md from the per-location instruction cache[/+] on Sep 28, 2026
  3. opencodejr commented on Oct 28, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report. I can confirm this on 2.0.18, and it still happens on the latest dev (86ce19d).

    Setup: AGENTS.md at the project root is a symlink to real/AGENTS.md, and a simulated model reports which instruction text it received in its request.

    1. Session 1 gets the original contents.
    2. I edited real/AGENTS.md (the target, not the symlink), waited a few seconds and started a new session with /new. That session still got the old contents.
    3. I touched the symlink itself, which is what touch -h AGENTS.md does, and started another new session. That one got the new contents, so your workaround works.

    The recording and screenshots below show this, and the script below reproduces it.

    The code matches your analysis: project AGENTS.md paths are watched without resolving the symlink, but they are read through the resolved path. The global AGENTS.md and files listed in instructions are already resolved before they are watched.

    recording.mp4

    Screenshot

    Screenshot

    Reproduction script (drive.ts)
    // Repro for #51936: symlinked project AGENTS.md edits are not picked up by new sessions.
    import { Effect, Stream } from "effect"
    import { Llm, OpenCodeDriver } from "opencode-drive"
    import { readdirSync, readFileSync, existsSync, symlinkSync, writeFileSync, lutimesSync } from "fs"
    import { join } from "path"
    
    const token = `tok-${Date.now()}-${Math.random().toString(36).slice(2)}`
    let projectDir = ""
    
    const sleep = (ms: number) => Effect.promise(() => new Promise((r) => setTimeout(r, ms)))
    
    export default OpenCodeDriver.use(
      {
        ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
        tui: { recording: true },
        project: { git: true, files: { "real/AGENTS.md": "Instruction marker: OLD_MARKER\n", ".token": token } },
        // Setup has no project path; locate the isolated project by its unique token and
        // make AGENTS.md a symlink to real/AGENTS.md before OpenCode starts.
        setup: () =>
          Effect.sync(() => {
            const root = "/tmp/opencode-drive"
            for (const run of readdirSync(root)) {
              const dir = join(root, run, "files")
              const f = join(dir, ".token")
              if (existsSync(f) && readFileSync(f, "utf8") === token) projectDir = dir
            }
            if (!projectDir) throw new Error("project dir not found")
            symlinkSync("real/AGENTS.md", join(projectDir, "AGENTS.md"))
          }),
      },
      ({ ui, llm }) =>
        Effect.gen(function* () {
          // The simulated model reports which AGENTS.md content it received in its request.
          yield* llm.serve((request) => {
            const body = JSON.stringify(request)
            const seen = body.includes("NEW_MARKER") ? "SAW_NEW_MARKER" : body.includes("OLD_MARKER") ? "SAW_OLD_MARKER" : "SAW_NO_MARKER"
            return Stream.make(Llm.text(`Model received: ${seen}`))
          })
    
          // Session 1: baseline, AGENTS.md -> real/AGENTS.md (OLD).
          yield* ui.submit("session 1: which instructions do you have?")
          yield* ui.waitFor("Model received:")
          yield* ui.screenshot("1-session1")
    
          // Edit the real target file (not the symlink).
          writeFileSync(join(projectDir, "real/AGENTS.md"), "Instruction marker: NEW_MARKER\n")
          yield* Effect.log("edited real/AGENTS.md -> NEW_MARKER; on disk via symlink: " + readFileSync(join(projectDir, "AGENTS.md"), "utf8"))
          yield* sleep(3000)
    
          // Session 2: brand-new session should see NEW.
          yield* ui.submit("/new")
          yield* sleep(1500)
          yield* ui.submit("session 2 (after editing real/AGENTS.md): which instructions?")
          yield* ui.waitFor("Model received:")
          yield* sleep(500)
          yield* ui.screenshot("2-session2-after-edit")
    
          // Workaround from the report: touch the symlink itself.
          const now = new Date()
          lutimesSync(join(projectDir, "AGENTS.md"), now, now)
          yield* Effect.log("touched symlink (touch -h AGENTS.md)")
          yield* sleep(3000)
    
          yield* ui.submit("/new")
          yield* sleep(1500)
          yield* ui.submit("session 3 (after touch -h AGENTS.md): which instructions?")
          yield* ui.waitFor("Model received:")
          yield* sleep(500)
          yield* ui.screenshot("3-session3-after-touch")
        }),
    )

    Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.

  4. rafaetri commented on Nov 13, 2026

    @rafaetri

    I would like to take this one. I have a fix with a test: OpenCode now also watches the file a symlinked AGENTS.md points to, so edits to it reach new sessions. I put it up in #63754.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions