clay-server 5.2.0-beta.1 → 5.2.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ // Ordinary Mate Knowledge bindings. The service supplies live validation and
2
+ // the already-authorized scope; this module only exposes the Mate operations.
3
+
4
+ function createMateBound(options) {
5
+ var settings = options || {};
6
+ var revalidate = settings.revalidate;
7
+ var initial = settings.initial;
8
+
9
+ function ownScope() {
10
+ return [revalidate().own];
11
+ }
12
+ function db(method, args) {
13
+ var current = revalidate();
14
+ if (!current.databaseService || typeof current.databaseService[method] !== "function") throw new Error("Knowledge databases are unavailable for this Mate.");
15
+ return current.databaseService[method](Object.assign({}, args || {}, { actor: current.actor }));
16
+ }
17
+ function text(method, args) {
18
+ var current = revalidate();
19
+ return settings.textTools[method](current.own, args || {}, current.actor);
20
+ }
21
+ return {
22
+ isClay: false,
23
+ mateId: initial.own.mateId,
24
+ scopeId: initial.own.scopeId,
25
+ listKnowledge: function (args) { return settings.listFor(ownScope(), args || {}, false); },
26
+ searchKnowledge: function (args) { return settings.searchFor(ownScope(), args || {}, false); },
27
+ readKnowledge: function (args) { return settings.readFor(ownScope(), args || {}, false); },
28
+ readKnowledgeDocument: function (args) { return text("read", args); },
29
+ createKnowledgeDocument: function (args) { return text("create", args); },
30
+ updateKnowledgeDocument: function (args) { return text("update", args); },
31
+ listKnowledgeDocumentHistory: function (args) { return text("history", args); },
32
+ restoreKnowledgeDocument: function (args) { return text("restore", args); },
33
+ listDatabases: function (args) { return db("list", args); },
34
+ createDatabase: function (args) { return db("create", args); },
35
+ readDatabase: function (args) { return db("read", args); },
36
+ renameDatabase: function (args) { return db("rename", args); },
37
+ archiveDatabase: function (args) { return db("archive", args); },
38
+ recoverDatabase: function (args) { return db("recover", args); },
39
+ updateDatabaseSchema: function (args) { return db("updateSchema", args); },
40
+ saveTableView: function (args) { return db("saveView", args); },
41
+ queryDatabase: function (args) { return db("query", args); },
42
+ createDatabaseRecord: function (args) { return db("createRecord", args); },
43
+ readDatabaseRecord: function (args) { return db("readRecord", args); },
44
+ updateDatabaseRecord: function (args) { return db("updateRecord", args); },
45
+ archiveDatabaseRecord: function (args) { return db("archiveRecord", args); },
46
+ recoverDatabaseRecord: function (args) { return db("recoverRecord", args); },
47
+ retryDatabaseSync: function (args) { return db("retryProjection", args); },
48
+ importDatabaseRecords: function (args) { return db("importRecords", args); },
49
+ readDatabaseImportProgress: function (args) { return db("readImportProgress", args); },
50
+ };
51
+ }
52
+
53
+ module.exports = { createMateBound: createMateBound };
@@ -9,11 +9,17 @@
9
9
 
10
10
  var buildShape = require("./session-spawn-mcp-server").buildShape;
11
11
  var service = require("./mate-knowledge-service");
12
+ var zod;
13
+ try { zod = require("zod"); } catch (error) { zod = null; }
12
14
 
13
15
  var MATE_CONTRACT =
14
16
  "Your Knowledge is the durable personal and expertise context you own: what you have learned, the material you keep, and your accumulated observations. " +
15
17
  "It is yours alone. There are no other Knowledge collections available to you here, and project Logs are a separate, unrelated surface. " +
18
+ "Use text documents for narrative or multiline Markdown content, and databases for structured records, relationships, filters, and numeric totals. " +
16
19
  "Search it when recalling something specific would genuinely change your answer, and read only the records you actually need. " +
20
+ "Database list and search results are summaries for database discovery, not database row content: discover a database, read its schema, then query_database with stable field ids, typed filters, explicit sorts, bounded pagination, and totals; read individual rows by stable record id. Text search and text-document reads retain their own content and revision semantics. " +
21
+ "For text edits, use the returned document id and revision, reread after a conflict, and retry with the current revision. " +
22
+ "Treat errors as failures. A successful revision/id with indexSyncPending or projectionPending means canonical content was saved but indexing is pending: report that exact state, do not claim it is indexed, and do not blindly retry a mutation that could create a duplicate. " +
17
23
  "Do not enumerate or restate your Knowledge to the user unasked, and never reproduce whole records as filler.";
18
24
 
19
25
  var CLAY_CONTRACT =
