pi-odd-worktree 3.12.2 → 3.12.4

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.
@@ -16,8 +16,20 @@
16
16
  // directory. `read` never registers, and neither does any other tool; a `.md`
17
17
  // outside `odd/tasks`, a document nested deeper, a dotfile and a non-Markdown file
18
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.
19
+ // the parent's record: the PARENT's own history is what carries them
20
+ // (`associatedFromHistory`, below), not this record.
21
+ //
22
+ // `associatedFromHistory(entries)` is the SECOND reader, and the source of truth
23
+ // for scope (odd-rail-session-scope S2-S4): given the ACTIVE branch's entries
24
+ // (`ctx.sessionManager.getBranch()` — never `getEntries()`, whose abandoned
25
+ // branches are alternative histories), it answers the NAMES of the ODD documents
26
+ // the session is associated with. An old session written before this record
27
+ // existed, and a resumed one, are covered by it because it reads the transcript
28
+ // itself: a successful `write`/`edit` toolCall on `odd/tasks/<name>.md`, the
29
+ // persisted touch entries, a `gentle-agents.result` report listing the path under
30
+ // `files_changed:`, and the `Spec: odd/tasks/<name>.md` line of a successful
31
+ // `subagent_run`/`subagent_continue`. Name-keyed, lexical like the record, and
32
+ // total: every malformed entry is skipped instead of thrown on.
21
33
  //
22
34
  // The event arrives normalized by the extension's own readers (`oddToolNameOf`,
23
35
  // `oddTouchedPaths`, `oddEventCwd` in extensions/odd-worktree-tools.ts), so there
@@ -52,6 +64,12 @@ const path = require('node:path');
52
64
  // the persisted entries may filter on.
53
65
  const TOUCH_ENTRY_TYPE = 'odd-worktree.odd-touch';
54
66
 
67
+ // S4: the parent's own evidence of a subagent's work. The finished report is a
68
+ // `custom_message` under this customType, and its `files_changed:` block lists the
69
+ // paths the worker changed; the tool that started it carries the ODD in its task.
70
+ const AGENTS_RESULT_TYPE = 'gentle-agents.result';
71
+ const SUBAGENT_TOOLS = new Set(['subagent_run', 'subagent_continue']);
72
+
55
73
  // Only a write or an edit lands on a document; `read` is not work on it (S8).
56
74
  const TOUCH_TOOLS = new Set(['write', 'edit']);
57
75
 
@@ -61,6 +79,12 @@ const ODD_ROOT = 'odd';
61
79
  const TASKS_DIR = 'tasks';
62
80
  const MD_SUFFIX = '.md';
63
81
 
82
+ // What prose uses to QUOTE an example document name (`<existing>`, `<name>`, `…`)
83
+ // and a real directory entry cannot mean: a name carrying angle brackets or an
84
+ // ellipsis is a placeholder. Every other character a filesystem holds — a space
85
+ // included — is a legitimate document name.
86
+ const PLACEHOLDER_PATTERN = /[<>\u2026]/;
87
+
64
88
  // The tool name, accepting the spellings the extension's `oddToolNameOf` accepts.
