@farmslot/capabilities 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,12 @@ All notable changes to `@farmslot/capabilities` are tracked here.
6
6
 
7
7
  - Active-development baseline; add user-facing changes here before release or package publication.
8
8
 
9
+ ## 0.6.2 - 2026-10-29
10
+
11
+ - Observe opened workspace names, bytes and linked-worktree Git metadata through one owned filesystem source.
12
+ - Report unavailable file observation watches rather than silently admitting missing parents or failed watchers.
13
+ - Report optional file-deletion and read-error observations, recover identical contents after an unavailable state, and discard late reads after replacement or stop.
14
+
9
15
  ## 0.6.1 - 2026-10-21
10
16
 
11
17
  - Align with `@farmslot/protocol` 0.61.0.
package/README.md CHANGED
@@ -34,6 +34,23 @@ import { createH264FrameSplitter } from '@farmslot/capabilities/screen-h264';
34
34
  | `screen-frame` — `encodeNodeFrame()` / `decodeNodeFrame()` | The node→gateway capture-frame binary envelope codec (`0xAF` magic). Node encodes, gateway decodes. |
35
35
  | `screen-h264` — `createH264FrameSplitter()` | Splits a raw `adb screenrecord --output-format=h264` byte stream into individual video frames. |
36
36
 
37
+ ## File observations
38
+
39
+ `watchFile(path, onContent, { onUnavailable })` keeps `onContent` for actual UTF-8
40
+ contents, including empty files. The optional callback receives `{ kind: 'deleted' }`
41
+ or `{ kind: 'error', error: { code?, message } }`. Recreating a file with identical
42
+ bytes restores content delivery. Reads superseded by another event or a stopped
43
+ handle cannot publish.
44
+
45
+ The node accepts `fs.watch { path, observations: 1 }` and replies with
46
+ `{ watching: true, observations: 1 }`. Opted-in `node.fs.changed` events retain
47
+ `requestId`, `machine`, `path` and `content`, and add `kind` for deletion or error.
48
+ The empty `content` on those events is a wire compatibility field; `kind` determines
49
+ the state. Requests without the option keep content-only events. Older nodes still
50
+ report writes and omit the observation version, so full state reporting requires
51
+ a coordinated node upgrade. Omitting the option rolls back delivery without
52
+ changing watched files.
53
+
37
54
  ## Source layout
38
55
 
39
56
  | Path | Owns |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farmslot/capabilities",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Machine-local capability primitives (fs-watch, screen capture) shared by the node (primary owner) and the gateway (local fallback when no node) — ADR-046.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -8,6 +8,7 @@
8
8
  "exports": {
9
9
  ".": "./src/index.ts",
10
10
  "./fs-watch": "./src/fs-watch.ts",
11
+ "./workspace-watch": "./src/workspace-watch.ts",
11
12
  "./screen-frame": "./src/screen-frame.ts",
12
13
  "./screen-h264": "./src/screen-h264.ts"
13
14
  },
@@ -26,7 +27,7 @@
26
27
  "quality": "yarn test && yarn typecheck"
27
28
  },
28
29
  "dependencies": {
29
- "@farmslot/protocol": "0.61.0"
30
+ "@farmslot/protocol": "0.74.1"
30
31
  },
