Skip to content

Add interactive tracking, text-file rules, and directory dataset access logging - #3

Merged
hodczak merged 58 commits into
mainfrom
ontrail
Nov 15, 2026
Merged

hodczak merged 58 commits into
mainfrom
ontrail

Conversation

@hodczak

@hodczak hodczak commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR extends Trail with automatic asset discovery, directory dataset tracking, and an interactive terminal.

  • Interactive terminal: inspect tracked resources and their event history while filesystem observation runs.
  • Text-file rules: configure automatic tracking in .ontrail and exclusions in .offtrail.
  • Directory datasets: track stores such as Zarr as resources and summarize activity inside them into access events.
  • Shared selections: use the trail.select expression language through Python collections and terminal listings.
  • Path normalization: resolve home-directory aliases consistently when formatting rules; normalize path fixtures for macOS.

Quick usage

From the repository checkout, using Python 3.12 or newer:

python -m pip install -e .
mkdir trail-demo
cd trail-demo
printf 'value\n1\n' > sample.csv
trail

Choose the general preset when prompted. At Trail's prompt:

assets
dirs
offtrail sample.csv
ontrail sample.csv
events src_path=sample.csv
quit

ontrail and offtrail change active tracking. Edit .ontrail and .offtrail to change automatic discovery, then restart Trail. The log persists between runs.

The class examples below use a temporary project containing new.csv, data/map.png, cube.zarr, and an initially untracked notes.md. The directory-access example uses a constructed event with representative notification counts. The directory dataset tests and access tests cover discovery and observation behavior.

Core classes

Trail

Trail is the project entry point. It exposes inclusion and exclusion rules, configured directories, tracked assets, and the event log.

For the Python examples, open a project containing the sample files:

from trail import Trail
trail = Trail('/path/to/project')

Later blocks such as trail.ontrail: OnTrail show an attribute's type. They are access hints, not setup statements.

Trail
    id: 38ca41930e0445368c84ee5516a40a9b
    dir: /tmp/trail-pr-example-1dbbg0k7/.trail
    dirs: [
        /tmp/trail-pr-example-1dbbg0k7,
        /tmp/trail-pr-example-1dbbg0k7/data,
    ]
    assets: [
        /tmp/trail-pr-example-1dbbg0k7/cube.zarr,
        /tmp/trail-pr-example-1dbbg0k7/new.csv,
        /tmp/trail-pr-example-1dbbg0k7/data/map.png,
    ]
  • Trail(path) opens the nearest project found from the supplied directory. A new project can start from an inclusion preset, such as Trail(path, ontrail='geospatial').
  • Trail.locate() searches the directory and its ancestors for .trail, stopping before directories listed in TRAIL_CEILING_DIRECTORIES.
  • Trail.clear() untracks assets and discards the log. The project ID and rule files remain; configured directories are logged again with their existing IDs.

Rules and scopes

The rule files define automatic discovery:

  • Rule parses rule syntax.
  • TXT reads the rule files.
  • Scopes matches inclusion patterns.
  • Rules supplies the common collection behavior inherited by OnTrail and OffTrail.

Rule(str)

Rule is an immutable string with the syntax operations used by both rule files.

  • Rule.parse() separates a rule into its directory anchor and matching pattern.
  • Rule.kind() describes it for rule listings, for example root scope or dir scope.
  • Rule.validate() rejects invalid syntax.
  • Rule.ambiguous_directory() identifies a directory written without its trailing / so diagnostics can explain how the rule will be read.

TXT

TXT wraps the text file stored in a rule collection's .txt attribute.