65
89
  function toolNameOf(event) {
66
90
  if (!event || typeof event !== 'object') return undefined;
@@ -115,6 +139,190 @@ function oddNameOf(absolute) {
115
139
  return path.basename(absolute).replace(/\.md$/i, '');
116
140
  }
117
141
 
142
+ // A transcript path's ODD name, or null. The same lexical rule as
143
+ // `documentPathOf`, minus the clock and the resolution: a branch entry carries no
144
+ // cwd, so a RELATIVE `odd/tasks/<name>.md` is read as typed and a path that climbs
145
+ // (`..`) is refused before anything is normalized. A dotfile is not a document and
146
+ // neither is a `.md` outside `odd/tasks` or one nested deeper.
147
+ function historyNameOf(raw) {
148
+ if (typeof raw !== 'string' || raw.length === 0) return null;
149
+ if (!raw.toLowerCase().endsWith(MD_SUFFIX)) return null;
150
+ if (raw.split(/[\\/]/).includes('..')) return null;
151
+ const file = path.basename(raw);
152
+ if (file.startsWith('.')) return null;
153
+ // A name, not a placeholder: prose that QUOTES an example document
154
+ // (`odd/tasks/<existing>.md`) reaches a transcript as an ordinary path, and
155
+ // electing it would invent an ODD that cannot exist.
156
+ if (PLACEHOLDER_PATTERN.test(oddNameOf(file))) return null;
157
+ if (path.basename(path.dirname(raw)) !== TASKS_DIR) return null;
158
+ if (path.basename(path.dirname(path.dirname(raw))) !== ODD_ROOT) return null;
159
+ return oddNameOf(file);
160
+ }
161
+
162
+ // The text a custom message carries, as one string: Pi stores it as a string or as
163
+ // an array of content blocks (docs/message-types.md), and anything else is no text.
164
+ function textOfContent(content) {
165
+ if (typeof content === 'string') return content;
166
+ if (!Array.isArray(content)) return '';
167
+ const parts = [];
168
+ for (const block of content) {
169
+ if (!block || typeof block !== 'object') continue;
170
+ if (block.type !== 'text' || typeof block.text !== 'string') continue;
171
+ parts.push(block.text);
172
+ }
173
+ return parts.join('\n');
174
+ }
175
+
176
+ // The ODD names one line of a report names, added to `out`. A `files_changed:` item
177
+ // is a path, optionally followed by `: <what changed>`, and several paths may share
178
+ // one line separated by commas. Anything that is not an `odd/tasks/*.md` document
179
+ // contributes nothing.
180
+ function addNamesInLine(text, out) {
181
+ if (typeof text !== 'string' || text.length === 0) return;
182
+ for (const raw of text.split(',')) {
183
+ const trimmed = raw.trim();
184
+ if (trimmed.length === 0) continue;
185
+ const colon = trimmed.indexOf(':');
186
+ const head = colon === -1 ? trimmed : trimmed.slice(0, colon).trim();
187
+ for (const candidate of [head, ...head.split(/\s+/)]) {
188
+ const name = historyNameOf(candidate.replace(/:+$/, ''));
189
+ if (name !== null) out.add(name);
190
+ }
191
+ }
192
+ }
193
+
194
+ // The paths under a `files_changed:` block, added to `out`. The block is the header
195
+ // line's own remainder plus the list items that follow it; the first line that is
196
+ // not a list item ends it, so the next section of the report is never read.
197
+ function addFilesChanged(text, out) {
198
+ if (typeof text !== 'string' || text.length === 0) return;
199
+ let inBlock = false;
200
+ for (const line of text.split(/\r?\n/)) {
201
+ const header = /^\s*files_changed\s*:\s*(.*)$/.exec(line);
202
+ if (header !== null) {
203
+ inBlock = true;
204
+ addNamesInLine(header[1], out);
205
+ continue;
206
+ }
207
+ if (!inBlock) continue;
208
+ const item = /^\s*[-*]\s+(.*)$/.exec(line);
209
+ if (item === null) {
210
+ inBlock = false;
211
+ continue;
212
+ }
213
+ addNamesInLine(item[1], out);
214
+ }
215
+ }
216
+
217
+ // Every `Spec: odd/tasks/<name>.md` a subagent task names, added to `out`.
218
+ function addSpecNames(text, out) {
219
+ if (typeof text !== 'string' || text.length === 0) return;
220
+ const pattern = /Spec:[ \t]*([^\s,]+)/g;
221
+ let match = pattern.exec(text);
222
+ while (match !== null) {
223
+ const name = historyNameOf(match[1].replace(/:+$/, ''));
224
+ if (name !== null) out.add(name);
225
+ match = pattern.exec(text);
226
+ }
227
+ }
228
+
229
+ // The toolCalls one transcript entry makes, in order. A message entry carries them
230
+ // under `message`; the bare message shape is accepted too, so a caller that hands
231
+ // over `getBranch()` or a normalized message both answer. Anything else is empty.
232
+ function toolCallsOf(entry, out) {
233
+ const message = entry.message !== undefined && entry.message !== null ? entry.message : entry;
234
+ if (!message || typeof message !== 'object') return;
235
+ if (message.role !== 'assistant') return;
236
+ if (!Array.isArray(message.content)) return;
237
+ for (const block of message.content) {
238
+ if (!block || typeof block !== 'object') continue;
239
+ if (block.type !== 'toolCall') continue;
240
+ const id = typeof block.id === 'string' ? block.id : undefined;
241
+ const name = typeof block.name === 'string' ? block.name : undefined;
242
+ if (id === undefined || name === undefined) continue;
243
+ out.push({ id, name, args: block.arguments && typeof block.arguments === 'object' ? block.arguments : null });
244
+ }
245
+ }
246
+
247
+ // One toolResult's verdict, or null. `isError === true` is the failed call; a result
248
+ // without the flag is a success, and a result with no toolCallId vouches for nothing.
249
+ function resultOf(entry) {
250
+ const message = entry.message !== undefined && entry.message !== null ? entry.message : entry;
251
+ if (!message || typeof message !== 'object') return null;
252
+ if (message.role !== 'toolResult') return null;
253
+ const toolCallId = typeof message.toolCallId === 'string' ? message.toolCallId : undefined;
254
+ if (toolCallId === undefined || toolCallId.length === 0) return null;
255
+ return { toolCallId, failed: message.isError === true };
256
+ }
257
+
258
+ /**
259
+ * The ODD NAMES the session's ACTIVE branch is associated with (S3, S4).
260
+ *
261
+ * `entries` is what `ctx.sessionManager.getBranch()` returns, so an abandoned
262
+ * branch's work is never in it. Total: a non-array answer is an empty association
263
+ * and a malformed entry is skipped, never thrown on.
264
+ *
265
+ * @param {Array<object>} entries
266
+ * @returns {Set<string>}
267
+ */
268
+ function associatedFromHistory(entries) {
269
+ const out = new Set();
270
+ if (!Array.isArray(entries)) return out;
271
+ const calls = [];
272
+ // The verdict per toolCallId: the LAST result of an id decides, so a retried call
273
+ // is judged by what finally happened.
274
+ const results = new Map();
275
+ for (const entry of entries) {
276
+ if (!entry || typeof entry !== 'object') continue;
277
+ try {
278
+ // S3: the persisted touch entries, written by the record above.
279
+ if (entry.type === 'custom') {
280
+ if (entry.customType !== TOUCH_ENTRY_TYPE) continue;
281
+ const data = entry.data;
282
+ if (!data || typeof data !== 'object') continue;
283
+ const name = historyNameOf(data.path);
284
+ if (name !== null) out.add(name);
285
+ continue;
286
+ }
287
+ // S4: a subagent's own report, persisted in the PARENT's session.
288
+ if (entry.type === 'custom_message') {
289
+ if (entry.customType !== AGENTS_RESULT_TYPE) continue;
290
+ addFilesChanged(textOfContent(entry.content), out);
291
+ continue;
292
+ }
293
+ // S3/S4: the calls, whose results may land anywhere in the branch.
294
+ if (entry.type !== 'message') continue;
295
+ toolCallsOf(entry, calls);
296
+ const verdict = resultOf(entry);
297
+ if (verdict !== null) results.set(verdict.toolCallId, verdict.failed);
298
+ } catch {
299
+ // One garbage entry costs only itself.
300
+ }
301
+ }
302
+ for (const call of calls) {
303
+ try {
304
+ if (results.get(call.id) !== false) continue;
305
+ if (TOUCH_TOOLS.has(call.name)) {
306
+ if (call.args === null) continue;
307
+ const target = call.args.paths ?? call.args.path;
308
+ const targets = Array.isArray(target) ? target : [target];
309
+ for (const raw of targets) {
310
+ const name = historyNameOf(raw);
311
+ if (name !== null) out.add(name);
312
+ }
313
+ continue;
314
+ }
315
+ if (SUBAGENT_TOOLS.has(call.name)) {
316
+ if (call.args === null) continue;
317
+ addSpecNames(call.args.task, out);
318
+ }
319
+ } catch {
320
+ // A malformed call costs only itself.
321
+ }
322
+ }
323
+ return out;
324
+ }
325
+
118
326
  /**
119
327
  * The session's record of touched ODD documents.
120
328
  *
@@ -226,6 +434,8 @@ function createOddSession(opts) {
226
434
  }
227
435
 
228
436
  module.exports = {
437
+ PLACEHOLDER_PATTERN,
229
438
  TOUCH_ENTRY_TYPE,
230
439
  createOddSession,
440
+ associatedFromHistory,
231
441
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.12.2",
3
+ "version": "3.12.4",
4
4
  "description": "Pi package for odd-worktree: the Git worktree tools a Pi session uses (create and list the checkouts the agent works in), the /warp worktree panel, the /odd ODD viewer, and the /issues GitHub issue reader. Needs only Pi and git: no companion app, no extra service.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -87,16 +87,16 @@ test('neither sentence ends in ", if it applies" any more (S3)', async () => {
87
87
  }
88
88
  });
89
89
 
90
- test('an explore agent gets the native wording, every other child the MCP one', async () => {
90
+ test('a child gets no reminder: its own rule text already says it and it lives a message or two', async () => {
91
91
  const child = (agent, tools) => setup({
92
92
  env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: tools },
93
93
  argv: ['node', `/tmp/gentle-pi-subagent-${agent}-a1b2c3/bin.js`],
94
94
  tools: [],
95
95
  });
96
96
  const explorer = child('gentle-ai-explore', 'read,bash,codegraph');
97
- assert.equal(await explorer.guard.onToolResult(bash('cat src/a.ts'), explorer.ctx), NATIVE);
97
+ assert.equal(await explorer.guard.onToolResult(bash('cat src/a.ts'), explorer.ctx), undefined);
98
98
  const worker = child('gentle-ai-worker', 'read,bash,mcp__codegraph__codegraph_explore');
99
- assert.equal(await worker.guard.onToolResult(bash('cat src/a.ts'), worker.ctx), MCP);
99
+ assert.equal(await worker.guard.onToolResult(bash('cat src/a.ts'), worker.ctx), undefined);
100
100
  });
101
101
 
102
102
  // ---- who gets which guard (S1, S2) ----
@@ -36,7 +36,12 @@ describe('the seven texts on disk', () => {
36
36
  for (const binary of ['fd', 'find', 'rg', 'grep', 'read', 'cat']) {
37
37
  assert.ok(text.includes(`\`${binary}\``), `${variant} names ${binary}`);
38
38
  }
39
- assert.match(text, /other tools stay|may skip it/, `${variant} leaves the other tools available`);
39
+ // S1: the primary and the generic texts carry no permission sentence; the five role texts keep theirs.
40
+ if (variant === 'orchestrator' || variant === 'generic') {
41
+ assert.doesNotMatch(text, /other tools stay|rather than a lookup|answer is a map|not proof/i, `${variant} has no escape hatch`);
42
+ } else {
43
+ assert.match(text, /other tools stay|may skip it/, `${variant} leaves the other tools available`);
44
+ }
40
45
  }
41
46
  });
42
47
 
@@ -81,9 +86,10 @@ describe('the orchestrator and explore texts stay inside their role', () => {
81
86
 
82
87
  test('the orchestrator calls the graph first for a where/who/how/what-reaches question, with one exemption and one literal call', () => {
83
88
  const text = prose('orchestrator');
84
- assert.match(text, /to answer where code lives, who calls it, how it works, or what a change reaches, call CodeGraph first/, text);
89
+ assert.match(text, /to answer where code lives, who calls it, how it works, or what a change reaches, your first call is CodeGraph/, text);
85
90
  assert.match(text, /`codegraph` with `operation: "explore"` and `query: "<symbols or the question>"`/, 'the literal call');
86
- assert.match(text, /Skip it only for an exact string or a file path the user gave you/, 'one exemption');
91
+ assert.match(text, /The one exemption is an exact string or a file path the user gave you/, 'one exemption');
92
+ assert.equal((text.match(/exemption|skip/gi) || []).length, 1, 'and only one');
87
93
  assert.match(text, /what scope, size and any handoff depend on/, 'the sizing use is kept');
88
94
  });
89
95
 
@@ -338,6 +338,16 @@ test('a code read in the session checkout gets one reminder part appended, and t
338
338
  assert.deepEqual(patch.structuredContent, { output: 'source' }, 'the structured content of the result is kept');
339
339
  });
340
340
 
341
+ test('a child is not reminded', async () => {
342
+ const { run } = setup({
343
+ toplevel: checkoutMap(),
344
+ env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,grep,mcp__codegraph__codegraph_explore' },
345
+ argv: ['node', '/tmp/gentle-pi-subagent-gentle-ai-worker-ab12cd/instructions.md'],
346
+ });
347
+ await run('before_agent_start', { systemPromptOptions: { selectedTools: [] } });
348
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined);
349
+ });
350
+
341
351
  test('ODD_WORKTREE_PROMPT=0 silences the reminders too, because they cite the rule that variable suppresses', async () => {
342
352
  const { run } = setup({ toplevel: checkoutMap(), env: { ODD_WORKTREE_PROMPT: '0' } });
343
353
  await run('before_agent_start', SESSION_TOOLS);
@@ -400,14 +410,14 @@ test('a new request re-arms the one reminder of the checkout (S3, S7)', async ()
400
410
  assert.equal(next.content[1].text, NATIVE_REMINDER, 'the first search of the next request hears it again');
401
411
  });
402
412
 
403
- test('a worker child is told to call the MCP tool, and a review agent is told nothing', async () => {
413
+ test('a worker child and a review agent are told nothing', async () => {
404
414
  const worker = setup({
405
415
  env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,bash,mcp__codegraph__codegraph_explore' },
406
416
  argv: ['node', '/tmp/gentle-pi-subagent-gentle-ai-worker-a1b2c3/bin.js'],
407
417
  toplevel: checkoutMap(),
408
418
  });
409
419
  const workerPatch = await worker.run('tool_result', readEvent('src/a.ts'));
410
- assert.equal(workerPatch.content[1].text, MCP_REMINDER);
420
+ assert.equal(workerPatch, undefined);
411
421
 
412
422
  const reviewer = setup({
413
423
  env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,bash,mcp__codegraph__codegraph_explore' },
@@ -33,6 +33,11 @@ const WT_B = path.resolve('/odd-rail-model/checkout-worktrees/wt-b');
33
33
  // WHICH copy was elected reads as one comparison.
34
34
  const picked = (rows) => rows.map((row) => [row.name, row.checkoutName, row.docPath]);
35
35
 
36
+ // T2 (odd-rail-session-scope S2): the association is the rail's FILTER, so every
37
+ // call names one. `all(...)` is "this session is associated with all of them",
38
+ // which is what the pre-association cases below mean by "draw the list".
39
+ const all = (...names) => new Set(names);
40
+
36
41
  function doc(name, root, mtimeMs) {
37
42
  return { name, docPath: path.join(root, 'odd', 'tasks', `${name}.md`), mtimeMs };
38
43
  }
@@ -57,7 +62,7 @@ describe('one row per ODD name (S12)', () => {
57
62
  mainGroup(['alpha', 'beta'], { alpha: 1000, beta: 2000 }),
58
63
  worktreeGroup('wt-a', WT_DIR, [doc('alpha', WT_DIR, 3000)]),
59
64
  ];
60
- const rows = railRows({ groups, touched: [] });
65
+ const rows = railRows({ groups, touched: [], associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) });
61
66
  assert.deepEqual(
62
67
  picked(rows),
63
68
  [
@@ -76,7 +81,7 @@ describe('one row per ODD name (S12)', () => {
76
81
  mainGroup(['alpha'], { alpha: 5000 }),
77
82
  worktreeGroup('wt-a', WT_DIR, [doc('alpha', WT_DIR, 5000)]),
78
83
  ];
79
- assert.deepEqual(picked(railRows({ groups, touched: [] })), [
84
+ assert.deepEqual(picked(railRows({ groups, touched: [], associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) })), [
80
85
  ['alpha', MAIN, path.join('/odd-rail-model/checkout/odd/tasks', 'alpha.md')],
81
86
  ]);
82
87
  });
@@ -87,7 +92,7 @@ describe('one row per ODD name (S12)', () => {
87
92
  worktreeGroup('wt-a', WT_DIR, [doc('alpha', WT_DIR, 7000)]),
88
93
  worktreeGroup('wt-b', WT_B, [doc('alpha', WT_B, 7000)]),
89
94
  ];
90
- assert.deepEqual(picked(railRows({ groups, touched: [] })), [
95
+ assert.deepEqual(picked(railRows({ groups, touched: [], associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) })), [
91
96
  ['alpha', 'wt-a', path.join(WT_DIR, 'odd', 'tasks', 'alpha.md')],
92
97
  ]);
93
98
  });
@@ -97,7 +102,7 @@ describe('one row per ODD name (S12)', () => {
97
102
  mainGroup(['alpha'], { alpha: 10 }),
98
103
  worktreeGroup('wt-a', WT_DIR, [doc('alpha', WT_DIR, 20)]),
99
104
  ];
100
- assert.deepEqual(picked(railRows({ groups, touched: [] })), [
105
+ assert.deepEqual(picked(railRows({ groups, touched: [], associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) })), [
101
106
  ['alpha', 'wt-a', path.join(WT_DIR, 'odd', 'tasks', 'alpha.md')],
102
107
  ]);
103
108
  });
@@ -107,7 +112,7 @@ describe('one row per ODD name (S12)', () => {
107
112
  mainGroup(['alpha', 'beta'], { alpha: 200, beta: 100 }),
108
113
  worktreeGroup('wt-a', WT_DIR, []),
109
114
  ];
110
- const rows = railRows({ groups, touched: [] });
115
+ const rows = railRows({ groups, touched: [], associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) });
111
116
  assert.deepEqual(rows.map((row) => [row.name, row.checkoutName]), [['alpha', MAIN], ['beta', MAIN]],
112
117
  'main only, and no row for the empty worktree');
113
118
  });
@@ -120,20 +125,20 @@ describe('order: attribution first, then recency, then name (S9)', () => {
120
125
  { path: path.join(DOC_DIR, 'gamma.md'), name: 'gamma', at: 20 },
121
126
  { path: path.join(DOC_DIR, 'beta.md'), name: 'beta', at: 10 },
122
127
  ];
123
- assert.deepEqual(railRows({ groups, touched }).map((row) => row.name), ['gamma', 'beta', 'alpha'],
128
+ assert.deepEqual(railRows({ groups, touched, associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) }).map((row) => row.name), ['gamma', 'beta', 'alpha'],
124
129
  'the MOST recent touch is first, then the older one, then plain recency');
125
130
  });
126
131
 
127
132
  test('a touched name no group lists produces no row, and never a duplicate (S9)', () => {
128
133
  const groups = [mainGroup(['alpha'], { alpha: 1 })];
129
134
  const touched = [{ path: path.join(DOC_DIR, 'ghost.md'), name: 'ghost', at: 99 }];
130
- assert.deepEqual(railRows({ groups, touched }).map((row) => row.name), ['alpha'],
135
+ assert.deepEqual(railRows({ groups, touched, associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) }).map((row) => row.name), ['alpha'],
131
136
  'attribution only orders: it adds nothing and removes nothing');
132
137
  });
133
138
 
134
139
  test('equal mtimes order by name in code units, never locale', () => {
135
140
  const groups = [mainGroup(['a', 'B', 'b'], { a: 1, B: 1, b: 1 })];
136
- assert.deepEqual(railRows({ groups, touched: [] }).map((row) => row.name), ['B', 'a', 'b'],
141
+ assert.deepEqual(railRows({ groups, touched: [], associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) }).map((row) => row.name), ['B', 'a', 'b'],
137
142
  'code units put B (66) before a (97); localeCompare would not');
138
143
  });
139
144
 
@@ -143,7 +148,7 @@ describe('order: attribution first, then recency, then name (S9)', () => {
143
148
  { path: path.join(DOC_DIR, 'beta.md'), name: 'beta', at: 50 },
144
149
  { path: path.join(DOC_DIR, 'alpha.md'), name: 'alpha', at: 50 },
145
150
  ];
146
- assert.deepEqual(railRows({ groups, touched }).map((row) => row.name), ['beta', 'alpha']);
151
+ assert.deepEqual(railRows({ groups, touched, associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) }).map((row) => row.name), ['beta', 'alpha']);
147
152
  });
148
153
  });
149
154
 
@@ -151,14 +156,15 @@ describe('malformed input is skipped, never thrown on', () => {
151
156
  test('garbage groups, documents and touches answer an empty or partial list', () => {
152
157
  assert.deepEqual(railRows({}), []);
153
158
  assert.deepEqual(railRows(), []);
154
- assert.deepEqual(railRows({ groups: 'nope', touched: 'nope' }), []);
155
- assert.deepEqual(railRows({ groups: [null, 7, {}, { docs: 'nope' }], touched: [null, 5] }), []);
159
+ assert.deepEqual(railRows({ groups: 'nope', touched: 'nope', associated: all('alpha') }), []);
160
+ assert.deepEqual(railRows({ groups: [null, 7, {}, { docs: 'nope' }], touched: [null, 5], associated: all('alpha') }), []);
156
161
  const rows = railRows({
157
162
  groups: [
158
163
  { docs: [{ name: 'alpha', docPath: '/x/alpha.md', mtimeMs: 4 }, null, { name: 5 }, { docPath: '/y/z.md' }] },
159
164
  { docs: [{ name: 'beta', docPath: '/x/beta.md', mtimeMs: 'nonsense' }] },
160
165
  ],
161
166
  touched: [{ name: 'alpha' }, null, { at: 3 }, { name: '', at: 1 }],
167
+ associated: all('alpha', 'beta'),
162
168
  });
163
169
  assert.deepEqual(rows.map((row) => [row.name, row.mtimeMs]), [['alpha', 4], ['beta', 0]],
164
170
  'a document with no usable time sorts oldest and reports 0; a touch with no instant is ignored');
@@ -169,7 +175,7 @@ describe('malformed input is skipped, never thrown on', () => {
169
175
  const touched = [{ path: path.join(DOC_DIR, 'beta.md'), name: 'beta', at: 9 }];
170
176
  const groupsBefore = JSON.stringify(groups);
171
177
  const touchedBefore = JSON.stringify(touched);
172
- railRows({ groups, touched });
178
+ railRows({ groups, touched, associated: all(...groups.flatMap((g) => (g.docs || []).map((d) => d.name))) });
173
179
  assert.equal(JSON.stringify(groups), groupsBefore);
174
180
  assert.equal(JSON.stringify(touched), touchedBefore);
175
181
  });
@@ -182,3 +188,61 @@ describe('malformed input is skipped, never thrown on', () => {
182
188
  assert.deepEqual(Object.keys(require('../lib/odd-rail-model.js')), ['railRows']);
183
189
  });
184
190
  });
191
+
192
+ // T2 (odd-rail-session-scope S2): the association is the FILTER. The rail lists
193
+ // only the ODDs the session is associated with — never "everything on disk" — and
194
+ // the live touch record is unioned in, so a document this session just wrote shows
195
+ // even before the history read sees it.
196
+ describe('only the session’s association draws (S2)', () => {
197
+ test('the associated names are drawn, and every other document on disk is not', () => {
198
+ const groups = [mainGroup(['alpha', 'beta', 'gamma'], { alpha: 900, beta: 800, gamma: 700 })];
199
+ assert.deepEqual(
200
+ railRows({ groups, touched: [], associated: all('beta') }).map((row) => row.name),
201
+ ['beta'],
202
+ 'a fresh session associated with one ODD draws one row, not the four the disk holds',
203
+ );
204
+ assert.deepEqual(
205
+ railRows({ groups, touched: [], associated: all('gamma', 'alpha') }).map((row) => row.name),
206
+ ['alpha', 'gamma'],
207
+ 'the election and the recency order are unchanged inside the association',
208
+ );
209
+ });
210
+
211
+ test('an empty association draws nothing at all', () => {
212
+ const groups = [mainGroup(['alpha', 'beta'], { alpha: 2, beta: 1 })];
213
+ assert.deepEqual(railRows({ groups, touched: [], associated: new Set() }), []);
214
+ assert.deepEqual(railRows({ groups, associated: new Set() }), []);
215
+ });
216
+
217
+ test('a live touch is unioned in, and a touched name with no document stays hidden', () => {
218
+ const groups = [mainGroup(['alpha', 'beta', 'gamma'], { alpha: 900, beta: 800, gamma: 700 })];
219
+ const touched = [
220
+ { path: path.join(DOC_DIR, 'gamma.md'), name: 'gamma', at: 30 },
221
+ { path: path.join(DOC_DIR, 'ghost.md'), name: 'ghost', at: 20 },
222
+ ];
223
+ assert.deepEqual(
224
+ railRows({ groups, touched, associated: all('beta') }).map((row) => row.name),
225
+ ['gamma', 'beta'],
226
+ 'the touched document draws (first, by its touch) although history does not name it yet',
227
+ );
228
+ assert.equal(
229
+ railRows({ groups, touched, associated: all('beta') }).some((row) => row.name === 'ghost'),
230
+ false,
231
+ 'a touched name no group lists produces nothing, exactly as before',
232
+ );
233
+ // A touch never ADDS a name outside the election to the association: it is one
234
+ // of the names already elected by the grouped model, not a row of its own.
235
+ assert.equal(railRows({ groups, touched, associated: all() }).length, 1);
236
+ });
237
+
238
+ test('a garbage association draws nothing instead of throwing', () => {
239
+ const groups = [mainGroup(['alpha'], { alpha: 1 })];
240
+ for (const associated of [undefined, null, 'alpha', 42, {}, [null, 5]]) {
241
+ assert.deepEqual(railRows({ groups, touched: [], associated }), [], String(associated));
242
+ }
243
+ // The two accepted shapes, and a malformed member inside one of them.
244
+ assert.deepEqual(railRows({ groups, touched: [], associated: new Set(['alpha']) }).map((row) => row.name), ['alpha']);
245
+ assert.deepEqual(railRows({ groups, touched: [], associated: ['alpha', null, 7] }).map((row) => row.name), ['alpha']);
246
+ assert.deepEqual(railRows({ groups, touched: [], associated: new Set([null, '']) }), []);
247
+ });
248
+ });
@@ -522,3 +522,43 @@ test('the refresh timer is unref\'d, reads once per floor, and stops itself outs
522
522
  disposed.dispose();
523
523
  assert.equal(disposeTimers.active().length, 0, 'dispose clears the floor timer');
524
524
  });
525
+
526
+ // ---------------------------------------------------------------------------
527
+ // S1 (odd-rail-session-scope): an empty body says so.
528
+ // ---------------------------------------------------------------------------
529
+
530
+ test('S1: a ready list with no associated ODD draws ONE dim `no ODD associated` row', async () => {
531
+ const opened = [];
532
+ const sched = manualSchedule();
533
+ const handle = createOddRailSection({
534
+ load: async () => [],
535
+ open: (target) => { opened.push(target); },
536
+ schedule: sched.schedule,
537
+ });
538
+ await handle.refresh();
539
+
540
+ const rows = handle.section.lines({});
541
+ // Exactly the `EMPTY_ROW` of lib/issues-section.js: one dim line, a copy per
542
+ // frame, and no click — there is nothing behind it to open.
543
+ assert.deepEqual(rows, [{ label: 'no ODD associated', tone: 'dim' }]);
544
+ assert.equal('onClick' in rows[0], false, 'the empty line is inert, like the issues one');
545
+ assert.deepEqual(opened, [], 'drawing the empty line opens nothing');
546
+ });
547
+
548
+ test('S1: the empty line is a state, not a failure: another frame inside the TTL keeps it, and a later list replaces it', async () => {
549
+ let items = [];
550
+ const handle = createOddRailSection({
551
+ load: async () => items,
552
+ open: () => {},
553
+ schedule: () => {},
554
+ });
555
+ await handle.refresh();
556
+ assert.deepEqual(handle.section.lines({}), [{ label: 'no ODD associated', tone: 'dim' }]);
557
+ // A second frame reads the same snapshot: no read, the same one line.
558
+ assert.deepEqual(handle.section.lines({}), [{ label: 'no ODD associated', tone: 'dim' }]);
559
+
560
+ items = FOUR;
561
+ await handle.refresh();
562
+ assert.deepEqual(handle.section.lines({}).map((row) => row.label), ['alpha', 'beta', 'gamma', 'delta'],
563
+ 'a list replaces the empty line, and its rows keep their own shape');
564
+ });