@khanglvm/outline-cli 0.1.6 → 0.1.8

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.
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "./errors.js";
2
2
  import { compactValue, ensureStringArray, mapLimit, toInteger } from "./utils.js";
3
3
  import { summarizeSafeText } from "./summary-redaction.js";
4
+ import { collectionsOpenTool, memoryResolveTool } from "./memory-store.js";
4
5
 
5
6
  function normalizeDocumentRow(row, view = "summary", excerptChars = 220) {
6
7
  if (!row) {
@@ -70,6 +71,186 @@ function normalizeSearchHit(hit, view = "summary", contextChars = 220) {
70
71
  return summary;
71
72
  }
72
73
 
74
+ function nonEmptyString(value) {
75
+ const text = String(value || "").trim();
76
+ return text || "";
77
+ }
78
+
79
+ function normalizeMemoryScoreThreshold(value, fallback = 85) {
80
+ const numeric = Number(value);
81
+ if (!Number.isFinite(numeric)) {
82
+ return fallback;
83
+ }
84
+ if (numeric >= 0 && numeric <= 1) {
85
+ return numeric * 100;
86
+ }
87
+ return numeric;
88
+ }
89
+
90
+ function firstFilterReference(args = {}, keys = [], arrayKeys = []) {
91
+ for (const key of keys) {
92
+ const value = nonEmptyString(args[key]);
93
+ if (value) {
94
+ return { key, value };
95
+ }
96
+ }
97
+ for (const key of arrayKeys) {
98
+ if (!Array.isArray(args[key])) {
99
+ continue;
100
+ }
101
+ for (const item of args[key]) {
102
+ const value = nonEmptyString(item);
103
+ if (value) {
104
+ return { key, value };
105
+ }
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+
111
+ function resolutionFromFilterCandidate(resolved, ref, config, args = {}) {
112
+ const candidates = resolved.result?.candidates || [];
113
+ const topCandidate = candidates[0] || null;
114
+ const strict = args.strict !== false;
115
+ const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
116
+ const topScore = Number(topCandidate?.score || 0);
117
+
118
+ if (!topCandidate) {
119
+ return {
120
+ error: {
121
+ failed: {
122
+ kind: ref.key,
123
+ value: ref.value,
124
+ status: "not_found",
125
+ },
126
+ memory: resolved.result?.memory || null,
127
+ },
128
+ };
129
+ }
130
+ if (strict && topScore < strictThreshold) {
131
+ return {
132
+ error: {
133
+ failed: {
134
+ kind: ref.key,
135
+ value: ref.value,
136
+ status: "low_confidence",
137
+ strictThreshold,
138
+ },
139
+ candidate: topCandidate,
140
+ candidates,
141
+ memory: resolved.result?.memory || null,
142
+ },
143
+ };
144
+ }
145
+
146
+ const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
147
+ || (resolved.result?.live || [])[0]
148
+ || null;
149
+ if (live && !live.ok) {
150
+ return {
151
+ error: {
152
+ failed: {
153
+ kind: ref.key,
154
+ value: ref.value,
155
+ status: "hydrate_failed",
156
+ error: live.error,
157
+ statusCode: live.status,
158
+ },
159
+ candidate: topCandidate,
160
+ memory: resolved.result?.memory || live.memory || null,
161
+ },
162
+ };
163
+ }
164
+
165
+ return {
166
+ id: topCandidate.id,
167
+ resultField: config.resultField,
168
+ resolution: compactValue({
169
+ mode: "memory",
170
+ kind: ref.key,
171
+ value: ref.value,
172
+ id: topCandidate.id,
173
+ name: topCandidate.name,
174
+ email: topCandidate.email,
175
+ candidate: topCandidate,
176
+ live,
177
+ memory: resolved.result?.memory || null,
178
+ }) || { id: topCandidate.id },
179
+ };
180
+ }
181
+
182
+ async function resolveFilter(ctx, args = {}, config) {
183
+ const exact = nonEmptyString(args[config.idKey]);
184
+ if (exact) {
185
+ return { id: exact, resultField: config.resultField };
186
+ }
187
+ const ref = firstFilterReference(args, config.queryKeys, config.arrayQueryKeys);
188
+ if (!ref) {
189
+ return null;
190
+ }
191
+
192
+ const threshold = Math.max(0, normalizeMemoryScoreThreshold(args.strictThreshold, 85));
193
+ const resolved = await memoryResolveTool(ctx, {
194
+ query: ref.value,
195
+ type: config.type,
196
+ profile: args.profile,
197
+ limit: Math.max(1, toInteger(args.resolveLimit, 5)),
198
+ hydrateLimit: 1,
199
+ maxAgeHours: args.maxAgeHours,
200
+ minScore: args.minScore === undefined && args.strict !== false ? threshold : args.minScore,
201
+ strict: args.strict,
202
+ strictThreshold: args.strictThreshold,
203
+ fallbackSearch: args.fallbackSearch,
204
+ fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false ? threshold : args.fallbackMinScore,
205
+ fallbackLimit: args.fallbackLimit,
206
+ refresh: args.refresh !== false,
207
+ maxAttempts: args.maxAttempts,
208
+ });
209
+
210
+ return {
211
+ ...resolutionFromFilterCandidate(resolved, ref, config, args),
212
+ resultField: config.resultField,
213
+ };
214
+ }
215
+
216
+ async function resolveRetrievalFilters(ctx, args = {}) {
217
+ const filters = [
218
+ await resolveFilter(ctx, args, {
219
+ type: "collection",
220
+ idKey: "collectionId",
221
+ resultField: "collectionId",
222
+ queryKeys: ["collectionQuery", "collectionRef"],
223
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
224
+ }),
225
+ await resolveFilter(ctx, args, {
226
+ type: "user",
227
+ idKey: "userId",
228
+ resultField: "userId",
229
+ queryKeys: ["userQuery", "userRef"],
230
+ arrayQueryKeys: ["userQueries", "userRefs"],
231
+ }),
232
+ ].filter(Boolean);
233
+
234
+ const failed = filters.find((filter) => filter?.error);
235
+ if (failed) {
236
+ return { error: failed.error, resultField: failed.resultField };
237
+ }
238
+
239
+ const ids = {};
240
+ const resolution = {};
241
+ for (const filter of filters) {
242
+ ids[filter.resultField] = filter.id;
243
+ if (filter.resolution) {
244
+ resolution[filter.resultField] = filter.resolution;
245
+ }
246
+ }
247
+
248
+ return {
249
+ ids,
250
+ resolution: Object.keys(resolution).length > 0 ? resolution : null,
251
+ };
252
+ }
253
+
73
254
  function normalizeRanking(ranking) {
74
255
  const val = Number(ranking);
75
256
  if (!Number.isFinite(val)) {
@@ -638,7 +819,8 @@ async function researchSingleQuery(ctx, query, args, maxAttempts, contextChars)
638
819
 
639
820
  const baseBody = compactValue({
640
821
  query,
641
- collectionId: args.collectionId,
822
+ collectionId: args.resolvedCollectionId || args.collectionId,
823
+ userId: args.resolvedUserId || args.userId,
642
824
  limit: limitPerQuery,
643
825
  offset,
644
826
  }) || {};
@@ -736,8 +918,32 @@ async function searchResearchTool(ctx, args) {
736
918
  : modeConfig.mmrLambda;
737
919
  const diversify = args.diversify !== false;
738
920
 
921
+ const resolvedFilters = await resolveRetrievalFilters(ctx, args);
922
+ if (resolvedFilters.error) {
923
+ return {
924
+ tool: "search.research",
925
+ profile: ctx.profile.id,
926
+ queryCount: queries.length,
927
+ result: compactValue({
928
+ ok: false,
929
+ status: resolvedFilters.error.status || "not_found",
930
+ [resolvedFilters.resultField || "filterId"]: "",
931
+ resolution: resolvedFilters.error,
932
+ queries,
933
+ perQuery: [],
934
+ merged: [],
935
+ expanded: [],
936
+ }) || {},
937
+ };
938
+ }
939
+ const searchArgs = {
940
+ ...args,
941
+ resolvedCollectionId: resolvedFilters.ids?.collectionId,
942
+ resolvedUserId: resolvedFilters.ids?.userId,
943
+ };
944
+
739
945
  const perQueryRaw = await mapLimit(queries, concurrency, async (query) =>
740
- researchSingleQuery(ctx, query, args, maxAttempts, contextChars)
946
+ researchSingleQuery(ctx, query, searchArgs, maxAttempts, contextChars)
741
947
  );
742
948
 
743
949
  const allHits = perQueryRaw.flatMap((item) => item.result.hits || []);
@@ -884,6 +1090,7 @@ async function searchResearchTool(ctx, args) {
884
1090
  result: {
885
1091
  question: args.question,
886
1092
  queries,
1093
+ resolution: resolvedFilters.resolution,
887
1094
  ...(includePerQuery ? { perQuery } : {}),
888
1095
  merged: mergedOut,
889
1096
  ...(includeExpanded ? { expanded } : {}),
@@ -1097,6 +1304,62 @@ function buildCandidateFromDocument(document, { confidence = 1, source = "explic
1097
1304
  };
1098
1305
  }
1099
1306
 
1307
+ function buildCandidateFromMemory(item, { source = "memory", query = "" } = {}) {
1308
+ if (!item?.id) {
1309
+ return null;
1310
+ }
1311
+ const score = Number(item.score || 0);
1312
+ return {
1313
+ id: String(item.id),
1314
+ title: item.title || item.name,
1315
+ collectionId: item.collectionId,
1316
+ parentDocumentId: item.parentDocumentId,
1317
+ updatedAt: item.updatedAt,
1318
+ publishedAt: item.publishedAt,
1319
+ urlId: item.urlId,
1320
+ ranking: Number.isFinite(score) ? score : undefined,
1321
+ confidence: clamp(Number.isFinite(score) ? score / 100 : 0, 0, 1),
1322
+ sources: [source],
1323
+ context: query ? `remembered match for ${query}` : "remembered match",
1324
+ document: item,
1325
+ };
1326
+ }
1327
+
1328
+ async function loadRememberedDocumentCandidates(ctx, args = {}, ref = {}) {
1329
+ if (args.memory === false) {
1330
+ return {
1331
+ candidates: [],
1332
+ memory: null,
1333
+ };
1334
+ }
1335
+
1336
+ const resolved = await memoryResolveTool(ctx, compactValue({
1337
+ query: ref.query,
1338
+ url: ref.url,
1339
+ urlId: ref.urlId,
1340
+ id: ref.id,
1341
+ type: "document",
1342
+ profile: args.profile,
1343
+ limit: Math.max(1, toInteger(args.limit, 8)),
1344
+ minScore: args.memoryMinScore ?? args.minScore,
1345
+ maxAgeHours: args.maxAgeHours,
1346
+ refresh: false,
1347
+ fallbackSearch: false,
1348
+ collectionId: args.resolvedCollectionId || args.collectionId,
1349
+ view: "summary",
1350
+ maxAttempts: args.maxAttempts,
1351
+ }) || {
1352
+ type: "document",
1353
+ refresh: false,
1354
+ fallbackSearch: false,
1355
+ });
1356
+
1357
+ return {
1358
+ candidates: resolved.result?.candidates || [],
1359
+ memory: resolved.result?.memory || null,
1360
+ };
1361
+ }
1362
+
1100
1363
  function normalizeStatusFilter(statusFilter) {
1101
1364
  if (statusFilter === undefined || statusFilter === null) {
1102
1365
  return undefined;
@@ -1150,10 +1413,51 @@ async function resolveSingleQuery(ctx, query, args) {
1150
1413
  const maxAttempts = toInteger(args.maxAttempts, 2);
1151
1414
  const limit = Math.max(1, toInteger(args.limit, 8));
1152
1415
  const strict = !!args.strict;
1416
+ const view = args.view || "summary";
1417
+ const excerptChars = toInteger(args.excerptChars, 220);
1418
+ const byId = new Map();
1419
+ const remembered = await loadRememberedDocumentCandidates(ctx, args, { query });
1420
+
1421
+ for (const item of remembered.candidates) {
1422
+ const candidate = buildCandidateFromMemory(item, { query });
1423
+ if (candidate?.id) {
1424
+ byId.set(candidate.id, candidate);
1425
+ }
1426
+ }
1427
+
1428
+ if (args.refresh === false) {
1429
+ const candidates = Array.from(byId.values()).sort((a, b) => {
1430
+ if (b.confidence !== a.confidence) {
1431
+ return b.confidence - a.confidence;
1432
+ }
1433
+ return String(a.title || "").localeCompare(String(b.title || ""));
1434
+ });
1435
+ const strictThreshold = Number.isFinite(Number(args.strictThreshold))
1436
+ ? Number(args.strictThreshold)
1437
+ : 0.82;
1438
+ const strictCandidates = strict ? candidates.filter((item) => item.confidence >= strictThreshold) : candidates;
1439
+ const trimmed = strictCandidates.slice(0, limit);
1440
+ return {
1441
+ query,
1442
+ bestMatch: trimmed[0] ? makeCandidateView(trimmed[0], view, excerptChars) : null,
1443
+ candidates: trimmed.map((item) => makeCandidateView(item, view, excerptChars)),
1444
+ stats: {
1445
+ titleHits: 0,
1446
+ semanticHits: 0,
1447
+ memoryHits: remembered.candidates.length,
1448
+ candidateCount: trimmed.length,
1449
+ strict,
1450
+ strictThreshold,
1451
+ memoryOnly: true,
1452
+ },
1453
+ memory: remembered.memory,
1454
+ };
1455
+ }
1153
1456
 
1154
1457
  const common = compactValue({
1155
1458
  query,
1156
- collectionId: args.collectionId,
1459
+ collectionId: args.resolvedCollectionId || args.collectionId,
1460
+ userId: args.resolvedUserId || args.userId,
1157
1461
  limit,
1158
1462
  offset: 0,
1159
1463
  }) || {};
@@ -1176,8 +1480,6 @@ async function resolveSingleQuery(ctx, query, args) {
1176
1480
 
1177
1481
  const semanticHits = Array.isArray(semanticResponse?.body?.data) ? semanticResponse.body.data : [];
1178
1482
 
1179
- const byId = new Map();
1180
-
1181
1483
  for (const hit of titleHits) {
1182
1484
  const id = hit?.id;
1183
1485
  if (!id) {
@@ -1203,6 +1505,15 @@ async function resolveSingleQuery(ctx, query, args) {
1203
1505
  document: hit,
1204
1506
  };
1205
1507
 
1508
+ const existing = byId.get(id);
1509
+ if (existing) {
1510
+ existing.confidence = Math.max(existing.confidence, candidate.confidence);
1511
+ existing.sources = uniqueStrings([...(existing.sources || []), "titles"]);
1512
+ existing.document = { ...existing.document, ...hit };
1513
+ existing.text = existing.text || hit.text;
1514
+ continue;
1515
+ }
1516
+
1206
1517
  byId.set(id, candidate);
1207
1518
  }
1208
1519
 
@@ -1272,9 +1583,6 @@ async function resolveSingleQuery(ctx, query, args) {
1272
1583
  const bestRaw = candidates[0] || null;
1273
1584
  const bestMatch = bestRaw && (!strict || bestRaw.confidence >= strictThreshold) ? bestRaw : null;
1274
1585
 
1275
- const view = args.view || "summary";
1276
- const excerptChars = toInteger(args.excerptChars, 220);
1277
-
1278
1586
  return {
1279
1587
  query,
1280
1588
  bestMatch: bestMatch ? makeCandidateView(bestMatch, view, excerptChars) : null,
@@ -1282,10 +1590,12 @@ async function resolveSingleQuery(ctx, query, args) {
1282
1590
  stats: {
1283
1591
  titleHits: titleHits.length,
1284
1592
  semanticHits: semanticHits.length,
1593
+ memoryHits: remembered.candidates.length,
1285
1594
  candidateCount: candidates.length,
1286
1595
  strict,
1287
1596
  strictThreshold,
1288
1597
  },
1598
+ memory: remembered.memory,
1289
1599
  };
1290
1600
  }
1291
1601
 
@@ -1295,8 +1605,29 @@ async function documentsResolveTool(ctx, args) {
1295
1605
  throw new CliError("documents.resolve requires args.query or args.queries[]");
1296
1606
  }
1297
1607
 
1608
+ const resolvedFilters = await resolveRetrievalFilters(ctx, args);
1609
+ if (resolvedFilters.error) {
1610
+ return {
1611
+ tool: "documents.resolve",
1612
+ profile: ctx.profile.id,
1613
+ result: compactValue({
1614
+ ok: false,
1615
+ status: resolvedFilters.error.status || "not_found",
1616
+ [resolvedFilters.resultField || "filterId"]: "",
1617
+ resolution: resolvedFilters.error,
1618
+ perQuery: [],
1619
+ mergedBestMatches: [],
1620
+ }) || {},
1621
+ };
1622
+ }
1623
+ const resolveArgs = {
1624
+ ...args,
1625
+ resolvedCollectionId: resolvedFilters.ids?.collectionId,
1626
+ resolvedUserId: resolvedFilters.ids?.userId,
1627
+ };
1628
+
1298
1629
  const perQuery = await mapLimit(queries, Math.max(1, toInteger(args.concurrency, 4)), async (query) =>
1299
- resolveSingleQuery(ctx, query, args)
1630
+ resolveSingleQuery(ctx, query, resolveArgs)
1300
1631
  );
1301
1632
 
1302
1633
  if (queries.length === 1 && !args.forceGroupedResult) {
@@ -1304,7 +1635,10 @@ async function documentsResolveTool(ctx, args) {
1304
1635
  tool: "documents.resolve",
1305
1636
  profile: ctx.profile.id,
1306
1637
  query: perQuery[0].query,
1307
- result: perQuery[0],
1638
+ result: {
1639
+ ...perQuery[0],
1640
+ resolution: resolvedFilters.resolution,
1641
+ },
1308
1642
  };
1309
1643
  }
1310
1644
 
@@ -1320,6 +1654,7 @@ async function documentsResolveTool(ctx, args) {
1320
1654
  result: {
1321
1655
  perQuery,
1322
1656
  mergedBestMatches,
1657
+ resolution: resolvedFilters.resolution,
1323
1658
  },
1324
1659
  };
1325
1660
  }
@@ -1336,6 +1671,7 @@ async function resolveSingleUrlReference(ctx, rawUrl, args) {
1336
1671
  const candidateMap = new Map();
1337
1672
  const warnings = [];
1338
1673
  let shareLookupAttempted = false;
1674
+ const remembered = await loadRememberedDocumentCandidates(ctx, args, { url: rawUrl });
1339
1675
 
1340
1676
  if (parsed.validUrl && args.strictHost === true && parsed.matchesProfileHost === false) {
1341
1677
  warnings.push("host_mismatch_skipped");
@@ -1355,6 +1691,52 @@ async function resolveSingleUrlReference(ctx, rawUrl, args) {
1355
1691
  };
1356
1692
  }
1357
1693
 
1694
+ for (const item of remembered.candidates) {
1695
+ const memoryCandidate = buildCandidateFromMemory(item, { source: "memory_url", query: rawUrl });
1696
+ if (!memoryCandidate?.id) {
1697
+ continue;
1698
+ }
1699
+ candidateMap.set(memoryCandidate.id, {
1700
+ ...memoryCandidate,
1701
+ rawConfidence: memoryCandidate.confidence,
1702
+ matchingReasons: ["memory"],
1703
+ matchedQueries: [],
1704
+ urlIdHintMatched: parsed.urlIdHints.length > 0 && parsed.urlIdHints.includes(String(memoryCandidate.urlId || "")),
1705
+ });
1706
+ }
1707
+
1708
+ if (args.refresh === false) {
1709
+ const memoryCandidates = Array.from(candidateMap.values()).sort((a, b) => {
1710
+ const confidenceDiff = Number(b.confidence || 0) - Number(a.confidence || 0);
1711
+ if (confidenceDiff !== 0) {
1712
+ return confidenceDiff;
1713
+ }
1714
+ return String(a.title || "").localeCompare(String(b.title || ""));
1715
+ });
1716
+ const strictCandidates = strict
1717
+ ? memoryCandidates.filter((item) => Number(item.confidence || 0) >= strictThreshold)
1718
+ : memoryCandidates;
1719
+ const trimmedCandidates = strictCandidates.slice(0, limit);
1720
+ const bestMatch = trimmedCandidates[0] || null;
1721
+ return {
1722
+ url: parsed.input,
1723
+ parsed,
1724
+ bestMatch: bestMatch ? shapeResolveUrlCandidate(bestMatch, view, excerptChars) : null,
1725
+ candidates: trimmedCandidates.map((item) => shapeResolveUrlCandidate(item, view, excerptChars)),
1726
+ stats: {
1727
+ queryCount: 0,
1728
+ candidateCount: trimmedCandidates.length,
1729
+ strict,
1730
+ strictThreshold,
1731
+ shareLookupAttempted,
1732
+ memoryHits: remembered.candidates.length,
1733
+ memoryOnly: true,
1734
+ },
1735
+ memory: remembered.memory,
1736
+ warnings,
1737
+ };
1738
+ }
1739
+
1358
1740
  if (parsed.validUrl && parsed.shareId) {
1359
1741
  shareLookupAttempted = true;
1360
1742
  try {
@@ -1489,7 +1871,9 @@ async function resolveSingleUrlReference(ctx, rawUrl, args) {
1489
1871
  strict,
1490
1872
  strictThreshold,
1491
1873
  shareLookupAttempted,
1874
+ memoryHits: remembered.candidates.length,
1492
1875
  },
1876
+ memory: remembered.memory,
1493
1877
  warnings,
1494
1878
  };
1495
1879
  }
@@ -1501,15 +1885,39 @@ async function documentsResolveUrlsTool(ctx, args) {
1501
1885
  throw new CliError("documents.resolve_urls requires args.url or args.urls[]");
1502
1886
  }
1503
1887
 
1888
+ const resolvedFilters = await resolveRetrievalFilters(ctx, args);
1889
+ if (resolvedFilters.error) {
1890
+ return {
1891
+ tool: "documents.resolve_urls",
1892
+ profile: ctx.profile.id,
1893
+ result: compactValue({
1894
+ ok: false,
1895
+ status: resolvedFilters.error.status || "not_found",
1896
+ [resolvedFilters.resultField || "filterId"]: "",
1897
+ resolution: resolvedFilters.error,
1898
+ perUrl: [],
1899
+ mergedBestMatches: [],
1900
+ }) || {},
1901
+ };
1902
+ }
1903
+ const resolveArgs = {
1904
+ ...args,
1905
+ resolvedCollectionId: resolvedFilters.ids?.collectionId,
1906
+ resolvedUserId: resolvedFilters.ids?.userId,
1907
+ };
1908
+
1504
1909
  const concurrency = Math.max(1, toInteger(args.concurrency, 4));
1505
- const perUrl = await mapLimit(urls, concurrency, async (url) => resolveSingleUrlReference(ctx, url, args));
1910
+ const perUrl = await mapLimit(urls, concurrency, async (url) => resolveSingleUrlReference(ctx, url, resolveArgs));
1506
1911
 
1507
1912
  if (urls.length === 1 && !args.forceGroupedResult) {
1508
1913
  return {
1509
1914
  tool: "documents.resolve_urls",
1510
1915
  profile: ctx.profile.id,
1511
1916
  url: perUrl[0].url,
1512
- result: perUrl[0],
1917
+ result: {
1918
+ ...perUrl[0],
1919
+ resolution: resolvedFilters.resolution,
1920
+ },
1513
1921
  };
1514
1922
  }
1515
1923
 
@@ -1525,6 +1933,7 @@ async function documentsResolveUrlsTool(ctx, args) {
1525
1933
  result: {
1526
1934
  perUrl,
1527
1935
  mergedBestMatches,
1936
+ resolution: resolvedFilters.resolution,
1528
1937
  },
1529
1938
  };
1530
1939
  }
@@ -1838,9 +2247,80 @@ function buildTree({ docs, view, maxDepth }) {
1838
2247
  return { tree, rootCount: roots.length };
1839
2248
  }
1840
2249
 
2250
+ async function resolveCollectionForTree(ctx, args) {
2251
+ if (args.collectionId) {
2252
+ return {
2253
+ ok: true,
2254
+ collectionId: args.collectionId,
2255
+ mode: "collectionId",
2256
+ collection: null,
2257
+ memory: null,
2258
+ };
2259
+ }
2260
+
2261
+ const refArgs = compactValue({
2262
+ query: args.query,
2263
+ id: args.id,
2264
+ urlId: args.urlId,
2265
+ url: args.url,
2266
+ profile: args.profile,
2267
+ limit: args.resolveLimit || args.limit,
2268
+ minScore: args.minScore,
2269
+ maxAgeHours: args.maxAgeHours,
2270
+ refresh: args.refresh,
2271
+ strict: args.strict,
2272
+ strictThreshold: args.strictThreshold,
2273
+ fallbackSearch: args.fallbackSearch,
2274
+ fallbackMinScore: args.fallbackMinScore,
2275
+ fallbackLimit: args.fallbackLimit,
2276
+ view: "summary",
2277
+ maxAttempts: args.maxAttempts,
2278
+ }) || {};
2279
+
2280
+ if (!refArgs.query && !refArgs.id && !refArgs.urlId && !refArgs.url) {
2281
+ throw new CliError("collections.tree requires args.collectionId, args.id, args.query, args.urlId, or args.url");
2282
+ }
2283
+
2284
+ const opened = await collectionsOpenTool(ctx, refArgs);
2285
+ if (!opened.result?.ok || !opened.result?.collection?.id) {
2286
+ return {
2287
+ ok: false,
2288
+ status: opened.result?.status || "not_found",
2289
+ collectionId: null,
2290
+ collection: opened.result?.collection || null,
2291
+ candidates: opened.result?.candidates,
2292
+ candidate: opened.result?.candidate,
2293
+ memory: opened.result?.memory,
2294
+ };
2295
+ }
2296
+
2297
+ return {
2298
+ ok: true,
2299
+ collectionId: opened.result.collection.id,
2300
+ mode: opened.result.mode,
2301
+ collection: opened.result.collection,
2302
+ candidate: opened.result.candidate,
2303
+ memory: opened.result.memory,
2304
+ };
2305
+ }
2306
+
1841
2307
  async function collectionsTreeTool(ctx, args) {
1842
- if (!args.collectionId) {
1843
- throw new CliError("collections.tree requires args.collectionId");
2308
+ const resolvedCollection = await resolveCollectionForTree(ctx, args);
2309
+ if (!resolvedCollection.ok) {
2310
+ return {
2311
+ tool: "collections.tree",
2312
+ profile: ctx.profile.id,
2313
+ collectionId: null,
2314
+ result: {
2315
+ ok: false,
2316
+ status: resolvedCollection.status,
2317
+ collection: null,
2318
+ candidate: resolvedCollection.candidate,
2319
+ candidates: resolvedCollection.candidates,
2320
+ memory: resolvedCollection.memory,
2321
+ tree: [],
2322
+ },
2323
+ };
1844
2324
  }
1845
2325
 
1846
2326
  const includeDrafts = !!args.includeDrafts;
@@ -1854,7 +2334,7 @@ async function collectionsTreeTool(ctx, args) {
1854
2334
  for (let page = 0; page < maxPages; page += 1) {
1855
2335
  const offset = page * pageSize;
1856
2336
  const body = compactValue({
1857
- collectionId: args.collectionId,
2337
+ collectionId: resolvedCollection.collectionId,
1858
2338
  limit: pageSize,
1859
2339
  offset,
1860
2340
  sort: args.sort || "index",
@@ -1878,8 +2358,15 @@ async function collectionsTreeTool(ctx, args) {
1878
2358
  return {
1879
2359
  tool: "collections.tree",
1880
2360
  profile: ctx.profile.id,
1881
- collectionId: args.collectionId,
2361
+ collectionId: resolvedCollection.collectionId,
1882
2362
  result: {
2363
+ ok: true,
2364
+ collection: resolvedCollection.collection,
2365
+ resolution: {
2366
+ mode: resolvedCollection.mode,
2367
+ candidate: resolvedCollection.candidate,
2368
+ memory: resolvedCollection.memory,
2369
+ },
1883
2370
  includeDrafts,
1884
2371
  maxDepth,
1885
2372
  totalDocuments: normalizedDocs.length,
@@ -1987,9 +2474,9 @@ async function expandSingleQuery(ctx, query, args, hydrationCache) {
1987
2474
 
1988
2475
  const body = compactValue({
1989
2476
  query,
1990
- collectionId: args.collectionId,
2477
+ collectionId: args.resolvedCollectionId || args.collectionId,
1991
2478
  documentId: args.documentId,
1992
- userId: args.userId,
2479
+ userId: args.resolvedUserId || args.userId,
1993
2480
  limit,
1994
2481
  offset: toInteger(args.offset, 0),
1995
2482
  snippetMinWords: mode === "semantic" ? toInteger(args.snippetMinWords, 16) : undefined,
@@ -2087,9 +2574,31 @@ async function searchExpandTool(ctx, args) {
2087
2574
  throw new CliError("search.expand requires args.query or args.queries[]");
2088
2575
  }
2089
2576
 
2577
+ const resolvedFilters = await resolveRetrievalFilters(ctx, args);
2578
+ if (resolvedFilters.error) {
2579
+ return {
2580
+ tool: "search.expand",
2581
+ profile: ctx.profile.id,
2582
+ queryCount: queries.length,
2583
+ result: compactValue({
2584
+ ok: false,
2585
+ status: resolvedFilters.error.status || "not_found",
2586
+ [resolvedFilters.resultField || "filterId"]: "",
2587
+ resolution: resolvedFilters.error,
2588
+ perQuery: [],
2589
+ mergedExpanded: [],
2590
+ }) || {},
2591
+ };
2592
+ }
2593
+ const searchArgs = {
2594
+ ...args,
2595
+ resolvedCollectionId: resolvedFilters.ids?.collectionId,
2596
+ resolvedUserId: resolvedFilters.ids?.userId,
2597
+ };
2598
+
2090
2599
  const hydrationCache = new Map();
2091
2600
  const perQuery = await mapLimit(queries, Math.max(1, toInteger(args.concurrency, 4)), async (query) =>
2092
- expandSingleQuery(ctx, query, args, hydrationCache)
2601
+ expandSingleQuery(ctx, query, searchArgs, hydrationCache)
2093
2602
  );
2094
2603
 
2095
2604
  if (queries.length === 1 && !args.forceGroupedResult) {
@@ -2097,7 +2606,9 @@ async function searchExpandTool(ctx, args) {
2097
2606
  tool: "search.expand",
2098
2607
  profile: ctx.profile.id,
2099
2608
  query: perQuery[0].query,
2100
- result: perQuery[0],
2609
+ result: resolvedFilters.resolution
2610
+ ? compactValue({ ...perQuery[0], resolution: resolvedFilters.resolution }) || perQuery[0]
2611
+ : perQuery[0],
2101
2612
  };
2102
2613
  }
2103
2614
 
@@ -2127,6 +2638,7 @@ async function searchExpandTool(ctx, args) {
2127
2638
  result: {
2128
2639
  perQuery,
2129
2640
  mergedExpanded: Array.from(mergedMap.values()),
2641
+ resolution: resolvedFilters.resolution,
2130
2642
  },
2131
2643
  };
2132
2644
  }
@@ -2134,7 +2646,7 @@ async function searchExpandTool(ctx, args) {
2134
2646
  export const NAVIGATION_TOOLS = {
2135
2647
  "documents.resolve": {
2136
2648
  signature:
2137
- "documents.resolve(args: { query?: string; queries?: string[]; collectionId?: string; limit?: number; strict?: boolean; strictThreshold?: number; view?: 'ids'|'summary'|'full'; concurrency?: number; })",
2649
+ "documents.resolve(args: { query?: string; queries?: string[]; collectionId?: string; collectionQuery?: string; userId?: string; userQuery?: string; refresh?: boolean; memory?: boolean; limit?: number; strict?: boolean; strictThreshold?: number; view?: 'ids'|'summary'|'full'; concurrency?: number; })",
2138
2650
  description:
2139
2651
  "Resolve fuzzy document references by combining title search with semantic fallback and returning confidence-ranked candidates.",
2140
2652
  usageExample: {
@@ -2146,6 +2658,9 @@ export const NAVIGATION_TOOLS = {
2146
2658
  },
2147
2659
  },
2148
2660
  bestPractices: [
2661
+ "Use refresh=false to resolve from local memory only when a prior session likely observed the document.",
2662
+ "Leave memory enabled to warm live resolver results with remembered candidates before title/semantic search.",
2663
+ "Pass collectionQuery/collectionRefs or userQuery/userRefs when scoping resolution by remembered collection or user names.",
2149
2664
  "Use `strict=true` when only near-exact matches should be auto-selected.",
2150
2665
  "Start with `view=ids` in planner loops, then hydrate selected IDs separately.",
2151
2666
  "Send multiple references in `queries[]` to reduce tool round trips.",
@@ -2154,7 +2669,7 @@ export const NAVIGATION_TOOLS = {
2154
2669
  },
2155
2670
  "documents.resolve_urls": {
2156
2671
  signature:
2157
- "documents.resolve_urls(args: { url?: string; urls?: string[]; collectionId?: string; limit?: number; strict?: boolean; strictHost?: boolean; strictThreshold?: number; view?: 'ids'|'summary'|'full'; concurrency?: number; snippetMinWords?: number; snippetMaxWords?: number; excerptChars?: number; forceGroupedResult?: boolean; maxAttempts?: number; })",
2672
+ "documents.resolve_urls(args: { url?: string; urls?: string[]; collectionId?: string; collectionQuery?: string; userId?: string; userQuery?: string; refresh?: boolean; memory?: boolean; limit?: number; strict?: boolean; strictHost?: boolean; strictThreshold?: number; view?: 'ids'|'summary'|'full'; concurrency?: number; snippetMinWords?: number; snippetMaxWords?: number; excerptChars?: number; forceGroupedResult?: boolean; maxAttempts?: number; })",
2158
2673
  description:
2159
2674
  "Resolve document URLs (doc/share links) into confidence-ranked document candidates with URL-id/host-aware boosts.",
2160
2675
  usageExample: {
@@ -2170,8 +2685,11 @@ export const NAVIGATION_TOOLS = {
2170
2685
  },
2171
2686
  },
2172
2687
  bestPractices: [
2688
+ "Use refresh=false to resolve remembered Outline URLs and urlIds without a network call.",
2689
+ "Leave memory enabled so remembered URL mappings can boost live URL resolution.",
2173
2690
  "Use strictHost=true when links should belong to the currently selected profile host only.",
2174
2691
  "Use strict=true for automation paths that should avoid weak URL matches.",
2692
+ "Pass collectionQuery/collectionRefs or userQuery/userRefs when URL hints should be resolved inside a remembered scope.",
2175
2693
  "Start with view=ids, then hydrate selected IDs with documents.info for low-token loops.",
2176
2694
  ],
2177
2695
  handler: documentsResolveUrlsTool,
@@ -2199,8 +2717,8 @@ export const NAVIGATION_TOOLS = {
2199
2717
  },
2200
2718
  "collections.tree": {
2201
2719
  signature:
2202
- "collections.tree(args: { collectionId: string; includeDrafts?: boolean; maxDepth?: number; view?: 'summary'|'full'; pageSize?: number; maxPages?: number; })",
2203
- description: "Build a parent/child document tree for a collection without modifying server data.",
2720
+ "collections.tree(args: { collectionId?: string; id?: string; query?: string; urlId?: string; url?: string; includeDrafts?: boolean; maxDepth?: number; view?: 'summary'|'full'; pageSize?: number; maxPages?: number; })",
2721
+ description: "Build a parent/child document tree for a collection, resolving remembered collection names or URLs when needed.",
2204
2722
  usageExample: {
2205
2723
  tool: "collections.tree",
2206
2724
  args: {
@@ -2211,6 +2729,7 @@ export const NAVIGATION_TOOLS = {
2211
2729
  },
2212
2730
  },
2213
2731
  bestPractices: [
2732
+ "Pass query/url/urlId directly when you know the collection name or URL but not the exact ID.",
2214
2733
  "Keep `view=summary` and low `maxDepth` for navigation tasks to save tokens.",
2215
2734
  "Set includeDrafts=true only if draft pages matter for your workflow.",
2216
2735
  "Use output tree IDs as anchors for targeted `documents.info` calls.",
@@ -2219,7 +2738,7 @@ export const NAVIGATION_TOOLS = {
2219
2738
  },
2220
2739
  "search.expand": {
2221
2740
  signature:
2222
- "search.expand(args: { query?: string; queries?: string[]; mode?: 'semantic'|'titles'; limit?: number; expandLimit?: number; view?: 'ids'|'summary'|'full'; concurrency?: number; hydrateConcurrency?: number; })",
2741
+ "search.expand(args: { query?: string; queries?: string[]; mode?: 'semantic'|'titles'; collectionId?: string; collectionQuery?: string; userId?: string; userQuery?: string; limit?: number; expandLimit?: number; view?: 'ids'|'summary'|'full'; concurrency?: number; hydrateConcurrency?: number; })",
2223
2742
  description:
2224
2743
  "Search and then hydrate top-ranked documents in one call, returning compact joined search+document output.",
2225
2744
  usageExample: {
@@ -2235,6 +2754,7 @@ export const NAVIGATION_TOOLS = {
2235
2754
  bestPractices: [
2236
2755
  "Use low `expandLimit` (2-5) to minimize payload while preserving answer quality.",
2237
2756
  "Use `queries[]` for multi-intent retrieval in one request.",
2757
+ "Pass collectionQuery/collectionRefs or userQuery/userRefs when filtering by remembered names.",
2238
2758
  "For multi-query runs, duplicate document hydration is automatically cached within the same tool call.",
2239
2759
  "Prefer `view=summary` unless a full markdown body is strictly needed.",
2240
2760
  ],
@@ -2242,7 +2762,7 @@ export const NAVIGATION_TOOLS = {
2242
2762
  },
2243
2763
  "search.research": {
2244
2764
  signature:
2245
- "search.research(args: { question?: string; query?: string; queries?: string[]; collectionId?: string; limitPerQuery?: number; offset?: number; includeTitleSearch?: boolean; includeSemanticSearch?: boolean; precisionMode?: 'balanced'|'precision'|'recall'; minScore?: number; diversify?: boolean; diversityLambda?: number; rrfK?: number; expandLimit?: number; maxDocuments?: number; seenIds?: string[]; view?: 'ids'|'summary'|'full'; perQueryView?: 'ids'|'summary'|'full'; perQueryHitLimit?: number; evidencePerDocument?: number; suggestedQueryLimit?: number; includePerQuery?: boolean; includeExpanded?: boolean; includeCoverage?: boolean; includeBacklinks?: boolean; backlinksLimit?: number; backlinksConcurrency?: number; concurrency?: number; hydrateConcurrency?: number; contextChars?: number; excerptChars?: number; maxAttempts?: number; })",
2765
+ "search.research(args: { question?: string; query?: string; queries?: string[]; collectionId?: string; collectionQuery?: string; userId?: string; userQuery?: string; limitPerQuery?: number; offset?: number; includeTitleSearch?: boolean; includeSemanticSearch?: boolean; precisionMode?: 'balanced'|'precision'|'recall'; minScore?: number; diversify?: boolean; diversityLambda?: number; rrfK?: number; expandLimit?: number; maxDocuments?: number; seenIds?: string[]; view?: 'ids'|'summary'|'full'; perQueryView?: 'ids'|'summary'|'full'; perQueryHitLimit?: number; evidencePerDocument?: number; suggestedQueryLimit?: number; includePerQuery?: boolean; includeExpanded?: boolean; includeCoverage?: boolean; includeBacklinks?: boolean; backlinksLimit?: number; backlinksConcurrency?: number; concurrency?: number; hydrateConcurrency?: number; contextChars?: number; excerptChars?: number; maxAttempts?: number; })",
2246
2766
  description:
2247
2767
  "Run multi-query, multi-source research retrieval with weighted reranking, optional diversification, hydration, and follow-up cursor support for multi-turn QA.",
2248
2768
  usageExample: {
@@ -2265,6 +2785,7 @@ export const NAVIGATION_TOOLS = {
2265
2785
  bestPractices: [
2266
2786
  "Pass prior `next.seenIds` into `seenIds` for follow-up turns to avoid repetition.",
2267
2787
  "Use `precisionMode=precision` for answer-grade retrieval and `precisionMode=recall` for exploration.",
2788
+ "Pass collectionQuery/collectionRefs or userQuery/userRefs to scope research by remembered names.",
2268
2789
  "Set `perQueryView=ids` + `perQueryHitLimit` to reduce token cost while preserving traceability.",
2269
2790
  "Enable `includeBacklinks` when one-call context gathering is more important than raw latency.",
2270
2791
  "Keep `expandLimit` small and raise only when answer confidence is insufficient.",