@qvac/core 1.0.0-rc.11 → 1.0.0-rc.13

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +66 -1
  2. package/dist-lib/lib/assistant/harness.d.ts +2 -2
  3. package/dist-lib/lib/assistant/history.js +30 -2
  4. package/dist-lib/lib/assistant.js +2 -1
  5. package/dist-lib/lib/core/archived-mesh.js +7 -3
  6. package/dist-lib/lib/core/chat-copy.d.ts +18 -3
  7. package/dist-lib/lib/core/chat-copy.js +73 -23
  8. package/dist-lib/lib/core/chat-group.js +14 -9
  9. package/dist-lib/lib/core/chat-move.d.ts +9 -0
  10. package/dist-lib/lib/core/chat-move.js +94 -3
  11. package/dist-lib/lib/core/chat.js +21 -8
  12. package/dist-lib/lib/core/collections.d.ts +1 -0
  13. package/dist-lib/lib/core/collections.js +1 -0
  14. package/dist-lib/lib/core/contract/activity.js +2 -2
  15. package/dist-lib/lib/core/contract/chat-group.d.ts +1 -0
  16. package/dist-lib/lib/core/contract/chat-group.js +21 -1
  17. package/dist-lib/lib/core/contract/chat.d.ts +9 -0
  18. package/dist-lib/lib/core/contract/chat.js +127 -5
  19. package/dist-lib/lib/core/contract/chunks.d.ts +1 -0
  20. package/dist-lib/lib/core/contract/chunks.js +37 -6
  21. package/dist-lib/lib/core/contract/features.d.ts +21 -0
  22. package/dist-lib/lib/core/contract/features.js +22 -0
  23. package/dist-lib/lib/core/contract/indexing.js +4 -2
  24. package/dist-lib/lib/core/contract/knowledge.js +5 -4
  25. package/dist-lib/lib/core/contract/members.js +2 -2
  26. package/dist-lib/lib/core/contract/projects.d.ts +5 -0
  27. package/dist-lib/lib/core/contract/projects.js +12 -4
  28. package/dist-lib/lib/core/contract/roles.js +30 -4
  29. package/dist-lib/lib/core/contract/run-requests.js +2 -2
  30. package/dist-lib/lib/core/contract/seed-defaults.js +2 -2
  31. package/dist-lib/lib/core/contract/tool-configs.js +3 -2
  32. package/dist-lib/lib/core/contract/workspace.d.ts +2 -0
  33. package/dist-lib/lib/core/contract/workspace.js +40 -7
  34. package/dist-lib/lib/core/contract/writers.js +2 -2
  35. package/dist-lib/lib/core/files/attachments.js +4 -1
  36. package/dist-lib/lib/core/files/index.d.ts +1 -0
  37. package/dist-lib/lib/core/files/index.js +19 -6
  38. package/dist-lib/lib/core/files/processing/index.js +4 -1
  39. package/dist-lib/lib/core/files/rag/build.js +23 -1
  40. package/dist-lib/lib/core/files/rag/load.d.ts +3 -0
  41. package/dist-lib/lib/core/files/rag/load.js +27 -6
  42. package/dist-lib/lib/core/local/index.d.ts +6 -2
  43. package/dist-lib/lib/core/local/index.js +12 -3
  44. package/dist-lib/lib/core/mesh.d.ts +6 -0
  45. package/dist-lib/lib/core/mesh.js +22 -12
  46. package/dist-lib/lib/core/migrations/workspace-from-0-21/index.d.ts +85 -0
  47. package/dist-lib/lib/core/migrations/workspace-from-0-21/index.js +690 -0
  48. package/dist-lib/lib/core/migrations/writer-links.d.ts +0 -1
  49. package/dist-lib/lib/core/migrations/writer-links.js +12 -10
  50. package/dist-lib/lib/core/project-keys.d.ts +6 -0
  51. package/dist-lib/lib/core/project-keys.js +11 -0
  52. package/dist-lib/lib/core/public-mesh.d.ts +2 -0
  53. package/dist-lib/lib/core/public-mesh.js +5 -0
  54. package/dist-lib/lib/core/sync/changed.d.ts +4 -2
  55. package/dist-lib/lib/core/sync/changed.js +1 -1
  56. package/dist-lib/lib/core/sync/index.js +27 -2
  57. package/dist-lib/lib/core/workspace-upgrade.d.ts +6 -0
  58. package/dist-lib/lib/core/workspace-upgrade.js +26 -16
  59. package/dist-lib/lib/core.d.ts +4 -32
  60. package/dist-lib/lib/core.js +143 -482
  61. package/dist-lib/lib/errors.d.ts +4 -0
  62. package/dist-lib/lib/errors.js +4 -0
  63. package/dist-lib/lib/run-transcript.d.ts +2 -1
  64. package/dist-lib/lib/run-transcript.js +11 -5
  65. package/dist-lib/schema/engine.js +2 -1
  66. package/dist-lib/schema/qvac.js +26 -1
  67. package/dist-lib/spec/hrpc/messages.js +17 -8
  68. package/dist-lib/spec/hyperschema/index.js +17 -8
  69. package/dist-lib/spec/hyperschema/schema.json +5 -0
  70. package/dist-lib/spec/hyperschema/types.d.ts +1 -0
  71. package/dist-lib/spec/mesh/hyperdb/db.json +15 -0
  72. package/dist-lib/spec/mesh/hyperdb/index.js +70 -1
  73. package/dist-lib/spec/mesh/hyperdb/messages.js +806 -438
  74. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +18 -0
  75. package/dist-lib/spec/mesh/hyperdispatch/index.js +52 -1
  76. package/dist-lib/spec/mesh/hyperdispatch/messages.js +303 -3
  77. package/dist-lib/spec/mesh/hyperschema/index.js +303 -3
  78. package/dist-lib/spec/mesh/hyperschema/schema.json +146 -0
  79. package/dist-lib/spec/mesh/hyperschema/types.d.ts +39 -0
  80. package/package.json +10 -8
  81. package/tui/README.md +2 -1
  82. package/tui/boot.mjs +2 -0
