Skip to content

Commit cee01a4

Browse files
tarasclaude
andauthored
Refresh the REPL checklist from todo.md change notifications instead of polling (#1544)
* feat(repl): notify Todo refreshes from a Chokidar watch of todo.md (#1530) The Todo service re-read todo.md every 250 ms. It now refreshes when a direct-path Chokidar 4.0.3 watch reports a change, so an idle session does no periodic work. The watch is subscribed before the first read and waits for readiness, so no edit falls between them; it handles a missing file, atomic saves, removal and recreation, ends the session on a watcher error, and closes with the session. Chokidar's CHOKIDAR_USEPOLLING override would reintroduce polling, so the watch refuses to start under it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(repl): read todo.md again after Chokidar's folding window (#1530) Chokidar drops a change within 50 ms of one it reported, so two quick saves left the checklist on the first. Each notification now arms one more read after that window; an idle session still does no periodic work, and the pending read ends with the session. The watch follows the workspace directory filtered to todo.md, so a missing file or a rename save cannot leave it on a parent subscription or a replaced inode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(repl): follow a missing Todo workspace from its nearest ancestor (#1530) A legacy execution has no paired directory until its first explicit Sidekick message publishes one, and Chokidar reports a watch of a missing directory ready while watching nothing, so that session never saw a todo.md change. Creating the directory would make the next open treat it as a broken pair. The watch now follows the nearest existing ancestor, one non-recursive level at a time, filtered to the next missing component; each deeper watch is ready before the shallower one closes, and arriving at the workspace notifies once so the first read covers the transition. The watcher never creates a directory and still does no periodic work. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(repl): register the arming watcher's cleanup with ensure (#1530) Cleanup that suspends in finally is not guaranteed to complete when the operation is halted, so a watch armed but not yet handed back now closes through ensure registered before its readiness wait. The Todo test file takes the repository formatter's layout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(repl): end the Todo watch's notification streams as it closes (#1530) The watch's outward change stream and its internal arrival stream were never-closing signals, so a reader still waiting when the watch closed waited forever. Both now end in the same teardown that closes the watcher, registered before any watcher or transition exists so it runs after all of them have stopped; closing a Chokidar watcher removes its listeners at once, so nothing sends after either stream ends. The outward stream stays open across legacy-workspace watcher replacement, and the service's refresh loop stops when it ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e356252 commit cee01a4

11 files changed

Lines changed: 412 additions & 11 deletions

File tree

‎bun.lock‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎deno.lock‎

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎examples/repl-bench/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,7 @@ viewport or the `sidekick-composer` region. Every other component refuses. It
565565
runs the current build.
566566

567567
Inside a `<Test>`, a mounted launch can set `todoRefresh="startup-only"` to
568-
load the checklist at startup and omit periodic external-file refresh. Explicit
568+
load the checklist at startup and not follow external edits to it. Explicit
569569
reads and writes still use the current file. Omit the option for journeys that
570570
exercise external edits. PTY launches and launches outside `<Test>` refuse it.
571571

‎examples/xmd-profile/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ the caret. It records
194194

195195
The three mounted baseline documents use `todoRefresh="startup-only"`. Each
196196
launch loads its checklist and supports explicit reads and writes. The capture
197-
exercises typing or scrolling without periodic external-file refresh. Record one
197+
exercises typing or scrolling without following external edits. Record one
198198
capture per case and compare it at the default 1% tolerance.
199199

200200
## Profile a REPL session

‎examples/xmd-profile/journeys/mounted-todo-refresh.test.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<Test name="mounted launch forwards startup-only and leaves default Todo polling enabled" timeout="60s">
1+
<Test name="mounted Todo does no idle refresh work with or without startup-only" timeout="60s">
22
<XMD.Repl mounted={true} todoRefresh="startup-only">
33
<Profile label="todo-startup-only-idle" mode="calls" as="configured">
44
<Terminal.Scroll pattern="...." tick={250} />
@@ -12,6 +12,6 @@
1212
<Terminal.Scroll pattern="...." tick={250} />
1313
</Profile>
1414
<File path={ordinary.calls} as="ordinaryCalls" />
15-
<AssertMatch actual={ordinaryCalls} expected={/repl\/todo\/service\.ts/} />
15+
<AssertNotMatch actual={ordinaryCalls} expected={/repl\/todo\/service\.ts/} />
1616
</XMD.Repl>
1717
</Test>

‎packages/cli/deno.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
"@effectionx/stream-helpers": "npm:@effectionx/stream-helpers@0.8.3",
1313
"@standard-schema/spec": "npm:@standard-schema/spec@^1.0.0",
1414
"zod": "npm:zod@^4.3.6",
15-
"@agentclientprotocol/sdk": "npm:@agentclientprotocol/sdk@1.3.0"
15+
"@agentclientprotocol/sdk": "npm:@agentclientprotocol/sdk@1.3.0",
16+
"chokidar": "npm:chokidar@4.0.3"
1617
},
1718
"publish": {
1819
"exclude": ["!generated/tty/**", "vendor/tty/**"]

‎packages/cli/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"@executablemd/workflow": "workspace:*",
3030
"@lezer/markdown": "1.8.1",
3131
"@standard-schema/spec": "^1.0.0",
32+
"chokidar": "4.0.3",
3233
"effection": "4.1.0",
3334
"marked": "^17.0.4",
3435
"semver": "^7.8.5",

‎packages/cli/src/repl/todo/service.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { applyTodoDiff, parseTodo, todoDiff, TodoEditError } from "./document.ts
2323
import type { TodoDocument, TodoItem } from "./document.ts";
2424
import { captureTodoSource } from "./source.ts";
2525
import { TodoSourceError } from "./source.ts";
26+
import { TODO_WATCH_SETTLE_MS, useTodoWatch } from "./watch.ts";
2627
import { Agent } from "@executablemd/agent/api";
2728
import type { AgentPromptEvent } from "@executablemd/agent/api";
2829

@@ -267,11 +268,21 @@ export function* useTodo(
267268
});
268269
},
269270
};
271+
// Subscribed before the first read, so an edit landing between the two is
272+
// either in that read or in a notification still waiting to be taken. A
273+
// startup-only checklist reads once and follows no external edit.
274+
const notifications =
275+
todoRefresh === "startup-only" ? undefined : yield* useTodoWatch(workspace);
270276
yield* refresh();
271-
if (todoRefresh !== "startup-only") {
277+
if (notifications !== undefined) {
272278
yield* spawn(function* () {
273-
while (true) {
274-
yield* sleep(250);
279+
// Until the watch ends its notifications, which it does as it closes.
280+
while (!(yield* notifications.next()).done) {
281+
yield* refresh();
282+
// Chokidar folds a change that closely follows a reported one into
283+
// it, so one more read after its window sees the edit it did not
284+
// announce.
285+
yield* sleep(TODO_WATCH_SETTLE_MS);
275286
yield* refresh();
276287
}
277288
});
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import { createSignal, ensure, race, resource, spawn, until, withResolvers } from "effection";
2+
import type { Operation, Subscription } from "effection";
3+
import { access } from "node:fs/promises";
4+
import { dirname, join, resolve } from "node:path";
5+
import { watch } from "chokidar";
6+
7+
/**
8+
* How long after a notification a second read still catches an edit Chokidar
9+
* folded into it: it drops a change within 50 ms of the last one it reported,
10+
* and holds an unlink up to 100 ms waiting for a replacing add.
11+
*/
12+
export const TODO_WATCH_SETTLE_MS = 150;
13+
14+
export class TodoWatchError extends Error {
15+
override name = "TodoWatchError";
16+
}
17+
18+
/**
19+
* Notifications that `todo.md` in one workspace may have changed.
20+
*
21+
* The file may be missing when the watch starts and appear, be replaced
22+
* atomically, disappear and reappear later. The workspace directory itself may
23+
* be missing too: a legacy execution has no paired directory until its first
24+
* explicit Sidekick message publishes one, and creating it here would turn that
25+
* execution into a broken pair. Until it exists, the nearest existing ancestor
26+
* is watched for the next missing component, one level at a time.
27+
* The subscription exists before the watcher reports ready, so a read taken
28+
* after this returns sees every edit that no later notification announces.
29+
*/
30+
export function* useTodoWatch(workspace: string): Operation<Subscription<void, void>> {
31+
return yield* resource<Subscription<void, void>>(function* (provide) {
32+
const changes = createSignal<void, void>();
33+
const subscription = yield* changes;
34+
const arrivals = createSignal<void, void>();
35+
const arrived = yield* arrivals;
36+
const failed = withResolvers<never>();
37+
const directory = resolve(workspace);
38+
const target = join(directory, "todo.md");
39+
let current: { readonly final: boolean; close(): Operation<void> } | undefined;
40+
// Registered before any watcher or transition exists, so it runs after
41+
// all of them have stopped: closing a watcher removes its listeners at
42+
// once, and only then do both streams end, with nothing left to send.
43+
yield* ensure(function* () {
44+
if (current !== undefined) {
45+
yield* current.close();
46+
}
47+
arrivals.close();
48+
changes.close();
49+
});
50+
51+
// One non-recursive watch of the nearest existing directory on the way to
52+
// the workspace, passing only the one path that moves this watch forward:
53+
// todo.md once the workspace exists, the next missing component before.
54+
function* arm(): Operation<{ readonly final: boolean; close(): Operation<void> }> {
55+
let base = directory;
56+
let next: string | undefined;
57+
while (!(yield* present(base))) {
58+
next = base;
59+
base = dirname(base);
60+
if (base === next) {
61+
throw new TodoWatchError(`no ancestor of ${directory} exists to watch.`);
62+
}
63+
}
64+
const awaited = next ?? target;
65+
const watcher = watch(base, {
66+
depth: 0,
67+
ignored: (path) => path !== base && path !== awaited,
68+
ignoreInitial: true,
69+
persistent: true,
70+
usePolling: false,
71+
atomic: true,
72+
});
73+
const close = () => until(watcher.close());
74+
// Closed by the scope that armed it unless it is handed back, because a
75+
// failure or a halt before then leaves it with no other owner.
76+
let armed = false;
77+
yield* ensure(function* () {
78+
if (!armed) {
79+
yield* close();
80+
}
81+
});
82+
// Chokidar lets CHOKIDAR_USEPOLLING override the option above for every
83+
// watcher in the process; polling is what this watch exists to replace.
84+
if (watcher.options.usePolling) {
85+
throw new TodoWatchError(
86+
"CHOKIDAR_USEPOLLING enables polling, which the TODO watch does not use. " +
87+
"Unset it or set it to false and start the REPL again.",
88+
);
89+
}
90+
const ready = withResolvers<void>();
91+
watcher.on("error", (error) => {
92+
failed.reject(
93+
new TodoWatchError("todo.md can no longer be watched for changes.", { cause: error }),
94+
);
95+
});
96+
watcher.on("ready", () => ready.resolve());
97+
watcher.on("all", (_event, path) => {
98+
if (path !== awaited) {
99+
return;
100+
}
101+
if (next === undefined) {
102+
changes.send();
103+
} else {
104+
arrivals.send();
105+
}
106+
});
107+
yield* race([ready.operation, failed.operation]);
108+
// Initial entries are not reported, so a component created between the
109+
// existence check and readiness would otherwise never arrive.
110+
if (next !== undefined && (yield* present(next))) {
111+
arrivals.send();
112+
}
113+
armed = true;
114+
return { final: next === undefined, close };
115+
}
116+
117+
current = yield* arm();
118+
if (!current.final) {
119+
yield* spawn(function* () {
120+
while (current !== undefined && !current.final) {
121+
const arrival = yield* race([arrived.next(), failed.operation]);
122+
if (arrival.done) {
123+
return;
124+
}
125+
// The deeper watch is ready before the shallower one closes, and
126+
// the notification after it covers whatever the workspace gained
127+
// while neither watch was looking at it.
128+
const previous = current;
129+
current = yield* arm();
130+
yield* previous.close();
131+
if (current.final) {
132+
changes.send();
133+
}
134+
}
135+
});
136+
}
137+
yield* provide({
138+
next: () => race([subscription.next(), failed.operation]),
139+
});
140+
});
141+
}
142+
143+
function present(path: string): Operation<boolean> {
144+
return until(
145+
access(path).then(
146+
() => true,
147+
() => false,
148+
),
149+
);
150+
}

0 commit comments

Comments
 (0)