31
32
  "devDependencies": {
32
33
  "@types/node": "^22.0.0",
package/src/fs-watch.ts CHANGED
@@ -8,6 +8,8 @@ import { readFile } from 'node:fs/promises';
8
8
  import { homedir } from 'node:os';
9
9
  import { basename, dirname } from 'node:path';
10
10
 
11
+ import type { FileWatchFailure, FileWatchUnavailable } from '@farmslot/protocol';
12
+
11
13
  // Pool configs can declare repos as `~/...`. `~` is a shell token, not a
12
14
  // filesystem prefix — node:fs treats it literally. Expand to $HOME first.
13
15
  export function expandTilde(p: string): string {
@@ -20,17 +22,58 @@ export interface FileWatchHandle {
20
22
  stop(): void;
21
23
  }
22
24
 
25
+ export interface FileWatchOptions {
26
+ onUnavailable?: (observation: FileWatchUnavailable) => void;
27
+ }
28
+
23
29
  /**
24
30
  * Watch a single file for content changes. `onChange` receives the file's UTF-8
25
31
  * content on every write. The parent directory remains watched so atomic file
26
32
  * replacement does not detach the watcher from subsequent updates. Returns a
27
33
  * handle the caller stops when done.
28
34
  */
29
- export function watchFile(filePath: string, onChange: (content: string) => void): FileWatchHandle {
35
+ export function watchFile(
36
+ filePath: string,
37
+ onChange: (content: string) => void,
38
+ options: FileWatchOptions = {},
39
+ ): FileWatchHandle {
30
40
  const targetPath = expandTilde(filePath);
31
41
  let watcher: FSWatcher | null = null;
32
42
  let stopped = false;
33
- let lastContent: string | null = null;
43
+ let lastObservation: string | undefined;
44
+ let generation = 0;
45
+
46
+ const unavailable = (error: unknown): FileWatchUnavailable => {
47
+ const code = (error as NodeJS.ErrnoException).code;
48
+ if (code === 'ENOENT') return { kind: 'deleted' };
49
+ const failure: FileWatchFailure = {
50
+ message: error instanceof Error ? error.message : String(error),
51
+ ...(typeof code === 'string' ? { code } : {}),
52
+ };
53
+ return { kind: 'error', error: failure };
54
+ };
55
+
56
+ const observe = async (): Promise<void> => {
57
+ if (stopped) return;
58
+ const current = ++generation;
59
+ let observation: FileWatchUnavailable | { kind: 'updated'; content: string };
60
+ try {
61
+ observation = { kind: 'updated', content: await readFile(targetPath, 'utf-8') };
62
+ } catch (error) {
63
+ observation = unavailable(error);
64
+ }
65
+ if (stopped || current !== generation) return;
66
+ const fingerprint = JSON.stringify(observation);
67
+ if (fingerprint === lastObservation) return;
68
+ lastObservation = fingerprint;
69
+ if (observation.kind === 'updated') onChange(observation.content);
70
+ else if (options.onUnavailable) options.onUnavailable(observation);
71
+ else if (observation.kind === 'error') {
72
+ // Content-only callers retain their last value; the parent watch stays armed
73
+ // so a subsequent permission change or replacement can restore delivery.
74
+ console.warn(`[fs.watch] read failed for ${targetPath}: ${observation.error.message}`);
75
+ }
76
+ };
34
77
 
35
78
  const start = (): void => {
36
79
  if (stopped) return;
@@ -39,25 +82,35 @@ export function watchFile(filePath: string, onChange: (content: string) => void)
39
82
  // sees the first replacement and then silently follows the orphaned inode.
40
83
  const dir = dirname(targetPath);
41
84
  if (!existsSync(dir)) {
42
- console.log(`[fs.watch] parent dir doesn't exist: ${dir} — skipping watch`);
85
+ if (options.onUnavailable) {
86
+ throw Object.assign(new Error(`Watch parent does not exist: ${dir}`), { code: 'ENOENT' });
87
+ }
88
+ // Legacy content-only consumers keep their existing inactive-watch behavior.
43
89
  return;
44
90
  }
45
91
  const target = basename(targetPath);
46
- watcher = watch(dir, { persistent: false }, async (_, filename) => {
92
+ watcher = watch(dir, { persistent: false }, (_, filename) => {
47
93
  if (filename != null && filename.toString() !== target) return;
48
- if (!existsSync(targetPath)) return;
49
- try {
50
- const content = await readFile(targetPath, 'utf-8');
51
- if (content === lastContent) return;
52
- lastContent = content;
53
- onChange(content);
54
- } catch (err) {
55
- // Atomic replacement can briefly remove the target between the directory
56
- // event and the read. The following event will read the replacement.
57
- const code = (err as NodeJS.ErrnoException).code;
58
- if (code !== 'ENOENT') {
59
- console.warn(`[fs.watch] read failed for ${targetPath}: ${(err as Error).message}`);
60
- }
94
+ void observe();
95
+ });
96
+ watcher.on('error', (error) => {
97
+ if (stopped) return;
98
+ // A failed native watch can no longer prove subsequent changes. Revoke
99
+ // admission explicitly; the caller must establish a new watch to retry.
100
+ generation++;
101
+ watcher?.close();
102
+ watcher = null;
103
+ stopped = true;
104
+ if (options.onUnavailable) {
105
+ options.onUnavailable({
106
+ kind: 'error',
107
+ error: {
108
+ message: error.message,
109
+ ...('code' in error && typeof error.code === 'string' ? { code: error.code } : {}),
110
+ },
111
+ });
112
+ } else {
113
+ throw error;
61
114
  }
62
115
  });
63
116
  };
@@ -67,6 +120,7 @@ export function watchFile(filePath: string, onChange: (content: string) => void)
67
120
  return {
68
121
  stop(): void {
69
122
  stopped = true;
123
+ generation++;
70
124
  if (watcher) {
71
125
  watcher.close();
72
126
  watcher = null;
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // @farmslot/capabilities — machine-local capability primitives shared by the node
2
2
  // (primary owner) and the gateway (local fallback when no node). ADR-046.
3
3
 
4
- export { expandTilde, type FileWatchHandle, watchFile } from './fs-watch.js';
4
+ export { expandTilde, type FileWatchHandle, type FileWatchOptions, watchFile } from './fs-watch.js';
5
5
  export {
6
6
  type DecodedNodeFrame,
7
7
  decodeNodeFrame,
@@ -0,0 +1,100 @@
1
+ import { execFile as execFileCallback } from 'node:child_process';
2
+ import { type FSWatcher, watch } from 'node:fs';
3
+ import { lstat, realpath } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ import { expandTilde } from './fs-watch.js';
7
+ interface GitDiscovery {
8
+ code: number;
9
+ stdout: string;
10
+ stderr: string;
11
+ }
12
+ function discoverGit(cwd: string): Promise<GitDiscovery> {
13
+ return new Promise((resolve, reject) =>
14
+ execFileCallback(
15
+ 'git',
16
+ ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'],
17
+ {
18
+ cwd,
19
+ timeout: 10_000,
20
+ maxBuffer: 64 * 1024,
21
+ env: Object.fromEntries(
22
+ Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')),
23
+ ),
24
+ },
25
+ (error, stdout, stderr) => {
26
+ // Numeric exit is Git-domain status. Spawn, timeout and signal failures are not plain directories.
27
+ if (error && (typeof error.code !== 'number' || error.killed || error.signal))
28
+ reject(error);
29
+ else resolve({ code: (error?.code as number) ?? 0, stdout, stderr });
30
+ },
31
+ ),
32
+ );
33
+ }
34
+
35
+ /** Arm all workspace bytes, names, index and refs. No periodic rereads or following symlinks. */
36
+ export async function armLocalWorkspace(
37
+ root: string,
38
+ changed: () => void,
39
+ failed: (error: Error) => void,
40
+ ): Promise<() => void> {
41
+ const watchers: FSWatcher[] = [];
42
+ let stopped = false;
43
+ const close = () => {
44
+ stopped = true;
45
+ for (const watcher of watchers) watcher.close();
46
+ };
47
+ const fail = (error: Error) => {
48
+ if (!stopped) {
49
+ close();
50
+ failed(error);
51
+ }
52
+ };
53
+ const actualRoot = await realpath(expandTilde(root));
54
+ // Root watch is armed before discovering git metadata so a concurrent checkout is fenced.
55
+ const add = async (target: string) => {
56
+ const initial = await lstat(target);
57
+ const watcher = watch(target, { recursive: true, persistent: false }, (_, filename) => {
58
+ if (stopped) return;
59
+ if (target === actualRoot && filename?.toString() === '.git') {
60
+ fail(new Error('Workspace git binding changed; retry to rearm'));
61
+ return;
62
+ }
63
+ changed();
64
+ });
65
+ watcher.on('error', fail);
66
+ watchers.push(watcher);
67
+ // Roots and linked metadata can be atomically removed/replaced. Watching an old inode is insufficient.
68
+ const parent = watch(path.dirname(target), { persistent: false }, async (_, filename) => {
69
+ if (filename != null && filename.toString() !== path.basename(target)) return;
70
+ try {
71
+ const current = await lstat(target);
72
+ if (current.ino !== initial.ino || current.dev !== initial.dev)
73
+ fail(new Error('Workspace source root replaced'));
74
+ } catch (error) {
75
+ fail(error instanceof Error ? error : new Error(String(error)));
76
+ }
77
+ });
78
+ parent.on('error', fail);
79
+ watchers.push(parent);
80
+ };
81
+ try {
82
+ await add(actualRoot);
83
+ const discovery = await discoverGit(actualRoot);
84
+ if (discovery.code === 0) {
85
+ for (const metadata of new Set(discovery.stdout.trim().split('\n'))) {
86
+ const target = await realpath(metadata);
87
+ const relative = path.relative(actualRoot, target);
88
+ if (relative.startsWith('..') || path.isAbsolute(relative)) await add(target);
89
+ }
90
+ } else if (discovery.code !== 128 || !discovery.stderr.includes('not a git repository')) {
91
+ throw new Error(`Git metadata discovery failed (${discovery.code}): ${discovery.stderr}`);
92
+ }
93
+ // Exit 128 with Git's specific diagnostic admits a plain directory, never runner state.
94
+ if (stopped) throw new Error('Workspace source failed while arming');
95
+ return close;
96
+ } catch (error) {
97
+ close();
98
+ throw error;
99
+ }
100
+ }