pi-odd-worktree 3.11.2 → 3.12.1

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.
@@ -0,0 +1,453 @@
1
+ 'use strict';
2
+ // The ODDs this machine is working on, as gentle-shell's second rail section
3
+ // (odd/tasks/odd-rail-section.md, T3: S1, S2, S5, S6).
4
+ //
5
+ // Pure and injectable: the read (`load`), the opener (`open`), a clock, a
6
+ // scheduler, the two timer seams and a repaint callback all arrive as options, so
7
+ // nothing here walks a directory, runs git or reads the clock on its own. The
8
+ // bridge calls `lines(ctx)` once per frame and it must answer synchronously: it
9
+ // reads ONE in-process snapshot and only ever SCHEDULES the read, so a frame
10
+ // never waits on the scan.
11
+ //
12
+ // ONE source (`load` resolves an ARRAY of `{ name, docPath, checkoutRoot,
13
+ // checkoutName, mtimeMs }`): the caller owns the walk of every owned checkout's
14
+ // `odd/` directory and the dedupe that keeps the most recently modified ODD
15
+ // (S3/S4), and it hands the rows over already ordered most-recent-first. The
16
+ // section never re-sorts — the order it resolves is the order drawn — and a read
17
+ // that rejects or throws is a failure like any other.
18
+ //
19
+ // At most FOUR rows (S2: "maximo 4, si hay mas sale linea 5 con N more"). A row
20
+ // is its label — the ODD's name — its click and its right-hand `meta`: the
21
+ // checkout name VERBATIM, `main` or the worktree's own name, never a path (S5).
22
+ // More than four appends ONE fifth row in the `dim` tone reading `N more`, `N`
23
+ // being the total beyond the four; that row is inert (`onClick: null`), because
24
+ // there is nothing behind it to open. Exactly four ODDs paint four rows and no
25
+ // elision row at all.
26
+ //
27
+ // S1: the section carries `placement: { after: "agents" }`, which is what puts
28
+ // the card right after the native AGENTS rail part. It carries no `meta`: no
29
+ // header count was asked for.
30
+ //
31
+ // S6: a row's `onClick` defers its opener onto the scheduler — it never runs on
32
+ // the paint path, it runs once per click, and it calls
33
+ // `open({ name, docPath, checkoutRoot })` with the target the ROW was built
34
+ // from, so a row the host retained across a refresh opens the ODD it was read
35
+ // from. A throw or a rejected promise from the opener is recorded in the
36
+ // snapshot's `error` instead of escaping into the host, and it never costs a row.
37
+ //
38
+ // A read that fails keeps the rows already on screen: the status becomes `stale`
39
+ // (the fourth value the issues section uses too), `error` records the reason and
40
+ // `at` keeps the time of the last SUCCESSFUL read. The TTL is measured from the
41
+ // last SETTLED attempt, success or failure, so a failure is not retried at the
42
+ // same instant. Only a failure with nothing to show is the ONE error row.
43
+ //
44
+ // `refreshFloorMs` is the issues section's floor timer, unchanged: while the
45
+ // section is DRAWN it keeps ONE self-scheduled, unref'd timer at that floor,
46
+ // which fires one read, arms the next floor and stops by itself once the section
47
+ // leaves the `drawnWindowMs` window. It is armed by a draw, so a section nobody
48
+ // draws keeps no timer at all — and no read either.
49
+ //
50
+ // `invalidate()` is the session boundary: the snapshot is dropped (the rail
51
+ // shows the loading row again), the latest-wins token moves on so an answer
52
+ // already on its way is discarded, and the floor timer is cleared. The module
53
+ // leaves no timer and no state write behind after `dispose()`.
54
+
55
+ const DEFAULT_TTL_MS = 60000;
56
+ // How long a section counts as DRAWN after its last frame. It is the caller's
57
+ // window unless it names one.
58
+ const DEFAULT_DRAWN_WINDOW_MS = 120000;
59
+ // S2: the body holds four ODDs; anything beyond them is the ONE elision row.
60
+ const MAX_ROWS = 4;
61
+ const LOADING_ROW = { label: 'loading…', tone: 'dim' };
62
+ const READ_FAILED = 'cannot read the ODDs';
63
+ const OPEN_FAILED = 'cannot open the ODD';
64
+
65
+ function textOf(value, fallback) {
66
+ if (value && typeof value.message === 'string' && value.message.length > 0) return value.message;
67
+ if (typeof value === 'string' && value.length > 0) return value;
68
+ return fallback;
69
+ }
70
+
71
+ // S2/S5: the fifth line. It is the issues section's elision row with its click
72
+ // removed — the count is what the four rows left out, and there is no panel to
73
+ // open for "the rest".
74
+ function elisionRow(total) {
75
+ return { label: `${total - MAX_ROWS} more`, tone: 'dim', onClick: null };
76
+ }
77
+
78
+ function createOddRailSection(options = {}) {
79
+ const opts = options && typeof options === 'object' ? options : {};
80
+ const load = typeof opts.load === 'function' ? opts.load : null;
81
+ const open = typeof opts.open === 'function' ? opts.open : null;
82
+ const now = typeof opts.now === 'function' ? opts.now : Date.now;
83
+ const schedule = typeof opts.schedule === 'function' ? opts.schedule : (fn) => setTimeout(fn, 0);
84
+ // The timer seams are injected exactly like `schedule`, so a caller (and a
85
+ // test) drives the floor without waiting for it. No floor named, no timer.
86
+ const setTimer = typeof opts.setTimer === 'function' ? opts.setTimer : (fn, ms) => setTimeout(fn, ms);
87
+ const cancelTimer = typeof opts.clearTimer === 'function' ? opts.clearTimer : (handle) => clearTimeout(handle);
88
+ const refreshFloorMs = Number.isFinite(opts.refreshFloorMs) && opts.refreshFloorMs > 0
89
+ ? opts.refreshFloorMs
90
+ : null;
91
+ const drawnWindowMs = Number.isFinite(opts.drawnWindowMs) && opts.drawnWindowMs >= 0
92
+ ? opts.drawnWindowMs
93
+ : DEFAULT_DRAWN_WINDOW_MS;
94
+ const ttlMs = Number.isFinite(opts.ttlMs) && opts.ttlMs >= 0 ? opts.ttlMs : DEFAULT_TTL_MS;
95
+ const requestRepaint = typeof opts.requestRepaint === 'function' ? opts.requestRepaint : null;
96
+
97
+ let snapshot = null;
98
+ // A read that is scheduled but has not started, and the one that runs. Both are
99
+ // module state so two stale frames schedule ONE read and a frame drawn while it
100
+ // runs schedules nothing. `runToken` is the latest-wins boundary: a result from
101
+ // a read that is no longer the latest is dropped instead of applied.
102
+ let scheduled = false;
103
+ let running = null;
104
+ let runToken = 0;
105
+ let disposed = false;
106
+ // When the last read SETTLED, success or failure — the instant the TTL
107
+ // measures from, so a failing scan is not retried at the same instant. And the
108
+ // token a DEFERRED refresh captured when it was queued, so a callback that
109
+ // outlives `invalidate()`/`dispose()` starts no read at all.
110
+ let lastAttemptAt = null;
111
+ let generation = 0;
112
+ // When the section was last DRAWN; an undrawn section costs nothing.
113
+ let lastDrawnAt = null;
114
+ // The ONE self-scheduled floor timer, and the token that makes a callback the
115
+ // host already queued inert once the timer was cleared.
116
+ let timer = null;
117
+ let timerToken = 0;
118
+
119
+ // The time the staleness checks measure from: the last SETTLED attempt when
120
+ // there is one, otherwise the last snapshot.
121
+ function lastAttempt() {
122
+ if (lastAttemptAt !== null) return lastAttemptAt;
123
+ return snapshot === null ? null : snapshot.at;
124
+ }
125
+
126
+ function isStale() {
127
+ if (snapshot === null) return true;
128
+ const age = now() - lastAttempt();
129
+ return !Number.isFinite(age) || age >= ttlMs;
130
+ }
131
+
132
+ function ensureFresh() {
133
+ if (disposed || scheduled || running !== null) return;
134
+ if (!isStale()) return;
135
+ const queuedGeneration = generation;
136
+ scheduled = true;
137
+ try {
138
+ schedule(() => {
139
+ // A callback that outlived the section it was queued for — an
140
+ // `invalidate()`, a `dispose()` or a newer checkout — does nothing. It
141
+ // leaves `scheduled` to whichever callback still owns it.
142
+ if (disposed || queuedGeneration !== generation) return undefined;
143
+ scheduled = false;
144
+ // A read that started while this one was queued already covers the
145
+ // staleness: the TTL path starts nothing besides its own read.
146
+ if (running !== null) return undefined;
147
+ return refresh();
148
+ });
149
+ } catch {
150
+ scheduled = false;
151
+ }
152
+ }
153
+
154
+ // Drop the floor timer. The token moves on FIRST, so a callback the host
155
+ // already queued cannot read through a timer this section no longer owns.
156
+ function clearFloorTimer() {
157
+ timerToken += 1;
158
+ if (timer === null) return;
159
+ const handle = timer;
160
+ timer = null;
161
+ try {
162
+ cancelTimer(handle);
163
+ } catch {
164
+ // A timer the host will not cancel still finds the token moved on.
165
+ }
166
+ }
167
+
168
+ // Arm the ONE floor timer. It is armed by a DRAW and never by a second timer of
169
+ // its own while one is running, so a burst of frames can never stack two reads;
170
+ // its fire turns into the next floor's arm.
171
+ function armFloorTimer() {
172
+ if (disposed || refreshFloorMs === null || timer !== null) return;
173
+ const token = (timerToken += 1);
174
+ let handle = null;
175
+ try {
176
+ handle = setTimer(() => {
177
+ // A timer that was cleared (or superseded) while the host held its
178
+ // callback: the token is what makes it inert.
179
+ if (token !== timerToken) return;
180
+ timer = null;
181
+ if (disposed) return;
182
+ // The moment the section is no longer drawn, the timer stops by itself —
183
+ // no read, and no next floor.
184
+ if (!drawnWithin(drawnWindowMs)) return;
185
+ // One read per floor: a read already in flight owns this instant.
186
+ refreshIfStale(refreshFloorMs);
187
+ armFloorTimer();
188
+ }, refreshFloorMs);
189
+ } catch {
190
+ timer = null;
191
+ return;
192
+ }
193
+ timer = handle;
194
+ // Unref'd: the floor is never a reason for the process to stay alive.
195
+ if (handle && typeof handle.unref === 'function') {
196
+ try {
197
+ handle.unref();
198
+ } catch {
199
+ // A handle without a working unref still bounds the wait.
200
+ }
201
+ }
202
+ }
203
+
204
+ function replace(next) {
205
+ snapshot = next;
206
+ if (requestRepaint !== null) {
207
+ try {
208
+ requestRepaint();
209
+ } catch {
210
+ // A repaint failure never breaks the frame that reads the snapshot.
211
+ }
212
+ }
213
+ }
214
+
215
+ function apply(items) {
216
+ const at = now();
217
+ // Every settled attempt — success or failure — starts the frame TTL.
218
+ lastAttemptAt = at;
219
+ const list = Array.isArray(items) ? items : [];
220
+ const rows = [];
221
+ for (const item of list.slice(0, MAX_ROWS)) {
222
+ const entry = item && typeof item === 'object' ? item : {};
223
+ const name = typeof entry.name === 'string' ? entry.name : '';
224
+ // S6: the target travels with the row it was built from, so the click never
225
+ // reads the current snapshot to learn where the ODD lives.
226
+ const target = { name, docPath: entry.docPath, checkoutRoot: entry.checkoutRoot };
227
+ const row = {
228
+ label: name,
229
+ tone: 'text',
230
+ // The click is one deferred run of the injected opener; a failure lands
231
+ // in the snapshot instead of the host.
232
+ onClick: deferSeam(() => (open === null ? undefined : open(target)), OPEN_FAILED),
233
+ };
234
+ // S5: the checkout name goes through VERBATIM — `main` or the worktree's
235
+ // own name. The section never touches a path. An entry that answers no
236
+ // name carries no `meta` key at all, so nothing pends on `undefined`
237
+ // meaning the same thing as absent.
238
+ if (typeof entry.checkoutName === 'string') row.meta = entry.checkoutName;
239
+ rows.push(row);
240
+ }
241
+ if (list.length > MAX_ROWS) rows.push(elisionRow(list.length));
242
+ replace({ status: 'ready', at, error: null, total: list.length, rows });
243
+ }
244
+
245
+ // A failed read. While a list is on screen this is a transient stall, not an
246
+ // empty machine: the rows stay exactly as they were (same rows, same order,
247
+ // same metadata), `error` records the reason and `status` becomes `stale`.
248
+ // `at` keeps the time of the last SUCCESSFUL read, while `lastAttemptAt` — set
249
+ // by the caller before this runs — is what keeps the retry behind the TTL.
250
+ function applyFailure(err) {
251
+ const at = now();
252
+ lastAttemptAt = at;
253
+ const error = textOf(err, READ_FAILED);
254
+ if (snapshot !== null && (snapshot.status === 'ready' || snapshot.status === 'stale')) {
255
+ replace({ ...snapshot, status: 'stale', error });
256
+ return;
257
+ }
258
+ replace({ status: 'error', at, error, total: 0, rows: [] });
259
+ }
260
+
261
+ function recordOpenError(err, fallback) {
262
+ if (disposed) return;
263
+ const error = textOf(err, fallback);
264
+ if (snapshot === null) {
265
+ replace({ status: 'error', at: now(), error, total: 0, rows: [] });
266
+ return;
267
+ }
268
+ // One field changes: a click failure never turns a ready list into an error
269
+ // row, it is only recorded for the next reader.
270
+ snapshot = { ...snapshot, error };
271
+ }
272
+
273
+ function recordOpenOutcome(outcome, fallback) {
274
+ if (disposed) return undefined;
275
+ if (outcome && typeof outcome === 'object' && outcome.ok === false) {
276
+ recordOpenError(outcome.error, fallback);
277
+ }
278
+ return undefined;
279
+ }
280
+
281
+ // One click is one deferred run of one injected seam, and the run's outcome is
282
+ // classified here: never a throw on the paint path, never an unhandled
283
+ // rejection, and a failure lands in the snapshot instead of the host.
284
+ function deferSeam(invoke, fallback) {
285
+ return () => {
286
+ if (disposed) return undefined;
287
+ try {
288
+ schedule(() => {
289
+ if (disposed) return undefined;
290
+ let outcome;
291
+ try {
292
+ outcome = invoke();
293
+ } catch (err) {
294
+ recordOpenError(err, fallback);
295
+ return undefined;
296
+ }
297
+ if (outcome && typeof outcome.then === 'function') {
298
+ return Promise.resolve(outcome).then(
299
+ (value) => recordOpenOutcome(value, fallback),
300
+ (err) => recordOpenError(err, fallback),
301
+ );
302
+ }
303
+ return recordOpenOutcome(outcome, fallback);
304
+ });
305
+ } catch {
306
+ // A scheduler that refuses the work leaves the list as it was.
307
+ }
308
+ return undefined;
309
+ };
310
+ }
311
+
312
+ // An explicit read always starts its own: the latest run wins, so an older one
313
+ // that settles later is dropped instead of overwriting it. The TTL path guards
314
+ // itself in `ensureFresh` and never reaches this while a read is in flight.
315
+ function refresh() {
316
+ if (disposed) return Promise.resolve(snapshot);
317
+ const token = (runToken += 1);
318
+ let pending;
319
+ try {
320
+ pending = load === null ? Promise.reject(new Error(READ_FAILED)) : Promise.resolve(load());
321
+ } catch (err) {
322
+ pending = Promise.reject(err);
323
+ }
324
+ const run = pending.then(
325
+ (result) => {
326
+ if (disposed || token !== runToken) return snapshot;
327
+ apply(result);
328
+ return snapshot;
329
+ },
330
+ (err) => {
331
+ if (disposed || token !== runToken) return snapshot;
332
+ applyFailure(err);
333
+ return snapshot;
334
+ },
335
+ );
336
+ running = run;
337
+ const settle = () => {
338
+ if (running === run) running = null;
339
+ };
340
+ run.then(settle, settle);
341
+ return run;
342
+ }
343
+
344
+ // The read an activity trigger or the floor timer asks for: it starts ONE read
345
+ // when the snapshot is absent or at least `maxAgeMs` old, and nothing at all
346
+ // while a read is in flight or after `dispose()`. It answers whether a read
347
+ // started, and it never throws or rejects.
348
+ function refreshIfStale(maxAgeMs) {
349
+ if (disposed) return false;
350
+ if (running !== null) return false;
351
+ if (snapshot !== null) {
352
+ // A failed attempt starts the floor too.
353
+ const age = now() - lastAttempt();
354
+ if (Number.isFinite(age) && age < maxAgeMs) return false;
355
+ }
356
+ try {
357
+ const pending = refresh();
358
+ if (pending && typeof pending.catch === 'function') pending.catch(() => {});
359
+ return true;
360
+ } catch {
361
+ return false;
362
+ }
363
+ }
364
+
365
+ // The supersede a session boundary performs. Dropping the snapshot is what
366
+ // makes the rail fall back to the loading row; bumping the token is what makes
367
+ // an in-flight answer land nowhere. It starts no read, repaints nothing, and
368
+ // after `dispose()` it does nothing at all.
369
+ function invalidate() {
370
+ if (disposed) return;
371
+ snapshot = null;
372
+ runToken += 1;
373
+ scheduled = false;
374
+ lastDrawnAt = null;
375
+ clearFloorTimer();
376
+ // The previous session's attempt no longer sets the TTL, and a refresh
377
+ // already queued for it is now stale.
378
+ lastAttemptAt = null;
379
+ generation += 1;
380
+ }
381
+
382
+ function lines(_ctx) {
383
+ try {
384
+ // A drawn body is the host painting the section, and that is what owns the
385
+ // floor timer.
386
+ noteDrawn();
387
+ ensureFresh();
388
+ if (snapshot === null) return [{ ...LOADING_ROW }];
389
+ if (snapshot.status === 'error') return [{ label: snapshot.error, tone: 'error' }];
390
+ // A ready list with nothing in it draws no rows at all: there is no copy
391
+ // this module may invent for an empty scan.
392
+ // A copy per frame: the host may keep the array it was handed, and the
393
+ // snapshot stays the one source the TTL and the clicks read.
394
+ return snapshot.rows.map((row) => (row.meta === undefined
395
+ ? { label: row.label, tone: row.tone, onClick: row.onClick }
396
+ : { label: row.label, tone: row.tone, meta: row.meta, onClick: row.onClick }));
397
+ } catch {
398
+ return [{ ...LOADING_ROW }];
399
+ }
400
+ }
401
+
402
+ // A drawing call stamps the frame. A clock that throws or answers nonsense
403
+ // costs the drawn window, never the frame itself.
404
+ function noteDrawn() {
405
+ try {
406
+ const at = now();
407
+ if (Number.isFinite(at)) lastDrawnAt = at;
408
+ } catch {
409
+ // The frame is drawn; only its stamp is lost.
410
+ }
411
+ // The drawn frame is also what owns the floor timer — a section the host
412
+ // stops painting keeps it no longer than the drawn window.
413
+ armFloorTimer();
414
+ }
415
+
416
+ // True only while a draw happened at or after `now() - maxAgeMs`. An undrawn,
417
+ // superseded or disposed section answers false, and that answer is what keeps
418
+ // a hidden section free. It starts no work and never throws.
419
+ function drawnWithin(maxAgeMs) {
420
+ if (disposed || lastDrawnAt === null) return false;
421
+ let at;
422
+ try {
423
+ at = now();
424
+ } catch {
425
+ return false;
426
+ }
427
+ const age = at - lastDrawnAt;
428
+ return Number.isFinite(age) && age <= maxAgeMs;
429
+ }
430
+
431
+ function dispose() {
432
+ disposed = true;
433
+ scheduled = false;
434
+ lastDrawnAt = null;
435
+ clearFloorTimer();
436
+ // A refresh already queued for this section is stale.
437
+ generation += 1;
438
+ }
439
+
440
+ const section = {
441
+ id: 'odd-worktree.odd-rail',
442
+ title: 'ODD',
443
+ rowLabel: 'odd',
444
+ defaultVisible: true,
445
+ // S1: right after the native AGENTS part, never at the top.
446
+ placement: { after: 'agents' },
447
+ lines,
448
+ };
449
+
450
+ return { section, refresh, refreshIfStale, invalidate, drawnWithin, dispose };
451
+ }
452
+
453
+ module.exports = { createOddRailSection };
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+ // The ODD documents THIS session wrote or edited (odd-rail-section, T8: S8, S9).
3
+ //
4
+ // This is an ANNOTATION, never the source of truth (S9). Which ODDs exist and where
5
+ // each one lives is the grouped model's answer (lib/odd-group.js), and which copy of
6
+ // a name is newest belongs to the rail's row model's own election
7
+ // (lib/odd-rail-model.js); this module only records "this session touched that
8
+ // document", so the rail can show it first and refresh immediately instead of waiting
9
+ // for its TTL. Nothing here decides existence, location or recency, and nothing here
10
+ // reads the filesystem or Git: the rule is lexical, like the scan it annotates.
11
+ //
12
+ // What registers (S8): a `write` or an `edit` whose target is a Markdown document
13
+ // DIRECTLY under an `odd/tasks` directory — lib/odd-docs.js's scan rule
14
+ // (`<root>/odd/tasks/*.md`, non-recursive, regular files only, dotfiles skipped,
15
+ // the suffix matched case-insensitively), applied to a path instead of a
16
+ // directory. `read` never registers, and neither does any other tool; a `.md`
17
+ // outside `odd/tasks`, a document nested deeper, a dotfile and a non-Markdown file
18
+ // never do either. A subagent runs in its own session, so its calls never reach
19
+ // the parent's record: only the filesystem scan covers those, which is by design
20
+ // (S9) and not a gap to work around here.
21
+ //
22
+ // The event arrives normalized by the extension's own readers (`oddToolNameOf`,
23
+ // `oddTouchedPaths`, `oddEventCwd` in extensions/odd-worktree-tools.ts), so there
24
+ // is no second tool-argument parser in this module: it accepts the same spellings
25
+ // those readers accept one level up — `toolName`/`tool`/`name`, `paths`/`path` —
26
+ // plus the call's `cwd` and `isError`. A FAILED call (`isError: true`) registers
27
+ // nothing, which is why the wiring observes `tool_result` and not `tool_call`: a
28
+ // write that never landed must not leave a phantom row.
29
+ //
30
+ // A relative target resolves against the call's cwd and the stored path is
31
+ // ABSOLUTE and normalized; a relative target with no cwd registers nothing rather
32
+ // than guessing the process's own directory. The record is idempotent per absolute
33
+ // path — a second touch moves the document to the front and updates `at`, never a
34
+ // second row — and one tool call is ONE timestamp, however many documents it names.
35
+ //
36
+ // Persistence: `entryOf(touch)` is the body of the ONE transcript entry the
37
+ // wiring appends, `{ customType, data: { path, at } }`, and `TOUCH_ENTRY_TYPE` is
38
+ // the customType every reader filters on. `restore(entries)` rebuilds the record
39
+ // from what `ctx.sessionManager.getEntries()` returns — Pi's CustomEntry shape,
40
+ // `{ type: "custom", id, parentId, timestamp, customType, data }` (docs/
41
+ // session-format.md), which is what the extension's other readers filter on
42
+ // (`entry.type === "custom"` plus the customType) — keeping one row per path with
43
+ // the newest `at` and skipping every garbage entry instead of throwing. It
44
+ // REPLACES the record: a session boundary is a fresh session, not a merge.
45
+ //
46
+ // Pure: no clock beyond the injected `now` (a call that registers nothing reads it
47
+ // zero times), no fs, no git, no timer.
48
+
49
+ const path = require('node:path');
50
+
51
+ // The customType of the entry this record persists, and the only name a reader of
52
+ // the persisted entries may filter on.
53
+ const TOUCH_ENTRY_TYPE = 'odd-worktree.odd-touch';
54
+
55
+ // Only a write or an edit lands on a document; `read` is not work on it (S8).
56
+ const TOUCH_TOOLS = new Set(['write', 'edit']);
57
+
58
+ // The two directory names a document must sit directly under, and the suffix the
59
+ // scan accepts case-insensitively.
60
+ const ODD_ROOT = 'odd';
61
+ const TASKS_DIR = 'tasks';
62
+ const MD_SUFFIX = '.md';
63
+
64
+ // The tool name, accepting the spellings the extension's `oddToolNameOf` accepts.
65
+ function toolNameOf(event) {
66
+ if (!event || typeof event !== 'object') return undefined;
67
+ const name = event.toolName ?? event.tool ?? event.name;
68
+ return typeof name === 'string' ? name : undefined;
69
+ }
70
+
71
+ // The targets, accepting the two spellings the extension's `oddTouchedPaths`
72
+ // accepts one level up (the args-object traversal stays in the extension).
73
+ function targetsOf(event) {
74
+ const out = [];
75
+ if (!event || typeof event !== 'object') return out;
76
+ const push = (value) => {
77
+ if (typeof value === 'string' && value.length > 0) out.push(value);
78
+ };
79
+ const target = event.paths ?? event.path;
80
+ if (Array.isArray(target)) target.forEach(push);
81
+ else push(target);
82
+ return out;
83
+ }
84
+
85
+ // The absolute, normalized path of an `odd/tasks/*.md` document, or null. Lexical
86
+ // on purpose: the worktree's own `odd/` may be a symlink to the principal's, and
87
+ // the document behind either spelling carries the same segments, so this costs no
88
+ // file read.
89
+ function documentPathOf(raw, cwd) {
90
+ if (typeof raw !== 'string' || raw.length === 0) return null;
91
+ if (!raw.toLowerCase().endsWith(MD_SUFFIX)) return null;
92
+ let absolute;
93
+ try {
94
+ if (!path.isAbsolute(raw)) {
95
+ if (typeof cwd !== 'string' || cwd.length === 0) return null;
96
+ absolute = path.resolve(cwd, raw);
97
+ } else {
98
+ absolute = path.resolve(raw);
99
+ }
100
+ } catch {
101
+ return null;
102
+ }
103
+ const file = path.basename(absolute);
104
+ // A dotfile is not a document: the scan skips it, so a touch of one is no touch.
105
+ if (file.startsWith('.')) return null;
106
+ const tasks = path.basename(path.dirname(absolute));
107
+ const odd = path.basename(path.dirname(path.dirname(absolute)));
108
+ if (tasks !== TASKS_DIR || odd !== ODD_ROOT) return null;
109
+ return absolute;
110
+ }
111
+
112
+ // The ODD's name, derived exactly like the scan's: the file's own name without the
113
+ // Markdown suffix.
114
+ function oddNameOf(absolute) {
115
+ return path.basename(absolute).replace(/\.md$/i, '');
116
+ }
117
+
118
+ /**
119
+ * The session's record of touched ODD documents.
120
+ *
121
+ * `opts.now` is the clock (defaults to `Date.now`); every other seam is none, so
122
+ * this is a pure object with no I/O of any kind.
123
+ */
124
+ function createOddSession(opts) {
125
+ const options = opts !== null && typeof opts === 'object' ? opts : {};
126
+ const now = typeof options.now === 'function' ? options.now : Date.now;
127
+
128
+ // The record: `absolute path -> { path, name, at }` plus the MRU order, so
129
+ // "most recently touched first" is the array this module maintains and never a
130
+ // sort a caller could disagree with.
131
+ const rows = new Map();
132
+ const order = [];
133
+
134
+ function register(absolute, at) {
135
+ const seen = order.indexOf(absolute);
136
+ if (seen !== -1) order.splice(seen, 1);
137
+ order.unshift(absolute);
138
+ rows.set(absolute, { path: absolute, name: oddNameOf(absolute), at });
139
+ }
140
+
141
+ /** Record one tool call. `true` only when it registered an ODD. */
142
+ function note(event) {
143
+ if (!event || typeof event !== 'object') return false;
144
+ // S8: a call that failed wrote nothing, so it touched nothing.
145
+ if (event.isError === true) return false;
146
+ const toolName = toolNameOf(event);
147
+ if (typeof toolName !== 'string' || !TOUCH_TOOLS.has(toolName)) return false;
148
+ const cwd = typeof event.cwd === 'string' && event.cwd.length > 0 ? event.cwd : undefined;
149
+ const targets = [];
150
+ for (const raw of targetsOf(event)) {
151
+ const absolute = documentPathOf(raw, cwd);
152
+ if (absolute !== null) targets.push(absolute);
153
+ }
154
+ if (targets.length === 0) return false;
155
+ // ONE timestamp for the whole call, so two documents of the same call can never
156
+ // reorder each other by clock jitter.
157
+ const stamp = Number(now());
158
+ const at = Number.isFinite(stamp) ? stamp : 0;
159
+ for (const absolute of targets) register(absolute, at);
160
+ return true;
161
+ }
162
+
163
+ /** Rebuild from persisted entries. Returns how many the record now holds. */
164
+ function restore(entries) {
165
+ rows.clear();
166
+ order.length = 0;
167
+ if (!Array.isArray(entries)) return 0;
168
+ const found = [];
169
+ for (const entry of entries) {
170
+ if (!entry || typeof entry !== 'object') continue;
171
+ // The CustomEntry shape, exactly as the extension's other readers filter it.
172
+ if (entry.type !== 'custom') continue;
173
+ if (entry.customType !== TOUCH_ENTRY_TYPE) continue;
174
+ const data = entry.data;
175
+ if (!data || typeof data !== 'object') continue;
176
+ if (typeof data.path !== 'string' || data.path.length === 0) continue;
177
+ const at = Number(data.at);
178
+ if (!Number.isFinite(at)) continue;
179
+ found.push({ path: data.path, at });
180
+ }
181
+ // Newest first, and on an equal `at` the LATER entry wins: entries arrive in
182
+ // append order, so the later one is the later touch. Applied oldest-first so
183
+ // the MRU list ends up with the newest document at the front.
184
+ const keyed = found.map((row, index) => ({ row, index }));
185
+ keyed.sort((left, right) => right.row.at - left.row.at || right.index - left.index);
186
+ for (let index = keyed.length - 1; index >= 0; index -= 1) {
187
+ register(keyed[index].row.path, keyed[index].row.at);
188
+ }
189
+ return rows.size;
190
+ }
191
+
192
+ /** The touched documents, most recently touched first, one per absolute path. */
193
+ function touched() {
194
+ const out = [];
195
+ for (const absolute of order) {
196
+ const row = rows.get(absolute);
197
+ if (row !== undefined) out.push({ path: row.path, name: row.name, at: row.at });
198
+ }
199
+ return out;
200
+ }
201
+
202
+ /** Whether this exact absolute path is in the record. */
203
+ function has(absolute) {
204
+ return typeof absolute === 'string' && rows.has(absolute);
205
+ }
206
+
207
+ /** The persisted entry body for one touch: the ONE shape a reader filters on. */
208
+ function entryOf(touch) {
209
+ const source = touch !== null && typeof touch === 'object' ? touch : {};
210
+ const at = Number(source.at);
211
+ return {
212
+ customType: TOUCH_ENTRY_TYPE,
213
+ data: {
214
+ path: typeof source.path === 'string' ? source.path : '',
215
+ at: Number.isFinite(at) ? at : 0,
216
+ },
217
+ };
218
+ }
219
+
220
+ function clear() {
221
+ rows.clear();
222
+ order.length = 0;
223
+ }
224
+
225
+ return { note, restore, touched, has, entryOf, clear };
226
+ }
227
+
228
+ module.exports = {
229
+ TOUCH_ENTRY_TYPE,
230
+ createOddSession,
231
+ };