@@ -1,5 +1,6 @@
1
1
  import { CoreError } from '../errors.js';
2
2
  import { TERMINAL_RUN_STATES } from './contract/run-requests.js';
3
+ import { nextUpdatedAt } from './contract/chat.js';
3
4
  import { mustGetActiveAgent } from './agent.js';
4
5
  import { listChatGroupsIn, mustGetActiveChatGroup } from './chat-group.js';
5
6
  import { appendChunk, listChunks, updateOp } from './chunk.js';
@@ -132,8 +133,12 @@ async function patchChat(store, id, patch) {
132
133
  return patchChatRow(store, await mustGetActiveChat(store, id), patch);
133
134
  }
134
135
  async function patchChatRow(store, current, patch) {
135
- const updated = { ...current, ...patch, updatedAt: Date.now() };
136
- await store.dispatch('put-chat', { chat: updated });
136
+ const updated = {
137
+ ...current,
138
+ ...patch,
139
+ updatedAt: nextUpdatedAt(current.updatedAt, Date.now())
140
+ };
141
+ await store.dispatch('patch-chat', { chat: updated, fields: Object.keys(patch) });
137
142
  return enrichChat(store, updated);
138
143
  }
139
144
  export function renameChat(store, id, title) {
@@ -156,7 +161,11 @@ export async function switchChatAgent(store, id, { deviceId, agentId }) {
156
161
  if (current.agentId === agentId) {
157
162
  return enrichChat(store, current);
158
163
  }
159
- const switched = { ...current, agentId, updatedAt: Date.now() };
164
+ const switched = {
165
+ ...current,
166
+ agentId,
167
+ updatedAt: nextUpdatedAt(current.updatedAt, Date.now())
168
+ };
160
169
  const batch = store.batch();
161
170
  await appendChunk(store, {
162
171
  chatId: id,
@@ -164,7 +173,7 @@ export async function switchChatAgent(store, id, { deviceId, agentId }) {
164
173
  originDeviceId: deviceId,
165
174
  agentSwitch: { agentId, name: agent.name }
166
175
  }, batch);
167
- batch.dispatch('put-chat', { chat: switched });
176
+ batch.dispatch('patch-chat', { chat: switched, fields: ['agentId'] });
168
177
  await batch.flush();
169
178
  await cancelActiveRuns(store, id, {
170
179
  deviceId,
@@ -257,14 +266,18 @@ export async function moveChat(store, id, { groupId, afterId }) {
257
266
  ...chat,
258
267
  rank,
259
268
  rankedAt: Math.max(now, lastActivityAt),
260
- updatedAt: Math.max(now, chat.updatedAt ?? 0)
269
+ updatedAt: nextUpdatedAt(chat.updatedAt, now)
261
270
  });
262
271
  const batch = store.batch();
263
272
  for (const { chat, lastActivityAt, rank } of respaced) {
264
- batch.dispatch('put-chat', { chat: stamp(chat, lastActivityAt, rank) });
273
+ batch.dispatch('patch-chat', {
274
+ chat: stamp(chat, lastActivityAt, rank),
275
+ fields: ['rank', 'rankedAt']
276
+ });
265
277
  }
266
- batch.dispatch('put-chat', {
267
- chat: { ...stamp(moved.chat, moved.lastActivityAt, placement.rank), groupId: target }
278
+ batch.dispatch('patch-chat', {
279
+ chat: { ...stamp(moved.chat, moved.lastActivityAt, placement.rank), groupId: target },
280
+ fields: ['rank', 'rankedAt', 'groupId']
268
281
  });
269
282
  await batch.flush();
270
283
  return enrichChat(store, await mustGetActiveChat(store, id));
@@ -108,3 +108,4 @@ export declare const PROJECT_MEMBER_SEALS = "@qvac/project-member-seals";
108
108
  export declare const PROJECT_HOST_SEALS = "@qvac/project-host-seals";
109
109
  export declare const PROJECT_DEVICE_SEALS = "@qvac/project-device-seals";
110
110
  export declare const SKILL_SECRETS = "@qvac/skill-secrets";
111
+ export declare const MOVED_OUT_CHATS = "@qvac/moved-out-chats";
@@ -108,3 +108,4 @@ export const PROJECT_MEMBER_SEALS = '@qvac/project-member-seals';
108
108
  export const PROJECT_HOST_SEALS = '@qvac/project-host-seals';
109
109
  export const PROJECT_DEVICE_SEALS = '@qvac/project-device-seals';
110
110
  export const SKILL_SECRETS = '@qvac/skill-secrets';
111
+ export const MOVED_OUT_CHATS = '@qvac/moved-out-chats';
@@ -1,5 +1,5 @@
1
1
  import b4a from 'b4a';
2
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
2
+ import { FEATURES, isFeatureSupported } from './features.js';
3
3
  import { DEVICES, DEVICES_BY_WRITER_KEY, DEVICES_BY_MEMBER, LIVE_DEVICES_BY_MEMBER, LIVE_DEVICES_BY_WRITER_KEY, WRITER_ACTIVITY } from '../collections.js';
4
4
  export function trackActivity(handler) {
5
5
  return async (op, ctx) => {
@@ -23,7 +23,7 @@ export function liveDeviceForWriter(db, writerKey) {
23
23
  });
24
24
  }
25
25
  async function indexed(db) {
26
- return (await rulesVersion(db)) >= WORKSPACES_RULES;
26
+ return isFeatureSupported(db, FEATURES.SHIPPED_ROWS_INDEXED);
27
27
  }
28
28
  function ownerOf(device) {
29
29
  return device.memberId ?? device.claimedMemberId ?? null;
@@ -1,2 +1,3 @@
1
1
  import type { Router } from '../../../spec/mesh/hyperdispatch/index.js';
2
+ export declare const PATCHABLE_GROUP: readonly ["name", "rank"];
2
3
  export declare function registerChatGroupRoutes(router: Router): void;
@@ -1,5 +1,8 @@
1
1
  import { trackActivity } from './activity.js';
2
+ import { nextUpdatedAt, patched } from './chat.js';
3
+ import { FEATURES, isFeatureSupported } from './features.js';
2
4
  import { CHAT_GROUPS } from '../collections.js';
5
+ export const PATCHABLE_GROUP = ['name', 'rank'];
3
6
  export function registerChatGroupRoutes(router) {
4
7
  router.add('@qvac/put-chat-group', trackActivity(async ({ group }, { tx, log }) => {
5
8
  const existing = await tx.get(CHAT_GROUPS, { id: group.id });
@@ -7,7 +10,10 @@ export function registerChatGroupRoutes(router) {
7
10
  log?.debug('contract', 'put-chat-group dropped: tombstone is sticky', { id: group.id });
8
11
  return;
9
12
  }
10
- if (existing && !group.deletedAt && existing.updatedAt > group.updatedAt) {
13
+ if (existing &&
14
+ !group.deletedAt &&
15
+ existing.updatedAt > group.updatedAt &&
16
+ !(await isFeatureSupported(tx, FEATURES.KEEP_STALE_PUTS))) {
11
17
  log?.debug('contract', 'put-chat-group dropped: stale updatedAt', { id: group.id });
12
18
  return;
13
19
  }
@@ -17,4 +23,18 @@ export function registerChatGroupRoutes(router) {
17
23
  });
18
24
  return group;
19
25
  }));
26
+ router.add('@qvac/patch-chat-group', trackActivity(async ({ group, fields }, { tx, log }) => {
27
+ const existing = await tx.get(CHAT_GROUPS, { id: group.id });
28
+ if (existing?.deletedAt) {
29
+ log?.debug('contract', 'patch-chat-group dropped: group is deleted', { id: group.id });
30
+ return;
31
+ }
32
+ const row = {
33
+ ...patched(existing ?? group, { from: group, fields, patchable: PATCHABLE_GROUP }),
34
+ updatedAt: nextUpdatedAt(existing?.updatedAt, group.updatedAt)
35
+ };
36
+ await tx.insert(CHAT_GROUPS, row);
37
+ log?.debug('contract', 'chat group patched', { id: group.id });
38
+ return row;
39
+ }));
20
40
  }
@@ -3,6 +3,15 @@ import type { Router } from '../../../spec/mesh/hyperdispatch/index.js';
3
3
  import type { QvacChunk } from '../../../spec/mesh/hyperschema/types.d.ts';
4
4
  export declare function isPurged(tx: HyperDB, chatId: string): Promise<boolean>;
5
5
  export declare function foreignChat(tx: HyperDB, chatId: string | null | undefined): Promise<boolean>;
6
+ export declare function nextUpdatedAt(prev: number | null | undefined, at: number): number;
7
+ export declare const PATCHABLE_CHAT: readonly ["title", "agentId", "ragEnabled", "webSearchEnabled", "groupId", "rank", "rankedAt", "projectId", "knowledgeSourcesOff", "suggestion"];
8
+ export interface Patch<T> {
9
+ readonly from: T;
10
+ readonly fields: readonly string[] | null | undefined;
11
+ readonly patchable: ReadonlyArray<keyof T & string>;
12
+ }
13
+ export declare function patched<T>(row: T, { from, fields, patchable }: Patch<T>): T;
6
14
  export declare function registerChatRoutes(router: Router): void;
15
+ export declare function movedOut(tx: HyperDB, chatId: string): Promise<boolean>;
7
16
  export declare function putChunk(tx: HyperDB, chunk: QvacChunk): Promise<void>;
8
17
  export declare function deleteChatChunks(tx: HyperDB, chatId: string): Promise<void>;
@@ -1,18 +1,42 @@
1
1
  import { liveDeviceForWriter, trackActivity } from './activity.js';
2
2
  import { meshKind } from './mesh-kind.js';
3
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
4
- import { CHATS, CHAT_CHUNKS, CHAT_READS, CHUNKS, CHUNKS_BY_CHAT, CHUNK_COUNTERS, INDEXING_STATUS, INDEXING_STATUS_BY_CHAT, KNOWLEDGE, KNOWLEDGE_ARTIFACTS, KNOWLEDGE_ARTIFACTS_BY_KNOWLEDGE, KNOWLEDGE_BY_CHAT, PURGED_CHATS, TOOL_ACTIVITY, TOOL_ACTIVITY_BY_AGENT } from '../collections.js';
3
+ import { FEATURES, isFeatureSupported } from './features.js';
4
+ import { CHATS, CHAT_CHUNKS, CHAT_READS, CHUNKS, CHUNKS_BY_CHAT, CHUNK_COUNTERS, INDEXING_STATUS, INDEXING_STATUS_BY_CHAT, KNOWLEDGE, KNOWLEDGE_ARTIFACTS, KNOWLEDGE_ARTIFACTS_BY_KNOWLEDGE, KNOWLEDGE_BY_CHAT, MOVED_OUT_CHATS, PURGED_CHATS, TOOL_ACTIVITY, TOOL_ACTIVITY_BY_AGENT } from '../collections.js';
5
5
  export async function isPurged(tx, chatId) {
6
6
  return (await tx.get(PURGED_CHATS, { chatId })) !== null;
7
7
  }
8
8
  export async function foreignChat(tx, chatId) {
9
9
  if (!chatId ||
10
- (await rulesVersion(tx)) < WORKSPACES_RULES ||
10
+ !(await isFeatureSupported(tx, FEATURES.PROJECT_OWN_CHATS)) ||
11
11
  (await meshKind(tx)) !== 'project') {
12
12
  return false;
13
13
  }
14
14
  return (await tx.get(CHATS, { id: chatId })) === null;
15
15
  }
16
+ export function nextUpdatedAt(prev, at) {
17
+ return Math.max(at, (prev ?? 0) + 1);
18
+ }
19
+ export const PATCHABLE_CHAT = [
20
+ 'title',
21
+ 'agentId',
22
+ 'ragEnabled',
23
+ 'webSearchEnabled',
24
+ 'groupId',
25
+ 'rank',
26
+ 'rankedAt',
27
+ 'projectId',
28
+ 'knowledgeSourcesOff',
29
+ 'suggestion'
30
+ ];
31
+ export function patched(row, { from, fields, patchable }) {
32
+ const out = { ...row };
33
+ for (const field of patchable) {
34
+ if (fields?.includes(field)) {
35
+ out[field] = from[field];
36
+ }
37
+ }
38
+ return out;
39
+ }
16
40
  export function registerChatRoutes(router) {
17
41
  router.add('@qvac/put-chat', trackActivity(async ({ chat }, { tx, log }) => {
18
42
  const existing = await tx.get(CHATS, { id: chat.id });
@@ -23,7 +47,10 @@ export function registerChatRoutes(router) {
23
47
  const readThrough = (await frozenRead(tx, existing))
24
48
  ? existing?.readThrough || undefined
25
49
  : Math.max(existing?.readThrough || 0, chat.readThrough || 0) || undefined;
26
- if (existing && !chat.deletedAt && (existing.updatedAt ?? 0) > (chat.updatedAt ?? 0)) {
50
+ if (existing &&
51
+ !chat.deletedAt &&
52
+ (existing.updatedAt ?? 0) > (chat.updatedAt ?? 0) &&
53
+ !(await isFeatureSupported(tx, FEATURES.KEEP_STALE_PUTS))) {
27
54
  if (readThrough === (existing.readThrough || undefined)) {
28
55
  log?.debug('contract', 'put-chat dropped: stale updatedAt', { id: chat.id });
29
56
  return;
@@ -38,10 +65,13 @@ export function registerChatRoutes(router) {
38
65
  }
39
66
  const row = { ...chat, readThrough };
40
67
  await tx.insert(CHATS, row);
68
+ await clearMovedOut(tx, chat.id);
41
69
  log?.debug('contract', existing ? 'chat updated' : 'chat created', { id: chat.id });
42
70
  return row;
43
71
  }));
72
+ router.add('@qvac/patch-chat', trackActivity(patchChat));
44
73
  router.add('@qvac/mark-chat-read', trackActivity(markChatRead));
74
+ router.add('@qvac/remove-chat-copy', trackActivity(removeChatCopy));
45
75
  router.add('@qvac/purge-chat', trackActivity(async ({ chatId, at }, { tx, log }) => {
46
76
  const chat = await tx.get(CHATS, { id: chatId });
47
77
  if (!chat?.deletedAt) {
@@ -58,8 +88,100 @@ export function registerChatRoutes(router) {
58
88
  return purged;
59
89
  }));
60
90
  }
91
+ async function removeChatCopy(op, { tx, log }) {
92
+ const { chatId } = op;
93
+ const chat = await tx.get(CHATS, { id: chatId });
94
+ const moved = chat ? !chat.deletedAt && chat.updatedAt === op.updatedAt : op.updatedAt === 0;
95
+ if (!moved || !(await isFeatureSupported(tx, FEATURES.CHAT_COPY_REMOVAL))) {
96
+ log?.debug('contract', 'remove-chat-copy dropped: the copy changed or is not one', { chatId });
97
+ return;
98
+ }
99
+ await removeNamed(tx, op);
100
+ if (chat && !(await holdsRows(tx, chatId))) {
101
+ await removeChatRow(tx, chatId);
102
+ }
103
+ else {
104
+ await tx.insert(MOVED_OUT_CHATS, { chatId });
105
+ }
106
+ log?.debug('contract', 'chat copy rows removed', { chatId });
107
+ }
108
+ async function removeNamed(tx, op) {
109
+ const { chatId } = op;
110
+ for (const id of op.chunkIds ?? []) {
111
+ const chunk = await tx.get(CHUNKS, { id });
112
+ if (chunk?.chatId === chatId) {
113
+ await tx.delete(CHUNKS, { id });
114
+ await tx.delete(CHAT_CHUNKS, { chatId, seq: chunk.seq });
115
+ }
116
+ }
117
+ for (const id of op.knowledgeIds ?? []) {
118
+ if ((await tx.get(KNOWLEDGE, { id }))?.chatId === chatId) {
119
+ await removeKnowledgeRows(tx, id);
120
+ }
121
+ }
122
+ for (const id of op.toolActivityIds ?? []) {
123
+ if ((await tx.get(TOOL_ACTIVITY, { id }))?.chatId === chatId) {
124
+ await tx.delete(TOOL_ACTIVITY, { id });
125
+ }
126
+ }
127
+ }
128
+ async function holdsRows(tx, chatId) {
129
+ const inChat = { gte: { chatId }, lte: { chatId } };
130
+ for (const index of [CHUNKS_BY_CHAT, KNOWLEDGE_BY_CHAT]) {
131
+ for await (const row of tx.find(index, inChat)) {
132
+ return !!row;
133
+ }
134
+ }
135
+ return false;
136
+ }
137
+ async function removeChatRow(tx, chatId) {
138
+ const inChat = { gte: { chatId }, lte: { chatId } };
139
+ for (const read of await tx.find(CHAT_READS, inChat).toArray()) {
140
+ await tx.delete(CHAT_READS, { chatId, memberId: read.memberId });
141
+ }
142
+ const statuses = tx.find(INDEXING_STATUS_BY_CHAT, inChat);
143
+ for (const status of await statuses.toArray()) {
144
+ await tx.delete(INDEXING_STATUS, { id: status.id });
145
+ }
146
+ await tx.delete(CHATS, { id: chatId });
147
+ await tx.insert(MOVED_OUT_CHATS, { chatId });
148
+ }
149
+ export async function movedOut(tx, chatId) {
150
+ if (!(await isFeatureSupported(tx, FEATURES.CHAT_COPY_REMOVAL))) {
151
+ return false;
152
+ }
153
+ return (await tx.get(MOVED_OUT_CHATS, { chatId })) !== null;
154
+ }
155
+ async function clearMovedOut(tx, chatId) {
156
+ if (await movedOut(tx, chatId)) {
157
+ await tx.delete(MOVED_OUT_CHATS, { chatId });
158
+ }
159
+ }
160
+ async function removeKnowledgeRows(tx, knowledgeId) {
161
+ const ofKnowledge = { gte: { knowledgeId }, lte: { knowledgeId } };
162
+ const artifacts = tx.find(KNOWLEDGE_ARTIFACTS_BY_KNOWLEDGE, ofKnowledge);
163
+ for (const artifact of await artifacts.toArray()) {
164
+ await tx.delete(KNOWLEDGE_ARTIFACTS, { id: artifact.id });
165
+ }
166
+ await tx.delete(KNOWLEDGE, { id: knowledgeId });
167
+ }
168
+ async function patchChat({ chat, fields }, { tx, log }) {
169
+ const existing = await tx.get(CHATS, { id: chat.id });
170
+ if (existing?.deletedAt) {
171
+ log?.debug('contract', 'patch-chat dropped: chat is deleted', { id: chat.id });
172
+ return;
173
+ }
174
+ const row = {
175
+ ...patched(existing ?? chat, { from: chat, fields, patchable: PATCHABLE_CHAT }),
176
+ updatedAt: nextUpdatedAt(existing?.updatedAt, chat.updatedAt ?? 0)
177
+ };
178
+ await tx.insert(CHATS, row);
179
+ await clearMovedOut(tx, chat.id);
180
+ log?.debug('contract', 'chat patched', { id: chat.id });
181
+ return row;
182
+ }
61
183
  async function frozenRead(tx, existing) {
62
- return !!existing && (await rulesVersion(tx)) >= WORKSPACES_RULES;
184
+ return !!existing && (await isFeatureSupported(tx, FEATURES.READ_ON_MEMBER_ROW));
63
185
  }
64
186
  async function markChatRead(read, { tx, node, log }) {
65
187
  const { chatId } = read;
@@ -5,5 +5,6 @@ import type { RouterContext } from './types.ts';
5
5
  export declare function runRequestOf(db: HyperDB, chatId: string, runId: string): Promise<QvacChunk | null>;
6
6
  type Signed = Pick<RouterContext, 'tx' | 'node'>;
7
7
  export declare function ownRunRequest(context: Signed, chatId: string | null | undefined, runId: string): Promise<QvacChunk | null>;
8
+ export declare function mayEditChunk(tx: HyperDB, chunk: QvacChunk, writerKey: Buffer): Promise<boolean>;
8
9
  export declare function registerChunkRoutes(router: Router): void;
9
10
  export {};
@@ -1,11 +1,12 @@
1
1
  import { devicesByWriterKey, liveDeviceForWriter, trackActivity } from './activity.js';
2
- import { deleteChatChunks, foreignChat, isPurged, putChunk } from './chat.js';
2
+ import { deleteChatChunks, foreignChat, isPurged, movedOut, putChunk } from './chat.js';
3
3
  import { appendRow, asModelRequest, closeRounds, hostOutputRefusal, openRound, outputRefusal, roundChunkRefusal, served } from './model-requests.js';
4
4
  import { outsideProject, projectRules, signerMember } from './projects.js';
5
+ import { FEATURES, isFeatureSupported } from './features.js';
5
6
  import { runHasTerminalStatus, runnerRefusal, TERMINAL_RUN_STATES } from './run-requests.js';
6
7
  import { CHUNK_PAYLOAD_FIELDS, ragSourcesWithinBounds } from '../../../schema/qvac.js';
7
8
  import b4a from 'b4a';
8
- import { CHAT_CHUNKS, CHUNKS, CHUNKS_BY_CHAT, DEVICES, RUN_REQUEST_BY_RUN } from '../collections.js';
9
+ import { CHAT_CHUNKS, CHUNKS, CHUNKS_BY_CHAT, DEVICES, RUN_REQUEST_BY_RUN, WRITER_ACTIVITY } from '../collections.js';
9
10
  import { isProbeRound } from '../../probe-rounds.js';
10
11
  const CREDITED_CHUNK_TYPES = new Set(['run-request', 'run-status']);
11
12
  export function runRequestOf(db, chatId, runId) {
@@ -63,6 +64,35 @@ async function isOriginWriter(tx, chunk, writerKey) {
63
64
  const device = await tx.get(DEVICES, { id: chunk.originDeviceId });
64
65
  return !!device?.writerKey && b4a.equals(device.writerKey, writerKey);
65
66
  }
67
+ async function signerDevice(tx, writerKey) {
68
+ const activity = await tx.get(WRITER_ACTIVITY, { writerKey });
69
+ const id = activity?.deviceId ?? (await devicesByWriterKey(tx, writerKey).one())?.id;
70
+ return id ? tx.get(DEVICES, { id }) : null;
71
+ }
72
+ async function isOriginsPerson(tx, chunk, writerKey) {
73
+ const signer = await signerDevice(tx, writerKey);
74
+ if (!signer || signer.revoked) {
75
+ return false;
76
+ }
77
+ if (b4a.equals(signer.id, chunk.originDeviceId)) {
78
+ return true;
79
+ }
80
+ const origin = await tx.get(DEVICES, { id: chunk.originDeviceId });
81
+ const claims = !(await projectRules(tx));
82
+ const [mine, theirs] = [personOf(signer, claims), origin && personOf(origin, claims)];
83
+ if (mine || theirs) {
84
+ return !!mine && !!theirs && b4a.equals(mine, theirs);
85
+ }
86
+ return claims;
87
+ }
88
+ export async function mayEditChunk(tx, chunk, writerKey) {
89
+ const byPerson = chunk.type === 'attachment' && (await isFeatureSupported(tx, FEATURES.PERSON_EDITS_ATTACHMENTS));
90
+ const mayEdit = byPerson ? isOriginsPerson : isOriginWriter;
91
+ return mayEdit(tx, chunk, writerKey);
92
+ }
93
+ function personOf(device, claims) {
94
+ return device.memberId ?? (claims ? device.claimedMemberId : null) ?? null;
95
+ }
66
96
  async function isAdmittedWriter(tx, writerKey) {
67
97
  for await (const device of devicesByWriterKey(tx, writerKey)) {
68
98
  if (!device.revoked)
@@ -86,11 +116,12 @@ export function registerChunkRoutes(router) {
86
116
  if (chunk) {
87
117
  return;
88
118
  }
89
- if (await isPurged(tx, op.chatId)) {
119
+ if (!(await isFeatureSupported(tx, FEATURES.KEEP_LATE_CHUNKS)) &&
120
+ (await isPurged(tx, op.chatId))) {
90
121
  log?.debug('contract', 'append-chunk dropped: chat is purged', { id: op.id });
91
122
  return;
92
123
  }
93
- if (await foreignChat(tx, op.chatId)) {
124
+ if ((await foreignChat(tx, op.chatId)) && !(await movedOut(tx, op.chatId))) {
94
125
  log?.warn('contract', 'append-chunk dropped: the chat is not in this project', {
95
126
  id: op.id
96
127
  });
@@ -185,8 +216,8 @@ export function registerChunkRoutes(router) {
185
216
  log?.debug('contract', 'update-chunk dropped: unknown chunk', { id: op.id });
186
217
  return;
187
218
  }
188
- if (!(await isOriginWriter(tx, chunk, node.key))) {
189
- log?.warn('contract', 'update-chunk dropped: writer is not the origin device', {
219
+ if (!(await mayEditChunk(tx, chunk, node.key))) {
220
+ log?.warn('contract', "update-chunk dropped: writer is not the origin's device", {
190
221
  id: op.id
191
222
  });
192
223
  return;
@@ -0,0 +1,21 @@
1
+ import type HyperDB from 'hyperdb';
2
+ export declare const FEATURES: {
3
+ readonly KEEP_LATE_CHUNKS: 1;
4
+ readonly KEEP_STALE_PUTS: 1;
5
+ readonly PERSON_EDITS_ATTACHMENTS: 1;
6
+ readonly ROLE_ROUTES: 1;
7
+ readonly WORKSPACE_UPGRADE: 1;
8
+ readonly PROJECT_MEMBERSHIP: 1;
9
+ readonly PROJECT_OWN_CHATS: 1;
10
+ readonly KNOWLEDGE_BASE_IN_PROJECT: 1;
11
+ readonly READ_ON_MEMBER_ROW: 1;
12
+ readonly ACCOUNT_OWN_MEMBER: 1;
13
+ readonly ACCOUNT_SEEDS_NO_CHAT: 1;
14
+ readonly TOOL_CONFIGS_WITHOUT_AGENT: 1;
15
+ readonly SHIPPED_ROWS_INDEXED: 1;
16
+ readonly INDEXING_STALE_LEASE: 1;
17
+ readonly OWN_LEAVE_HOLDS: 1;
18
+ readonly CHAT_COPY_REMOVAL: 1;
19
+ };
20
+ export type Feature = (typeof FEATURES)[keyof typeof FEATURES];
21
+ export declare function isFeatureSupported(tx: HyperDB, feature: Feature): Promise<boolean>;
@@ -0,0 +1,22 @@
1
+ import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
2
+ export const FEATURES = {
3
+ KEEP_LATE_CHUNKS: WORKSPACES_RULES,
4
+ KEEP_STALE_PUTS: WORKSPACES_RULES,
5
+ PERSON_EDITS_ATTACHMENTS: WORKSPACES_RULES,
6
+ ROLE_ROUTES: WORKSPACES_RULES,
7
+ WORKSPACE_UPGRADE: WORKSPACES_RULES,
8
+ PROJECT_MEMBERSHIP: WORKSPACES_RULES,
9
+ PROJECT_OWN_CHATS: WORKSPACES_RULES,
10
+ KNOWLEDGE_BASE_IN_PROJECT: WORKSPACES_RULES,
11
+ READ_ON_MEMBER_ROW: WORKSPACES_RULES,
12
+ ACCOUNT_OWN_MEMBER: WORKSPACES_RULES,
13
+ ACCOUNT_SEEDS_NO_CHAT: WORKSPACES_RULES,
14
+ TOOL_CONFIGS_WITHOUT_AGENT: WORKSPACES_RULES,
15
+ SHIPPED_ROWS_INDEXED: WORKSPACES_RULES,
16
+ INDEXING_STALE_LEASE: WORKSPACES_RULES,
17
+ OWN_LEAVE_HOLDS: WORKSPACES_RULES,
18
+ CHAT_COPY_REMOVAL: WORKSPACES_RULES
19
+ };
20
+ export async function isFeatureSupported(tx, feature) {
21
+ return (await rulesVersion(tx)) >= feature;
22
+ }
@@ -1,7 +1,7 @@
1
1
  import { trackActivity } from './activity.js';
2
2
  import { oldestVersion } from './oldest-version.js';
3
3
  import { claimSource } from '../files/index.js';
4
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
4
+ import { FEATURES, isFeatureSupported } from './features.js';
5
5
  import b4a from 'b4a';
6
6
  import { INDEXING_STATUS, INDEXING_STATUS_BY_KNOWLEDGE, KNOWLEDGE, KNOWLEDGE_ARTIFACTS } from '../collections.js';
7
7
  export const INDEXING_CLAIM_TTL_MS = 10 * 60 * 1000;
@@ -122,5 +122,7 @@ export function registerIndexingRoutes(router) {
122
122
  }));
123
123
  }
124
124
  async function claimLeaseMs(tx) {
125
- return (await rulesVersion(tx)) >= WORKSPACES_RULES ? INDEXING_STALE_MS : INDEXING_CLAIM_TTL_MS;
125
+ return (await isFeatureSupported(tx, FEATURES.INDEXING_STALE_LEASE))
126
+ ? INDEXING_STALE_MS
127
+ : INDEXING_CLAIM_TTL_MS;
126
128
  }
@@ -1,17 +1,18 @@
1
1
  import { trackActivity } from './activity.js';
2
- import { foreignChat } from './chat.js';
2
+ import { foreignChat, movedOut } from './chat.js';
3
3
  import { oldestVersion } from './oldest-version.js';
4
4
  import { meshKind } from './mesh-kind.js';
5
5
  import { inProject, signerMember } from './projects.js';
6
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
6
+ import { FEATURES, isFeatureSupported } from './features.js';
7
7
  import { assertArtifactOutput } from '../files/index.js';
8
8
  import { CHATS, KNOWLEDGE, KNOWLEDGE_ARTIFACTS, KNOWLEDGE_CAPS } from '../collections.js';
9
9
  export const KNOWLEDGE_CAP_ROW = 'mesh';
10
10
  async function misplaced(tx, chatId) {
11
11
  if (chatId) {
12
- return foreignChat(tx, chatId);
12
+ return (await foreignChat(tx, chatId)) && !(await movedOut(tx, chatId));
13
13
  }
14
- return (await rulesVersion(tx)) >= WORKSPACES_RULES && (await meshKind(tx)) !== 'project';
14
+ return ((await isFeatureSupported(tx, FEATURES.KNOWLEDGE_BASE_IN_PROJECT)) &&
15
+ (await meshKind(tx)) !== 'project');
15
16
  }
16
17
  export function registerKnowledgeRoutes(router) {
17
18
  router.add('@qvac/add-knowledge', trackActivity(async ({ knowledge }, { tx, log }) => {
@@ -3,7 +3,7 @@ import { bareDeviceProof, claimAttestation, verifyDeviceProof, verifyMemberClaim
3
3
  import { isKickedRow } from '../helpers/index.js';
4
4
  import { liveDeviceForWriter, markWriterLinked, trackActivity } from './activity.js';
5
5
  import { accountKind, sharedKind } from './mesh-kind.js';
6
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
6
+ import { FEATURES, isFeatureSupported } from './features.js';
7
7
  import { admitDevice } from './writers.js';
8
8
  import b4a from 'b4a';
9
9
  import { DEVICES, MEMBERS, MESH_FOUNDERS } from '../collections.js';
@@ -32,7 +32,7 @@ export async function accountMember(tx) {
32
32
  return only;
33
33
  }
34
34
  export async function outsideAccount(tx, memberId) {
35
- if ((await rulesVersion(tx)) < WORKSPACES_RULES || !(await accountKind(tx))) {
35
+ if (!(await isFeatureSupported(tx, FEATURES.ACCOUNT_OWN_MEMBER)) || !(await accountKind(tx))) {
36
36
  return false;
37
37
  }
38
38
  const own = await accountMember(tx);
@@ -19,5 +19,10 @@ export declare function outsideProject(tx: HyperDB, memberId: Buffer | null | un
19
19
  export declare function liveMember(tx: HyperDB, memberId: Buffer, since?: number): Promise<boolean>;
20
20
  export declare function signerMember({ tx, node }: Signed): Promise<Buffer | null>;
21
21
  export declare function projectOfGroup(tx: HyperDB, groupId: string): Promise<QvacProject | null>;
22
+ export interface Birth {
23
+ readonly signer: Buffer;
24
+ readonly groupId?: string | null;
25
+ }
26
+ export declare function bornMembers(tx: HyperDB, { signer, groupId }: Birth): Promise<Buffer[]>;
22
27
  export declare function registerProjectRoutes(router: Router): void;
23
28
  export {};
@@ -1,7 +1,7 @@
1
1
  import { liveDeviceForWriter, liveDevicesOf, trackActivity } from './activity.js';
2
2
  import { meshKind } from './mesh-kind.js';
3
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
4
- import { isWorkspace, readMemberKey, upgradeMembers } from './workspace.js';
3
+ import { FEATURES, isFeatureSupported } from './features.js';
4
+ import { countedMembers, isWorkspace, readMemberKey, upgradeMembers } from './workspace.js';
5
5
  import { dropMemberAgentUses, dropUser } from './agents.js';
6
6
  import { dropMemberHostKeys, dropProjectHostKeys, readProjectHostKey } from './project-host-keys.js';
7
7
  import { dropListingDeviceKeys, dropProjectDeviceKeys, readProjectDeviceKey } from './project-device-keys.js';
@@ -54,7 +54,8 @@ export async function addedSince(tx, memberId, at) {
54
54
  return ((await projectMember(tx, memberId))?.addedAt ?? 0) > at;
55
55
  }
56
56
  export async function projectRules(tx) {
57
- return (await rulesVersion(tx)) >= WORKSPACES_RULES && (await meshKind(tx)) === 'project';
57
+ return ((await isFeatureSupported(tx, FEATURES.PROJECT_MEMBERSHIP)) &&
58
+ (await meshKind(tx)) === 'project');
58
59
  }
59
60
  export async function outsideProject(tx, memberId) {
60
61
  if (!(await projectRules(tx))) {
@@ -78,6 +79,13 @@ export async function projectOfGroup(tx, groupId) {
78
79
  async function namesGroup(tx, groupId) {
79
80
  return groupId === UNGROUPED || !!(await tx.get(CHAT_GROUPS, { id: groupId }));
80
81
  }
82
+ export async function bornMembers(tx, { signer, groupId }) {
83
+ if (!groupId) {
84
+ return [signer];
85
+ }
86
+ const counted = (await countedMembers(tx)).filter((id) => !b4a.equals(id, signer));
87
+ return [signer, ...counted];
88
+ }
81
89
  async function putProject({ project }, context) {
82
90
  const { tx, log } = context;
83
91
  if (!(await isWorkspace(tx))) {
@@ -108,7 +116,7 @@ async function putProject({ project }, context) {
108
116
  }
109
117
  const created = {
110
118
  ...project,
111
- memberIds: [signer],
119
+ memberIds: await bornMembers(tx, { signer, groupId: project.groupId }),
112
120
  createdBy: signer,
113
121
  deletedAt: undefined
114
122
  };
@@ -1,6 +1,7 @@
1
1
  import { CoreError } from '../../errors.js';
2
2
  import { meshKind } from './mesh-kind.js';
3
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
3
+ import { FEATURES, isFeatureSupported } from './features.js';
4
+ import { upgradeWriter } from './workspace.js';
4
5
  const ALL = ['account', 'public', 'workspace', 'project'];
5
6
  const CONTENT = ['public', 'project'];
6
7
  const PRIVATE = ['account', 'project'];
@@ -82,8 +83,33 @@ export const ROUTE_ROLES = {
82
83
  '@qvac/take-run-request': CONTENT,
83
84
  '@qvac/put-skill-secret': ['account'],
84
85
  '@qvac/continue-run-here': CONTENT,
85
- '@qvac/reindex-chat-chunks': CONTENT
86
+ '@qvac/reindex-chat-chunks': CONTENT,
87
+ '@qvac/patch-chat': CONTENT,
88
+ '@qvac/patch-chat-group': CONTENT,
89
+ '@qvac/remove-chat-copy': PROJECT
86
90
  };
91
+ const HISTORY = new Set([
92
+ '@qvac/append-chunk',
93
+ '@qvac/update-chunk',
94
+ '@qvac/resolve-approval',
95
+ '@qvac/add-knowledge',
96
+ '@qvac/remove-knowledge',
97
+ '@qvac/add-knowledge-artifact',
98
+ '@qvac/claim-indexing',
99
+ '@qvac/resolve-indexing',
100
+ '@qvac/put-chat',
101
+ '@qvac/append-tool-activity',
102
+ '@qvac/migrate-agent-catalog',
103
+ '@qvac/put-chat-group',
104
+ '@qvac/purge-chat',
105
+ '@qvac/reindex-chat-chunks'
106
+ ]);
107
+ async function asHistory(name, { tx, node }) {
108
+ if (!HISTORY.has(name)) {
109
+ return false;
110
+ }
111
+ return (await meshKind(tx)) !== 'workspace' || upgradeWriter(tx, node.key);
112
+ }
87
113
  export function inRole(role, route) {
88
114
  return ROUTE_ROLES[route]?.includes(role) ?? false;
89
115
  }
@@ -110,11 +136,11 @@ export function roleDrops(router, role) {
110
136
  add: (name, handler) => router.add(name, inRole(role, name) && !byKind(role)
111
137
  ? handler
112
138
  : async (op, context) => {
113
- if ((await rulesVersion(context.tx)) < WORKSPACES_RULES) {
139
+ if (!(await isFeatureSupported(context.tx, FEATURES.ROLE_ROUTES))) {
114
140
  return handler(op, context);
115
141
  }
116
142
  const applied = byKind(role) ? appliedRole(role, await meshKind(context.tx)) : role;
117
- if (inRole(applied, name)) {
143
+ if (inRole(applied, name) || (await asHistory(name, context))) {
118
144
  return handler(op, context);
119
145
  }
120
146
  context.log?.warn('contract', `${name} dropped: not a route of a ${applied} mesh`);
@@ -2,12 +2,12 @@ import b4a from 'b4a';
2
2
  import { liveDeviceForWriter, trackActivity } from './activity.js';
3
3
  import { putChunk } from './chat.js';
4
4
  import { ownerSigner } from './model-requests.js';
5
- import { WORKSPACES_RULES, rulesVersion } from './mesh-rules.js';
5
+ import { FEATURES, isFeatureSupported } from './features.js';
6
6
  import { chunkTypeOrdinal, terminalRunStates } from '../../../schema/indexes.js';
7
7
  import { CHUNKS, CHUNKS_BY_TYPE, DEVICES, TERMINAL_RUN_STATUSES } from '../collections.js';
8
8
  export const TERMINAL_RUN_STATES = new Set(terminalRunStates);
9
9
  export async function runHasTerminalStatus(tx, chatId, runId) {
10
- if ((await rulesVersion(tx)) < WORKSPACES_RULES) {
10
+ if (!(await isFeatureSupported(tx, FEATURES.SHIPPED_ROWS_INDEXED))) {
11
11
  const type = chunkTypeOrdinal('run-status');
12
12
  const statuses = tx.find(CHUNKS_BY_TYPE, {
13
13
  gte: { chatId, type },