@@ -56,24 +62,35 @@ var OPERATION = { type: "string", description: "Stable retry id formatted label_
56
62
  var FIELD = { type: "object", description: "Field with stable id, name, type, required, and type-specific options or reference target." };
57
63
  var FILTER = { type: "object", description: "Validated filter: fieldId, op, and value. Supported ops are eq, neq, contains, gt, gte, lt, lte, empty, not-empty." };
58
64
  var SORT = { type: "object", description: "Validated sort with fieldId and asc or desc direction." };
65
+ var FIELD_SCHEMA = zod ? zod.object({ id: zod.string(), name: zod.string(), type: zod.string(), required: zod.boolean().optional(), options: zod.any().optional(), target: zod.string().optional(), targetDatabaseId: zod.string().optional(), archived: zod.boolean().optional() }) : null;
66
+ var FILTER_SCHEMA = zod ? zod.object({ fieldId: zod.string(), op: zod.string(), value: zod.any().optional() }) : null;
67
+ var SORT_SCHEMA = zod ? zod.object({ fieldId: zod.string(), direction: zod.enum(["asc", "desc"]) }) : null;
68
+ var VALUES_SCHEMA = zod ? zod.record(zod.string(), zod.any()) : null;
69
+ var VIEW_SCHEMA = zod ? zod.object({ id: zod.string(), name: zod.string(), columns: zod.array(zod.string()), filters: zod.array(FILTER_SCHEMA || zod.any()).optional(), sorts: zod.array(SORT_SCHEMA || zod.any()).optional(), archived: zod.boolean().optional() }) : null;
70
+ var IMPORT_ROW_SCHEMA = zod ? zod.object({ sourceKey: zod.string(), sourcePayload: zod.any(), values: zod.record(zod.string(), zod.any()) }) : null;
71
+ var IMPORT_ROW = IMPORT_ROW_SCHEMA ? { schema: IMPORT_ROW_SCHEMA, description: "Source row with sourceKey, immutable JSON sourcePayload, and typed values keyed by stable schema field id. Record references use sourceNamespace/sourceKey, including forward references within this batch." } : { type: "object", description: "Source row with sourceKey, immutable JSON sourcePayload, and typed values keyed by stable schema field id. Record references use sourceNamespace/sourceKey, including forward references within this batch." };
72
+ var DOCUMENT_ID = { type: "string", description: "Stable document id returned by a text-document tool." };
73
+ var DOCUMENT_REVISION = { type: "string", description: "Revision returned by the most recent text-document read or mutation; required for updates and restore." };
59
74
 
60
75
  function databaseTools(bound) {
61
76
  return [
62
- { name: "list_databases", description: "List canonical Knowledge databases, including archived databases when requested, so the Mate can discover and recover them without relying on summary projection.", inputSchema: buildShape({ archived: { type: "boolean" } }, []), handler: handler(bound, "listDatabases") },
63
- { name: "create_database", description: "Create a first-class database in this Mate's Knowledge. Defaults to one required title field and a Table view.", inputSchema: buildShape({ name: { type: "string" }, schema: { type: "array", items: FIELD }, operationId: OPERATION }, ["name", "operationId"]), handler: handler(bound, "createDatabase") },
64
- { name: "read_database", description: "Read one Knowledge database's current schema, views, revision, and record count.", inputSchema: buildShape({ databaseId: ID, includeArchived: { type: "boolean" } }, ["databaseId"]), handler: handler(bound, "readDatabase") },
77
+ { name: "list_databases", description: "Discover canonical Knowledge databases, including archived databases when requested. Results are database summaries only, not row content; read a chosen database before querying it.", inputSchema: buildShape({ archived: { type: "boolean" } }, []), handler: handler(bound, "listDatabases") },
78
+ { name: "create_database", description: "Create a first-class structured database in this Mate's Knowledge. Define typed fields for values, relationships, and numeric totals; use text documents for narrative or multiline material.", inputSchema: buildShape({ name: { type: "string" }, schema: FIELD_SCHEMA ? { schema: zod.array(FIELD_SCHEMA), description: "Typed field descriptors." } : { type: "array", items: FIELD }, operationId: OPERATION }, ["name", "operationId"]), handler: handler(bound, "createDatabase") },
79
+ { name: "read_database", description: "Read one discovered Knowledge database by stable database id to obtain its current schema, views, revision, and record count before querying rows.", inputSchema: buildShape({ databaseId: ID, includeArchived: { type: "boolean" } }, ["databaseId"]), handler: handler(bound, "readDatabase") },
65
80
  { name: "rename_database", description: "Rename a Knowledge database with optimistic revision checking.", inputSchema: buildShape({ databaseId: ID, name: { type: "string" }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "name", "expectedRevision", "operationId"]), handler: handler(bound, "renameDatabase") },
66
81
  { name: "archive_database", description: "Recoverably archive a Knowledge database.", inputSchema: buildShape({ databaseId: ID, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "expectedRevision", "operationId"]), handler: handler(bound, "archiveDatabase") },
67
82
  { name: "recover_database", description: "Recover an archived Knowledge database.", inputSchema: buildShape({ databaseId: ID, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "expectedRevision", "operationId"]), handler: handler(bound, "recoverDatabase") },
68
- { name: "update_database_schema", description: "Replace the schema using stable field ids. Exactly one active title field is required; populated fields cannot be removed or change type and should be archived instead.", inputSchema: buildShape({ databaseId: ID, schema: { type: "array", items: FIELD }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "schema", "expectedRevision", "operationId"]), handler: handler(bound, "updateDatabaseSchema") },
69
- { name: "save_table_view", description: "Create or revise a persisted Table view with selected columns, validated filters, and deterministic sorts.", inputSchema: buildShape({ databaseId: ID, view: { type: "object", description: "View with stable id, name, columns, filters, and sorts." }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "view", "expectedRevision", "operationId"]), handler: handler(bound, "saveTableView") },
70
- { name: "query_database", description: "Query a bounded deterministic page of records using a saved view or explicit validated filters and sorts. Returns count and numeric sums.", inputSchema: buildShape({ databaseId: ID, viewId: ID, filters: { type: "array", items: FILTER }, sorts: { type: "array", items: SORT }, cursor: { type: "string" }, limit: { type: "number" }, archived: { type: "boolean" } }, ["databaseId"]), handler: handler(bound, "queryDatabase") },
71
- { name: "create_database_record", description: "Create a typed record. Values are keyed by stable field id; unknown fields and unsafe keys are rejected.", inputSchema: buildShape({ databaseId: ID, values: { type: "object" }, expectedDatabaseRevision: REVISION, operationId: OPERATION }, ["databaseId", "values", "expectedDatabaseRevision", "operationId"]), handler: handler(bound, "createDatabaseRecord") },
83
+ { name: "update_database_schema", description: "Replace the schema using stable field ids. Exactly one active title field is required; populated fields cannot be removed or change type and should be archived instead.", inputSchema: buildShape({ databaseId: ID, schema: FIELD_SCHEMA ? { schema: zod.array(FIELD_SCHEMA), description: "Complete typed field descriptor array." } : { type: "array", items: FIELD }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "schema", "expectedRevision", "operationId"]), handler: handler(bound, "updateDatabaseSchema") },
84
+ { name: "save_table_view", description: "Create or revise a persisted Table view with selected columns, validated filters, and deterministic sorts.", inputSchema: buildShape({ databaseId: ID, view: VIEW_SCHEMA ? { schema: VIEW_SCHEMA, description: "View with stable id, name, columns, filters, and sorts." } : { type: "object", description: "View with stable id, name, columns, filters, and sorts." }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "view", "expectedRevision", "operationId"]), handler: handler(bound, "saveTableView") },
85
+ { name: "query_database", description: "Query a bounded deterministic page using stable field ids, typed validated filters, explicit sorts, and a cursor. Returns only the requested rows plus count and numeric sums for the same filter scope; do not infer totals from one page.", inputSchema: buildShape({ databaseId: ID, viewId: ID, filters: FILTER_SCHEMA ? { schema: zod.array(FILTER_SCHEMA) } : { type: "array", items: FILTER }, sorts: SORT_SCHEMA ? { schema: zod.array(SORT_SCHEMA) } : { type: "array", items: SORT }, cursor: { type: "string" }, limit: { type: "number" }, archived: { type: "boolean" } }, ["databaseId"]), handler: handler(bound, "queryDatabase") },
86
+ { name: "create_database_record", description: "Create a typed record. Values are keyed by stable field id; unknown fields and unsafe keys are rejected.", inputSchema: buildShape({ databaseId: ID, values: VALUES_SCHEMA ? { schema: VALUES_SCHEMA } : { type: "object" }, expectedDatabaseRevision: REVISION, operationId: OPERATION }, ["databaseId", "values", "expectedDatabaseRevision", "operationId"]), handler: handler(bound, "createDatabaseRecord") },
72
87
  { name: "read_database_record", description: "Read one record with its values, revision, attribution, archive state, and bounded history.", inputSchema: buildShape({ databaseId: ID, recordId: ID }, ["databaseId", "recordId"]), handler: handler(bound, "readDatabaseRecord") },
73
- { name: "update_database_record", description: "Update selected typed values using the record revision. Edits to other fields made since a prior save are not overwritten.", inputSchema: buildShape({ databaseId: ID, recordId: ID, values: { type: "object" }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "recordId", "values", "expectedRevision", "operationId"]), handler: handler(bound, "updateDatabaseRecord") },
88
+ { name: "update_database_record", description: "Update selected typed values using the record revision. Edits to other fields made since a prior save are not overwritten.", inputSchema: buildShape({ databaseId: ID, recordId: ID, values: VALUES_SCHEMA ? { schema: VALUES_SCHEMA } : { type: "object" }, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "recordId", "values", "expectedRevision", "operationId"]), handler: handler(bound, "updateDatabaseRecord") },
74
89
  { name: "archive_database_record", description: "Recoverably archive one record using its current revision.", inputSchema: buildShape({ databaseId: ID, recordId: ID, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "recordId", "expectedRevision", "operationId"]), handler: handler(bound, "archiveDatabaseRecord") },
75
90
  { name: "recover_database_record", description: "Recover one archived record using its current revision.", inputSchema: buildShape({ databaseId: ID, recordId: ID, expectedRevision: REVISION, operationId: OPERATION }, ["databaseId", "recordId", "expectedRevision", "operationId"]), handler: handler(bound, "recoverDatabaseRecord") },
76
91
  { name: "retry_database_sync", description: "Retry the shared append-only Knowledge summary projection after a canonical database mutation reported projectionPending.", inputSchema: buildShape({ databaseId: ID }, ["databaseId"]), handler: handler(bound, "retryDatabaseSync") },
92
+ { name: "import_database_records", description: "Import up to 100 source rows (256 KiB per batch) into a discovered database using immutable source identities and typed values. Use sourceNamespace/sourceKey references for same-batch or already-imported cross-database links; replay the exact operation and payload after uncertainty, and reread the current database revision before a stale retry.", inputSchema: buildShape({ databaseId: ID, expectedDatabaseRevision: REVISION, operationId: OPERATION, sourceNamespace: { type: "string", description: "Stable source namespace for this import mapping." }, rows: IMPORT_ROW_SCHEMA ? { schema: zod.array(IMPORT_ROW_SCHEMA), description: "At most 100 source rows and 256 KiB of serialized row JSON." } : { type: "array", description: "At most 100 source rows and 256 KiB of serialized row JSON.", items: IMPORT_ROW } }, ["databaseId", "expectedDatabaseRevision", "operationId", "sourceNamespace", "rows"]), handler: handler(bound, "importDatabaseRecords") },
93
+ { name: "read_database_import_progress", description: "Read bounded source-to-native record mappings by database id and source namespace. Use returned stable record ids for later corrections; this does not read arbitrary filesystem paths or caller-selected owners.", inputSchema: buildShape({ databaseId: ID, sourceNamespace: { type: "string" }, offset: { type: "number" }, limit: { type: "number", description: "Mapping page size from 1 to 100." } }, ["databaseId", "sourceNamespace"]), handler: handler(bound, "readDatabaseImportProgress") },
77
94
  ].map(function (tool) { tool.description = MATE_CONTRACT + " " + tool.description; return tool; });
78
95
  }
79
96
 
@@ -110,6 +127,36 @@ function mateTools(bound) {
110
127
  }, ["ref"]),
