> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Overview

> Subscribe to external file changes on any TypeScript mount. Mirage invalidates its caches before every event is delivered.

## What It Does

Files on a mounted backend change outside your workspace all the time: a
teammate uploads to Nextcloud, a pipeline rewrites an S3 object, or a cron job
deletes a report. `watch` turns those changes into an async event stream.

```ts theme={null}
import { NextcloudVFS, Workspace } from "@struktoai/mirage-node";

const vfs = new NextcloudVFS({ url: process.env.NEXTCLOUD_URL! });
const ws = new Workspace({ "/nc": vfs });

for await (const event of ws.watch("/nc/Documents")) {
  console.log(event.kind, event.path.virtual);
  const result = await ws.shell(`cat ${event.path.virtual}`); // guaranteed fresh
  console.log(result.stdoutText);
}
```

No setup call is needed. The watch runtime attaches lazily on first use, and an
idle workspace carries no watch state. Mirage runs **no server and no
background loop**. Detection is yours—a webhook receiver or a small poll
loop—while Mirage handles cache invalidation, scope matching, and delivery.

```mermaid theme={null}
flowchart LR
    NC[Backend<br/>Nextcloud, S3, ...] -->|webhook| RX[Your receiver]
    NC -->|delta pull| PL[Your poll loop]
    RX --> N["ws.notify(event)"]
    PL --> N
    N --> INV[invalidate caches<br/>path + ancestor listings<br/>+ removed subtree if a listing is cached]
    INV --> Q[per-watch queues<br/>scope matching]
    Q --> W["for await (const event of ws.watch(...))"]
```

## Scopes

The root's shape defines the depth, using GNU shell glob semantics. `*` never
crosses `/`, and matching happens at delivery time, so newly created files can
match.

| root | scope |
| - | - |
| `/nc/data` | the whole subtree |
| `/nc/data/*` | entries at that level only (shallow) |
| `/nc/data/*/` | everything inside child directories |
| `/nc/data/*.txt` | `.txt` entries at that level |
| `/nc/data/*/reports/` | everything inside each child's `reports` directory |
| `['/nc/docs', '/nc/cfg/app.yaml']` | any of several roots, one event stream |

```ts theme={null}
for await (const event of ws.watch("/nc/data/*.pdf")) {
  // ...
}

for await (const event of ws.watch(["/nc/inbox/*", "/nc/config"])) {
  // ...
}
```

## The Event

```ts theme={null}
class FileEvent {
  readonly kind: FileChangeKind; // create / update / delete / move / unknown
  readonly path: PathSpec;
  readonly timestamp: Date;
  readonly previousPath: PathSpec | null;
  readonly metadata: FileMetadata | null;
}
```

`FileMetadata` carries `fingerprint`, `size`, and `modified`. Producers fill
only what their signal honestly knows. A listing walk usually supplies all
three; a webhook payload may supply none.

Events are **level-triggered**: an event says what is dirty, not every
intermediate edit. Read current content through the workspace after receiving
one. Mirage invalidates the changed path and every cached ancestor listing up
to its mount root before the event reaches a subscriber.
A `delete`, or the old path of a `move`, drops the cached subtree when a listing
is retained at or below that path. Without one, descendant file bodies can
remain cached until their TTL. An `unknown` event always invalidates the
subtree, regardless of retained listings.

`unknown` is the overflow signal. If a burst exceeds the queue cap, pending
events collapse into one `unknown` event per watch root, meaning “re-inventory
this subtree.” Precision degrades, but dirtiness is not lost.

## Push Mode

Your application hosts the endpoint; mirage opens no socket and runs no
watcher. What arrives is the provider's own payload, and turning that into a
path is the only real work. Four backends ship a mapper for it:

```ts theme={null}
import { SlackEventHook } from "@struktoai/mirage-core/core/slack/watch/index";

const hook = new SlackEventHook(vfs.accessor);

// your Express/Hono/Fastify route:
const { event } = await request.json();
for (const change of await hook.toEvents(root, event.type, event)) {
  await ws.notify(change);
}
```

You import the mapper for the backend you mounted rather than asking the
mount for one, because a push payload has no vendor-neutral shape: the code
that builds the call already names the backend, so a generic accessor would
buy nothing.

| Backend | Import | Notification |
| - | - | - |
| Slack | `SlackEventHook` (`mirage-core/core/slack/watch/index`) | Events API delivery (inner `event` object) |
| Disk | `DiskEventHook` (`mirage-node`, `core/disk/watch/hook`) | watchdog-shaped fields (`src_path`, `dest_path`) |
| Redis | `RedisEventHook` (`mirage-node`, `core/redis/watch/hook`) | keyspace notification (`__keyevent@N__:<verb>`, the key) |
| Box | `BoxEventHook` (`mirage-core/core/box/watch`) | one `/events` entry, read after the long poll (`realtimeServer`) answers `new_change` |