TXT
    path: /tmp/trail-pr-example-1dbbg0k7/.ontrail
    tail:
        ./
        *.csv
        data/*.png
        *.zarr
  • TXT.read() loads rules in file order, skipping comments and blank lines. It does not rewrite the file or itself rebuild project state.
  • TXT.numbered() retains source line numbers for diagnostics.
  • TXT.create() initializes a missing file from its owner's preset directory or a supplied file. This setup operation remains necessary with direct text editing.

Scopes(Sequence[str])

Scopes holds inclusion rules beside their compiled patterns. Root scopes apply beneath configured roots; local scopes apply relative to one configured directory.

trail.scopes: Scopes

This PR exposes root inclusion scopes as trail.scopes. A future commit moves them to trail.ontrail.scopes and exposes exclusion scopes as trail.offtrail.scopes.

Scopes (2)
    *.csv
    *.zarr
  • Scopes.decide() returns the last matching rule. Matching ignores case; a leading ! excludes the match.
  • Local directory patterns address direct children unless they reach subfolders, such as with **. A root rule alone watches a directory without selecting all its files.

Rules(Sequence[Rule])

Rules holds the ordered rules of one file. Its inclusion and exclusion subclasses share iteration, indexing, diagnostics, and preset lookup.

  • Rules.available() lists the presets belonging to the subclass. Inclusion and exclusion presets stay separate.
  • Rule files are edited directly as text, for example with Vim. Restart the console or reopen the project to apply external edits; automatic rule-file reload is not implemented.
  • Changing discovery rules leaves already tracked assets in place. Explicit untracking removes them from active tracking.

OnTrail(Rules)

OnTrail holds .ontrail, the text file beside .trail that names directories to watch and files or datasets to discover.

trail.ontrail: OnTrail
OnTrail (4)
    ./
    *.csv
    data/*.png
    *.zarr
  • trail.ontrail(*paths) tracks paths immediately. A directory becomes one directory dataset. A single path returns its asset; multiple paths return a list. Neither rule file changes.
  • Root rules such as ./ name directories to watch recursively. Root patterns such as *.csv apply at any depth beneath those roots; data/*.png applies relative to data.
  • OnTrail.warnings reports invalid rules, ambiguous directory syntax, and attempts to use directory datasets as scan roots.
  • Bundled presets are default, general, geospatial, and ml. The default contains only ./; the others also select extensions.

OffTrail(Rules)

OffTrail holds .offtrail, whose rules exclude paths from automatic discovery before inclusion rules are considered.

trail.offtrail: OffTrail
OffTrail (1)
    .*
  • trail.offtrail(*paths) untracks assets and remembers their paths so later discovery, including after reopening, does not take them again. Neither rule file changes.
  • OffTrail.default() initializes a missing .offtrail with .*, excluding dotfiles and hidden folders. An empty file ignores nothing; a missing file receives the default again.
  • OffTrail.decide() uses case-insensitive matching and the last matching rule. A negation such as !.env makes the path eligible for inclusion rules again.
  • Explicit trail.ontrail(path) can track a path excluded by .offtrail. Trail metadata remains protected.

Entries and collections

  • Collection supplies ordered storage.
  • EntryCollection adds path lookup for the directory and asset collections.
  • Entries provides one lookup across those collections.
  • Entry is the shared record base for configured directories and tracked assets.
  • Dir represents a configured directory; Dirs holds those records.
  • Asset represents a tracked file; DirAsset represents a directory dataset. Assets holds both.

Collection

Collection supplies ordered storage shared by event, asset, and directory collections.

  • Iteration yields records. Membership accepts a record or its lookup key.
  • Collection.select exposes positional and expression-based selection, described under Select below.
  • Collection.get() supports a default for missing keys.

EntryCollection(Collection[EntryKey, E])

EntryCollection supplies ID and path lookup for Assets (tracked files and datasets) and Dirs (configured directories). Passing several keys returns a tuple of entries. EntryKey accepts an ID or path; E is the entry record type.

Entries

Entries is a combined view over assets and configured directories, without maintaining a second collection of records.

trail.entries: Entries
  • entries[key] looks up an ID or path, trying assets first. Several keys return a tuple; missing keys raise KeyError.
  • Entries.get() returns a default for missing keys.
  • Iteration yields configured directories followed by assets. Selections remain on the individual collections.
  • Entries.untracked remembers explicitly untracked paths across log replay. Tracking a path again removes it from this set.
  • Entries.is_metadata() protects .trail and its contents, .ontrail, and .offtrail from tracking and filesystem-event handling.
  • Entries.is_trackable() applies discovery eligibility, exclusions, remembered untracking, and dataset ownership.
  • Entries.is_walkable() prevents descending into symlinks, metadata, remembered untracked paths, and directory datasets. An excluded directory is traversed only when a configured directory at or below it requires access.

Dir(Entry)

Dir now represents a directory named by inclusion rules, with its root status and local scopes. Ordinary subfolders encountered by recursive observation do not acquire separate directory records.

Dir
    id: 76af82f6291f4f389397ae14b69a74df
    path: /tmp/trail-pr-example-1dbbg0k7/data
    root: False
    scopes: [
        ./*.png,
    ]
  • Dir.decide() evaluates its local scope patterns.
  • Moving a configured directory repaths tracked descendant assets. The rule remains anchored at its configured path, and a warning identifies the moved directory.
  • A directory tracked as one dataset is excluded from the configured-directory collection.

Dirs(EntryCollection[Dir])

Dirs holds the configured directory records and the root scopes used during matching.

trail.dirs: Dirs
  • Dirs.refresh() reconciles records with inclusion rules and records directory additions or removals. Surviving records retain their IDs across refreshes and reopening.
  • Dirs.match() consults the deepest matching directory before its ancestors and the root scopes.
  • Dirs.clear() refuses direct clearing: a configured directory goes when its rules leave .ontrail.

Asset(Entry)

Asset represents a tracked file. Its repr now includes its current size and modification time; a missing resource displays <missing>.

Asset
    id: 2a0737e73af0421d8792abbcef140708
    path: /tmp/trail-pr-example-1dbbg0k7/new.csv
    st_size: 19 B
    st_mtime: 2026-11-04 22:12:54
  • Asset.from_path() chooses a file asset or a directory dataset from the supplied path.

DirAsset(Asset)

DirAsset represents a directory tracked as one dataset. It shares the asset collection with files and retains one resource ID across dataset rewrites and moves.

DirAsset
    id: 3678d4736f734c17b653762632dac855
    path: /tmp/trail-pr-example-1dbbg0k7/cube.zarr
    files: 2
    st_size: 5 B
    st_mtime: 2026-11-04 22:12:54
  • DirAsset.is_match() recognizes .zarr, .n5, .gdb, and .safe directories during automatic discovery. Explicit tracking also accepts other directories as datasets.
  • DirAsset.children chooses the format-specific filename patterns that distinguish dataset activity from locks, temporary files, and unrelated files. Other explicitly tracked directories include every child.
  • DirAsset.access exposes the current Access, the object accumulating filesystem notifications for that dataset.

Assets(EntryCollection[Asset])

Assets holds tracked files and directory datasets, using the shared entry-collection lookup and selection behavior.

trail.assets: Assets
  • Assets.add() accepts resolved paths mapped to their selecting rule, or None for explicit additions. It returns assets in request order, reuses existing assets without duplicate addition events, and reconciles directory records and watches.
  • Assets.scan() discovers eligible paths. It can select a directory dataset itself and skips descending into its dataset contents.
  • Assets.holder() identifies the dataset owning a path and prevents separate tracking of dataset children. Unrelated files within recognized dataset directories can still be tracked independently. Tracking a directory whole untracks already tracked children it absorbs and warns about them.

Filesystem observation and dataset accesses

  • Watchdog chooses what to watch.
  • WatchdogSession runs the observer.
  • Handler receives filesystem notifications.
  • Access accumulates a directory dataset's notifications and produces one DirectoryAccessEvent.

Watchdog

Watchdog manages watch placement separately from the observer run; synchronous inspection shows the watches a later run would place.

trail.watchdog: Watchdog
Watchdog
    running: False
    watches: [
        /tmp,
        /tmp/trail-pr-example-1dbbg0k7,
    ]
  • Watchdog.desired() requests recursive watches for configured directories and directory datasets, plus parent watches for moves and deletion. Watches already covered by recursive ancestors are omitted.

WatchdogSession

WatchdogSession owns the observer and consumes its notifications. Handler receives notifications on the observer thread, using rule snapshots published by the session. For directory datasets, Access accumulates notifications into one DirectoryAccessEvent. Concurrent readers and writers share the same access.

trail.watchdog.session: WatchdogSession
  • WatchdogSession.start() starts observation on a running asyncio loop. Synchronous use remains dormant until a loop starts a session.
  • async with trail.watchdog.session manages a run explicitly.
  • WatchdogSession.reconcile() updates watch placement and publishes rule snapshots for the observer thread.
  • Idle dataset accesses close after the configured gap, 30 seconds by default.
  • Missing-watch failures warn without stopping unrelated watches.
  • WatchdogSession.stop() stops observation, drains delivered events, and closes remaining accesses. A later run creates a fresh observer and per-run state.
  • Clearing the live event log drops pending accesses so they cannot repopulate the discarded history.

DirectoryAccessEvent(WatchdogEvent)

DirectoryAccessEvent records a completed dataset access as one synthetic event. The representative fixture below contains one open and 72 modification notifications over 242 ms.

>>> trail.events.select('cls=DirectoryAccessEvent')
Events (1)
    0. DirectoryAccessEvent
        id: 1a145093167f4b13b04277fe5bd8fd01
        timestamp: 06:12:54.111
        src_path: /tmp/trail-pr-example-1dbbg0k7/cube.zarr
        event_type: modified
        started: 06:12:53.869
        count: opened 1, modified 72
  • An access is opened when only opens occurred, or modified when other counted activity occurred. Empty accesses are discarded.
  • Counts measure delivered opened, created, modified, moved, and deleted notifications, not distinct files or application operations. Temporary-file renames into dataset children count as writes; ignored lock files do not turn a read into a write.
  • started is the first notification's arrival time; timestamp is the last.
  • Start time and operation counts are serialized for replay.
  • Accesses close before moves, deletion, or untracking so their resource and path remain associated with the preceding activity.

Command-line interface

The terminal combines setup, a live event feed, and commands for inspecting or changing active tracking. Rule configuration stays in the two text files.


Project setup

Initialization prepares a project before opening the console. Picker lets the user choose the inclusion rules during that setup.

Initialization

main() opens the console, running setup first when the directory has no project. Setup can also run alone:

trail [PATH]
trail init [PATH]
python -m trail [PATH]
  • --nodir skips setup and holds events in memory.
  • Setup writes the selected .ontrail and initializes a missing .offtrail, then discovers eligible assets.
  • Reinitialization replaces .ontrail while retaining .offtrail, the project ID, tracked assets, and event history.
  • Package data includes both preset directories. Pattern matching uses pathspec, and terminal input uses prompt_toolkit>=3.0.52.

From the shell, initialize a project and open its interactive console:

trail init /path/to/project
trail /path/to/project

Running trail /path/to/project alone also starts setup if needed. The commands below are entered at Trail's prompt, without the trail prefix.

Picker

Picker previews bundled presets and supplied rule files during initialization.

  • Arrow keys browse presets and Enter chooses one. A typed path previews a file or the .ontrail inside a directory.
  • Escape starts with no inclusion rules. Interrupting setup writes nothing.

Console and output

  • Console owns the command bar.
  • Run prints events during observation.
  • Feed keeps terminal output.
  • Renderer formats records and counts.

Console

Console holds the editable command bar, command dispatch, and rendering objects.

To inspect its Python components, construct it from the project opened above:

from trail.cli.console import Console
console = Console(trail, root=trail.dir.parent)

The shell command trail constructs and runs the console during normal use.

🪵🏔️🍁 Welcome back to Trail! 🍁🏔️🪵

trail #38ca41930e0445368c84ee5516a40a9b on /tmp/trail-pr-example-1dbbg0k7
assets 3  dirs 2  events 6
type 'help' for help

The header keeps project, asset, directory, event, and open-access counts current while a session runs. These synchronous examples show the console idle.

Use help to list commands, assets to inspect tracked files and datasets, and dirs to inspect watched directories:

help
assets
dirs

Tab completes commands and paths. Up and Down recall earlier commands. Ctrl+L clears terminal output. Enter quit or press Ctrl+C to stop; the saved log loads when the project is reopened.

Run

Run prints the banner and events recorded during the run. Earlier history remains available through events, and shutdown drains access events closed by the session.

console.run: Run

Feed

Feed prints ordinary terminal output, retaining native scrollback and text selection, with an in-memory history bounded to 2,000 rows.

console.feed: Feed
  • Feed.write() prints events with their collection positions and a date row when the day changes.
  • Feed.clear() discards retained rows and the current date. Clearing the terminal does not clear tracked resources or event history.

Renderer

Renderer turns resources and events into feed rows with project-relative paths, collection positions, resource IDs, and counts.

console.renderer: Renderer
  • Renderer.header() reports counts, open dataset accesses, and whether observation is active.
  • Renderer.verb() chooses the event verb used to color each heading: tracking, untracking, directory watching, or a filesystem operation.

Commands and tracking

  • Commands holds the registered commands.
  • Command supplies their dispatch hooks and shared path handling.
  • RulesCommand and its two subclasses list rules and change active tracking.

Commands

Commands holds the registered commands. Named command subclasses register themselves so dispatch, help, and completion use the same table.

console.commands: Commands
>>> console.commands.find('ev')
EventsCommand('events')
  • Commands.find() accepts exact names and unambiguous prefixes.
  • help lists commands, key bindings, path-versus-rule behavior, selections, and clearing.
  • clear -f untracks assets and empties the project log. Ctrl-L clears terminal output.
  • restart reopens the console in a new process, picking up source and rule-file edits. With --nodir, it requires -f because the in-memory log would be lost.

To apply rule-file edits, reopen the project in a new process:

restart

To leave the console:

quit

Command

Command is the base of terminal commands. Named subclasses register themselves for dispatch, help, and completion. RulesCommand adds rule listings and path operations; Listing adds filtered collection listings.

RulesCommand(Command)

RulesCommand supplies rule listings and path operations for the inclusion and exclusion commands. With no arguments, each lists its rule file; paths change active tracking.

  • RulesCommand.show() prints each rule's kind and owning directory, then diagnostics.
  • Rule files can be edited directly in the user's text editor.

OnTrailCommand(RulesCommand)

OnTrailCommand implements ontrail: list inclusion rules or track supplied paths immediately.

> ontrail
  ./          root                        ./
  *.csv       root scope                  every root
  data/*.png  dir scope · not subfolders  data/
  *.zarr      root scope                  every root
> ontrail notes.md
Wednesday 04 November 2026
6. AddAssetEvent
    id: 79354092aca24796a021283fc9b071b4
    timestamp: 06:12:54.131
    src_path: notes.md
    st_size: 6 B
    st_mtime: 2026-11-04 22:12:54
    entry: 9a25d4f95a844164821f8d26dcf536ca
  • Path patterns expand against the filesystem. Tracking a directory adds one dataset.
  • Tab completes filesystem paths. Explicit path operations leave .ontrail and .offtrail unchanged.
  • The shell form, trail ontrail [PATH...], performs the same kind of operation without opening the console.

Track a file, inspect it, or track the sample Zarr directory as one dataset:

ontrail notes.md
assets path=notes.md
ontrail cube.zarr

The file and directory must already exist. To discover future CSV files automatically, edit .ontrail in Vim and add *.csv, then restart the console.

OffTrailCommand(RulesCommand)

OffTrailCommand implements offtrail: list exclusion rules or untrack supplied paths.

> offtrail
  .*  root scope  every root
> offtrail notes.md
7. RemoveAssetEvent
    id: ea1f6350eb7448f6bcc8b4172b552124
    timestamp: 06:12:54.133
    src_path: notes.md
    entry: 9a25d4f95a844164821f8d26dcf536ca
  • Globs match tracked paths, including resources already deleted from disk. Tab completes tracked paths.
  • Each removal records an event and keeps the path out of later automatic discovery.
  • The shell form is trail offtrail [PATH...].

Stop tracking the file and then track it again:

offtrail notes.md
assets path=notes.md
ontrail notes.md

After offtrail, the asset listing is empty for that path. Explicit ontrail tracks it again.


Resource and history listings

  • Listing supplies filtered listings for the three concrete commands below.
  • Query parses their selections and resolves terminal paths against the project root.

Listing(Command)

Listing supplies resource and event listings. It applies Query to the named collection.

  • Without a slice, a listing shows the last 20 matches. Its header reports the displayed count against the whole collection, and records keep their positions in the original collection.
  • Tab completes field names as field= terms.
  • clear previews clearing the whole named collection; -f confirms it. It does not reuse a previous listing's filter.

AssetsCommand(Listing)

AssetsCommand lists tracked resources. Here the 5-byte dataset is excluded by a numeric size comparison:

> assets st_size>5
assets (2 of 3)
1. Asset
    id: 2a0737e73af0421d8792abbcef140708
    path: new.csv
    st_size: 19 B
    st_mtime: 2026-11-04 22:12:54
2. Asset
    id: 0e6996dc54324106886287e0f2cda49c
    path: data/map.png
    st_size: 8 B
    st_mtime: 2026-11-04 22:12:54

assets clear -f untracks all assets and records their removals.

List all tracked resources or select the sample CSV by its path:

assets
assets path=new.csv

Use path for asset and directory records; use src_path for event records.

DirsCommand(Listing)

DirsCommand lists configured directories, including their root status and local scopes. It refuses dirs clear: remove their rules from .ontrail and reopen the project instead.

dirs
dirs path=data

EventsCommand(Listing)

EventsCommand lists recorded history:

> events src_path=new.csv
events (1 of 6)
3. AddAssetEvent
    id: 1f201596c7cd4529abd976dbe54ebf15
    timestamp: 06:12:54.110
    src_path: new.csv
    rule: *.csv
    st_size: 19 B
    st_mtime: 2026-11-04 22:12:54
    entry: 2a0737e73af0421d8792abbcef140708

events clear -f discards the log and records the configured directories again. Tracked assets remain active during the session; reopening reconstructs assets from the remaining log and current discovery rules.

Read the last 20 events, the last five events, or the sample CSV's last five events:

events
events -5:
events src_path=new.csv -5:

Filters support adjacent terms (and), alternatives (or), and exclusions (not):

events cls=WatchdogEvent event_type=moved
events src_path=new.csv or src_path=data/map.png
events cls=WatchdogEvent not event_type=deleted

A slice acts on the records left by the terms before it. events src_path=new.csv -5: shows that file's last five events; events -5: src_path=new.csv searches only the log's last five events.


Shared selections

The collections and CLI listings above share one expression language:

  • Select implements Python selections.
  • Query adds project-relative paths for terminal commands.

Select

Select implements the selections reached through each collection's .select. The terminal uses the same parser and comparison rules.

>>> trail.events.select('cls=AddAssetEvent rule=*.csv')
Events (1)
    0. AddAssetEvent
        id: 1f201596c7cd4529abd976dbe54ebf15
        timestamp: 06:12:54.110
        src_path: /tmp/trail-pr-example-1dbbg0k7/new.csv
        rule: *.csv
        st_size: 19 B
        st_mtime: 2026-11-04 22:12:54
  • select[index] supports positive and negative positions. A slice returns a selection of the same collection type.
  • select(expression) supports field comparisons, quoted values, parentheses, not, and, and or. Adjacent terms imply and.
  • Slices act in expression order: event_type=modified -5: takes the last five matching events; -5: event_type=modified filters only the last five events.
  • Select.compare() converts comparison values to the field's type. Class comparisons include subclasses, record references compare by ID, and timestamps accept ISO datetimes or a UTC clock time for today.
  • Select.subset() copies membership while sharing records and their project parent. Clearing an event selection leaves the persisted log unchanged; clearing an asset selection untracks the selected assets from the project.

Query(Select[T, V])

Query parses selection expressions for terminal commands. T is the selected collection type; V is its record type. Relative path comparisons resolve against the project root, so src_path=new.csv matches an absolute stored path. Numeric fields compare numerically.


Validation

Coverage relevant to this PR includes:

The test workflow runs pytest with Python 3.12 on Ubuntu, macOS, and Windows. Open-event coverage accounts for backend support.

Known macOS CI failures: 11 filesystem-notification tests remain failing. All 37 rule and scope tests pass after the path-normalization fix. Notification handling remains follow-up work.

Validated commit: 55bc37116f3454f53153c1e137ab3e48e27edf9a, in an isolated Linux copy using Python 3.12.16, pytest 9.2.0, and Ruff 0.17.5.

$ ruff check src tests
All checks passed!

$ python -m pytest -q
244 passed in 12.32s

🔍 Preview: https://geojupyter-trail--3.org.readthedocs.build/
Note: This Pull Request preview is provided by ReadTheDocs. Our production website, however, is currently deployed with GitHub Pages.

hodczak and others added 30 commits September 30, 2026 23:42
- Add `trail.cli` package: argument parsing and entry point in `__init__`,
  the prompt_toolkit `Console` application, a `Command` base with the
  concrete `commands`, `Column` layout, `Node` listing rows, `Feed`
  event streaming, `render` helpers, and `theme`
- Add `trail.__main__` so `python -m trail` runs the console
- Add tests for input handling and listing
- Split source lines into separate strings in the notebook cell to improve readability
- Introduce `Select` class inheriting from `Node` to pick records from a collection
- Implement methods for slicing, comparison, and timestamp comparison
- Add functionality to handle paths, IDs, and text lookups
- Implement union and subset operations for record selection
- Add helper methods for comparison, equality checks, and value coercion
- Replace `EntryLookup` with `Entries` class to provide a unified interface for assets and directories
- Implement `_synced` property to ensure changes in `assets` and `dirs` are reflected in `entries`
- Simplify entry tracking and untracking logic
- Update `entry` method to streamline entry lookup by ID or path
- Remove redundant id shortening and prefix handling in CLI commands
- Add tests for entry movement and path handling
- Refactor repr and str methods for cleaner output
…`Select` class inheriting from `Node` to pick records from a collection

- Implement methods for slicing, comparison, and timestamp comparison
- Add functionality to handle paths, IDs, and text lookups
- Implement union and subset operations for record selection
- Add helper methods for comparison, equality checks, and value coercion
- Refactor `Entries` class to use `Select` for event selection
- Update tests to use `Select` for event selection and slicing
- Refactor `select.py` to streamline string splitting and improve readability
- Update `commands.py` to simplify command definitions and improve usability
- Enhance `test_listing.py` to cover new behaviors and edge cases
- Refactor `command.py` to improve command handling and query processing
- Update `console.py` to simplify command execution and improve error handling
- Update `CLI` to enhance query handling and improve user experience
…eration

Replace .values() calls with direct iteration now that collections are iterable.
Rename Collection protocol to Selectable to avoid naming conflict with new Collection base class.
Add extend() method to Events for batch recording, replacing update().
… storage

Introduce generic Collection[K, V] base class that stores records by id while maintaining insertion order. Provides dict-like access patterns (get, __getitem__, __setitem__, __delitem__) and iterable interface over records rather than keys. Includes Select property for filtering operations.
- Introduce `TestSelect` class with various test methods to validate event selection
- Test slicing, field selection, logical operations, and error handling
- Validate timestamp comparison and coercion
- Ensure selections do not alter the original log or collection
- Test entry selection by ID, path, and name
- Validate the behavior of the `Select` class with different scenarios
- Introduce `Markers` class inheriting from `Node` and `MutableSet` to manage asset extensions
- Implement methods for adding, removing, and clearing markers
- Add `Text` class to handle the `.markers` file operations
- Integrate `Markers` with `Trail` class for automatic extension tracking
- Update `Trail` class to include a `markers` property for accessing the `Markers` instance
- Change marker normalization to keep the leading dot, as per `Path.suffix`
- Update docstring to reflect the new marker format
- Modify `normalize` method to return the normalized marker with a leading dot
- Adjust `matches` method to handle the new marker format without removing the prefix dot
- Update comments to clarify the behavior of the `matches` method
- Introduce `mark` method to track files indicated by markers but not yet tracked
- Implement `_scoped` method to determine if a path is within the project directory or tracked directories
- Add `_markable` method to check if a path should be marked based on markers and other conditions
- Implement `_walk` method to iterate over files in specified directories
- Add `_descends` method to determine if a path should be included based on ignoring and symlink conditions
- Update `watchdog.py` to call `mark` method for files created or moved in watched directories
- Modify `event.py` to handle marked files in tracked directories
- Update `dir.py` to only include marked files in the trail assets
- Add `mark` method to `Markers` class to update tracked entries when markers change
- Update `trail.py` to call `mark` method after replaying events and tracking new directories
- Add tests for marking files with markers and tracking them in the trail
- Add `test_a_new_trail_tracks_its_project_directory` to verify project directory tracking
- Update event selection indices to account for the project directory event
- Adjust assertions in `test_track_untrack_and_retrack_history_can_be_restored` for new event order
- Update slicing and filtering tests in `test_listing.py` to reflect new event positions
- Modify `Trail` initialization to track the project directory if it's a new trail
- Update `Trail` replay logic to handle existing project directory tracking
- Add `create` method to `Markers` class for creating a project's .markers file
- Implement logic to copy premade markers files or use user-provided paths
- Update `Trail` initialization to create markers if they don't exist
- Add package data configuration for premade markers files in `pyproject
- Add `test_a_subdirectory_opens_the_enclosing_trail` to verify subdirectory behavior
- Add `test_the_nearest_trail_wins` to ensure the nearest trail is opened
- Add `test_the_search_stops_at_a_ceiling_directory` to test ceiling directory behavior
- Update `Trail` initialization to search for nearest `.trail` directory
- Modify `Trail` class to handle ceiling directories using environment variables
- Improve representation logic in `Trail` class for cleaner output
…ality

- Replace `ask` function with `display`, `bare`, `Paths`, `expand`, `respecify`, `directory`, `Picker`, `offer`, `Asked`, and `ask` functions for improved user interaction
- Add `toggle` function to manage markers
- Update `resolve` function to handle errors in path resolution
- Replace `gather` function with new implementation for better path tracking
- Update `init` function to handle directory selection and initialization
- Remove `YES` and `NO` constants
- Add new imports from `prompt_toolkit` and `trail` modules
- Add a cursor to `gather` so the arrows move through the listed paths and <ENTER> removes the one under it
- Let the Trail directory be removed from the listing, and add a `tracked` option to `Trail` for a new Trail that skips its own directory
- Offtrail the Trail directory on re-initialization if it was removed
- Scope markers to tracked directories only, rather than always including the project directory
- Add `tabbing` bindings so <TAB> takes a completion and descends into directories
- Accept a live `request` and `extra` bindings in `ask`, and style its session with `STYLE`
- Report an already listed path instead of toggling it off
- Update the walkthrough hints for adding, removing, and continuing
- Add geospatial.markers covering vector, raster, and tabular GIS extensions
- Add ml.markers covering model checkpoints, arrays, and serialized data
- Keep `Trail.locate` from climbing into any directory listed in TRAIL_CEILING_DIRECTORIES (split on os.pathsep), the same way GIT_CEILING_DIRECTORIES works
- Mention the ceiling in the `Trail` docstring
- Use `pytest.MonkeyPatch.context()` in the ceiling test so it runs without the fixture, and add it to the `__main__` test list
hodczak added 28 commits October 1, 2026 00:02
- Move markers files from `premade` to `markers` directory
- Update `pyproject.toml` to reflect the new markers file path
- Update docstrings and comments in `trail.py` and `markers.py` to reflect the new directory structure
- Rename `premade` function to `available` in `markers.py`
- Update function calls and references in `cli/init.py` to use the new function and directory names
- Remove the use of `PREMADE_NAME` and replace with `DEFAULT_MARKERS`
- Update the `offer` function to list available markers files from the new directory
- Change markers file extension from `.markers` to `.txt` in `pyproject.toml`
- Rename all markers files from `.markers` to `.txt`
- Update `markers.py` to recognize `.txt` extension instead of `.markers`
- Modify `cli/init.py` to correctly reference the new `.txt` markers files
- Add `json` to the list of supported file types in `default.txt`
- Update function docstrings and error messages to reflect the new file extension
- Add `test_init.py` with comprehensive test cases for the `init` function:
  - Test accepting every default starts a trail with the default markers
  - Test the arrow climbs to the parent directory
  - Test a typed directory replaces the suggestion
  - Test a directory nested in a trail starts its own
  - Test escape turns down the default markers
  - Test a typed path chooses a markers file of its own
  - Test a typed directory offers the markers inside it
  - Test an arrow after typing returns to the markers files
  - Test extensions toggle
  - Test a bad extension is refused without ending the step
  - Test entered paths are tracked and entered again are kept
  - Test the path under the cursor is removed
  - Test a pasted list is entered whole
  - Test right and left choose what the arrows scroll
  - Test reinitializing starts from the default markers
  - Test reinitializing keeps the project markers when they are named
  - Test escape with nothing toggled leaves a blank markers file
  - Test a completed directory is typed on into
  - Test an interrupt writes nothing
  - Test an interrupt in the picker writes nothing

- Add `test_markers.py` with comprehensive test cases for the `Markers` class:
  - Test instantiation tracks marked files
  - Test marking is idempotent and survives reload
  - Test offtrailed files stay offtrailed
  - Test adding a marker tracks existing files
  - Test tracking a hidden directory tracks its marked files
  - Test tracked directory outside the project is marked
  - Test created file beside a tracked asset is marked
  - Test tracked directory takes in only marked files
  - Test a new trail copies the default markers
  - Test a new trail copies markers from a path
  - Test existing markers are not overwritten
  - Test a reopened trail does not copy markers
  - Test an unknown markers name is refused
- Update `Console` class to move run logic to a new `Run` class
- Refactor command submission and error handling in `Console` class
- Update method names and logic for streaming events and monitoring watchdog
- Add new `Run` class to manage live session and event streaming
- Update `Node` class to include parent node property
- Refactor command collection property to use `@property` decorator
- Update marker description in `init.py` to clarify file types
- Refactor `command.py` to simplify command handling and query processing
- Add comprehensive docstrings to `TrackCommand`, `UntrackCommand`, `AssetsCommand`, and other command classes
- Update `Feed` and `Console` class docstrings to provide detailed descriptions of their roles and properties
- Expand `Render` and `Renderer` class docstrings to clarify their responsibilities and usage
- Add detailed explanations for the CLI initialization and main function
- Improve documentation for key bindings, command line parsing, and error handling
- Add `blank` method to `Feed` class for separating banner from events
- Remove `backlog` and update `Run` class to print only new events
- Update `banner` method to display welcome message and asset counts
- Add `welcome` method to `Render` class for personalized welcome messages
- Add `returning` parameter to `Console` class to track session continuity
- Update `theme.py` to include new styles for welcome messages
- Remove redundant code and improve overall readability
A Dir is a directory named by .markers. It now has an ID and a history in
the log, so events are associated with watched directories as they are
with assets. .markers still decides which Dirs are live, and the log
records their identity and what happened to them.

- Add entry.py with Entry (id, path, track, offtrail, repr) and
  Entries (lookup by id and path). Asset and Dir derive from Entry, and
  Assets and Dirs derive from Entries.
- Dir keeps its ID while its root and scopes follow .markers.
  Dirs.refresh logs an AddDirEvent or RemoveDirEvent for each Dir that
  comes or goes. It runs after the log is replayed, after each change to
  .markers, and when a directory asset is tracked or offtrailed.
- A .markers edited by hand is read on the next start as removals and
  additions. No rename is inferred.
- A Dir's directory renamed or deleted on disk is logged against the
  Dir. A rename warns, and the Dir keeps its path, since its line still
  names it. Replaying a moved event never moves a Dir.
- Rename Event.asset to Event.entry, including the record key. The
  replay makes a Dir or an Asset from the first record about each ID.
- Events.clear logs the live Dirs again with their IDs, so later events
  about them still replay.
- Apply a repeated directory event once per batch. A deleted directory
  was reported by its own watch and by its parent's.
- Make the console's dirs command a selectable listing again, refuse
  dirs clear, and word the new events as watched and unwatched.
- Add tests/test_dirs.py and update the other tests for the renames and
  the Dir events that now open a new log.
…havior

- Remove RIGHT and LEFT key constants from test_init.py
- Update test_escape_turns_down_the_default_markers to reflect new behavior
- Modify test_the_arrows_choose_another_marker_set to use general.txt markers
- Update test_a_file_longer_than_the_preview_is_cut_off to handle single file case
- Refactor test_markers.py to reflect changes in default markers behavior
- Update test_trail.py to use general markers in Trail initialization
- Remove redundant tests and update docstrings to reflect new behavior
- Drop `Editor`, `ask`, `Asked` and `tally`; init now writes the chosen markers file as is
- Pass the imported flag to `trail.markers` so warnings name anchored lines from elsewhere
- Point the user at `.markers` to change the markers after init
- Update the `Picker` docstring and margin now that no editor follows
- Remove `TestEditor` and the editor-driven init tests; cover import warnings and blank escape
…mples that use them

- Call methods on `self` in method examples instead of reaching through `trail`
- Use `Renderer.home` in the `Renderer.home` example
- Build the `Markers` repr example from `lines_repr` directly in `util`
- Define `dirs` and `scopes` in the `match` example
- Describe the chosen file as the starting point for a new `.markers` rather than its copy source
- Note that the preview truncates long files since the following editor shows every line
- Reduce `Picker.margin` from 15 to 14 terminal rows
- Split compound boolean returns in `Assets._markable` and `Assets._descends` into early returns
- Build `Assets` walk depths as a dict comprehension merged with `|`
- Name intermediate values for `iglob` results, `create_task` calls, prompt_toolkit windows, completion documents and `list_repr` output instead of nesting them inline
- Replace nested `next(...)` generators in `markers.parse` and `markers.canonical_path` with named `wildcards` generators
- Extract `EVENT_TYPES` in `event` and `EVENT_FILTER` in `watchdog` as module-level `Final` constants
- Break single-line comprehensions and `Path` method chains across multiple lines
- Unpack `(style, text, *_)` directly in `Feed.append` instead of indexing fragments
- Apply the `within` filter in `Watchdog.desired` as a separate pass before the ignore and `is_dir` checks
- Reindent continuation lines in `watchdog` conditions and the `_reaches` signature
- Add notes/10-8-1-dirasset-access-plan.md with a summary at the top
- Add notes/10-8-directory-asset-sessions-plan.md, which 10-8-1 replaces and cites for the inotify measurements
- Rename the plan's PRs to commits on one local branch off dhodczak
- Review the series together at the tip
- Rename `trail.cli.scopes` to `trail.cli.marker_completion`
- Rename `Scope` to `MarkerCompleter` and `ScopePaths` to `MarkerPaths`
- Move `CHILDREN` and `EVERYTHING` from `trail.util` to `trail.asset`
- Move `OPS` from `trail.util` to `trail.event`
- Rename `Assets._is_markable` to `_is_trackable` and `Assets._descends` to `_is_descending`
- List the per-command completions in `Console`'s completer docstring as bullets, adding `unmark`
- Build `Scopes.relative` with a comprehension
- Wrap the condition in `Trail._is_ignored` across lines
- Update imports in tests for the moved names
- Add `Entries` in `trail/entries.py`, reached as `trail.entries`, to look up an asset or a Dir by id or path with `[]`, `get`, `in`, iteration and `len`
- Rename the per-kind base class `Entries` in `trail/entry.py` to `EntryCollection`
- Move `Trail._offtrailed_paths` to `trail.entries.untracked`
- Move `Trail._is_ignored` to `trail.entries.is_metadata`
- Move `Assets._is_trackable` and `Assets._is_descending` to `trail.entries.is_trackable` and `trail.entries.is_walkable`
- Replace `Trail._entry` with `trail.entries` lookups in `Event.from_record` and `JSONL` loading
- Move the module constant `CHILDREN` to the class attribute `DirAsset.suffix2children` and make `DirAsset.is_match` a classmethod
- Add tests for `trail.entries` lookups, membership, iteration, untracked paths across reloads and metadata checks
…tory dataset access logging

- Update the PR draft to include `.offtrail` rules and shared rules base
- Add `trail.entries` to look up assets and Dirs together
- Add `Rule`, `Rules`, and `TXT` classes for rule management; inherited by `OnTrail` and `OffTrail`
- Add `OffTrail` for exclusion rules and its integration with `OnTrail`
- Update `Dir`, `Dirs`, `Asset`, and `DirAsset` classes with new methods and properties
- Update `Entries` class to include `untracked`, `is_metadata`, `is_trackable`, and `is_walkable` methods
- Add `DirectoryAccessEvent` and `Access` for directory dataset access logging
- Update `Watchdog` and `WatchdogSession` classes for observation and event handling
- Update command-line interface for interactive console and initialization
@hodczak
hodczak merged commit cb15249 into main Nov 15, 2026
3 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant