@khanglvm/outline-cli 0.1.7 → 0.2.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.
@@ -7,6 +7,7 @@ import {
7
7
  } from "./action-gate.js";
8
8
  import { compactValue, mapLimit, toInteger } from "./utils.js";
9
9
  import { summarizeSafeText } from "./summary-redaction.js";
10
+ import { documentsOpenBatchTool } from "./memory-store.js";
10
11
 
11
12
  function normalizeDocumentSummary(doc, view = "summary", excerptChars = 220) {
12
13
  if (!doc) {
@@ -47,6 +48,31 @@ function buildRevisionConflict({ id, expectedRevision, actualRevision }) {
47
48
  };
48
49
  }
49
50
 
51
+ function resolveExpectedRevisionGuard(args, actualRevision, toolName) {
52
+ if (typeof args.expectedRevision === "string") {
53
+ const mode = args.expectedRevision.trim().toLowerCase();
54
+ if (mode !== "latest") {
55
+ throw new CliError("expectedRevision must be a number or \"latest\"");
56
+ }
57
+ if (!Number.isFinite(actualRevision)) {
58
+ throw new CliError(`${toolName} could not read the latest document revision`);
59
+ }
60
+ return {
61
+ expectedRevision: actualRevision,
62
+ source: "latest",
63
+ };
64
+ }
65
+
66
+ const expectedRevision = Number(args.expectedRevision);
67
+ if (!Number.isFinite(expectedRevision)) {
68
+ throw new CliError("expectedRevision must be a number or \"latest\"");
69
+ }
70
+ return {
71
+ expectedRevision,
72
+ source: "explicit",
73
+ };
74
+ }
75
+
50
76
  function ensureUpdatePayload(args) {
51
77
  const body = compactValue({
52
78
  id: args.id,
@@ -1096,9 +1122,6 @@ async function documentsDeleteTool(ctx, args) {
1096
1122
  }
1097
1123
 
1098
1124
  async function documentsSafeUpdateTool(ctx, args) {
1099
- if (!args.id) {
1100
- throw new CliError("documents.safe_update requires args.id");
1101
- }
1102
1125
  if (args.expectedRevision === undefined || args.expectedRevision === null) {
1103
1126
  throw new CliError("documents.safe_update requires args.expectedRevision");
1104
1127
  }
@@ -1107,31 +1130,49 @@ async function documentsSafeUpdateTool(ctx, args) {
1107
1130
  action: "update a document",
1108
1131
  });
1109
1132
 
1110
- const expectedRevision = Number(args.expectedRevision);
1111
- if (!Number.isFinite(expectedRevision)) {
1112
- throw new CliError("expectedRevision must be a number");
1133
+ const resolved = await resolveMutationDocumentTarget(ctx, args, "documents.safe_update");
1134
+ if (resolved.error || !resolved.id) {
1135
+ return {
1136
+ tool: "documents.safe_update",
1137
+ profile: ctx.profile.id,
1138
+ result: {
1139
+ ok: false,
1140
+ updated: false,
1141
+ status: resolved.error?.failed?.status || "not_found",
1142
+ id: "",
1143
+ resolution: resolved.error,
1144
+ },
1145
+ };
1113
1146
  }
1114
1147
 
1115
- const info = await ctx.client.call("documents.info", { id: args.id }, {
1148
+ const info = await ctx.client.call("documents.info", { id: resolved.id }, {
1116
1149
  maxAttempts: toInteger(args.maxAttempts, 2),
1117
1150
  });
1118
1151
 
1119
1152
  const current = info.body?.data;
1120
1153
  const actualRevision = Number(current?.revision);
1154
+ const expected = resolveExpectedRevisionGuard(args, actualRevision, "documents.safe_update");
1155
+ const expectedRevision = expected.expectedRevision;
1121
1156
 
1122
1157
  if (actualRevision !== expectedRevision) {
1123
1158
  return {
1124
1159
  tool: "documents.safe_update",
1125
1160
  profile: ctx.profile.id,
1126
- result: buildRevisionConflict({
1127
- id: args.id,
1128
- expectedRevision,
1129
- actualRevision,
1130
- }),
1161
+ result: {
1162
+ ...buildRevisionConflict({
1163
+ id: resolved.id,
1164
+ expectedRevision,
1165
+ actualRevision,
1166
+ }),
1167
+ ...(resolved.resolution ? { resolution: resolved.resolution } : {}),
1168
+ },
1131
1169
  };
1132
1170
  }
1133
1171
 
1134
- const updateBody = ensureUpdatePayload(args);
1172
+ const updateBody = ensureUpdatePayload({
1173
+ ...args,
1174
+ id: resolved.id,
1175
+ });
1135
1176
  const updated = await ctx.client.call("documents.update", updateBody, {
1136
1177
  maxAttempts: toInteger(args.maxAttempts, 1),
1137
1178
  });
@@ -1142,7 +1183,9 @@ async function documentsSafeUpdateTool(ctx, args) {
1142
1183
  result: {
1143
1184
  ok: true,
1144
1185
  updated: true,
1145
- id: args.id,
1186
+ id: resolved.id,
1187
+ ...(resolved.resolution ? { resolution: resolved.resolution } : {}),
1188
+ ...(expected.source === "latest" ? { expectedRevision, expectedRevisionSource: "latest" } : {}),
1146
1189
  previousRevision: actualRevision,
1147
1190
  currentRevision: updated.body?.data?.revision,
1148
1191
  data: normalizeDocumentSummary(updated.body?.data, args.view || "summary", toInteger(args.excerptChars, 220)),
@@ -1150,19 +1193,267 @@ async function documentsSafeUpdateTool(ctx, args) {
1150
1193
  };
1151
1194
  }
1152
1195
 
1153
- async function documentsDiffTool(ctx, args) {
1154
- if (!args.id) {
1155
- throw new CliError("documents.diff requires args.id");
1196
+ async function resolveDiffDocument(ctx, args) {
1197
+ if (args.id || args.documentId) {
1198
+ const id = String(args.id || args.documentId);
1199
+ const info = await ctx.client.call("documents.info", { id }, {
1200
+ maxAttempts: toInteger(args.maxAttempts, 2),
1201
+ });
1202
+ return {
1203
+ document: info.body?.data || null,
1204
+ resolution: {
1205
+ mode: "direct",
1206
+ id,
1207
+ memory: null,
1208
+ },
1209
+ };
1156
1210
  }
1211
+
1212
+ const refArgs = compactValue({
1213
+ refs: args.refs || args.documentRefs || (args.documentRef ? [args.documentRef] : undefined),
1214
+ queries: args.queries || args.documentQueries || (args.query ? [args.query] : args.documentQuery ? [args.documentQuery] : undefined),
1215
+ shareIds: args.shareIds || (args.shareId ? [args.shareId] : undefined),
1216
+ urlIds: args.urlIds || (args.urlId ? [args.urlId] : undefined),
1217
+ urls: args.urls || (args.url ? [args.url] : undefined),
1218
+ profile: args.profile,
1219
+ limit: args.resolveLimit,
1220
+ minScore: args.minScore,
1221
+ maxAgeHours: args.maxAgeHours,
1222
+ refresh: args.refresh,
1223
+ strict: args.strict,
1224
+ strictThreshold: args.strictThreshold,
1225
+ fallbackSearch: args.fallbackSearch,
1226
+ fallbackMinScore: args.fallbackMinScore,
1227
+ fallbackLimit: args.fallbackLimit,
1228
+ fallbackMode: args.fallbackMode,
1229
+ collectionId: args.resolveCollectionId,
1230
+ view: "full",
1231
+ concurrency: args.resolveConcurrency,
1232
+ hydrateConcurrency: args.resolveHydrateConcurrency,
1233
+ maxAttempts: args.maxAttempts,
1234
+ }) || {};
1235
+
1236
+ if (!refArgs.refs && !refArgs.queries && !refArgs.shareIds && !refArgs.urlIds && !refArgs.urls) {
1237
+ throw new CliError("documents.diff requires args.id or document refs");
1238
+ }
1239
+
1240
+ const opened = await documentsOpenBatchTool(ctx, refArgs);
1241
+ const item = (opened.result?.items || []).find((row) => row?.ok && row.document?.id)
1242
+ || (opened.result?.items || [])[0]
1243
+ || null;
1244
+ if (item?.ok && item.document) {
1245
+ return {
1246
+ document: item.document,
1247
+ resolution: {
1248
+ mode: item.mode,
1249
+ index: item.index,
1250
+ kind: item.kind,
1251
+ value: item.value,
1252
+ id: item.document.id,
1253
+ title: item.document.title,
1254
+ candidate: item.candidate,
1255
+ memory: item.memory || opened.result?.memory || null,
1256
+ },
1257
+ };
1258
+ }
1259
+
1260
+ return {
1261
+ document: null,
1262
+ resolution: {
1263
+ failed: item
1264
+ ? {
1265
+ index: item.index,
1266
+ kind: item.kind,
1267
+ value: item.value,
1268
+ status: item.status || "not_found",
1269
+ candidate: item.candidate,
1270
+ candidates: item.candidates,
1271
+ error: item.error,
1272
+ }
1273
+ : { status: "not_found" },
1274
+ memory: item?.memory || opened.result?.memory || null,
1275
+ },
1276
+ };
1277
+ }
1278
+
1279
+ async function resolveDocumentIdForRevisionList(ctx, args) {
1280
+ if (args.documentId || args.id) {
1281
+ const id = String(args.documentId || args.id);
1282
+ return {
1283
+ documentId: id,
1284
+ resolution: {
1285
+ mode: "direct",
1286
+ id,
1287
+ memory: null,
1288
+ },
1289
+ };
1290
+ }
1291
+
1292
+ const refArgs = compactValue({
1293
+ refs: args.refs || args.documentRefs || (args.documentRef ? [args.documentRef] : undefined),
1294
+ queries: args.queries || args.documentQueries || (args.query ? [args.query] : args.documentQuery ? [args.documentQuery] : undefined),
1295
+ shareIds: args.shareIds || (args.shareId ? [args.shareId] : undefined),
1296
+ urlIds: args.urlIds || (args.urlId ? [args.urlId] : undefined),
1297
+ urls: args.urls || (args.url ? [args.url] : undefined),
1298
+ profile: args.profile,
1299
+ limit: args.resolveLimit,
1300
+ minScore: args.minScore,
1301
+ maxAgeHours: args.maxAgeHours,
1302
+ refresh: args.refresh,
1303
+ strict: args.strict,
1304
+ strictThreshold: args.strictThreshold,
1305
+ fallbackSearch: args.fallbackSearch,
1306
+ fallbackMinScore: args.fallbackMinScore,
1307
+ fallbackLimit: args.fallbackLimit,
1308
+ fallbackMode: args.fallbackMode,
1309
+ collectionId: args.resolveCollectionId,
1310
+ view: "summary",
1311
+ concurrency: args.resolveConcurrency,
1312
+ hydrateConcurrency: args.resolveHydrateConcurrency,
1313
+ maxAttempts: args.maxAttempts,
1314
+ }) || {};
1315
+
1316
+ if (!refArgs.refs && !refArgs.queries && !refArgs.shareIds && !refArgs.urlIds && !refArgs.urls) {
1317
+ throw new CliError("revisions.list requires args.documentId or document refs");
1318
+ }
1319
+
1320
+ const opened = await documentsOpenBatchTool(ctx, refArgs);
1321
+ const item = (opened.result?.items || []).find((row) => row?.ok && row.document?.id)
1322
+ || (opened.result?.items || [])[0]
1323
+ || null;
1324
+ if (item?.ok && item.document?.id) {
1325
+ return {
1326
+ documentId: item.document.id,
1327
+ resolution: {
1328
+ mode: item.mode,
1329
+ index: item.index,
1330
+ kind: item.kind,
1331
+ value: item.value,
1332
+ id: item.document.id,
1333
+ title: item.document.title,
1334
+ candidate: item.candidate,
1335
+ memory: item.memory || opened.result?.memory || null,
1336
+ },
1337
+ };
1338
+ }
1339
+
1340
+ return {
1341
+ documentId: "",
1342
+ resolution: {
1343
+ failed: item
1344
+ ? {
1345
+ index: item.index,
1346
+ kind: item.kind,
1347
+ value: item.value,
1348
+ status: item.status || "not_found",
1349
+ candidate: item.candidate,
1350
+ candidates: item.candidates,
1351
+ error: item.error,
1352
+ }
1353
+ : { status: "not_found" },
1354
+ memory: item?.memory || opened.result?.memory || null,
1355
+ },
1356
+ };
1357
+ }
1358
+
1359
+ async function resolveMutationDocumentTarget(ctx, args, toolName) {
1360
+ if (args.id || args.documentId) {
1361
+ const id = String(args.id || args.documentId);
1362
+ return {
1363
+ id,
1364
+ resolution: null,
1365
+ };
1366
+ }
1367
+
1368
+ const refArgs = compactValue({
1369
+ refs: args.refs || args.documentRefs || (args.documentRef ? [args.documentRef] : undefined),
1370
+ queries: args.queries || args.documentQueries || (args.query ? [args.query] : args.documentQuery ? [args.documentQuery] : undefined),
1371
+ shareIds: args.shareIds || (args.shareId ? [args.shareId] : undefined),
1372
+ urlIds: args.urlIds || (args.urlId ? [args.urlId] : undefined),
1373
+ urls: args.urls || (args.url ? [args.url] : undefined),
1374
+ profile: args.profile,
1375
+ limit: args.resolveLimit,
1376
+ minScore: args.minScore,
1377
+ maxAgeHours: args.maxAgeHours,
1378
+ refresh: args.refresh,
1379
+ strict: args.strict,
1380
+ strictThreshold: args.strictThreshold,
1381
+ fallbackSearch: args.fallbackSearch,
1382
+ fallbackMinScore: args.fallbackMinScore,
1383
+ fallbackLimit: args.fallbackLimit,
1384
+ fallbackMode: args.fallbackMode,
1385
+ collectionId: args.resolveCollectionId,
1386
+ view: "summary",
1387
+ concurrency: args.resolveConcurrency,
1388
+ hydrateConcurrency: args.resolveHydrateConcurrency,
1389
+ maxAttempts: args.maxAttempts,
1390
+ }) || {};
1391
+
1392
+ if (!refArgs.refs && !refArgs.queries && !refArgs.shareIds && !refArgs.urlIds && !refArgs.urls) {
1393
+ throw new CliError(`${toolName} requires args.id or document refs`);
1394
+ }
1395
+
1396
+ const opened = await documentsOpenBatchTool(ctx, refArgs);
1397
+ const item = (opened.result?.items || []).find((row) => row?.ok && row.document?.id)
1398
+ || (opened.result?.items || [])[0]
1399
+ || null;
1400
+ if (item?.ok && item.document?.id) {
1401
+ return {
1402
+ id: item.document.id,
1403
+ resolution: {
1404
+ mode: item.mode,
1405
+ index: item.index,
1406
+ kind: item.kind,
1407
+ value: item.value,
1408
+ id: item.document.id,
1409
+ title: item.document.title,
1410
+ candidate: item.candidate,
1411
+ memory: item.memory || opened.result?.memory || null,
1412
+ },
1413
+ };
1414
+ }
1415
+
1416
+ return {
1417
+ id: "",
1418
+ error: {
1419
+ failed: item
1420
+ ? {
1421
+ index: item.index,
1422
+ kind: item.kind,
1423
+ value: item.value,
1424
+ status: item.status || "not_found",
1425
+ candidate: item.candidate,
1426
+ candidates: item.candidates,
1427
+ error: item.error,
1428
+ }
1429
+ : { status: "not_found" },
1430
+ memory: item?.memory || opened.result?.memory || null,
1431
+ },
1432
+ };
1433
+ }
1434
+
1435
+ async function documentsDiffTool(ctx, args) {
1157
1436
  if (typeof args.proposedText !== "string") {
1158
1437
  throw new CliError("documents.diff requires args.proposedText as string");
1159
1438
  }
1160
1439
 
1161
- const info = await ctx.client.call("documents.info", { id: args.id }, {
1162
- maxAttempts: toInteger(args.maxAttempts, 2),
1163
- });
1440
+ const resolved = await resolveDiffDocument(ctx, args);
1441
+ const current = resolved.document;
1442
+ if (!current) {
1443
+ return {
1444
+ tool: "documents.diff",
1445
+ profile: ctx.profile.id,
1446
+ result: {
1447
+ ok: false,
1448
+ status: "not_found",
1449
+ resolution: resolved.resolution,
1450
+ stats: { added: 0, removed: 0, unchanged: 0 },
1451
+ hunks: [],
1452
+ truncated: false,
1453
+ },
1454
+ };
1455
+ }
1164
1456
 
1165
- const current = info.body?.data;
1166
1457
  const currentText = current?.text || "";
1167
1458
  const diff = computeLineDiff(currentText, args.proposedText);
1168
1459
  const payload = buildDiffPayload(diff, args);
@@ -1172,9 +1463,10 @@ async function documentsDiffTool(ctx, args) {
1172
1463
  profile: ctx.profile.id,
1173
1464
  result: {
1174
1465
  ok: true,
1175
- id: args.id,
1466
+ id: current.id || args.id || args.documentId,
1176
1467
  revision: current?.revision,
1177
1468
  title: current?.title,
1469
+ resolution: resolved.resolution,
1178
1470
  stats: payload.stats,
1179
1471
  hunks: payload.hunks,
1180
1472
  truncated: payload.truncated,
@@ -1183,20 +1475,86 @@ async function documentsDiffTool(ctx, args) {
1183
1475
  }
1184
1476
 
1185
1477
  async function revisionsDiffTool(ctx, args) {
1186
- if (!args.id) {
1187
- throw new CliError("revisions.diff requires args.id");
1188
- }
1189
- if (!args.baseRevisionId) {
1190
- throw new CliError("revisions.diff requires args.baseRevisionId");
1478
+ const maxAttempts = toInteger(args.maxAttempts, 2);
1479
+ let documentId = args.id || args.documentId || "";
1480
+ let resolution = null;
1481
+ let baseRevisionId = args.baseRevisionId || "";
1482
+ let targetRevisionId = args.targetRevisionId || "";
1483
+
1484
+ if (!documentId) {
1485
+ const resolved = await resolveDocumentIdForRevisionList(ctx, args);
1486
+ documentId = resolved.documentId;
1487
+ resolution = resolved.resolution;
1488
+ if (!documentId) {
1489
+ return {
1490
+ tool: "revisions.diff",
1491
+ profile: ctx.profile.id,
1492
+ result: {
1493
+ ok: false,
1494
+ status: "not_found",
1495
+ id: "",
1496
+ resolution,
1497
+ baseRevisionId: "",
1498
+ targetRevisionId: "",
1499
+ stats: { added: 0, removed: 0, unchanged: 0 },
1500
+ hunks: [],
1501
+ truncated: false,
1502
+ },
1503
+ };
1504
+ }
1505
+ } else {
1506
+ resolution = {
1507
+ mode: "direct",
1508
+ id: documentId,
1509
+ memory: null,
1510
+ };
1191
1511
  }
1192
- if (!args.targetRevisionId) {
1193
- throw new CliError("revisions.diff requires args.targetRevisionId");
1512
+
1513
+ if (!baseRevisionId || !targetRevisionId) {
1514
+ const revisionPair = String(args.revisionPair || "latest").trim().toLowerCase();
1515
+ if (revisionPair !== "latest") {
1516
+ throw new CliError("revisions.diff requires args.baseRevisionId and args.targetRevisionId unless args.revisionPair is latest");
1517
+ }
1518
+ const listRes = await ctx.client.call(
1519
+ "revisions.list",
1520
+ compactValue({
1521
+ documentId,
1522
+ limit: Math.min(20, Math.max(2, toInteger(args.revisionLimit, 2))),
1523
+ offset: 0,
1524
+ sort: args.sort,
1525
+ direction: args.direction,
1526
+ }) || { documentId, limit: 2, offset: 0 },
1527
+ { maxAttempts }
1528
+ );
1529
+ const revisions = Array.isArray(listRes.body?.data) ? listRes.body.data : [];
1530
+ if (revisions.length < 2) {
1531
+ return {
1532
+ tool: "revisions.diff",
1533
+ profile: ctx.profile.id,
1534
+ result: {
1535
+ ok: false,
1536
+ status: "insufficient_revisions",
1537
+ id: documentId,
1538
+ resolution,
1539
+ revisionCount: revisions.length,
1540
+ baseRevisionId: "",
1541
+ targetRevisionId: "",
1542
+ stats: { added: 0, removed: 0, unchanged: 0 },
1543
+ hunks: [],
1544
+ truncated: false,
1545
+ },
1546
+ };
1547
+ }
1548
+ targetRevisionId = String(revisions[0]?.id || "");
1549
+ baseRevisionId = String(revisions[1]?.id || "");
1550
+ if (!baseRevisionId || !targetRevisionId) {
1551
+ throw new CliError("revisions.diff could not derive latest revision IDs from revisions.list");
1552
+ }
1194
1553
  }
1195
1554
 
1196
- const maxAttempts = toInteger(args.maxAttempts, 2);
1197
1555
  const [baseRes, targetRes] = await Promise.all([
1198
- ctx.client.call("revisions.info", { id: args.baseRevisionId }, { maxAttempts }),
1199
- ctx.client.call("revisions.info", { id: args.targetRevisionId }, { maxAttempts }),
1556
+ ctx.client.call("revisions.info", { id: baseRevisionId }, { maxAttempts }),
1557
+ ctx.client.call("revisions.info", { id: targetRevisionId }, { maxAttempts }),
1200
1558
  ]);
1201
1559
 
1202
1560
  const baseRevision = baseRes.body?.data;
@@ -1211,19 +1569,19 @@ async function revisionsDiffTool(ctx, args) {
1211
1569
 
1212
1570
  const baseDocumentId = resolveRevisionDocumentId(baseRevision);
1213
1571
  const targetDocumentId = resolveRevisionDocumentId(targetRevision);
1214
- if (baseDocumentId && baseDocumentId !== args.id) {
1572
+ if (baseDocumentId && baseDocumentId !== documentId) {
1215
1573
  throw new CliError("revisions.diff base revision does not belong to args.id", {
1216
1574
  code: "REVISION_DOCUMENT_MISMATCH",
1217
- id: args.id,
1218
- baseRevisionId: args.baseRevisionId,
1575
+ id: documentId,
1576
+ baseRevisionId,
1219
1577
  revisionDocumentId: baseDocumentId,
1220
1578
  });
1221
1579
  }
1222
- if (targetDocumentId && targetDocumentId !== args.id) {
1580
+ if (targetDocumentId && targetDocumentId !== documentId) {
1223
1581
  throw new CliError("revisions.diff target revision does not belong to args.id", {
1224
1582
  code: "REVISION_DOCUMENT_MISMATCH",
1225
- id: args.id,
1226
- targetRevisionId: args.targetRevisionId,
1583
+ id: documentId,
1584
+ targetRevisionId,
1227
1585
  revisionDocumentId: targetDocumentId,
1228
1586
  });
1229
1587
  }
@@ -1237,9 +1595,11 @@ async function revisionsDiffTool(ctx, args) {
1237
1595
  profile: ctx.profile.id,
1238
1596
  result: {
1239
1597
  ok: true,
1240
- id: args.id,
1241
- baseRevisionId: args.baseRevisionId,
1242
- targetRevisionId: args.targetRevisionId,
1598
+ id: documentId,
1599
+ resolution,
1600
+ revisionPair: !args.baseRevisionId || !args.targetRevisionId ? "latest" : "explicit",
1601
+ baseRevisionId,
1602
+ targetRevisionId,
1243
1603
  baseRevision: normalizeRevisionDiffMeta(baseRevision, view),
1244
1604
  targetRevision: normalizeRevisionDiffMeta(targetRevision, view),
1245
1605
  stats: payload.stats,
@@ -1253,9 +1613,6 @@ async function documentsApplyPatchTool(ctx, args, options = {}) {
1253
1613
  const toolName = options.toolName || "documents.apply_patch";
1254
1614
  const requireExpectedRevision = options.requireExpectedRevision === true;
1255
1615
 
1256
- if (!args.id) {
1257
- throw new CliError(`${toolName} requires args.id`);
1258
- }
1259
1616
  if (typeof args.patch !== "string") {
1260
1617
  throw new CliError(`${toolName} requires args.patch as string`);
1261
1618
  }
@@ -1270,17 +1627,32 @@ async function documentsApplyPatchTool(ctx, args, options = {}) {
1270
1627
  throw new CliError(`${toolName} requires args.expectedRevision`);
1271
1628
  }
1272
1629
 
1273
- const info = await ctx.client.call("documents.info", { id: args.id }, {
1630
+ const resolved = await resolveMutationDocumentTarget(ctx, args, toolName);
1631
+ if (resolved.error || !resolved.id) {
1632
+ return {
1633
+ tool: toolName,
1634
+ profile: ctx.profile.id,
1635
+ result: {
1636
+ ok: false,
1637
+ updated: false,
1638
+ status: resolved.error?.failed?.status || "not_found",
1639
+ id: "",
1640
+ resolution: resolved.error,
1641
+ },
1642
+ };
1643
+ }
1644
+
1645
+ const info = await ctx.client.call("documents.info", { id: resolved.id }, {
1274
1646
  maxAttempts: toInteger(args.maxAttempts, 2),
1275
1647
  });
1276
1648
 
1277
1649
  const current = info.body?.data;
1278
1650
  const currentText = current?.text || "";
1279
1651
  const previousRevision = Number(current?.revision);
1280
- const expectedRevision = hasExpectedRevision ? Number(args.expectedRevision) : undefined;
1281
- if (hasExpectedRevision && !Number.isFinite(expectedRevision)) {
1282
- throw new CliError("expectedRevision must be a number");
1283
- }
1652
+ const expected = hasExpectedRevision
1653
+ ? resolveExpectedRevisionGuard(args, previousRevision, toolName)
1654
+ : { expectedRevision: undefined, source: "none" };
1655
+ const expectedRevision = expected.expectedRevision;
1284
1656
 
1285
1657
  const actualRevision = Number.isFinite(previousRevision) ? previousRevision : undefined;
1286
1658
  if (hasExpectedRevision && actualRevision !== expectedRevision) {
@@ -1289,10 +1661,11 @@ async function documentsApplyPatchTool(ctx, args, options = {}) {
1289
1661
  profile: ctx.profile.id,
1290
1662
  result: {
1291
1663
  ...buildRevisionConflict({
1292
- id: args.id,
1664
+ id: resolved.id,
1293
1665
  expectedRevision,
1294
1666
  actualRevision,
1295
1667
  }),
1668
+ ...(resolved.resolution ? { resolution: resolved.resolution } : {}),
1296
1669
  mode,
1297
1670
  previousRevision: actualRevision,
1298
1671
  },
@@ -1309,7 +1682,8 @@ async function documentsApplyPatchTool(ctx, args, options = {}) {
1309
1682
  result: {
1310
1683
  ok: false,
1311
1684
  updated: false,
1312
- id: args.id,
1685
+ id: resolved.id,
1686
+ ...(resolved.resolution ? { resolution: resolved.resolution } : {}),
1313
1687
  mode,
1314
1688
  previousRevision,
1315
1689
  error: applied.error,
@@ -1321,7 +1695,7 @@ async function documentsApplyPatchTool(ctx, args, options = {}) {
1321
1695
 
1322
1696
  const updateBody = ensureUpdatePayload({
1323
1697
  ...args,
1324
- id: args.id,
1698
+ id: resolved.id,
1325
1699
  text: nextText,
1326
1700
  editMode: "replace",
1327
1701
  });
@@ -1336,7 +1710,9 @@ async function documentsApplyPatchTool(ctx, args, options = {}) {
1336
1710
  result: {
1337
1711
  ok: true,
1338
1712
  updated: true,
1339
- id: args.id,
1713
+ id: resolved.id,
1714
+ ...(resolved.resolution ? { resolution: resolved.resolution } : {}),
1715
+ ...(expected.source === "latest" ? { expectedRevision, expectedRevisionSource: "latest" } : {}),
1340
1716
  mode,
1341
1717
  previousRevision,
1342
1718
  currentRevision: updated.body?.data?.revision,
@@ -1370,13 +1746,13 @@ async function documentsBatchUpdateTool(ctx, args) {
1370
1746
 
1371
1747
  const runner = async (update, index) => {
1372
1748
  try {
1373
- if (!update || typeof update !== "object" || !update.id) {
1374
- throw new CliError(`updates[${index}] must include id`);
1749
+ if (!update || typeof update !== "object") {
1750
+ throw new CliError(`updates[${index}] must be an object`);
1375
1751
  }
1376
1752
 
1377
- const body = ensureUpdatePayload(update);
1378
-
1379
- if (Object.prototype.hasOwnProperty.call(update, "expectedRevision")) {
1753
+ const hasExpectedRevision = Object.prototype.hasOwnProperty.call(update, "expectedRevision");
1754
+ const hasExactId = Boolean(update.id || update.documentId);
1755
+ if (hasExpectedRevision || !hasExactId) {
1380
1756
  const safe = await documentsSafeUpdateTool(ctx, {
1381
1757
  ...update,
1382
1758
  performAction: true,
@@ -1385,21 +1761,26 @@ async function documentsBatchUpdateTool(ctx, args) {
1385
1761
  });
1386
1762
  return {
1387
1763
  index,
1388
- id: update.id,
1764
+ id: safe.result?.id || update.id || update.documentId,
1389
1765
  ok: safe.result?.ok === true,
1390
1766
  result: safe.result,
1391
1767
  };
1392
1768
  }
1393
1769
 
1770
+ const body = ensureUpdatePayload({
1771
+ ...update,
1772
+ id: update.id || update.documentId,
1773
+ });
1774
+
1394
1775
  const updated = await ctx.client.call("documents.update", body, { maxAttempts });
1395
1776
  return {
1396
1777
  index,
1397
- id: update.id,
1778
+ id: body.id,
1398
1779
  ok: true,
1399
1780
  result: {
1400
1781
  ok: true,
1401
1782
  updated: true,
1402
- id: update.id,
1783
+ id: body.id,
1403
1784
  revision: updated.body?.data?.revision,
1404
1785
  data: normalizeDocumentSummary(updated.body?.data, update.view || "summary"),
1405
1786
  },
@@ -1408,12 +1789,12 @@ async function documentsBatchUpdateTool(ctx, args) {
1408
1789
  if (err instanceof ApiError || err instanceof CliError) {
1409
1790
  return {
1410
1791
  index,
1411
- id: update?.id,
1792
+ id: update?.id || update?.documentId,
1412
1793
  ok: false,
1413
1794
  result: {
1414
1795
  ok: false,
1415
1796
  updated: false,
1416
- id: update?.id,
1797
+ id: update?.id || update?.documentId,
1417
1798
  error: {
1418
1799
  code: err instanceof ApiError ? "api_error" : "invalid_input",
1419
1800
  message: err.message,
@@ -1475,12 +1856,24 @@ function normalizeRevisionRow(row, view = "summary") {
1475
1856
  }
1476
1857
 
1477
1858
  async function revisionsListTool(ctx, args) {
1478
- if (!args.documentId) {
1479
- throw new CliError("revisions.list requires args.documentId");
1859
+ const resolved = await resolveDocumentIdForRevisionList(ctx, args);
1860
+ if (!resolved.documentId) {
1861
+ return {
1862
+ tool: "revisions.list",
1863
+ profile: ctx.profile.id,
1864
+ result: {
1865
+ ok: false,
1866
+ status: "not_found",
1867
+ documentId: "",
1868
+ resolution: resolved.resolution,
1869
+ data: [],
1870
+ revisionCount: 0,
1871
+ },
1872
+ };
1480
1873
  }
1481
1874
 
1482
1875
  const body = compactValue({
1483
- documentId: args.documentId,
1876
+ documentId: resolved.documentId,
1484
1877
  limit: toInteger(args.limit, 20),
1485
1878
  offset: toInteger(args.offset, 0),
1486
1879
  sort: args.sort,
@@ -1496,6 +1889,8 @@ async function revisionsListTool(ctx, args) {
1496
1889
 
1497
1890
  const payload = {
1498
1891
  ...res.body,
1892
+ documentId: resolved.documentId,
1893
+ resolution: resolved.resolution,
1499
1894
  data: rows,
1500
1895
  revisionCount: rows.length,
1501
1896
  };
@@ -1544,19 +1939,21 @@ async function revisionsRestoreTool(ctx, args) {
1544
1939
  export const MUTATION_TOOLS = {
1545
1940
  "documents.safe_update": {
1546
1941
  signature:
1547
- "documents.safe_update(args: { id: string; expectedRevision: number; title?: string; text?: string; editMode?: 'replace'|'append'|'prepend'; icon?: string; color?: string; fullWidth?: boolean; templateId?: string; collectionId?: string; insightsEnabled?: boolean; publish?: boolean; dataAttributes?: any[]; view?: 'summary'|'full'; performAction?: boolean })",
1942
+ "documents.safe_update(args: { id?: string; documentId?: string; query?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; expectedRevision: number|'latest'; title?: string; text?: string; editMode?: 'replace'|'append'|'prepend'; icon?: string; color?: string; fullWidth?: boolean; templateId?: string; collectionId?: string; insightsEnabled?: boolean; publish?: boolean; dataAttributes?: any[]; view?: 'summary'|'full'; performAction?: boolean })",
1548
1943
  description: "Update document only if current revision matches expectedRevision.",
1549
1944
  usageExample: {
1550
1945
  tool: "documents.safe_update",
1551
1946
  args: {
1552
- id: "doc-id",
1553
- expectedRevision: 3,
1947
+ query: "incident runbook",
1948
+ expectedRevision: "latest",
1554
1949
  text: "\n\n## Changes\n- added new action",
1555
1950
  editMode: "append",
1556
1951
  },
1557
1952
  },
1558
1953
  bestPractices: [
1559
- "Read document first and pass returned revision as expectedRevision.",
1954
+ "Pass id/documentId for exact targets, or query/refs/url when you only have a remembered title or pasted Outline URL.",
1955
+ "Pass expectedRevision='latest' only when the requested edit should apply to the current revision read inside this tool call.",
1956
+ "Pass a numeric revision from a prior read when coordinating an externally reviewed edit.",
1560
1957
  "Handle revision_conflict deterministically and re-read before retry.",
1561
1958
  "Use append/prepend for low-token incremental writes.",
1562
1959
  "This tool is action-gated; set performAction=true only after explicit confirmation.",
@@ -1565,17 +1962,19 @@ export const MUTATION_TOOLS = {
1565
1962
  },
1566
1963
  "documents.diff": {
1567
1964
  signature:
1568
- "documents.diff(args: { id: string; proposedText: string; includeFullHunks?: boolean; hunkLimit?: number; hunkLineLimit?: number })",
1569
- description: "Compute line-level diff between current document text and proposed text.",
1965
+ "documents.diff(args: { id?: string; documentId?: string; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; proposedText: string; includeFullHunks?: boolean; hunkLimit?: number; hunkLineLimit?: number })",
1966
+ description: "Resolve a document and compute a line-level diff between current document text and proposed text.",
1570
1967
  usageExample: {
1571
1968
  tool: "documents.diff",
1572
1969
  args: {
1573
- id: "doc-id",
1970
+ query: "incident runbook",
1574
1971
  proposedText: "# Title\n\nUpdated body",
1575
1972
  },
1576
1973
  },
1577
1974
  bestPractices: [
1975
+ "Pass id/documentId for exact targets, or query/refs/url when you only have a remembered title or pasted Outline URL.",
1578
1976
  "Run diff before patch/apply to reduce accidental destructive edits.",
1977
+ "Use strict=true defaults for remembered titles so weak fuzzy matches return a structured miss instead of guessing.",
1579
1978
  "Use preview hunks first; request full hunks only when needed.",
1580
1979
  "Track added/removed counts to detect large unintended changes.",
1581
1980
  ],
@@ -1583,20 +1982,21 @@ export const MUTATION_TOOLS = {
1583
1982
  },
1584
1983
  "documents.apply_patch": {
1585
1984
  signature:
1586
- "documents.apply_patch(args: { id: string; patch: string; mode?: 'unified'|'replace'; expectedRevision?: number; title?: string; view?: 'summary'|'full'; performAction?: boolean })",
1985
+ "documents.apply_patch(args: { id?: string; documentId?: string; query?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; patch: string; mode?: 'unified'|'replace'; expectedRevision?: number|'latest'; title?: string; view?: 'summary'|'full'; performAction?: boolean })",
1587
1986
  description: "Apply unified diff patch (or full replace) to a document and persist update.",
1588
1987
  usageExample: {
1589
1988
  tool: "documents.apply_patch",
1590
1989
  args: {
1591
- id: "doc-id",
1990
+ query: "incident runbook",
1592
1991
  expectedRevision: 7,
1593
1992
  mode: "unified",
1594
1993
  patch: "@@ -1,1 +1,1 @@\n-Old\n+New",
1595
1994
  },
1596
1995
  },
1597
1996
  bestPractices: [
1997
+ "Pass id/documentId for exact targets, or query/refs/url when you only have a remembered title or pasted Outline URL.",
1598
1998
  "Prefer unified mode for minimal, auditable text changes.",
1599
- "Pass expectedRevision when coordinating concurrent editors to prevent stale writes.",
1999
+ "Pass expectedRevision='latest' only when the patch should apply to the current revision read inside this tool call; pass a number for externally reviewed edits.",
1600
2000
  "On patch_apply_failed, re-read latest text and regenerate patch.",
1601
2001
  "Use replace mode only for full-document rewrites.",
1602
2002
  "This tool is action-gated; set performAction=true only after explicit confirmation.",
@@ -1605,20 +2005,22 @@ export const MUTATION_TOOLS = {
1605
2005
  },
1606
2006
  "documents.apply_patch_safe": {
1607
2007
  signature:
1608
- "documents.apply_patch_safe(args: { id: string; expectedRevision: number; patch: string; mode?: 'unified'|'replace'; title?: string; view?: 'summary'|'full'; performAction?: boolean })",
2008
+ "documents.apply_patch_safe(args: { id?: string; documentId?: string; query?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; expectedRevision: number|'latest'; patch: string; mode?: 'unified'|'replace'; title?: string; view?: 'summary'|'full'; performAction?: boolean })",
1609
2009
  description:
1610
2010
  "Apply patch with mandatory revision guard so writes only proceed from the expected document revision.",
1611
2011
  usageExample: {
1612
2012
  tool: "documents.apply_patch_safe",
1613
2013
  args: {
1614
- id: "doc-id",
1615
- expectedRevision: 7,
2014
+ query: "incident runbook",
2015
+ expectedRevision: "latest",
1616
2016
  mode: "unified",
1617
2017
  patch: "@@ -1,1 +1,1 @@\n-Old\n+New",
1618
2018
  },
1619
2019
  },
1620
2020
  bestPractices: [
2021
+ "Pass id/documentId for exact targets, or query/refs/url when you only have a remembered title or pasted Outline URL.",
1621
2022
  "Use this wrapper for all automated patch writes to enforce optimistic concurrency.",
2023
+ "Pass expectedRevision='latest' only when the patch should apply to the current revision read inside this tool call; pass a number for externally reviewed edits.",
1622
2024
  "Re-read the document and regenerate patch when revision_conflict is returned.",
1623
2025
  "Keep unified mode for minimal, auditable edits; use replace mode for full rewrites only.",
1624
2026
  "This tool is action-gated; set performAction=true only after explicit confirmation.",
@@ -1627,13 +2029,13 @@ export const MUTATION_TOOLS = {
1627
2029
  },
1628
2030
  "documents.batch_update": {
1629
2031
  signature:
1630
- "documents.batch_update(args: { updates: Array<{ id: string; expectedRevision?: number; title?: string; text?: string; editMode?: 'replace'|'append'|'prepend' }>; concurrency?: number; continueOnError?: boolean; performAction?: boolean })",
2032
+ "documents.batch_update(args: { updates: Array<{ id?: string; documentId?: string; query?: string; refs?: string[]; url?: string; expectedRevision?: number|'latest'; title?: string; text?: string; editMode?: 'replace'|'append'|'prepend' }>; concurrency?: number; continueOnError?: boolean; performAction?: boolean })",
1631
2033
  description: "Run multiple document updates in one call with per-item results.",
1632
2034
  usageExample: {
1633
2035
  tool: "documents.batch_update",
1634
2036
  args: {
1635
2037
  updates: [
1636
- { id: "doc-1", text: "\n\nupdate one", editMode: "append" },
2038
+ { query: "incident runbook", expectedRevision: "latest", text: "\n\nupdate one", editMode: "append" },
1637
2039
  { id: "doc-2", title: "Renamed" },
1638
2040
  ],
1639
2041
  concurrency: 2,
@@ -1641,7 +2043,9 @@ export const MUTATION_TOOLS = {
1641
2043
  },
1642
2044
  },
1643
2045
  bestPractices: [
1644
- "Use expectedRevision per update for multi-agent safety.",
2046
+ "Use query/refs/url per item when batching named documents; fuzzy targets require expectedRevision.",
2047
+ "Use expectedRevision='latest' only when each edit should apply to the current revision read inside that item.",
2048
+ "Use numeric expectedRevision per update for externally reviewed multi-agent safety.",
1645
2049
  "Set continueOnError=false for transactional-style stop-on-first-failure flows.",
1646
2050
  "Use per-item results to retry only failed updates.",
1647
2051
  "This tool is action-gated; set performAction=true only after explicit confirmation.",
@@ -1749,17 +2153,18 @@ export const MUTATION_TOOLS = {
1749
2153
  },
1750
2154
  "revisions.list": {
1751
2155
  signature:
1752
- "revisions.list(args: { documentId: string; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'summary'|'full' })",
1753
- description: "List revisions for a document.",
2156
+ "revisions.list(args: { documentId?: string; id?: string; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'summary'|'full' })",
2157
+ description: "Resolve a document and list its revisions.",
1754
2158
  usageExample: {
1755
2159
  tool: "revisions.list",
1756
2160
  args: {
1757
- documentId: "doc-id",
2161
+ query: "incident runbook",
1758
2162
  limit: 10,
1759
2163
  view: "summary",
1760
2164
  },
1761
2165
  },
1762
2166
  bestPractices: [
2167
+ "Pass documentId/id for exact targets, or query/refs/url when you only have a remembered title or pasted Outline URL.",
1763
2168
  "Use small limits and paginate for long histories.",
1764
2169
  "Capture revision IDs before performing restore operations.",
1765
2170
  "Use summary view for fast planning loops.",
@@ -1768,18 +2173,19 @@ export const MUTATION_TOOLS = {
1768
2173
  },
1769
2174
  "revisions.diff": {
1770
2175
  signature:
1771
- "revisions.diff(args: { id: string; baseRevisionId: string; targetRevisionId: string; includeFullHunks?: boolean; hunkLimit?: number; hunkLineLimit?: number; view?: 'summary'|'full'; maxAttempts?: number })",
1772
- description: "Compute line-level diff between two revisions by hydrating both with revisions.info.",
2176
+ "revisions.diff(args: { id?: string; documentId?: string; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; baseRevisionId?: string; targetRevisionId?: string; revisionPair?: 'latest'; revisionLimit?: number; includeFullHunks?: boolean; hunkLimit?: number; hunkLineLimit?: number; view?: 'summary'|'full'; maxAttempts?: number })",
2177
+ description: "Resolve a document and compute a line-level diff between explicit revision IDs or the latest two revisions.",
1773
2178
  usageExample: {
1774
2179
  tool: "revisions.diff",
1775
2180
  args: {
1776
- id: "doc-id",
1777
- baseRevisionId: "revision-id-older",
1778
- targetRevisionId: "revision-id-newer",
2181
+ query: "incident runbook",
2182
+ revisionPair: "latest",
1779
2183
  view: "summary",
1780
2184
  },
1781
2185
  },
1782
2186
  bestPractices: [
2187
+ "Pass query/refs/url for one-call latest revision diffs when the exact document ID is unknown.",
2188
+ "Pass explicit baseRevisionId and targetRevisionId when comparing non-adjacent revisions.",
1783
2189
  "Pass adjacent revisions first to isolate rollback root causes.",
1784
2190
  "Use preview hunks first; set includeFullHunks=true only when needed.",
1785
2191
  "Verify revision metadata before applying restore or patch actions.",