A mapper answers with zero or more `FileEvent`s and never invents a path it
was not told about. When a notification names only a scope, it returns
`UNKNOWN` on that directory, which the watcher reads as "re-inventory
everything below".

Slack is where the mapping earns its place. A message maps to
`channels/<name>__<CID>/<YYYY-MM-DD>/chat.jsonl`, and the day is bucketed in
**UTC** while Slack's client shows local time, so a hand-written mapper names
tomorrow's directory for a fifth of every day and never errors, because
notifying a path the mount does not serve evicts nothing. A **thread reply**
is the other trap: `chat.jsonl` renders `conversations.history`, which returns
parents only, so a reply appears in no day file at all. What changed is the
parent's `reply_count`, in the parent's day.

For a backend with no mapper, build the `FileEvent` yourself:

```ts theme={null}
import { FileChangeKind, FileEvent, PathSpec } from "@struktoai/mirage-node";

await ws.notify(
  new FileEvent({
    kind: FileChangeKind.CREATE,
    path: PathSpec.fromStrPath("/nc/data/report.txt"),
    timestamp: new Date(),
  }),
);
```

The provider receiver stays in your application, so it can use your existing
HTTP framework, authentication, retries, and deployment model.

## Pull Mode

Backends that implement `deltaHook()` answer one question: what changed under
this root since the last checkpoint? Eleven VFS families ship one today,
listed in the [Watch Matrix](/typescript/watch-matrix) with the fingerprint
each one compares on. A baseline pull (`checkpoint === null`) establishes
state and emits no changes.

```ts theme={null}
import { PathSpec } from "@struktoai/mirage-node";

const mount = ws.registry.mountFor("/nc");
if (mount === null || mount.vfs.deltaHook === undefined) {
  throw new Error("mount does not support pull detection");
}

const hook = mount.vfs.deltaHook();
const root = PathSpec.fromStrPath("/nc", "");
let checkpoint: string | null = null;

for (;;) {
  const delta = await hook.pull(root, checkpoint);
  checkpoint = delta.checkpoint;
  for (const event of delta.changes) await ws.notify(event);
  await new Promise((resolve) => setTimeout(resolve, 30_000));
}
```

A runnable version needing no credentials is
[`examples/typescript/disk/watch.ts`](https://github.com/strukto-ai/mirage/blob/main/examples/typescript/disk/watch.ts):
it writes to the mount's directory behind mirage's back, pulls the diff, and
reads the changed file back through the workspace.

Pull is self-healing because current backend state is compared with the saved
checkpoint. Events missed while your service was down appear on the next pull.
A common production shape is push-first with a startup pull for recovery, or a
webhook used only as a doorbell that triggers one pull.

## Queues

Each `watch()` owns its own queue. `notify` fans an event out to every matching
queue, so overlapping watches consume independently and a slow consumer only
overflows its own queue.

The default `RAMWatchQueue` keeps one pending change per path. Create followed
by update stays create; create followed by delete cancels; delete followed by
create becomes update. Overflow policy is `collapse` (default), `drop_oldest`,
or `error`.

Attach a custom runtime before the first `watch()` or `notify()` call:

```ts theme={null}
import { RAMWatchQueue, Watcher } from "@struktoai/mirage-node";

ws.attachWatchRuntime(
  new Watcher(
    ws.registry,
    (roots) => new RAMWatchQueue(roots, { maxPending: 64 }),
  ),
);
```

Any object satisfying `WatchQueue` (`push`, `pop`, `pending`, `clear`, and
`close`) can replace the RAM queue. This is the extension point for a durable
Redis, SQS, or database-backed queue.

Call `await ws.detachWatchRuntime()` to close subscriber queues and end active
watch loops cleanly without closing the workspace. The next `watch()` or
`notify()` lazily creates a fresh default runtime.

## Scope Notes

* Watch roots are fixed at subscription time. Start a new `watch()` to change
  the scope.
* One watch may span mounts, including nested mounts. Each event is invalidated
  on the longest-prefix mount that owns its path.
* Delivery works on every backend. Pull detection ships for eleven VFS
  families; see the [Watch Matrix](/typescript/watch-matrix).
* Events are in-memory and at-most-once per subscriber unless you provide a
  durable queue implementation.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.