@robhowley/pi-remembrancer 0.2.0 → 0.4.0

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/README.md CHANGED
@@ -6,32 +6,38 @@ Remembrancer is an agent-powered personal task manager built on Taskwarrior. It
6
6
 
7
7
  ## Install
8
8
 
9
- Requires [Taskwarrior 3](https://taskwarrior.org/download/) (`task` on your `PATH`).
9
+ Requires [Taskwarrior 3](https://taskwarrior.org/download/) (`task` on your `PATH`). If you do not already use it, install and initialize it. On macOS:
10
+
11
+ ```shell
12
+ brew install task
13
+ task
14
+ ```
15
+
16
+ Then install Remembrancer:
10
17
 
11
18
  ```shell
12
19
  pi install npm:@robhowley/pi-remembrancer
13
20
  ```
14
21
 
15
- Then run `/reload` or start a new session.
22
+ Run `/reload` in Pi or start a new session.
16
23
 
17
- ### Set up Taskwarrior
24
+ ## First review
18
25
 
19
- If you do not already use Taskwarrior, install and initialize it. On macOS:
26
+ Optionally, build your initial todo list from your recent Pi sessions:
20
27
 
21
- ```shell
22
- brew install task
23
- task
28
+ ```text
29
+ /remembrancer seed 14d
24
30
  ```
25
31
 
26
- To track what a task is waiting on, add this optional field:
32
+ This starts with the past 14 days. Use any positive whole number of days, such as `30d`.
27
33
 
28
- ```shell
29
- task config uda.waitingon.type string
30
- ```
34
+ Remembrancer checks your existing tasks and suggests additions, progress notes, and completions. Accept, edit, or dismiss the suggestions before anything is written.
35
+
36
+ Your tasks stay in Taskwarrior. Use `task list` or `task completed` any time.
31
37
 
32
- The `waitingon` field is optional. Configure it only for operations that record waiting conditions. Ordinary list, add, update, and close operations do not require it.
38
+ ## Everyday examples
33
39
 
34
- ## Try it
40
+ Explicit requests to add or change a task are applied directly after the actual record is checked. Changes inferred from your sessions need your approval.
35
41
 
36
42
  | Say this in Pi | What happens |
37
43
  | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
@@ -41,33 +47,39 @@ The `waitingon` field is optional. Configure it only for operations that record
41
47
  | “Wrap up this session.” | Suggest new tasks, progress notes, and completions from this conversation. |
42
48
  | “What changed since my last review?” | Review new activity across saved sessions and suggest changes together. |
43
49
 
50
+ The waiting-condition examples require the [optional field below](#optional-waiting-conditions).
51
+
44
52
  You can also invoke the skill directly:
45
53
 
46
54
  ```text
47
55
  /skill:remembrancer review commitments across my saved sessions
48
56
  ```
49
57
 
50
- Explicit requests to add or change a task are applied directly after the actual record is checked. Changes inferred from your sessions are suggestions: accept, edit, or dismiss them before anything is written.
58
+ ## Optional waiting conditions
51
59
 
52
- Historical review is a full review of eligible enrolled saved sessions. The review tool cannot select a historical slice or finish a partial historical checkpoint. For a narrower need, choose a full review or a current-session scope rather than silently broadening the request.
60
+ To record what a task is waiting on, add the `waitingon` field:
53
61
 
54
- Your tasks stay in Taskwarrior. Use `task list` or `task completed` any time.
62
+ ```shell
63
+ task config uda.waitingon.type string
64
+ ```
65
+
66
+ Skip this setup if you do not need waiting conditions; other task operations work without it.
55
67
 
56
68
  ## What gets reviewed
57
69
 
58
- - Only saved sessions opened or resumed with Remembrancer enabled. Resume an older session to include it in your next review.
59
- - Reviews use user and assistant messages, not tool outputs, model thinking, or images. That text is sent to the model in your reviewing session.
60
- - Forked sessions can repeat shared context. A cancelled or interrupted review can also return previously considered candidates. Reconcile branch provenance and applicable dismissals rather than treating recurrence as new authority.
61
- - Reviews happen when you ask, not in the background. Unavailable saved-session ranges remain unreviewed.
70
+ - Regular reviews cover sessions opened or resumed with Remembrancer enabled. An older session included for the first time this way can bring in its full history; use seed to set a starting point instead.
71
+ - Seed also searches Pi's configured session archive, including saved worker sessions. It does not reconstruct which sessions had Remembrancer disabled in the past.
72
+ - A shorter seed duration does not narrow existing review coverage. Repeating a seed skips unchanged text that has already been reviewed.
73
+ - Only user and assistant text is sent to the model in your reviewing session, not tool outputs, model thinking, or images.
74
+ - Reviews run only when you ask. Activity added during a review waits for the next one.
75
+ - If a session cannot be read, Remembrancer reports it and leaves it for a later review. Cancelling a review leaves review progress unsaved, but it does not undo task changes already applied.
62
76
 
63
77
  ## Settings
64
78
 
65
- Remembrancer is enabled by default. To disable extension review and enrollment, add this to the global settings file in Pi's active agent directory, normally `~/.pi/agent/settings.json`:
79
+ Remembrancer is enabled by default. To turn off saved-session reviews and stop including newly opened or resumed sessions in future reviews, add this to Pi's global settings file, normally `~/.pi/agent/settings.json`:
66
80
 
67
81
  ```json
68
82
  { "pi-remembrancer": { "disabled": true } }
69
83
  ```
70
84
 
71
- A trusted project's `.pi/settings.json` takes precedence over the global value. After changing settings, run `/reload` or start a new session. This setting disables extension review and enrollment only; it does not unload the separately discoverable skill or prevent Taskwarrior writes.
72
-
73
- Only the main user-facing session should write personal Taskwarrior changes. Delegated workers should return evidence and proposed changes to that session. This is a workflow convention, not a hard write restriction enforced by the extension or Taskwarrior. If you launch delegated workers, keep personal task changes in the main user-facing session.
85
+ A trusted project's `.pi/settings.json` takes precedence over the global value. After changing settings, run `/reload` or start a new session. The skill remains available: direct task requests can still change Taskwarrior tasks.
@@ -3,7 +3,15 @@ import { homedir } from 'node:os';
3
3
  import { dirname, isAbsolute, join } from 'node:path';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
5
 
6
- import type { Source, Tip } from './evidence.js';
6
+ import type { Checkpoint, SeedDefault, Source, Tip } from './evidence.js';
7
+
8
+ export type StoredSource = Omit<Source, 'seedSince'> & { seedSince: string | null };
9
+
10
+ export type FinishPlan = {
11
+ sources?: readonly Source[];
12
+ sourceDefaults?: readonly SeedDefault[];
13
+ checkpoints?: readonly (Tip | Checkpoint)[];
14
+ };
7
15
 
8
16
  function defaultFile(): string {
9
17
  const state = process.env['XDG_STATE_HOME'];
@@ -29,6 +37,24 @@ function openPrivate(filename: string): DatabaseSync {
29
37
  return new DatabaseSync(filename);
30
38
  }
31
39
 
40
+ function absoluteTimestamp(value: string | null | undefined): string | null {
41
+ if (value === null || value === undefined) return null;
42
+ const milliseconds = Date.parse(value);
43
+ if (!Number.isFinite(milliseconds)) throw new Error(`Invalid checkpoint timestamp: ${value}`);
44
+ return new Date(milliseconds).toISOString();
45
+ }
46
+
47
+ function tableHasColumn(db: DatabaseSync, table: string, column: string): boolean {
48
+ return (db.prepare(`PRAGMA table_info(${table})`).all() as { name?: string }[]).some(
49
+ (item) => item.name === column,
50
+ );
51
+ }
52
+
53
+ function checkpointFromTip(tip: Tip): Checkpoint {
54
+ const candidate = tip as Tip & { since?: string | null };
55
+ return { ...tip, since: candidate.since ?? null };
56
+ }
57
+
32
58
  export class CheckpointStore {
33
59
  private db: DatabaseSync;
34
60
  private filename: string;
@@ -37,16 +63,33 @@ export class CheckpointStore {
37
63
  constructor(filename = defaultFile()) {
38
64
  this.filename = filename;
39
65
  this.db = openPrivate(filename);
40
- this.db.exec(`PRAGMA busy_timeout = 5000;
41
- CREATE TABLE IF NOT EXISTS sources (
42
- session_id TEXT PRIMARY KEY,
43
- session_file TEXT NOT NULL
44
- );
45
- CREATE TABLE IF NOT EXISTS reviewed_boundaries (
46
- session_id TEXT NOT NULL REFERENCES sources(session_id),
47
- tip_id TEXT NOT NULL CHECK(tip_id <> ''),
48
- PRIMARY KEY (session_id, tip_id)
49
- )`);
66
+ try {
67
+ this.db.exec('PRAGMA busy_timeout = 5000; BEGIN IMMEDIATE;');
68
+ this.db.exec(`
69
+ CREATE TABLE IF NOT EXISTS sources (
70
+ session_id TEXT PRIMARY KEY,
71
+ session_file TEXT NOT NULL,
72
+ seed_since TEXT
73
+ );
74
+ CREATE TABLE IF NOT EXISTS reviewed_boundaries (
75
+ session_id TEXT NOT NULL REFERENCES sources(session_id),
76
+ tip_id TEXT NOT NULL CHECK(tip_id <> ''),
77
+ since TEXT,
78
+ PRIMARY KEY (session_id, tip_id)
79
+ )`);
80
+ if (!tableHasColumn(this.db, 'sources', 'seed_since'))
81
+ this.db.exec('ALTER TABLE sources ADD COLUMN seed_since TEXT');
82
+ if (!tableHasColumn(this.db, 'reviewed_boundaries', 'since'))
83
+ this.db.exec('ALTER TABLE reviewed_boundaries ADD COLUMN since TEXT');
84
+ this.db.exec('COMMIT');
85
+ } catch (error) {
86
+ try {
87
+ this.db.exec('ROLLBACK');
88
+ } finally {
89
+ this.db.close();
90
+ }
91
+ throw error;
92
+ }
50
93
  }
51
94
 
52
95
  // A separate lock file lets other Pi sessions enroll during an interactive review.
@@ -79,32 +122,101 @@ export class CheckpointStore {
79
122
  .run(sessionId, file);
80
123
  }
81
124
 
82
- sources(): Source[] {
125
+ sources(): StoredSource[] {
83
126
  return this.db
84
- .prepare(`SELECT session_id AS sessionId, session_file AS file FROM sources ORDER BY rowid`)
85
- .all() as unknown as Source[];
127
+ .prepare(
128
+ `SELECT session_id AS sessionId, session_file AS file, seed_since AS seedSince
129
+ FROM sources ORDER BY rowid`,
130
+ )
131
+ .all() as unknown as StoredSource[];
86
132
  }
87
133
 
88
- reviewed(): Tip[] {
134
+ reviewed(): Checkpoint[] {
89
135
  return this.db
90
136
  .prepare(
91
- `SELECT tip.session_id AS sessionId, tip.tip_id AS entryId, source.session_file AS file
92
- FROM reviewed_boundaries AS tip JOIN sources AS source USING (session_id) ORDER BY tip.rowid`,
137
+ `SELECT tip.session_id AS sessionId, tip.tip_id AS entryId,
138
+ source.session_file AS file, tip.since AS since
139
+ FROM reviewed_boundaries AS tip
140
+ JOIN sources AS source USING (session_id)
141
+ ORDER BY tip.rowid`,
93
142
  )
94
- .all() as unknown as Tip[];
143
+ .all() as unknown as Checkpoint[];
95
144
  }
96
145
 
97
- finish(tips: readonly Tip[]): void {
98
- const mark = this.db.prepare(
99
- `INSERT INTO reviewed_boundaries (session_id, tip_id)
100
- SELECT session_id, ? FROM sources WHERE session_id = ?
101
- ON CONFLICT DO NOTHING`,
102
- );
146
+ finish(tips: readonly Tip[]): void;
147
+ finish(plan: FinishPlan): void;
148
+ finish(input: readonly Tip[] | FinishPlan): void {
149
+ const plan: FinishPlan = Array.isArray(input)
150
+ ? { checkpoints: input.map(checkpointFromTip) }
151
+ : (input as FinishPlan);
152
+ const sources = plan.sources ?? [];
153
+ const sourceDefaults = (plan.sourceDefaults ?? []).map((source) => ({
154
+ ...source,
155
+ since: absoluteTimestamp(source.since),
156
+ }));
157
+ const checkpoints = (plan.checkpoints ?? []).map((checkpoint) => {
158
+ const candidate = checkpoint as Tip & { since?: string | null };
159
+ return { ...checkpoint, since: absoluteTimestamp(candidate.since) };
160
+ });
161
+
162
+ for (const source of sources) {
163
+ if (!source.sessionId || !source.file) throw new Error('Cannot finish an invalid source');
164
+ absoluteTimestamp(source.seedSince);
165
+ }
166
+ for (const source of sourceDefaults) {
167
+ if (!source.sessionId || source.since === null)
168
+ throw new Error('Cannot finish an invalid source default');
169
+ }
170
+ for (const checkpoint of checkpoints) {
171
+ if (!checkpoint.sessionId || !checkpoint.entryId)
172
+ throw new Error('Cannot finish an invalid checkpoint');
173
+ }
174
+
175
+ const known = new Set(this.sources().map((source) => source.sessionId));
103
176
  this.db.exec('BEGIN IMMEDIATE');
104
177
  try {
105
- for (const tip of tips) {
106
- if (!tip.entryId || mark.run(tip.entryId, tip.sessionId).changes === 0)
178
+ const enroll = this.db.prepare(
179
+ `INSERT INTO sources (session_id, session_file, seed_since) VALUES (?, ?, ?)
180
+ ON CONFLICT (session_id) DO UPDATE SET
181
+ session_file = excluded.session_file,
182
+ seed_since = CASE
183
+ WHEN excluded.seed_since IS NULL THEN sources.seed_since
184
+ WHEN sources.seed_since IS NULL THEN excluded.seed_since
185
+ WHEN excluded.seed_since < sources.seed_since THEN excluded.seed_since
186
+ ELSE sources.seed_since
187
+ END`,
188
+ );
189
+ for (const source of sources) {
190
+ enroll.run(source.sessionId, source.file, absoluteTimestamp(source.seedSince));
191
+ known.add(source.sessionId);
192
+ }
193
+
194
+ const saveDefault = this.db.prepare(
195
+ `UPDATE sources SET seed_since = CASE
196
+ WHEN seed_since IS NULL OR ? < seed_since THEN ?
197
+ ELSE seed_since
198
+ END
199
+ WHERE session_id = ?`,
200
+ );
201
+ for (const source of sourceDefaults) {
202
+ if (!known.has(source.sessionId))
203
+ throw new Error('Cannot finish an unknown source default');
204
+ saveDefault.run(source.since, source.since, source.sessionId);
205
+ }
206
+
207
+ const mark = this.db.prepare(
208
+ `INSERT INTO reviewed_boundaries (session_id, tip_id, since) VALUES (?, ?, ?)
209
+ ON CONFLICT (session_id, tip_id) DO UPDATE SET
210
+ since = CASE
211
+ WHEN reviewed_boundaries.since IS NULL OR excluded.since IS NULL THEN NULL
212
+ WHEN excluded.since < reviewed_boundaries.since THEN excluded.since
213
+ ELSE reviewed_boundaries.since
214
+ END`,
215
+ );
216
+ for (const checkpoint of checkpoints) {
217
+ if (!known.has(checkpoint.sessionId))
107
218
  throw new Error('Cannot finish an unknown checkpoint');
219
+ mark.run(checkpoint.sessionId, checkpoint.entryId, checkpoint.since);
108
220
  }
109
221
  this.db.exec('COMMIT');
110
222
  } catch (error) {
@@ -0,0 +1,270 @@
1
+ import { readdirSync, statSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import type { StoredSource } from './checkpoints.js';
4
+ import { createWarning, type WarningRecord } from './warnings.js';
5
+ import {
6
+ readSession,
7
+ ReviewBudget,
8
+ ReviewLimitError,
9
+ type SessionSnapshot,
10
+ type Source,
11
+ type SessionTree,
12
+ } from './evidence.js';
13
+
14
+ export type DiscoveryResult = {
15
+ sources: Source[];
16
+ newSources: Source[];
17
+ snapshots: SessionSnapshot[];
18
+ warnings: WarningRecord[];
19
+ incomplete: boolean;
20
+ };
21
+
22
+ type Candidate = {
23
+ file: string;
24
+ tree: SessionTree;
25
+ };
26
+
27
+ type FileScan = {
28
+ files: string[];
29
+ warnings: WarningRecord[];
30
+ incomplete: boolean;
31
+ };
32
+
33
+ function sourceKey(source: Pick<Source, 'sessionId' | 'file'>): string {
34
+ return `${source.sessionId}\u0000${resolve(source.file)}`;
35
+ }
36
+
37
+ function collisionWarning(sessionId: string, files: readonly string[]): WarningRecord {
38
+ const reason = `Session ${sessionId} has multiple archive files: ${files.join(', ')}`;
39
+ return createWarning(reason, files, reason, 'identity-ambiguity');
40
+ }
41
+
42
+ function scanFiles(sessionDir: string, scanAllProjects: boolean): FileScan {
43
+ const directory = resolve(sessionDir);
44
+ const warnings: WarningRecord[] = [];
45
+ let incomplete = false;
46
+ let files: string[] = [];
47
+
48
+ if (!scanAllProjects) {
49
+ try {
50
+ files = readdirSync(directory, { withFileTypes: true })
51
+ .filter((entry) => entry.name.endsWith('.jsonl') && entry.isFile())
52
+ .map((entry) => join(directory, entry.name))
53
+ .sort();
54
+ } catch (error) {
55
+ const reason = String(error);
56
+ return {
57
+ files: [],
58
+ warnings: [
59
+ createWarning(
60
+ `${directory}: unable to enumerate session archive: ${reason}`,
61
+ [directory],
62
+ reason,
63
+ 'archive-scan',
64
+ ),
65
+ ],
66
+ incomplete: true,
67
+ };
68
+ }
69
+ return { files, warnings, incomplete };
70
+ }
71
+
72
+ const root = resolve(directory, '..');
73
+ let buckets;
74
+ try {
75
+ buckets = readdirSync(root, { withFileTypes: true }).filter(
76
+ (entry) => entry.isDirectory() || entry.isSymbolicLink(),
77
+ );
78
+ } catch (error) {
79
+ const reason = String(error);
80
+ return {
81
+ files: [],
82
+ warnings: [
83
+ createWarning(
84
+ `${root}: unable to enumerate session archive: ${reason}`,
85
+ [root],
86
+ reason,
87
+ 'archive-scan',
88
+ ),
89
+ ],
90
+ incomplete: true,
91
+ };
92
+ }
93
+
94
+ for (const bucket of buckets) {
95
+ const bucketPath = join(root, bucket.name);
96
+ try {
97
+ files.push(
98
+ ...readdirSync(bucketPath)
99
+ .filter((file) => file.endsWith('.jsonl'))
100
+ .map((file) => join(bucketPath, file)),
101
+ );
102
+ } catch (error) {
103
+ incomplete = true;
104
+ const reason = String(error);
105
+ warnings.push(
106
+ createWarning(
107
+ `${bucketPath}: unable to enumerate session archive: ${reason}`,
108
+ [bucketPath],
109
+ reason,
110
+ 'archive-scan',
111
+ ),
112
+ );
113
+ }
114
+ }
115
+
116
+ return { files: files.sort(), warnings, incomplete };
117
+ }
118
+
119
+ /**
120
+ * Enumerate the active configured session directory for seed batches. Default
121
+ * Pi storage is a cwd bucket, so scan its sibling buckets; custom storage is a
122
+ * flat directory and is scanned directly. Ordinary reviews use enrollment only.
123
+ */
124
+ export function discoverSources(
125
+ sessionDir: string,
126
+ enrolled: readonly StoredSource[],
127
+ requestedSince: string | null,
128
+ scanAllProjects = false,
129
+ budget = new ReviewBudget(),
130
+ ): DiscoveryResult {
131
+ const warnings: WarningRecord[] = [];
132
+ let incomplete = false;
133
+ const sources: Source[] = [];
134
+ const newSources: Source[] = [];
135
+ const snapshots: SessionSnapshot[] = [];
136
+ const enrolledById = new Map<string, Source>();
137
+ const enrolledByFile = new Map<string, Source[]>();
138
+ const enrolledKeys = new Set<string>();
139
+ const conflictingEnrolledPaths = new Set<string>();
140
+ for (const source of enrolled) {
141
+ const normalized = { ...source, file: resolve(source.file) };
142
+ const key = sourceKey(normalized);
143
+ if (enrolledKeys.has(key)) continue;
144
+ enrolledKeys.add(key);
145
+ const samePath = enrolledByFile.get(normalized.file) ?? [];
146
+ if (samePath.some((candidate) => candidate.sessionId !== normalized.sessionId))
147
+ conflictingEnrolledPaths.add(normalized.file);
148
+ samePath.push(normalized);
149
+ enrolledByFile.set(normalized.file, samePath);
150
+ sources.push(normalized);
151
+ enrolledById.set(normalized.sessionId, normalized);
152
+ }
153
+ const candidates: Candidate[] = [];
154
+ const snapshotKeys = new Set<string>();
155
+ const addSnapshot = (source: Source, tree: SessionTree) => {
156
+ const key = sourceKey(source);
157
+ if (snapshotKeys.has(key)) return;
158
+ snapshotKeys.add(key);
159
+ snapshots.push({ source, tree });
160
+ };
161
+ const blockedSessionIds = new Set<string>();
162
+ const scan = scanFiles(sessionDir, scanAllProjects);
163
+ warnings.push(...scan.warnings);
164
+ incomplete = scan.incomplete;
165
+
166
+ const candidatePaths = new Set<string>();
167
+ for (const file of scan.files) {
168
+ const resolvedFile = resolve(file);
169
+ if (candidatePaths.has(resolvedFile)) continue;
170
+ candidatePaths.add(resolvedFile);
171
+ budget.reserveSource(resolvedFile);
172
+ try {
173
+ if (!statSync(resolvedFile).isFile()) continue;
174
+ const tree = readSession(resolvedFile, budget.limits);
175
+ budget.retain(tree);
176
+ candidates.push({ file: resolvedFile, tree });
177
+ } catch (error) {
178
+ if (error instanceof ReviewLimitError) throw error;
179
+ const enrolledSources = enrolledByFile.get(resolvedFile) ?? [];
180
+ for (const enrolledSource of enrolledSources) blockedSessionIds.add(enrolledSource.sessionId);
181
+ incomplete = true;
182
+ const reason = String(error);
183
+ warnings.push(
184
+ createWarning(`${resolvedFile}: ${reason}`, [resolvedFile], reason, 'source-failure'),
185
+ );
186
+ }
187
+ }
188
+
189
+ for (const path of conflictingEnrolledPaths) {
190
+ if (candidatePaths.has(path)) continue;
191
+ incomplete = true;
192
+ const identities = (enrolledByFile.get(path) ?? []).map((source) => source.sessionId);
193
+ const reason = `enrolled for multiple session IDs: ${identities.join(', ')}`;
194
+ warnings.push(createWarning(`${path}: ${reason}`, [path], reason, 'identity-ambiguity'));
195
+ }
196
+
197
+ const freshById = new Map<string, Candidate[]>();
198
+ for (const candidate of candidates) {
199
+ const enrolledAtPath = enrolledByFile.get(candidate.file) ?? [];
200
+ if (enrolledAtPath.length > 0) {
201
+ for (const enrolledSource of enrolledAtPath) {
202
+ if (enrolledSource.sessionId !== candidate.tree.sessionId) {
203
+ incomplete = true;
204
+ const reason = `session header ID changed from ${enrolledSource.sessionId} to ${candidate.tree.sessionId}`;
205
+ warnings.push(
206
+ createWarning(
207
+ `${candidate.file}: ${reason}`,
208
+ [candidate.file],
209
+ reason,
210
+ 'identity-ambiguity',
211
+ ),
212
+ );
213
+ }
214
+ addSnapshot(enrolledSource, candidate.tree);
215
+ }
216
+ continue;
217
+ }
218
+
219
+ const enrolledSource = enrolledById.get(candidate.tree.sessionId);
220
+ if (enrolledSource) {
221
+ incomplete = true;
222
+ blockedSessionIds.add(candidate.tree.sessionId);
223
+ warnings.push(
224
+ collisionWarning(candidate.tree.sessionId, [enrolledSource.file, candidate.file]),
225
+ );
226
+ continue;
227
+ }
228
+
229
+ const group = freshById.get(candidate.tree.sessionId) ?? [];
230
+ group.push(candidate);
231
+ freshById.set(candidate.tree.sessionId, group);
232
+ }
233
+
234
+ for (const [sessionId, group] of freshById) {
235
+ if (group.length !== 1) {
236
+ incomplete = true;
237
+ warnings.push(
238
+ collisionWarning(
239
+ sessionId,
240
+ group.map((candidate) => candidate.file),
241
+ ),
242
+ );
243
+ continue;
244
+ }
245
+ const candidate = group[0]!;
246
+ const source: Source = {
247
+ sessionId,
248
+ file: candidate.file,
249
+ seedSince: requestedSince,
250
+ };
251
+ sources.push(source);
252
+ newSources.push(source);
253
+ addSnapshot(source, candidate.tree);
254
+ }
255
+
256
+ const seen = new Set<string>();
257
+ return {
258
+ sources: sources.filter((source) => {
259
+ if (blockedSessionIds.has(source.sessionId)) return false;
260
+ const key = sourceKey(source);
261
+ if (seen.has(key)) return false;
262
+ seen.add(key);
263
+ return true;
264
+ }),
265
+ newSources,
266
+ snapshots: snapshots.filter((snapshot) => !blockedSessionIds.has(snapshot.source.sessionId)),
267
+ warnings,
268
+ incomplete,
269
+ };
270
+ }