111
128
  handler: handler(bound, "readKnowledge"),
112
129
  },
130
+ {
131
+ name: "read_knowledge_document",
132
+ description: MATE_CONTRACT + " Read the complete current Markdown document by its relative path or stable document id, including its current revision.",
133
+ inputSchema: buildShape({ name: { type: "string", description: "Relative Markdown path under this Mate's Knowledge directory." }, documentId: DOCUMENT_ID }, []),
134
+ handler: handler(bound, "readKnowledgeDocument"),
135
+ },
136
+ {
137
+ name: "create_knowledge_document",
138
+ description: MATE_CONTRACT + " Create a new Markdown document at a safe relative path. Use this for narrative or multiline content; it is synchronized into Knowledge search after the canonical save.",
139
+ inputSchema: buildShape({ name: { type: "string", description: "Relative Markdown path under this Mate's Knowledge directory." }, content: { type: "string", description: "Complete Markdown document content." } }, ["name", "content"]),
140
+ handler: handler(bound, "createKnowledgeDocument"),
141
+ },
142
+ {
143
+ name: "update_knowledge_document",
144
+ description: MATE_CONTRACT + " Update an existing Markdown document by relative path or stable document id. The current revision is mandatory, and stale writes are rejected.",
145
+ inputSchema: buildShape({ name: { type: "string", description: "Relative Markdown path under this Mate's Knowledge directory." }, documentId: DOCUMENT_ID, content: { type: "string", description: "Complete replacement Markdown document content." }, expectedRevision: DOCUMENT_REVISION }, ["content", "expectedRevision"]),
146
+ handler: handler(bound, "updateKnowledgeDocument"),
147
+ },
148
+ {
149
+ name: "list_knowledge_document_history",
150
+ description: MATE_CONTRACT + " List recoverable revisions for one Markdown document by relative path or stable document id.",
151
+ inputSchema: buildShape({ name: { type: "string", description: "Relative Markdown path under this Mate's Knowledge directory." }, documentId: DOCUMENT_ID }, []),
152
+ handler: handler(bound, "listKnowledgeDocumentHistory"),
153
+ },
154
+ {
155
+ name: "restore_knowledge_document",
156
+ description: MATE_CONTRACT + " Restore a selected historical Markdown revision. The current revision is mandatory so a concurrent edit cannot be overwritten.",
157
+ inputSchema: buildShape({ name: { type: "string", description: "Relative Markdown path under this Mate's Knowledge directory." }, documentId: DOCUMENT_ID, version: { type: "string", description: "Version returned by list_knowledge_document_history." }, expectedRevision: DOCUMENT_REVISION }, ["version", "expectedRevision"]),
158
+ handler: handler(bound, "restoreKnowledgeDocument"),
159
+ },
113
160
  ].concat(databaseTools(bound));
114
161
  }
115
162
 
@@ -15,6 +15,8 @@ var builtinMates = require("./builtin-mates");
15
15
  var knowledgeImport = require("./knowledge-import");
16
16
  var knowledgeSearch = require("./knowledge-search");
17
17
  var mateSync = require("./mate-knowledge-sync");
18
+ var textToolsModule = require("./mate-knowledge-text-tools");
19
+ var mateBoundModule = require("./mate-knowledge-mate-bound");
18
20
 
19
21
  var MAX_PAGE = 50;
20
22
  var DEFAULT_PAGE = 20;
@@ -97,6 +99,7 @@ function attachMateKnowledgeService(ctx) {
97
99
  var listMates = context.listMates || function () { return []; };
98
100
  var baseDir = context.baseDir;
99
101
  var importerCache = new Map();
102
+ var textTools = textToolsModule.createMateKnowledgeTextTools({ baseDir: baseDir });
100
103
 
101
104
  function importerForScope(scopeId) {
102
105
  if (context.openImporter) return context.openImporter(scopeId);
@@ -379,6 +382,8 @@ function attachMateKnowledgeService(ctx) {
379
382
  if (source.session) {
380
383
  var manager = project.getSessionManager ? project.getSessionManager() : project.sm;
381
384
  if (!manager || !manager.sessions || manager.sessions.get(source.session.localId) !== source.session) return null;
385
+ if (source.projectOwnerId && source.session.ownerId && source.session.ownerId !== source.projectOwnerId) return null;
386
+ if (isMultiUser() && (!source.projectOwnerId || source.session.ownerId !== source.projectOwnerId)) return null;
382
387
  }
383
388
  if (typeof resolveMate !== "function") return null;
384
389
  var mate = resolveMate(source.projectOwnerId || null, source.mateId);
@@ -422,36 +427,10 @@ function attachMateKnowledgeService(ctx) {
422
427
  // An ordinary Mate's own scope, and nothing else. There is no argument on
423
428
  // any tool that could widen it.
424
429
  function createMateBound(revalidate, initial) {
425
- function ownScope() {
426
- return [revalidate().own];
427
- }
428
- function db(method, args) {
429
- var current = revalidate(); if (!current.databaseService || typeof current.databaseService[method] !== "function") throw new Error("Knowledge databases are unavailable for this Mate.");
430
- return current.databaseService[method](Object.assign({}, args || {}, { actor: current.actor }));
431
- }
432
- return {
433
- isClay: false,
434
- mateId: initial.own.mateId,
435
- scopeId: initial.own.scopeId,
436
- listKnowledge: function (args) { return listFor(ownScope(), args || {}, false); },
437
- searchKnowledge: function (args) { return searchFor(ownScope(), args || {}, false); },
438
- readKnowledge: function (args) { return readFor(ownScope(), args || {}, false); },
439
- listDatabases: function (args) { return db("list", args); },
440
- createDatabase: function (args) { return db("create", args); },
441
- readDatabase: function (args) { return db("read", args); },
442
- renameDatabase: function (args) { return db("rename", args); },
443
- archiveDatabase: function (args) { return db("archive", args); },
444
- recoverDatabase: function (args) { return db("recover", args); },
445
- updateDatabaseSchema: function (args) { return db("updateSchema", args); },
446
- saveTableView: function (args) { return db("saveView", args); },
447
- queryDatabase: function (args) { return db("query", args); },
448
- createDatabaseRecord: function (args) { return db("createRecord", args); },
449
- readDatabaseRecord: function (args) { return db("readRecord", args); },
450
- updateDatabaseRecord: function (args) { return db("updateRecord", args); },
451
- archiveDatabaseRecord: function (args) { return db("archiveRecord", args); },
452
- recoverDatabaseRecord: function (args) { return db("recoverRecord", args); },
453
- retryDatabaseSync: function (args) { return db("retryProjection", args); },
454
- };
430
+ return mateBoundModule.createMateBound({
431
+ revalidate: revalidate, initial: initial, textTools: textTools,
432
+ listFor: listFor, searchFor: searchFor, readFor: readFor,
433
+ });
455
434
  }
456
435
 
457
436
  // Every Mate belonging to the same user, resolved fresh on each call so a
@@ -0,0 +1,106 @@
1
+ // Session-bound text Knowledge mutations for one authorized Mate.
2
+ //
3
+ // This module deliberately uses the existing portable file store and
4
+ // write-through synchronizer. It never accepts a Mate, owner, or filesystem
5
+ // root from a tool caller; the caller supplies only a relative document name
6
+ // or the stable identity returned by the store.
7
+
8
+ var crypto = require("crypto");
9
+ var path = require("path");
10
+ var knowledgeFiles = require("./knowledge-file-store");
11
+ var mateSync = require("./mate-knowledge-sync");
12
+
13
+ function metadataRoot(baseDir, mateDir) {
14
+ var key = crypto.createHash("sha256").update(path.resolve(mateDir)).digest("hex").slice(0, 24);
15
+ return path.join(baseDir || path.join(mateDir, ".clay"), "knowledge-documents", key);
16
+ }
17
+
18
+ function failedSync(summary) {
19
+ if (!summary) return { indexSyncPending: true, syncError: "Knowledge index synchronization returned no result." };
20
+ if (summary.failed === 0) return { indexSyncPending: false, syncError: null };
21
+ var error = summary.errors && summary.errors[0];
22
+ return { indexSyncPending: true, syncError: error && error.message || "Knowledge index synchronization failed." };
23
+ }
24
+
25
+ function createMateKnowledgeTextTools(options) {
26
+ var settings = options || {};
27
+ var stores = new Map();
28
+
29
+ function storeFor(mate) {
30
+ if (!mate || typeof mate.mateDir !== "string") throw new Error("Knowledge text tools require an authorized Mate.");
31
+ var directory = path.resolve(mate.mateDir);
32
+ if (!stores.has(directory)) stores.set(directory, knowledgeFiles.createKnowledgeFileStore(directory, { metaDir: metadataRoot(settings.baseDir, directory) }));
33
+ return stores.get(directory);
34
+ }
35
+
36
+ function find(store, input) {
37
+ var args = input || {};
38
+ var hasName = typeof args.name === "string" && args.name.length > 0;
39
+ var hasId = typeof args.documentId === "string" && args.documentId.length > 0;
40
+ if (!hasName && !hasId) throw new Error("A document name or stable document id is required.");
41
+ var item = null;
42
+ if (hasId) item = store.list().filter(function (entry) { return entry.id === args.documentId; })[0] || null;
43
+ if (hasId && !item) throw Object.assign(new Error("Knowledge document not found."), { code: "ENOENT" });
44
+ if (hasName) {
45
+ var byName = store.read(args.name);
46
+ if (item && item.id !== byName.id) throw new Error("The document name and id identify different documents.");
47
+ item = byName;
48
+ }
49
+ if (!item) throw Object.assign(new Error("Knowledge document not found."), { code: "ENOENT" });
50
+ if (hasId && !hasName) item = store.read(item.name);
51
+ if (item.itemType !== "text") throw Object.assign(new Error("Only Markdown Knowledge documents are writable through these tools."), { code: "READ_ONLY" });
52
+ return item;
53
+ }
54
+
55
+ function sync(mate, name, actor) {
56
+ try {
57
+ var summary = mateSync.syncMateSource({ mateDir: mate.mateDir, fileName: name, baseDir: settings.baseDir, actor: actor });
58
+ return failedSync(summary);
59
+ } catch (error) {
60
+ return { indexSyncPending: true, syncError: error.message || "Knowledge index synchronization failed." };
61
+ }
62
+ }
63
+
64
+ function read(mate, args) {
65
+ var item = find(storeFor(mate), args);
66
+ return { documentId: item.id, name: item.name, content: item.content, revision: item.revision };
67
+ }
68
+
69
+ function create(mate, args, actor) {
70
+ var input = args || {};
71
+ if (typeof input.name !== "string" || !input.name) throw new Error("A document name is required to create a Knowledge document.");
72
+ if (typeof input.content !== "string") throw new Error("Document content is required.");
73
+ var store = storeFor(mate);
74
+ var saved = store.save(input.name, input.content, null);
75
+ return Object.assign({ documentId: saved.id, name: saved.name, revision: saved.revision }, sync(mate, saved.name, actor));
76
+ }
77
+
78
+ function update(mate, args, actor) {
79
+ var input = args || {};
80
+ if (typeof input.expectedRevision !== "string" || !input.expectedRevision) throw Object.assign(new Error("A current document revision is required for updates."), { code: "STALE" });
81
+ if (typeof input.content !== "string") throw new Error("Document content is required.");
82
+ var store = storeFor(mate);
83
+ var current = find(store, input);
84
+ var saved = store.save(current.name, input.content, input.expectedRevision);
85
+ return Object.assign({ documentId: saved.id, name: saved.name, revision: saved.revision }, sync(mate, saved.name, actor));
86
+ }
87
+
88
+ function history(mate, args) {
89
+ var current = find(storeFor(mate), args);
90
+ return { documentId: current.id, name: current.name, versions: storeFor(mate).history(current.id) };
91
+ }
92
+
93
+ function restore(mate, args, actor) {
94
+ var input = args || {};
95
+ if (typeof input.expectedRevision !== "string" || !input.expectedRevision) throw Object.assign(new Error("A current document revision is required for restore."), { code: "STALE" });
96
+ if (typeof input.version !== "string" || !input.version) throw new Error("A history version is required.");
97
+ var store = storeFor(mate);
98
+ var current = find(store, input);
99
+ var restored = store.restore(current.id, input.version, current.name, input.expectedRevision);
100
+ return Object.assign({ documentId: restored.id, name: restored.name, revision: restored.revision }, sync(mate, restored.name, actor));
101
+ }
102
+
103
+ return { read: read, create: create, update: update, history: history, restore: restore };
104
+ }
105
+
106
+ module.exports = { createMateKnowledgeTextTools: createMateKnowledgeTextTools };
@@ -301,7 +301,7 @@ function attachConnection(ctx) {
301
301
  }
302
302
  sendTo(ws, { type: "history_meta", total: total, from: fromIndex });
303
303
  for (var i = fromIndex; i < total; i++) {
304
- sendTo(ws, hydrateImageRefs(active.history[i]));
304
+ sendTo(ws, Object.assign({}, hydrateImageRefs(active.history[i]), { _historyIndex: i }));
305
305
  }
306
306
  var _lastUsage = null, _lastModelUsage = null, _lastCost = null, _lastStreamInputTokens = null;
307
307
  for (var _ri = total - 1; _ri >= 0; _ri--) {
@@ -3,6 +3,7 @@ var fs = require("fs");
3
3
  var path = require("path");
4
4
  var crypto = require("crypto");
5
5
  var mateSync = require("./mate-knowledge-sync");
6
+ var dmDigestCursor = require("./dm-digest-cursor");
6
7
 
7
8
  // Mirror a Mate-owned journal into the Clay-wide Knowledge backend after the
8
9
  // legacy append has already succeeded. Reconciling the whole journal keeps the
@@ -294,6 +295,9 @@ function attachMateInteraction(ctx) {
294
295
  mirrorMateJournal(mateDir, "session-digests.jsonl", job);
295
296
  } catch (e) {
296
297
  console.error("[digest-worker] Write failed for " + job.mateId + ":", e.message);
298
+ if (job.onError) job.onError(e);
299
+ processDigestQueue();
300
+ return;
297
301
  }
298
302
 
299
303
  // Write user observations if present
@@ -422,63 +426,19 @@ function attachMateInteraction(ctx) {
422
426
  // Delta-based: only collects new turns since the last successful digest.
423
427
  // Concurrency debounce: turns that arrive while a digest is in-flight
424
428
  // are naturally batched into the next flush.
425
- var _dmDigestPending = false;
426
- function digestDmTurn(session, responsePreview) {
427
- if (!isMate || _dmDigestPending) return;
429
+ var _dmDigestPending = new WeakSet();
430
+ function digestDmTurn(session) {
431
+ if (!isMate || _dmDigestPending.has(session)) return;
428
432
  var mateId = path.basename(cwd);
429
433
  var mateCtx = matesModule.buildMateCtx(projectOwnerId);
430
434
  if (!matesModule.isMate(mateCtx, mateId)) return;
431
435
 
432
- // Track digest index per session so switching sessions doesn't misalign.
433
- // On resumed sessions (after restart), recover index from the last
434
- // digest_checkpoint entry in history so undigested turns aren't lost.
435
- if (typeof session._dmLastDigestedIndex !== "number") {
436
- session._dmLastDigestedIndex = 0;
437
- for (var ci = session.history.length - 1; ci >= 0; ci--) {
438
- if (session.history[ci].type === "digest_checkpoint") {
439
- session._dmLastDigestedIndex = session.history[ci].digestedIndex;
440
- break;
441
- }
442
- }
443
- }
444
-
445
- // Collect only new turns since the last successful digest
446
- var conversationParts = [];
447
- var totalLen = 0;
448
- var CONV_CAP = 6000;
449
- var startIndex = session._dmLastDigestedIndex;
450
- for (var hi = startIndex; hi < session.history.length; hi++) {
451
- if (totalLen >= CONV_CAP) break;
452
- var entry = session.history[hi];
453
- if (entry.type === "user_message" && entry.text) {
454
- var uText = entry.text;
455
- if (totalLen + uText.length > CONV_CAP) {
456
- uText = uText.substring(0, Math.max(200, CONV_CAP - totalLen)) + "...";
457
- }
458
- conversationParts.push("User: " + uText);
459
- totalLen += uText.length;
460
- } else if (entry.type === "assistant_message" && entry.text) {
461
- var aText = entry.text;
462
- if (totalLen + aText.length > CONV_CAP) {
463
- aText = aText.substring(0, Math.max(200, CONV_CAP - totalLen)) + "...";
464
- }
465
- conversationParts.push("Mate: " + aText);
466
- totalLen += aText.length;
467
- }
468
- }
469
- // If the latest response hasn't landed in history yet, append it
470
- var lastResponseText = responsePreview || "";
471
- if (lastResponseText && conversationParts.length > 0) {
472
- var lastPart = conversationParts[conversationParts.length - 1];
473
- if (lastPart.indexOf("Mate:") !== 0 || lastPart.indexOf(lastResponseText.substring(0, 50)) === -1) {
474
- var rText = lastResponseText;
475
- if (totalLen + rText.length > CONV_CAP) {
476
- rText = rText.substring(0, Math.max(200, CONV_CAP - totalLen)) + "...";
477
- }
478
- conversationParts.push("Mate: " + rText);
479
- }
480
- }
481
- if (conversationParts.length === 0) return;
436
+ // Recover the exact next unread position. Legacy index-only checkpoints
437
+ // remain readable and are treated as fully consumed entries.
438
+ var digestState = dmDigestCursor.readState(session.history);
439
+ var startCursor = digestState.cursor;
440
+ var chunk = dmDigestCursor.collectChunk(session.history, startCursor);
441
+ if (!chunk.conversationContent) return;
482
442
 
483
443
  var mateDir = matesModule.getMateDir(mateCtx, mateId);
484
444
  var knowledgeDir = path.join(mateDir, "knowledge");
@@ -500,8 +460,8 @@ function attachMateInteraction(ctx) {
500
460
  }
501
461
  } catch (e) {}
502
462
 
503
- _dmDigestPending = true;
504
- var snapshotIndex = session.history.length;
463
+ _dmDigestPending.add(session);
464
+ var checkpointCursor = chunk.cursor;
505
465
 
506
466
  enqueueDigest({
507
467
  mateCtx: mateCtx,
@@ -509,17 +469,27 @@ function attachMateInteraction(ctx) {
509
469
  mateId: mateId,
510
470
  type: "dm",
511
471
  priorSummary: priorSummary || "",
512
- conversationContent: conversationParts.join("\n"),
472
+ conversationContent: chunk.conversationContent,
513
473
  onDone: function () {
514
- session._dmLastDigestedIndex = snapshotIndex;
515
- // Persist checkpoint so resumed sessions know where to continue
516
- var checkpoint = { type: "digest_checkpoint", digestedIndex: snapshotIndex };
474
+ // Journal and checkpoint are separate appends: if this append fails,
475
+ // retry may duplicate the saved digest, but must never skip its input.
476
+ var checkpoint = { type: "digest_checkpoint", cursor: checkpointCursor };
477
+ var saved = false;
478
+ try { saved = sm.appendToSessionFile(session, checkpoint) !== false; } catch (e) {
479
+ console.error("[dm-digest] Checkpoint append failed:", e.message);
480
+ }
481
+ if (!saved) {
482
+ _dmDigestPending.delete(session);
483
+ return;
484
+ }
517
485
  session.history.push(checkpoint);
518
- sm.appendToSessionFile(session, checkpoint);
519
- _dmDigestPending = false;
486
+ _dmDigestPending.delete(session);
487
+ if (dmDigestCursor.hasPending(session.history, checkpointCursor)) {
488
+ setImmediate(function () { digestDmTurn(session, ""); });
489
+ }
520
490
  },
521
491
  onError: function () {
522
- _dmDigestPending = false;
492
+ _dmDigestPending.delete(session);
523
493
  },
524
494
  });
525
495
  }
@@ -588,7 +588,9 @@ function attachSessions(ctx) {
588
588
  var targetFrom = typeof msg.target === "number" ? msg.target : before - sm.HISTORY_PAGE_SIZE;
589
589
  var from = sm.findTurnBoundary(session.history, Math.max(0, targetFrom));
590
590
  var to = before;
591
- var items = session.history.slice(from, to).map(hydrateImageRefs);
591
+ var items = session.history.slice(from, to).map(function (item, index) {
592
+ return Object.assign({}, hydrateImageRefs(item), { _historyIndex: from + index });
593
+ });
592
594
  sendTo(ws, {
593
595
  type: "history_prepend",
594
596
  items: items,
package/lib/public/app.js CHANGED
@@ -315,6 +315,8 @@ import { initDebate, handleDebatePreparing, handleDebateStarted, handleDebateRes
315
315
  historyTotal: 0,
316
316
  replayingHistory: false,
317
317
  historyReplayBatch: null,
318
+ pendingSessionEntryNavigation: null,
319
+ sessionNavigationRequestId: null,
318
320
  projectName: projectName,
319
321
  cwd: "",
320
322
  currentSlug: currentSlug,
@@ -550,41 +550,20 @@ body.mate-dm-active .search-clay-transcript .search-clay-message-user .bubble,
550
550
  .clayos-issue-link { --record-color: var(--link, var(--accent)); }
551
551
  .clayos-log-link { --record-color: var(--accent); }
552
552
 
553
- .clayos-session-link {
554
- display: inline-flex;
555
- align-items: center;
556
- gap: 6px;
557
- min-height: 26px;
558
- margin: 2px 1px;
559
- padding: 3px 8px 3px 6px;
560
- border: 1px solid color-mix(in srgb, var(--accent) 28%, var(--border));
561
- border-radius: 7px;
562
- background: color-mix(in srgb, var(--accent) 7%, var(--bg-alt));
563
- color: var(--text);
564
- font: inherit;
565
- font-size: 11px;
566
- line-height: 1;
567
- vertical-align: middle;
568
- cursor: pointer;
553
+ .clayos-session-link { --record-color: var(--accent); }
554
+
555
+ #messages .session-entry-target {
556
+ outline: 2px solid color-mix(in srgb, var(--accent) 72%, transparent);
557
+ outline-offset: 3px;
558
+ border-radius: 8px;
559
+ background: color-mix(in srgb, var(--accent) 7%, transparent);
560
+ animation: sessionEntryTargetFade 1800ms ease-out forwards;
569
561
  }
570
- .clayos-session-link::before {
571
- content: "\2197";
572
- display: grid;
573
- place-items: center;
574
- width: 17px;
575
- height: 17px;
576
- border-radius: 5px;
577
- background: color-mix(in srgb, var(--accent) 14%, transparent);
578
- color: var(--accent);
579
- font-size: 12px;
562
+
563
+ @keyframes sessionEntryTargetFade {
564
+ 0%, 72% { background: color-mix(in srgb, var(--accent) 10%, transparent); }
565
+ 100% { background: transparent; }
580
566
  }
581
- .clayos-session-link > span { font-weight: 620; }
582
- .clayos-session-link > small { color: var(--text-muted); font-size: 10px; }
583
- .clayos-session-link:hover { border-color: color-mix(in srgb, var(--accent) 52%, var(--border)); background: color-mix(in srgb, var(--accent) 11%, var(--bg-alt)); }
584
- .clayos-session-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
585
- .clayos-session-link.is-loading { opacity: 0.62; cursor: progress; }
586
- .clayos-session-link.is-loading::before { animation: searchClaySpin 1.2s linear infinite; }
587
- .clayos-session-link.is-error { border-color: color-mix(in srgb, var(--warning) 48%, var(--border)); }
588
567
 
589
568
  .search-clay-pending {
590
569
  align-self: flex-start;
@@ -350,6 +350,7 @@ export function prependOlderHistory(items, meta) {
350
350
 
351
351
  // Save current rendering state
352
352
  var savedMsgEl = store.get('currentMsgEl');
353
+ var savedReplayingHistory = store.get('replayingHistory');
353
354
  var savedActivity = getActivityEl();
354
355
  var savedFullText = store.get('currentFullText');
355
356
  var savedTurnCounter = getTurnCounter();
@@ -359,7 +360,7 @@ export function prependOlderHistory(items, meta) {
359
360
  var savedUsage = JSON.parse(JSON.stringify(getSessionUsage()));
360
361
 
361
362
  // Reset to initial values for clean rendering
362
- store.set({ currentMsgEl: null, currentFullText: "" });
363
+ store.set({ currentMsgEl: null, currentFullText: "", replayingHistory: true });
363
364
  setActivityEl(null);
364
365
  setTurnCounter(0);
365
366
  resetToolState();
@@ -387,7 +388,7 @@ export function prependOlderHistory(items, meta) {
387
388
  setPrependAnchor(null);
388
389
 
389
390
  // Restore saved state
390
- store.set({ currentMsgEl: savedMsgEl, currentFullText: savedFullText });
391
+ store.set({ currentMsgEl: savedMsgEl, currentFullText: savedFullText, replayingHistory: savedReplayingHistory });
391
392
  setActivityEl(savedActivity);
392
393
  setTurnCounter(savedTurnCounter);
393
394
  restoreToolState(savedToolsState);