Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Recover Git context after worktree and watcher changes

dee578ec952357e
diff --git a/desktop/lib/core/local_git_projects.dart b/desktop/lib/core/local_git_projects.dart
index 90916cf47..d3e4d010b 100644
--- a/desktop/lib/core/local_git_projects.dart
+++ b/desktop/lib/core/local_git_projects.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
@@ -9,8 +10,11 @@ import 'models.dart';
/// directory watches invalidate the cache when a checkout or remote changes.
/// No Git processes, network calls, terminal reads, or work on the render path.
class LocalGitProjects {
- LocalGitProjects({required this.onChanged});
+ LocalGitProjects({required this.onChanged, DateTime Function()? now})
+ : _now = now ?? DateTime.now;
final void Function() onChanged;
+ final DateTime Function() _now;
+ static const _cacheAge = Duration(minutes: 1);
final _entries = <String, _LocalGitEntry>{};
bool _disposed = false;
@@ -21,23 +25,52 @@ class LocalGitProjects {
final existing = _entries[cwd];
if (existing != null) {
if (existing.pending != null) return existing.pending!;
- if (existing.watchers.isNotEmpty ||
- DateTime.now().difference(existing.checkedAt) <
- const Duration(minutes: 1)) {
+ // Even a live watcher can miss a rename or a coalesced OS event. Check
+ // again on ordinary discovery after the TTL; there is no polling timer.
+ if (_now().difference(existing.checkedAt) < _cacheAge) {
return Future.value();
}
- return existing.pending = _resolve(cwd, existing);
+ return _refresh(cwd, existing);
}
if (_entries.length >= 256) {
_entries.remove(_entries.keys.first)?.dispose();
}
final entry = _LocalGitEntry();
_entries[cwd] = entry;
- return entry.pending = _resolve(cwd, entry);
+ return _refresh(cwd, entry);
+ }
+
+ Future<void> _refresh(String cwd, _LocalGitEntry entry) {
+ if (_disposed || entry.disposed) return Future.value();
+ if (entry.pending != null) {
+ entry.dirty = true;
+ return entry.pending!;
+ }
+ return entry.pending = _refreshEntry(cwd, entry);
+ }
+
+ Future<void> _refreshEntry(String cwd, _LocalGitEntry entry) async {
+ try {
+ do {
+ entry.dirty = false;
+ await _resolve(cwd, entry);
+ } while (entry.dirty && !_disposed && !entry.disposed);
+ } finally {
+ entry.checkedAt = _now();
+ entry.pending = null;
+ }
}
Future<void> _resolve(String cwd, _LocalGitEntry entry) async {
+ final targets = <String, Set<String>>{};
+ void watch(String directory, Set<String> names) =>
+ (targets[directory] ??= {}).addAll(names);
try {
+ if (!await Directory(cwd).exists()) {
+ _publish(entry, null);
+ return;
+ }
+ watch(p.normalize(cwd), {'.git'});
var root = p.normalize(cwd);
String? gitDir;
for (var depth = 0; depth < 32; depth++) {
@@ -48,9 +81,12 @@ class LocalGitProjects {
break;
}
if (type == FileSystemEntityType.file) {
+ targets.clear();
+ watch(root, {'.git'});
final pointer = await _text(marker);
if (pointer?.startsWith('gitdir: ') == true) {
- gitDir = p.normalize(p.join(root, pointer!.substring(8).trim()));
+ final path = pointer!.substring(8).trim();
+ if (path.isNotEmpty) gitDir = p.normalize(p.join(root, path));
}
break;
}
@@ -59,16 +95,23 @@ class LocalGitProjects {
root = parent;
}
if (gitDir == null) {
- if (!_disposed && !entry.disposed && entry.project != null) {
- entry.project = null;
- onChanged();
- }
+ _publish(entry, null);
return;
}
+ // The working tree owns the .git pointer (and directory replacement),
+ // while HEAD/config may live elsewhere. Keep watching that connection.
+ targets.clear();
+ watch(root, {'.git'});
+ if (!await Directory(gitDir).exists()) {
+ _publish(entry, null);
+ return;
+ }
+ watch(gitDir, {'HEAD', 'commondir'});
final shared = await _text(p.join(gitDir, 'commondir'));
final common = shared == null
? gitDir
: p.normalize(p.join(gitDir, shared.trim()));
+ watch(common, {'config'});
final head = (await _text(p.join(gitDir, 'HEAD')))?.trim();
final config = await _text(p.join(common, 'config'));
if (_disposed || entry.disposed) return;
@@ -84,48 +127,124 @@ class LocalGitProjects {
'remote': _origin(config),
'branch': branch,
});
- if (entry.watchers.isEmpty) {
- for (final directory in {gitDir, common}) {
- try {
- entry.watchers.add(
- Directory(directory).watch().listen((event) {
- if (!{
- 'HEAD',
- 'config',
- 'commondir',
- }.contains(p.basename(event.path))) {
- return;
- }
- entry.debounce?.cancel();
- entry.debounce = Timer(const Duration(milliseconds: 100), () {
- if (!_disposed && !entry.disposed) {
- entry.pending = _resolve(cwd, entry);
- }
- });
- }, onError: (Object _) {}),
- );
- } on FileSystemException {
- // Metadata is still useful when the filesystem cannot watch it.
- }
- }
- }
- if (entry.project != project) {
- entry.project = project;
- onChanged();
- }
+ _publish(entry, project);
} on FileSystemException {
// A removed/unreadable working folder must not interfere with discovery.
+ _publish(entry, null);
} finally {
- entry.checkedAt = DateTime.now();
- entry.pending = null;
+ if (!_disposed && !entry.disposed) _syncWatches(cwd, entry, targets);
+ }
+ }
+
+ void _publish(_LocalGitEntry entry, AgentProject? project) {
+ if (_disposed || entry.disposed || entry.project == project) return;
+ entry.project = project;
+ onChanged();
+ }
+
+ void _invalidate(String cwd, _LocalGitEntry entry) {
+ if (_disposed || entry.disposed) return;
+ entry.debounce?.cancel();
+ entry.debounce = Timer(const Duration(milliseconds: 100), () {
+ entry.debounce = null;
+ unawaited(_refresh(cwd, entry));
+ });
+ }
+
+ void _syncWatches(
+ String cwd,
+ _LocalGitEntry entry,
+ Map<String, Set<String>> targets,
+ ) {
+ entry.watchTargets = targets;
+ for (final directory in entry.watchers.keys.toList()) {
+ if (!targets.containsKey(directory)) {
+ unawaited(entry.watchers.remove(directory)!.cancel());
+ }
+ }
+ entry.retryWatchAt.removeWhere((path, _) => !targets.containsKey(path));
+ for (final directory in targets.keys) {
+ if (entry.watchers.containsKey(directory) ||
+ entry.retryWatchAt[directory]?.isAfter(_now()) == true) {
+ continue;
+ }
+ late StreamSubscription<FileSystemEvent> subscription;
+ void lost() {
+ if (_disposed ||
+ entry.disposed ||
+ entry.watchers[directory] != subscription) {
+ return;
+ }
+ entry.watchers.remove(directory);
+ unawaited(subscription.cancel());
+ // Refresh the data once, but wait for later discovery to retry a
+ // failed watch. A permanently unavailable watcher must not loop.
+ entry.retryWatchAt[directory] = _now().add(_cacheAge);
+ _invalidate(cwd, entry);
+ }
+
+ bool related(String path) =>
+ p.normalize(path) == directory ||
+ entry.watchTargets[directory]?.contains(p.basename(path)) == true;
+ try {
+ subscription = Directory(directory).watch().listen(
+ (event) {
+ if (_disposed ||
+ entry.disposed ||
+ entry.watchers[directory] != subscription) {
+ return;
+ }
+ if (related(event.path) ||
+ event is FileSystemMoveEvent &&
+ event.destination != null &&
+ related(event.destination!)) {
+ if (event.isDirectory &&
+ (event is FileSystemCreateEvent ||
+ event is FileSystemDeleteEvent ||
+ event is FileSystemMoveEvent)) {
+ // A replacement can reuse the path while the OS watch still
+ // follows the old directory. Rebind those subscriptions.
+ final changed = {
+ p.normalize(event.path),
+ if (event is FileSystemMoveEvent && event.destination != null)
+ p.normalize(event.destination!),
+ };
+ for (final watched in entry.watchers.keys.toList()) {
+ if (changed.any(
+ (path) => path == watched || p.isWithin(path, watched),
+ )) {
+ unawaited(entry.watchers.remove(watched)!.cancel());
+ entry.retryWatchAt.remove(watched);
+ }
+ }
+ }
+ _invalidate(cwd, entry);
+ }
+ },
+ onError: (Object _) => lost(),
+ onDone: lost,
+ cancelOnError: true,
+ );
+ entry.watchers[directory] = subscription;
+ entry.retryWatchAt.remove(directory);
+ } on FileSystemException {
+ entry.retryWatchAt[directory] = _now().add(_cacheAge);
+ } on UnsupportedError {
+ entry.retryWatchAt[directory] = _now().add(_cacheAge);
+ }
}
}
Future<String?> _text(String path) async {
- final file = File(path);
try {
- if (await file.length() > 64 * 1024) return null;
- return await file.readAsString();
+ final file = await File(path).open();
+ try {
+ // Bound the read itself, including a file growing during discovery.
+ final bytes = await file.read(64 * 1024 + 1);
+ return bytes.length <= 64 * 1024 ? utf8.decode(bytes) : null;
+ } finally {
+ await file.close();
+ }
} on FileSystemException {
return null;
} on FormatException {
@@ -198,17 +317,21 @@ String? canonicalGitRemote(String raw) {
}
class _LocalGitEntry {
- DateTime checkedAt = DateTime.now();
+ DateTime checkedAt = DateTime.fromMillisecondsSinceEpoch(0);
AgentProject? project;
Future<void>? pending;
- final watchers = <StreamSubscription<FileSystemEvent>>[];
+ bool dirty = false;
+ final watchers = <String, StreamSubscription<FileSystemEvent>>{};
+ Map<String, Set<String>> watchTargets = {};
+ final retryWatchAt = <String, DateTime>{};
Timer? debounce;
bool disposed = false;
void dispose() {
disposed = true;
debounce?.cancel();
- for (final watcher in watchers) {
+ for (final watcher in watchers.values) {
unawaited(watcher.cancel());
}
+ watchers.clear();
}
}
diff --git a/desktop/test/local_git_projects_test.dart b/desktop/test/local_git_projects_test.dart
index e3abdf348..5665de880 100644
--- a/desktop/test/local_git_projects_test.dart
+++ b/desktop/test/local_git_projects_test.dart
@@ -1,10 +1,388 @@
import 'dart:async';
import 'dart:io';
+import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/local_git_projects.dart';
+Future<void> _metadata(
+ String path,
+ String branch, {
+ String remote = 'repo',
+}) async {
+ await Directory(path).create(recursive: true);
+ await File('$path/HEAD').writeAsString('ref: refs/heads/$branch\n');
+ await File('$path/config').writeAsString(
+ '[remote "origin"]\n url = [email protected]:team/$remote.git\n',
+ );
+}
+
+class _Watches {
+ final streams = <String, List<StreamController<FileSystemEvent>>>{};
+
+ Stream<FileSystemEvent> watch(String path, int events, bool recursive) {
+ expect(recursive, isFalse);
+ final controller = StreamController<FileSystemEvent>();
+ (streams[path] ??= []).add(controller);
+ return controller.stream;
+ }
+
+ void change(String directory, String path) {
+ emit(directory, FileSystemModifyEvent(path, false, true));
+ }
+
+ void emit(String directory, FileSystemEvent event) {
+ for (final stream in streams[directory] ?? []) {
+ if (stream.hasListener) stream.add(event);
+ }
+ }
+
+ Future<void> dispose() async {
+ for (final stream in streams.values.expand((streams) => streams)) {
+ await stream.close();
+ }
+ }
+}
+
+class _HeldFile implements File {
+ _HeldFile(this.file, this.started, this.release);
+ final File file;
+ final Completer<void> started;
+ final Future<void> release;
+ @override
+ Future<RandomAccessFile> open({FileMode mode = FileMode.read}) async =>
+ _HeldHandle(await file.open(mode: mode), started, release);
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _HeldHandle implements RandomAccessFile {
+ _HeldHandle(this.file, this.started, this.release);
+ final RandomAccessFile file;
+ final Completer<void> started;
+ final Future<void> release;
+ @override
+ Future<Uint8List> read(int bytes) async {
+ final result = await file.read(bytes);
+ started.complete();
+ await release;
+ return result;
+ }
+
+ @override
+ Future<void> close() => file.close();
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
void main() {
+ test(
+ 'a changed worktree pointer follows the new metadata directory',
+ () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-git-move-',
+ );
+ final root = '${fixture.path}/work';
+ await Directory(root).create();
+ final oldMetadata = '${fixture.path}/before';
+ final newMetadata = '${fixture.path}/after';
+ await _metadata(oldMetadata, 'before');
+ await _metadata(newMetadata, 'after', remote: 'new-project');
+ final pointer = File('$root/.git');
+ await pointer.writeAsString('gitdir: $oldMetadata\n');
+ final watches = _Watches();
+ final changes = StreamController<void>.broadcast();
+ final reader = LocalGitProjects(onChanged: () => changes.add(null));
+ addTearDown(() async {
+ reader.dispose();
+ await watches.dispose();
+ await changes.close();
+ await fixture.delete(recursive: true);
+ });
+ await IOOverrides.runZoned(() async {
+ await reader.read(root);
+ expect(reader.cached(root)!.branch, 'before');
+ final changed = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.branch == 'after',
+ );
+ await pointer.writeAsString('gitdir: $newMetadata\n');
+ watches.change(root, pointer.path);
+ await changed.timeout(const Duration(seconds: 3));
+ expect(reader.cached(root)!.remote, 'github.com/team/new-project');
+ expect(watches.streams[oldMetadata]!.single.hasListener, isFalse);
+ final next = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.branch == 'next',
+ );
+ await File('$newMetadata/HEAD').writeAsString('ref: refs/heads/next\n');
+ watches.change(newMetadata, '$newMetadata/HEAD');
+ await next.timeout(const Duration(seconds: 3));
+
+ final shared = '${fixture.path}/shared';
+ await _metadata(shared, 'unrelated-main', remote: 'shared-project');
+ final commonChanged = changes.stream.firstWhere(
+ (_) =>
+ reader.cached(root)?.remote == 'github.com/team/shared-project',
+ );
+ await File('$newMetadata/commondir').writeAsString('../shared\n');
+ watches.change(newMetadata, '$newMetadata/commondir');
+ await commonChanged.timeout(const Duration(seconds: 3));
+ expect(reader.cached(root)!.branch, 'next');
+ final remoteChanged = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.remote == 'github.com/team/renamed',
+ );
+ await File('$shared/config').writeAsString(
+ '[remote "origin"]\n url = https://github.com/team/renamed.git\n',
+ );
+ watches.change(shared, '$shared/config');
+ await remoteChanged.timeout(const Duration(seconds: 3));
+ }, fsWatch: watches.watch);
+ },
+ );
+
+ for (final failure in ['done', 'error']) {
+ test(
+ 'a watcher $failure refreshes stale metadata without retrying forever',
+ () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-git-watch-',
+ );
+ final root = fixture.path;
+ final metadata = '$root/.git';
+ await _metadata(metadata, 'before');
+ final watches = _Watches();
+ final changes = StreamController<void>.broadcast();
+ var now = DateTime(2026, 9, 13);
+ final reader = LocalGitProjects(
+ onChanged: () => changes.add(null),
+ now: () => now,
+ );
+ addTearDown(() async {
+ reader.dispose();
+ await watches.dispose();
+ await changes.close();
+ await fixture.delete(recursive: true);
+ });
+ await IOOverrides.runZoned(() async {
+ await reader.read(root);
+ final changed = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.branch == 'after',
+ );
+ await File('$metadata/HEAD').writeAsString('ref: refs/heads/after\n');
+ final stream = watches.streams[metadata]!.single;
+ if (failure == 'done') {
+ await stream.close();
+ } else {
+ stream.addError(const FileSystemException('watch stopped'));
+ }
+ await changed.timeout(const Duration(seconds: 3));
+ expect(reader.cached(root)!.branch, 'after');
+ expect(watches.streams[metadata], hasLength(1));
+ await reader.read(root);
+ now = now.add(const Duration(minutes: 1));
+ await reader.read(root);
+ expect(watches.streams[metadata], hasLength(2));
+ final recovered = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.branch == 'recovered',
+ );
+ await File('$metadata/HEAD')
+ .writeAsString('ref: refs/heads/recovered\n');
+ watches.change(metadata, '$metadata/HEAD');
+ await recovered.timeout(const Duration(seconds: 3));
+ }, fsWatch: watches.watch);
+ },
+ );
+ }
+
+ test('unsupported watches preserve metadata and retry only after discovery expires', () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-git-unwatched-',
+ );
+ final metadata = '${fixture.path}/.git';
+ await _metadata(metadata, 'before');
+ var attempts = 0;
+ var now = DateTime(2026, 9, 13);
+ final reader = LocalGitProjects(onChanged: () {}, now: () => now);
+ addTearDown(() async {
+ reader.dispose();
+ await fixture.delete(recursive: true);
+ });
+ await IOOverrides.runZoned(
+ () async {
+ await reader.read(fixture.path);
+ expect(reader.cached(fixture.path)!.branch, 'before');
+ final firstAttempts = attempts;
+ expect(firstAttempts, greaterThan(0));
+ await File('$metadata/HEAD').writeAsString('ref: refs/heads/after\n');
+ await reader.read(fixture.path);
+ expect(attempts, firstAttempts);
+ now = now.add(const Duration(minutes: 1));
+ await reader.read(fixture.path);
+ expect(reader.cached(fixture.path)!.branch, 'after');
+ expect(attempts, firstAttempts * 2);
+ },
+ fsWatch: (_, _, _) {
+ attempts++;
+ throw UnsupportedError('No filesystem watcher');
+ },
+ );
+ });
+
+ test(
+ 'discovery expires a silent watch and clears a removed working folder',
+ () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-git-cache-',
+ );
+ final metadata = '${fixture.path}/.git';
+ final cwd = Directory('${fixture.path}/src');
+ await _metadata(metadata, 'before');
+ await cwd.create();
+ final watches = _Watches();
+ var now = DateTime(2026, 9, 13);
+ var changes = 0;
+ final reader = LocalGitProjects(
+ onChanged: () => changes++,
+ now: () => now,
+ );
+ addTearDown(() async {
+ reader.dispose();
+ await watches.dispose();
+ await fixture.delete(recursive: true);
+ });
+ await IOOverrides.runZoned(() async {
+ await reader.read(cwd.path);
+ final first = reader.cached(cwd.path)!;
+ await File('$metadata/HEAD').writeAsString('ref: refs/heads/after\n');
+ await reader.read(cwd.path);
+ expect(reader.cached(cwd.path), same(first));
+ now = now.add(const Duration(minutes: 1));
+ await reader.read(cwd.path);
+ expect(reader.cached(cwd.path)!.branch, 'after');
+ await cwd.delete();
+ now = now.add(const Duration(minutes: 1));
+ await reader.read(cwd.path);
+ expect(reader.cached(cwd.path), isNull);
+ expect(
+ watches.streams.values.expand((s) => s).any((s) => s.hasListener),
+ isFalse,
+ );
+ await cwd.create();
+ now = now.add(const Duration(minutes: 1));
+ await reader.read(cwd.path);
+ expect(reader.cached(cwd.path)!.branch, 'after');
+ expect(changes, 4);
+ }, fsWatch: watches.watch);
+ },
+ );
+
+ test('replacing a Git directory rebinds watches at the same path', () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-git-replace-',
+ );
+ final root = '${fixture.path}/repo';
+ final metadata = '$root/.git';
+ await _metadata(metadata, 'before');
+ final watches = _Watches();
+ final changes = StreamController<void>.broadcast();
+ final reader = LocalGitProjects(onChanged: () => changes.add(null));
+ addTearDown(() async {
+ reader.dispose();
+ await watches.dispose();
+ await changes.close();
+ await fixture.delete(recursive: true);
+ });
+ await IOOverrides.runZoned(() async {
+ await reader.read(root);
+ final changed = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.branch == 'replacement',
+ );
+ final moved = await Directory(metadata).rename('${fixture.path}/old');
+ await _metadata(metadata, 'replacement');
+ watches.emit(root, FileSystemMoveEvent(metadata, true, moved.path));
+ await changed.timeout(const Duration(seconds: 3));
+ expect(watches.streams[metadata], hasLength(2));
+ expect(watches.streams[metadata]!.first.hasListener, isFalse);
+ expect(watches.streams[metadata]!.last.hasListener, isTrue);
+ final next = changes.stream.firstWhere(
+ (_) => reader.cached(root)?.branch == 'next',
+ );
+ await File('$metadata/HEAD').writeAsString('ref: refs/heads/next\n');
+ watches.change(metadata, '$metadata/HEAD');
+ await next.timeout(const Duration(seconds: 3));
+ }, fsWatch: watches.watch);
+ });
+
+ for (final disposeWhileReading in [false, true]) {
+ test(
+ 'a delayed read serializes invalidation (dispose=$disposeWhileReading)',
+ () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-git-pending-',
+ );
+ final root = fixture.path;
+ final metadata = '$root/.git';
+ final head = File('$metadata/HEAD');
+ await _metadata(metadata, 'before');
+ final watches = _Watches();
+ final reader = LocalGitProjects(onChanged: () {});
+ final started = Completer<void>();
+ final release = Completer<void>();
+ var hold = false;
+ var headReads = 0;
+ final outside = Zone.current;
+ addTearDown(() async {
+ if (!release.isCompleted) release.complete();
+ reader.dispose();
+ await watches.dispose();
+ await fixture.delete(recursive: true);
+ });
+ await IOOverrides.runZoned(
+ () async {
+ await reader.read(root);
+ hold = true;
+ await head.writeAsString('ref: refs/heads/intermediate\n');
+ watches.change(metadata, head.path);
+ await started.future.timeout(const Duration(seconds: 3));
+ final pending = reader.read(root);
+ expect(reader.read(root), same(pending));
+ await head.writeAsString('ref: refs/heads/latest\n');
+ watches.change(metadata, head.path);
+ await Future<void>.delayed(const Duration(milliseconds: 180));
+ expect(headReads, 2);
+ if (disposeWhileReading) reader.dispose();
+ release.complete();
+ await pending;
+ expect(
+ reader.cached(root)?.branch,
+ disposeWhileReading ? null : 'latest',
+ );
+ if (disposeWhileReading) {
+ expect(
+ watches.streams.values
+ .expand((s) => s)
+ .any((s) => s.hasListener),
+ isFalse,
+ );
+ } else {
+ expect(headReads, 3);
+ }
+ },
+ fsWatch: watches.watch,
+ createFile: (path) {
+ if (path == head.path) {
+ headReads++;
+ if (hold) {
+ hold = false;
+ return _HeldFile(head, started, release.future);
+ }
+ }
+ return outside.run(() => File(path));
+ },
+ );
+ },
+ );
+ }
+
test('local Git metadata shares repository identity and watches worktree branches', () async {
final fixture = await Directory.systemTemp.createTemp(
'harness-git-context-',
diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.md
index 8838d4b38..0ed6a8b4b 100644
--- a/docs/harness-v2-developer-tools-research.md
+++ b/docs/harness-v2-developer-tools-research.md
@@ -17,6 +17,7 @@ Updated 2026-09-13 after user review. Keep the existing simple Command shortcuts
| In the rebuilt preview | Settings gear removed on macOS; native File/History menus and Cmd+P routing. Menus and picker typing verified live; focus/input regression tests pass. |
| Rebuilt; native menu reviewed live | Models replaces Swarm; Subscription shows existing account limits, while API, Local and Add Model are disabled placeholders. History uses provider icons and restores both closed agents and closed Swarms. Recovery is covered with isolated sessions; live agents were not closed to test it. |
| Rebuilt and reviewed live | Chrome-style Back/Forward, Recently Closed/Visited and full session History; compact branch-aware headers; Workshop includes its requested iMac Home agent. |
+| Local Git recovery implemented and regression checked | The older-daemon compatibility reader follows moved worktree metadata, recovers from stopped watchers and expires silently stale context during ordinary discovery. Per-entry refresh is serialized and bounded. No Git subprocess or terminal work is introduced; [performance notes](harness-v2-performance.md) record the limits and evidence. |
| In the rebuilt preview; regression verified | Preserve the session, terminal view, Find, viewport, selection and draft context through reconnect/keyframe replacement. Stale output/input/upload completions cannot affect the replacement stream. A real remote interruption remains to be validated. |
| Rebuilt; live search/project review passed | One top-right Cmd-P search for agents, Swarms, machines and projects, with Open and explicit Add here actions. Follow-up in validation: New swarm searches in place, and machine/project results open their swarm directly. Separate Add picker, floating pane + and titlebar bell removed. New swarm uses only the selected mountain/lake wallpaper; rotation and other assets removed. Native typing, Cmd-P select-all and Escape were verified from an existing empty New swarm after the focus correction. |
| Implemented; measured in isolation | Unified search construction and ranking avoid repeated scans/metadata work. Median catalog construction fell 50% in the 2,059-destination debug fixture; native input-to-display measurement remains separate. |
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index 5fc6f5d11..aadcd38b7 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -10,6 +10,16 @@ flutter test --no-pub --reporter expanded test/benchmarks/swarm_benchmark.dart
It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in `_test.dart`, so ordinary correctness runs do not include timing measurements.
+## Local Git context recovery (2026-09-13)
+
+[Dart's filesystem watch documentation](https://api.dart.dev/dart-io/FileSystemEntity/watch.html) warns that events can coalesce or arrive out of order, and that watches end when their target disappears or the watcher stops. [Git's repository layout](https://git-scm.com/docs/gitrepository-layout) distinguishes the working tree's `.git` pointer, worktree-specific HEAD and shared configuration through `commondir`. The compatibility reader now observes those relationships and treats a subscription as fallible.
+
+The cache still holds at most 256 working folders. Each entry watches at most three nonrecursive directories, filters metadata events, and retains the 100 ms debounce. Changed targets cancel obsolete subscriptions; a replaced directory rebinds its watches even when the path is reused. Watch loss schedules one refresh and delays another subscription attempt for one minute. Normal daemon discovery rechecks one-minute-old entries even if their watches appear live; no periodic timer was added. Removed working folders clear context. Work is serialized per entry, so a slow older result cannot finish after a newer one and replace it.
+
+Reads traverse at most 32 ancestors and request at most 64 KiB plus one byte per metadata file, rejecting oversized/invalid text. They open no Git processes, read no terminal output, send no input/network traffic and perform no work on the render path. This limited compatibility reader does not replace Git's full config/environment resolution or richer daemon metadata.
+
+All three stale-cache regressions failed on the earlier code. The final focused run passed 38 tests, including directory and common-path changes, ended/failed/unsupported watches, missed events, deletion, same-path replacement, serialized slow reads and disposal. The preexisting real temporary-filesystem worktree watch also passes; synthetic watchers cover failure ordering without relying on OS timing. Logs: `/private/tmp/harness-v2-git-watch-{before,tests,analyze}.log`. This establishes recovery and bounded work; it is not a new native latency measurement.
+
## Native calibration remains unmeasured (2026-09-13)
A fresh disposable Release copy of the existing native benchmark built at `/private/tmp/harness-native-benchmark-4t74nfhn`. Its separate bundle identity, temporary store, blocked networking and synthetic retained terminals isolate it from real agents. AppKit events are posted only to that fixture's own queue. The planned metric joins each observed input to Flutter's matching frame number and raster-finish timestamp; it excludes network and physical display latency. [Flutter's FrameTiming reference](https://api.flutter.dev/flutter/dart-ui/FrameTiming-class.html) describes those fields and recommends profile/release performance collection. The distinction between input latency under load and throughput follows the measurement discussion in [Dan Luu's terminal study](https://danluu.com/term-latency/); its old terminal rankings are not treated as current comparisons.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 18edcf35a..561a9ac9d 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -2,12 +2,19 @@
Updated 2026-09-13 with coordinated palettes, Models, combined closed-work History and faster unified search. This is a working preview, not a release.
+## Git context recovery checkpoint
+
+- Three regressions reproduced stale branch context after a worktree pointer changed or a directory watch ended/errored. The local compatibility reader now watches the working tree's `.git` connection, follows changed Git/common directories, and rebinds subscriptions after same-path directory replacement. Removed working folders clear their cached context instead of borrowing the parent repository.
+- Stopped watches trigger one coalesced refresh, with a one-minute retry delay. Ordinary discovery rechecks entries older than one minute even when a watch still appears healthy; there is no polling timer. Concurrent invalidations serialize behind a pending read, and disposal cannot republish or recreate watches. Metadata reads themselves are bounded to 64 KiB plus one byte; oversized content is rejected.
+- Validation: all three new regressions failed before the fix. **38 focused metadata, project membership, screen, navigation and search checks passed** afterward, including simulated missed/stopped/unsupported watches, delayed reads, directory replacement and the existing actual-filesystem worktree branch watch. Analyzer has zero errors/warnings and the existing 12 vendored infos. Logs: `/private/tmp/harness-v2-git-watch-{before,tests,analyze}.log`.
+- This remains a small read-only compatibility path for local agents on older daemons, not a complete Git configuration resolver. No terminal/network input, Git process, remote daemon upgrade or real worktree modification was used. [The performance notes](harness-v2-performance.md) record its limits and source documentation. Rebuild is pending for this checkpoint.
+
## First-folder checkpoint
- A genuinely empty, discovered local workspace now offers **Choose folder…**. That action opens the native folder chooser directly, then the ordinary New agent form with the selected folder. Installed-agent discovery overlaps folder selection, and the form reuses that request. The returning-user button and Cmd-N still open New agent normally.
- Repeated activation cannot stack native choosers. Cancellation, a changed swarm/machine, loss of local identity, disconnection or a newly required link discards the late result. No agent starts until Create agent is selected; no task is sent automatically.
- Validation: **65 focused onboarding, engine/profile, split and inline-search checks passed**, followed by an isolated visual render of the welcome and prefilled form at 880×560. Analyzer has zero errors/warnings and the existing 12 vendored infos. Artifacts: `/private/tmp/harness-v2-first-folder-{tests,render,analyze}.log` and `/private/tmp/harness-v2-first-folder-{welcome,form}.png`.
-- The preceding search-highlighting and first-agent-recovery changes were rebuilt successfully (`/private/tmp/harness-v2-search-onboarding-build.log`). The first-folder change is awaiting its own rebuild. Live capture is still unavailable; visual evidence here is from isolated renders.
+- Saved as local commit `9b7bff9`. Release build succeeded (`/private/tmp/harness-v2-first-folder-build.log`) and the exact preview reopened after PID 76047 was normally quit and confirmed exited. This includes the preceding search-highlighting and first-agent-recovery changes. Live capture is still unavailable; visual evidence here is from isolated renders.
- Native latency calibration is paused: the disposable Release benchmark window was visible, but macOS reported it inactive and not key. No timings were accepted. See [performance notes](harness-v2-performance.md) for the failed calibration artifacts and restart condition. The real preview was reopened after the fixture exited.
- Continue local commits. Public-origin approval remains pending; do not retry pushing or include the unrelated naming edits, collaboration draft or native benchmark directory in this checkpoint.
@@ -425,7 +432,7 @@ Earlier logs contain superseded failures. Temporary logs and toolchains are loca
4. Visually confirm app-menu modal behavior and overflow accessibility in AppKit; route/shortcut behavior is covered by passing Flutter tests.
5. Build/review Linux and Windows when their toolchains are available. Remote full project/branch metadata requires daemons running the new wire format; do not upgrade them automatically.
6. Optional retained-context preview/highlights, deliberate right/down splits, controlled resizing, file-based keyboard customization and existing-command search are implemented and regression checked. Continue targeted real-workflow verification; ordinary-shell creation is outside the current agent-workspace scope. Keep the rejected shelf/hierarchy/dashboard/manager surfaces absent.
-7. Audit local Git watch failure/removal and relocated-worktree invalidation before broadening that compatibility path. It deliberately reads a small subset of Git metadata; prefer richer daemon metadata as available. Continue the active goal using the current research status list, distinguishing shipped reductions from proposed follow-ups.
+7. Local Git watch failure/removal, directory replacement and relocated-worktree invalidation are now regression checked. The compatibility path deliberately reads a small subset of Git metadata; prefer richer daemon metadata as available. Continue the active goal using the current research status list, distinguishing shipped reductions from proposed follow-ups.
## Toolchain and workflow