@qvac/core 0.1.4 → 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.
Files changed (105) hide show
  1. package/.claude/skills/asana/SKILL.md +86 -0
  2. package/.claude/skills/compaction/SKILL.md +127 -0
  3. package/.claude/skills/device-mesh-debug/SKILL.md +328 -0
  4. package/.claude/skills/gh-stack/SKILL.md +181 -0
  5. package/.claude/skills/gh-stack/references/commands.md +177 -0
  6. package/.claude/skills/gh-stack/references/stack-design.md +97 -0
  7. package/.claude/skills/gh-stack/references/troubleshooting.md +159 -0
  8. package/.claude/skills/js-house-style/SKILL.md +670 -0
  9. package/.claude/skills/pr-create/SKILL.md +180 -0
  10. package/.claude/skills/pr-review/SKILL.md +216 -0
  11. package/CLAUDE.md +45 -0
  12. package/README.md +10 -5
  13. package/dist-lib/lib/api/agents.js +3 -3
  14. package/dist-lib/lib/api/chat-groups.d.ts +1 -1
  15. package/dist-lib/lib/api/chat-groups.js +5 -3
  16. package/dist-lib/lib/api/chat.js +2 -2
  17. package/dist-lib/lib/api/current-mesh.d.ts +3 -2
  18. package/dist-lib/lib/api/current-mesh.js +4 -3
  19. package/dist-lib/lib/api/devices.js +1 -0
  20. package/dist-lib/lib/api/index.js +2 -0
  21. package/dist-lib/lib/api/members.d.ts +3 -0
  22. package/dist-lib/lib/api/members.js +23 -0
  23. package/dist-lib/lib/api/mesh.d.ts +14 -3
  24. package/dist-lib/lib/api/mesh.js +20 -3
  25. package/dist-lib/lib/api/watchable.d.ts +1 -1
  26. package/dist-lib/lib/api/watchable.js +1 -1
  27. package/dist-lib/lib/assistant.js +2 -1
  28. package/dist-lib/lib/core/agent.d.ts +1 -0
  29. package/dist-lib/lib/core/agent.js +29 -1
  30. package/dist-lib/lib/core/chat-group.d.ts +4 -0
  31. package/dist-lib/lib/core/chat-group.js +43 -1
  32. package/dist-lib/lib/core/chat.d.ts +10 -0
  33. package/dist-lib/lib/core/chat.js +75 -9
  34. package/dist-lib/lib/core/contract/index.js +2 -0
  35. package/dist-lib/lib/core/contract/joined-meshes.d.ts +2 -0
  36. package/dist-lib/lib/core/contract/joined-meshes.js +41 -0
  37. package/dist-lib/lib/core/contract/members.js +68 -2
  38. package/dist-lib/lib/core/contract/writers.js +19 -3
  39. package/dist-lib/lib/core/departures.d.ts +3 -1
  40. package/dist-lib/lib/core/departures.js +6 -4
  41. package/dist-lib/lib/core/device-attestation.d.ts +8 -0
  42. package/dist-lib/lib/core/device-attestation.js +25 -0
  43. package/dist-lib/lib/core/device-invites.d.ts +9 -0
  44. package/dist-lib/lib/core/device-invites.js +40 -0
  45. package/dist-lib/lib/core/files/index.d.ts +2 -1
  46. package/dist-lib/lib/core/files/index.js +1 -1
  47. package/dist-lib/lib/core/files/store/index.d.ts +1 -0
  48. package/dist-lib/lib/core/files/store/server.d.ts +5 -4
  49. package/dist-lib/lib/core/files/store/server.js +10 -6
  50. package/dist-lib/lib/core/helpers/index.d.ts +1 -1
  51. package/dist-lib/lib/core/hosted-agents.d.ts +3 -1
  52. package/dist-lib/lib/core/hosted-agents.js +9 -3
  53. package/dist-lib/lib/core/identity.d.ts +10 -0
  54. package/dist-lib/lib/core/identity.js +45 -0
  55. package/dist-lib/lib/core/invite.d.ts +3 -0
  56. package/dist-lib/lib/core/invite.js +8 -2
  57. package/dist-lib/lib/core/local/index.d.ts +22 -7
  58. package/dist-lib/lib/core/local/index.js +202 -66
  59. package/dist-lib/lib/core/membership.d.ts +8 -2
  60. package/dist-lib/lib/core/membership.js +33 -9
  61. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +17 -0
  62. package/dist-lib/lib/core/mesh-seed-handoff.js +34 -0
  63. package/dist-lib/lib/core/mesh.d.ts +13 -1
  64. package/dist-lib/lib/core/mesh.js +61 -8
  65. package/dist-lib/lib/core/migrations/index.d.ts +3 -1
  66. package/dist-lib/lib/core/migrations/index.js +2 -2
  67. package/dist-lib/lib/core/migrations/membership.js +27 -15
  68. package/dist-lib/lib/core/rank.d.ts +14 -0
  69. package/dist-lib/lib/core/rank.js +23 -0
  70. package/dist-lib/lib/core/sync/index.js +6 -0
  71. package/dist-lib/lib/core.d.ts +91 -13
  72. package/dist-lib/lib/core.js +1051 -207
  73. package/dist-lib/schema/build.js +3 -2
  74. package/dist-lib/schema/engine.js +153 -9
  75. package/dist-lib/schema/field-order.js +4 -1
  76. package/dist-lib/schema/local.js +32 -0
  77. package/dist-lib/schema/qvac.js +45 -6
  78. package/dist-lib/spec/bind.js +35 -0
  79. package/dist-lib/spec/calls.js +37 -27
  80. package/dist-lib/spec/capabilities.d.ts +30 -10
  81. package/dist-lib/spec/hrpc/hrpc.json +135 -5
  82. package/dist-lib/spec/hrpc/index.js +130 -9
  83. package/dist-lib/spec/hrpc/messages.js +408 -14
  84. package/dist-lib/spec/hyperschema/index.js +408 -14
  85. package/dist-lib/spec/hyperschema/schema.json +309 -1
  86. package/dist-lib/spec/hyperschema/types.d.ts +90 -1
  87. package/dist-lib/spec/local/hyperdb/db.json +46 -1
  88. package/dist-lib/spec/local/hyperdb/index.js +209 -2
  89. package/dist-lib/spec/local/hyperdb/messages.js +557 -90
  90. package/dist-lib/spec/local/hyperschema/index.js +240 -2
  91. package/dist-lib/spec/local/hyperschema/schema.json +120 -1
  92. package/dist-lib/spec/local/hyperschema/types.d.ts +33 -1
  93. package/dist-lib/spec/mesh/hyperdb/db.json +16 -1
  94. package/dist-lib/spec/mesh/hyperdb/index.js +71 -2
  95. package/dist-lib/spec/mesh/hyperdb/messages.js +571 -192
  96. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +13 -1
  97. package/dist-lib/spec/mesh/hyperdispatch/index.js +35 -1
  98. package/dist-lib/spec/mesh/hyperdispatch/messages.js +283 -20
  99. package/dist-lib/spec/mesh/hyperschema/index.js +283 -20
  100. package/dist-lib/spec/mesh/hyperschema/schema.json +179 -1
  101. package/dist-lib/spec/mesh/hyperschema/types.d.ts +45 -1
  102. package/package.json +6 -6
  103. package/tui/app.mjs +416 -50
  104. package/tui/boot.mjs +1 -1
  105. package/tui/lib/sidebar.mjs +3 -2
@@ -2,6 +2,20 @@ import { watchable } from "./watchable.js";
2
2
  export function createMeshApi(status) {
3
3
  return {
4
4
  meshStatusWatch: watchable('meshStatusWatch', () => status, async () => status.snapshot()),
5
+ listMeshes: () => status.list(),
6
+ meshesWatch: watchable('meshesWatch', () => status, () => status.list()),
7
+ openMesh: async ({ meshId }) => {
8
+ await status.open(meshId);
9
+ return { ok: true };
10
+ },
11
+ selectMesh: async ({ meshId }) => {
12
+ await status.select(meshId);
13
+ return { ok: true };
14
+ },
15
+ closeMesh: async ({ meshId }) => {
16
+ await status.close(meshId);
17
+ return { ok: true };
18
+ },
5
19
  leaveMesh: async () => {
6
20
  await status.leave();
7
21
  return { ok: true };
@@ -18,8 +32,11 @@ export function createMeshApi(status) {
18
32
  status.cancelJoin();
19
33
  return { ok: true };
20
34
  },
21
- meshInvite: async () => ({
22
- invite: (await status.invite()) ?? undefined
23
- })
35
+ meshInvite: async ({ member, meshId }) => status.invite(member ?? false, meshId ?? undefined),
36
+ setMeshLabel: async ({ meshId, label }) => {
37
+ await status.label(meshId, label ?? '');
38
+ return { ok: true };
39
+ },
40
+ createRoom: async () => ({ meshId: await status.createRoom() })
24
41
  };
25
42
  }
@@ -8,5 +8,5 @@ interface WatchableStore {
8
8
  closing?: unknown;
9
9
  closed?: boolean;
10
10
  }
11
- export declare function watchable<TRequest, TResult, TStore extends WatchableStore = WatchableStore>(name: string, storeOf: () => TStore | null | Promise<TStore | null>, query: (request: TRequest, store: TStore) => Promise<TResult>): (request: TRequest) => Readable & AsyncIterable<TResult>;
11
+ export declare function watchable<TRequest, TResult, TStore extends WatchableStore = WatchableStore>(name: string, storeOf: (request: TRequest) => TStore | null | Promise<TStore | null>, query: (request: TRequest, store: TStore) => Promise<TResult>): (request: TRequest) => Readable & AsyncIterable<TResult>;
12
12
  export {};
@@ -26,7 +26,7 @@ function isRecord(value) {
26
26
  }
27
27
  export function watchable(name, storeOf, query) {
28
28
  return (request) => {
29
- const resolved = storeOf();
29
+ const resolved = storeOf(request);
30
30
  const pending = resolved instanceof Promise ? resolved.catch(noop) : null;
31
31
  let store = resolved instanceof Promise ? null : resolved;
32
32
  let dirty = true;
@@ -421,7 +421,8 @@ export function historyFromChunks(chunks, stale = {}) {
421
421
  const loaded = chunk.toolResult.result?.name;
422
422
  if (typeof loaded === 'string' && !replayedSkills.has(loaded)) {
423
423
  replayedSkills.add(loaded);
424
- history.push({ role: 'tool', content: skillLoadedTurn(loaded) });
424
+ const at = history.indexOf(anchor(chunk.runId)) + 1;
425
+ history.splice(at, 0, { role: 'tool', content: skillLoadedTurn(loaded) });
425
426
  }
426
427
  continue;
427
428
  }
@@ -10,6 +10,7 @@ export declare function liveProviderIds(store: Mesh): Promise<Set<string>>;
10
10
  export declare function mustGetAgent(store: Mesh, id: string): Promise<QvacAgent>;
11
11
  export declare function mustGetActiveAgent(store: Mesh, id: string): Promise<QvacAgent>;
12
12
  export declare function createAgent(store: Mesh, input: CreateAgentInput): Promise<QvacAgent>;
13
+ export declare function ownDefaultAgents(store: Mesh): Promise<QvacAgent[]>;
13
14
  export declare function updateAgent(store: Mesh, input: UpdateAgentInput): Promise<QvacAgent>;
14
15
  export declare function deleteAgent(store: Mesh, deviceId: Buffer | null, id: string): Promise<QvacAgent>;
15
16
  export {};
@@ -82,7 +82,7 @@ export async function createAgent(store, input) {
82
82
  enabledSkills,
83
83
  enabledTools,
84
84
  installedSkills: mergeSkills(installedBase, enabledSkills),
85
- isDefault: false,
85
+ isDefault: input.isDefault ?? false,
86
86
  createdAt: now,
87
87
  updatedAt: now,
88
88
  deletedAt: undefined,
@@ -102,8 +102,35 @@ export async function createAgent(store, input) {
102
102
  await store.dispatch('put-agent', { agent });
103
103
  return agent;
104
104
  }
105
+ export async function ownDefaultAgents(store) {
106
+ const self = store.ourDeviceId;
107
+ const ours = store.ourMemberId;
108
+ const own = [];
109
+ const snap = store.view.snapshot();
110
+ try {
111
+ for await (const agent of snap.find(AGENTS)) {
112
+ if (agent.deletedAt || !agent.isDefault || !agent.providerDeviceId)
113
+ continue;
114
+ const host = await snap.get(DEVICES, { id: agent.providerDeviceId });
115
+ if (!host || host.revoked)
116
+ continue;
117
+ if (self?.equals(host.id) || (ours && host.memberId?.equals(ours)))
118
+ own.push(agent);
119
+ }
120
+ return own;
121
+ }
122
+ finally {
123
+ await snap.close();
124
+ }
125
+ }
105
126
  export async function updateAgent(store, input) {
106
127
  const current = await mustGetActiveAgent(store, input.id);
128
+ if (input.clearIsDefault && current.isDefault) {
129
+ const own = await ownDefaultAgents(store);
130
+ if (own.length === 1 && own[0].id === current.id) {
131
+ throw new Error('cannot clear the last default agent of this member');
132
+ }
133
+ }
107
134
  const enabledSkills = patch(input.enabledSkills, current.enabledSkills);
108
135
  const installedBase = patch(input.installedSkills, current.installedSkills);
109
136
  const imageBase = input.clearImageSettings
@@ -119,6 +146,7 @@ export async function updateAgent(store, input) {
119
146
  enabledSkills,
120
147
  enabledTools: patch(input.enabledTools, current.enabledTools),
121
148
  installedSkills: mergeSkills(installedBase, enabledSkills),
149
+ isDefault: input.clearIsDefault ? false : input.isDefault || current.isDefault,
122
150
  imageModelChoice: patch(input.imageModelChoice, imageBase.imageModelChoice),
123
151
  kvCacheK: patch(input.kvCacheK, current.kvCacheK),
124
152
  kvCacheV: patch(input.kvCacheV, current.kvCacheV),
@@ -1,6 +1,7 @@
1
1
  import type HyperDB from 'hyperdb';
2
2
  import type { QvacChatGroup } from '../../spec/mesh/hyperschema/types.d.ts';
3
3
  import type { Mesh } from './mesh.ts';
4
+ export declare function groupSortKey(group: QvacChatGroup): number;
4
5
  export declare function byGroupOrder(a: QvacChatGroup, b: QvacChatGroup): number;
5
6
  export declare function listChatGroupsIn(snap: HyperDB): Promise<QvacChatGroup[]>;
6
7
  export declare function listChatGroups(store: Mesh): Promise<QvacChatGroup[]>;
@@ -11,4 +12,7 @@ export declare function createChatGroup(store: Mesh, input: {
11
12
  name: string;
12
13
  }): Promise<QvacChatGroup>;
13
14
  export declare function renameChatGroup(store: Mesh, id: string, name: string): Promise<QvacChatGroup>;
15
+ export declare function moveChatGroup(store: Mesh, id: string, { afterId }: {
16
+ afterId?: string | null;
17
+ }): Promise<QvacChatGroup>;
14
18
  export declare function deleteChatGroup(store: Mesh, id: string): Promise<QvacChatGroup>;
@@ -1,9 +1,13 @@
1
1
  import { randomId } from "./id.js";
2
+ import { place } from "./rank.js";
2
3
  const CHAT_GROUPS = '@qvac/chat-groups';
3
4
  const ACTIVE_CHAT_GROUPS = '@qvac/active-chat-groups';
4
5
  const NAME_MAX_LENGTH = 100;
6
+ export function groupSortKey(group) {
7
+ return group.rank || group.createdAt;
8
+ }
5
9
  export function byGroupOrder(a, b) {
6
- return b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1);
10
+ return groupSortKey(b) - groupSortKey(a) || (a.id < b.id ? -1 : 1);
7
11
  }
8
12
  export async function listChatGroupsIn(snap) {
9
13
  const groups = await snap.find(ACTIVE_CHAT_GROUPS).toArray();
@@ -70,6 +74,44 @@ async function patchChatGroup(store, id, patch) {
70
74
  export async function renameChatGroup(store, id, name) {
71
75
  return patchChatGroup(store, id, { name: assertGroupName(name) });
72
76
  }
77
+ export async function moveChatGroup(store, id, { afterId }) {
78
+ const anchor = afterId || undefined;
79
+ if (anchor === id)
80
+ throw new Error(`a chat group cannot be placed after itself: ${id}`);
81
+ const now = Date.now();
82
+ const snap = store.view.snapshot();
83
+ let current;
84
+ let placement;
85
+ try {
86
+ const group = await snap.get(CHAT_GROUPS, { id });
87
+ if (!group || group.deletedAt)
88
+ throw new Error(`chat group not found: ${id}`);
89
+ current = group;
90
+ const siblings = (await listChatGroupsIn(snap)).filter((sibling) => sibling.id !== id);
91
+ let at = -1;
92
+ if (anchor) {
93
+ at = siblings.findIndex((sibling) => sibling.id === anchor);
94
+ if (at === -1)
95
+ throw new Error(`chat group not found: ${anchor}`);
96
+ }
97
+ placement = place(siblings, groupSortKey, { at, now });
98
+ }
99
+ finally {
100
+ await snap.close();
101
+ }
102
+ const stamp = (row, rank) => ({
103
+ ...row,
104
+ rank,
105
+ updatedAt: Math.max(now, row.updatedAt)
106
+ });
107
+ const batch = store.batch();
108
+ for (const { row, rank } of placement.respaced) {
109
+ batch.dispatch('put-chat-group', { group: stamp(row, rank) });
110
+ }
111
+ batch.dispatch('put-chat-group', { group: stamp(current, placement.rank) });
112
+ await batch.flush();
113
+ return mustGetActiveChatGroup(store, id);
114
+ }
73
115
  export async function deleteChatGroup(store, id) {
74
116
  const current = await mustGetChatGroup(store, id);
75
117
  const now = Date.now();
@@ -8,12 +8,18 @@ export interface Sidebar {
8
8
  readonly chats: ChatListing[];
9
9
  readonly groups: QvacChatGroup[];
10
10
  }
11
+ export declare function chatSortKey(chat: {
12
+ rank?: number;
13
+ rankedAt?: number;
14
+ lastActivityAt: number;
15
+ }): number;
11
16
  export declare function liveGroupIds(snap: HyperDB): Promise<Set<string>>;
12
17
  export declare function lastActivity(snap: HyperDB): Promise<Map<string, number>>;
13
18
  export declare function enrichChat(store: Mesh, chat: QvacChat): Promise<ChatListing>;
14
19
  export declare function enrichIn(snap: HyperDB, chat: QvacChat): Promise<ChatListing>;
15
20
  export declare function enrichAll(chats: ReadonlyArray<QvacChat>, activity: Map<string, number>, liveGroups: Set<string>): ChatListing[];
16
21
  export declare function listSidebar(store: Mesh): Promise<Sidebar>;
22
+ export declare function listSidebarIn(snap: HyperDB): Promise<Sidebar>;
17
23
  export declare function listChats(store: Mesh): Promise<ChatListing[]>;
18
24
  export declare function getChat(store: Mesh, id: string): Promise<QvacChat | null>;
19
25
  export declare function mustGetChat(store: Mesh, id: string): Promise<QvacChat>;
@@ -30,6 +36,10 @@ export declare function createChat(store: Mesh, input: {
30
36
  export declare function renameChat(store: Mesh, id: string, title: string): Promise<ChatListing>;
31
37
  export declare function setChatRagEnabled(store: Mesh, id: string, ragEnabled: boolean): Promise<ChatListing>;
32
38
  export declare function setChatGroup(store: Mesh, id: string, groupId: string | null | undefined): Promise<ChatListing>;
39
+ export declare function moveChat(store: Mesh, id: string, { groupId, afterId }: {
40
+ groupId?: string | null;
41
+ afterId?: string | null;
42
+ }): Promise<ChatListing>;
33
43
  export declare function setChatWebSearchEnabled(store: Mesh, id: string, webSearchEnabled: boolean): Promise<ChatListing>;
34
44
  export declare function removeChatKnowledge(store: Mesh, chatId: string, at: number): Promise<void>;
35
45
  export declare function removeChatAttachments(store: Mesh, deviceId: Buffer, chatId: string, at: number): Promise<void>;
@@ -2,6 +2,7 @@ import { listChatGroupsIn, mustGetActiveChatGroup } from "./chat-group.js";
2
2
  import { appendChunk, listChunks, updateOp } from "./chunk.js";
3
3
  import { randomId } from "./id.js";
4
4
  import { assertRemovableAt } from "./files/index.js";
5
+ import { place } from "./rank.js";
5
6
  const CHATS = '@qvac/chats';
6
7
  const CHAT_GROUPS = '@qvac/chat-groups';
7
8
  const ACTIVE_CHATS = '@qvac/active-chats';
@@ -9,8 +10,11 @@ const ACTIVE_CHATS_BY_AGENT = '@qvac/active-chats-by-agent';
9
10
  const ACTIVE_CHAT_GROUPS = '@qvac/active-chat-groups';
10
11
  const CHUNK_COUNTERS = '@qvac/chunk-counters';
11
12
  const TERMINAL_RUN_STATES = new Set(['completed', 'failed', 'canceled']);
13
+ export function chatSortKey(chat) {
14
+ return chat.rank && (chat.rankedAt ?? 0) >= chat.lastActivityAt ? chat.rank : chat.lastActivityAt;
15
+ }
12
16
  function byChatOrder(a, b) {
13
- return a.lastActivityAt - b.lastActivityAt || (a.id < b.id ? -1 : 1);
17
+ return chatSortKey(a) - chatSortKey(b) || (a.id < b.id ? -1 : 1);
14
18
  }
15
19
  export async function liveGroupIds(snap) {
16
20
  const groups = await snap.find(ACTIVE_CHAT_GROUPS).toArray();
@@ -51,15 +55,18 @@ export function enrichAll(chats, activity, liveGroups) {
51
55
  export async function listSidebar(store) {
52
56
  const snap = store.view.snapshot();
53
57
  try {
54
- const chats = await snap.find(ACTIVE_CHATS).toArray();
55
- const [activity, groups] = await Promise.all([lastActivity(snap), listChatGroupsIn(snap)]);
56
- const live = new Set(groups.map((group) => group.id));
57
- return { chats: enrichAll(chats, activity, live).sort(byChatOrder), groups };
58
+ return await listSidebarIn(snap);
58
59
  }
59
60
  finally {
60
61
  await snap.close();
61
62
  }
62
63
  }
64
+ export async function listSidebarIn(snap) {
65
+ const chats = await snap.find(ACTIVE_CHATS).toArray();
66
+ const [activity, groups] = await Promise.all([lastActivity(snap), listChatGroupsIn(snap)]);
67
+ const live = new Set(groups.map((group) => group.id));
68
+ return { chats: enrichAll(chats, activity, live).sort(byChatOrder), groups };
69
+ }
63
70
  export async function listChats(store) {
64
71
  return (await listSidebar(store)).chats;
65
72
  }
@@ -107,7 +114,9 @@ export async function createChat(store, input) {
107
114
  return listingOf(chat, false, undefined);
108
115
  }
109
116
  async function patchChat(store, id, patch) {
110
- const current = await mustGetActiveChat(store, id);
117
+ return patchChatRow(store, await mustGetActiveChat(store, id), patch);
118
+ }
119
+ async function patchChatRow(store, current, patch) {
111
120
  const updated = { ...current, ...patch, updatedAt: Date.now() };
112
121
  await store.dispatch('put-chat', { chat: updated });
113
122
  return enrichChat(store, updated);
@@ -119,9 +128,66 @@ export function setChatRagEnabled(store, id, ragEnabled) {
119
128
  return patchChat(store, id, { ragEnabled });
120
129
  }
121
130
  export async function setChatGroup(store, id, groupId) {
122
- if (groupId)
123
- await mustGetActiveChatGroup(store, groupId);
124
- return patchChat(store, id, { groupId: groupId || undefined });
131
+ const target = groupId || undefined;
132
+ if (target)
133
+ await mustGetActiveChatGroup(store, target);
134
+ const current = await mustGetActiveChat(store, id);
135
+ const kept = (current.groupId || undefined) === target;
136
+ return patchChatRow(store, current, kept ? { groupId: target } : { groupId: target, rank: undefined, rankedAt: undefined });
137
+ }
138
+ export async function moveChat(store, id, { groupId, afterId }) {
139
+ const target = groupId || undefined;
140
+ const anchor = afterId || undefined;
141
+ if (anchor === id)
142
+ throw new Error(`a chat cannot be placed after itself: ${id}`);
143
+ const now = Date.now();
144
+ const snap = store.view.snapshot();
145
+ let moved;
146
+ let placement;
147
+ let stored;
148
+ try {
149
+ if (target) {
150
+ const group = await snap.get(CHAT_GROUPS, { id: target });
151
+ if (!group || group.deletedAt)
152
+ throw new Error(`chat group not found: ${target}`);
153
+ }
154
+ const { chats } = await listSidebarIn(snap);
155
+ const me = chats.find((chat) => chat.id === id);
156
+ if (!me)
157
+ throw new Error(`chat not found: ${id}`);
158
+ moved = me;
159
+ const siblings = chats
160
+ .filter((sibling) => sibling.id !== id && (sibling.groupId || undefined) === target)
161
+ .reverse();
162
+ let at = -1;
163
+ if (anchor) {
164
+ at = siblings.findIndex((sibling) => sibling.id === anchor);
165
+ if (at === -1) {
166
+ throw new Error(`chat ${anchor} is not in the ${target ? `group ${target}` : 'ungrouped list'}`);
167
+ }
168
+ }
169
+ placement = place(siblings, chatSortKey, { at, now });
170
+ stored = new Map(await Promise.all(placement.respaced.map(async ({ row }) => [row.id, (await snap.get(CHATS, { id: row.id })) ?? row])));
171
+ }
172
+ finally {
173
+ await snap.close();
174
+ }
175
+ const stamp = (chat, lastActivityAt, rank) => ({
176
+ ...chat,
177
+ rank,
178
+ rankedAt: Math.max(now, lastActivityAt),
179
+ updatedAt: Math.max(now, chat.updatedAt ?? 0)
180
+ });
181
+ const batch = store.batch();
182
+ for (const { row, rank } of placement.respaced) {
183
+ batch.dispatch('put-chat', { chat: stamp(stored.get(row.id), row.lastActivityAt, rank) });
184
+ }
185
+ const { lastActivityAt, ...chat } = moved;
186
+ batch.dispatch('put-chat', {
187
+ chat: { ...stamp(chat, lastActivityAt, placement.rank), groupId: target }
188
+ });
189
+ await batch.flush();
190
+ return enrichChat(store, await mustGetActiveChat(store, id));
125
191
  }
126
192
  export function setChatWebSearchEnabled(store, id, webSearchEnabled) {
127
193
  return patchChat(store, id, { webSearchEnabled });
@@ -7,6 +7,7 @@ import { registerChunkRoutes } from "./chunks.js";
7
7
  import { registerDeviceRoutes } from "./devices.js";
8
8
  import { registerIndexingRoutes } from "./indexing.js";
9
9
  import { registerKnowledgeRoutes } from "./knowledge.js";
10
+ import { registerJoinedMeshRoutes } from "./joined-meshes.js";
10
11
  import { registerMemberRoutes } from "./members.js";
11
12
  import { registerSeedDefaultsRoutes } from "./seed-defaults.js";
12
13
  import { registerToolActivityRoutes } from "./tool-activity.js";
@@ -26,5 +27,6 @@ export function registerRoutes(router) {
26
27
  registerToolConfigsRoutes(router);
27
28
  registerToolActivityRoutes(router);
28
29
  registerAttestationRoutes(router);
30
+ registerJoinedMeshRoutes(router);
29
31
  registerMemberRoutes(router);
30
32
  }
@@ -0,0 +1,2 @@
1
+ import type { Router } from '../../../spec/mesh/hyperdispatch/index.js';
2
+ export declare function registerJoinedMeshRoutes(router: Router): void;
@@ -0,0 +1,41 @@
1
+ import { liveDeviceForWriter, trackActivity } from "./activity.js";
2
+ const JOINED_MESHES = '@qvac/joined-meshes';
3
+ export function registerJoinedMeshRoutes(router) {
4
+ router.add('@qvac/put-joined-mesh', trackActivity(async ({ room }, { tx, node, log }) => {
5
+ const author = await liveDeviceForWriter(tx, node.key);
6
+ if (!author?.memberId?.equals(room.memberId)) {
7
+ log?.warn('contract', 'put-joined-mesh refused: author is not a device of that member', {
8
+ meshKey: room.meshKey.toString('hex').slice(0, 8)
9
+ });
10
+ return;
11
+ }
12
+ const existing = await tx.get(JOINED_MESHES, { meshKey: room.meshKey });
13
+ if (existing && existing.joinedAt > room.joinedAt) {
14
+ log?.debug('contract', 'put-joined-mesh dropped: stale joinedAt', {
15
+ meshKey: room.meshKey.toString('hex').slice(0, 8)
16
+ });
17
+ return;
18
+ }
19
+ const rejoin = Boolean(existing) && room.joinedAt > existing.joinedAt;
20
+ const next = existing ? merge(room, existing, rejoin) : room;
21
+ await tx.insert(JOINED_MESHES, next);
22
+ log?.debug('contract', next.leftAt ? 'joined room released' : 'joined room recorded', {
23
+ meshKey: room.meshKey.toString('hex').slice(0, 8)
24
+ });
25
+ return next;
26
+ }));
27
+ }
28
+ function merge(room, existing, rejoin) {
29
+ const relabels = (room.labeledAt ?? 0) > (existing.labeledAt ?? 0);
30
+ const remarks = (room.sharedAt ?? 0) > (existing.sharedAt ?? 0);
31
+ return {
32
+ meshKey: room.meshKey,
33
+ memberId: room.memberId,
34
+ joinedAt: room.joinedAt,
35
+ leftAt: rejoin ? room.leftAt : room.leftAt || existing.leftAt,
36
+ label: relabels ? room.label : existing.label,
37
+ labeledAt: relabels ? room.labeledAt : existing.labeledAt,
38
+ shared: remarks ? room.shared : existing.shared,
39
+ sharedAt: remarks ? room.sharedAt : existing.sharedAt
40
+ };
41
+ }
@@ -1,9 +1,19 @@
1
- import { verifyDeviceProof } from "../identity.js";
1
+ import { bareDeviceProof, claimAttestation, verifyDeviceProof, verifyMemberClaim } from "../identity.js";
2
2
  import { liveDeviceForWriter, trackActivity } from "./activity.js";
3
3
  const DEVICES = '@qvac/devices';
4
4
  const MEMBERS = '@qvac/members';
5
+ function hex(buffer) {
6
+ return buffer.toString('hex').slice(0, 16);
7
+ }
5
8
  function link(device, memberId, proof, attestedAt) {
6
- return { ...device, memberId, memberProof: proof, attestedAt };
9
+ return {
10
+ ...device,
11
+ memberId,
12
+ memberProof: proof,
13
+ attestedAt,
14
+ claimedMemberId: null,
15
+ inviteToken: null
16
+ };
7
17
  }
8
18
  export function registerMemberRoutes(router) {
9
19
  router.add('@qvac/mint-member', trackActivity(async ({ member, proof }, { tx, node, log }) => {
@@ -59,6 +69,62 @@ export function registerMemberRoutes(router) {
59
69
  await tx.insert(MEMBERS, next);
60
70
  return next;
61
71
  }));
72
+ router.add('@qvac/join-member', trackActivity(async ({ member, proof }, context) => {
73
+ const { tx, node, log, meshPublicKey } = context;
74
+ const author = await liveDeviceForWriter(tx, node.key);
75
+ const ids = {
76
+ writer: hex(node.key),
77
+ device: author ? hex(author.id) : null,
78
+ member: hex(member.id)
79
+ };
80
+ if (!author) {
81
+ log?.warn('contract', 'join-member dropped: the writer has no device row', ids);
82
+ return;
83
+ }
84
+ if (author.memberId) {
85
+ if (author.memberId.equals(member.id)) {
86
+ log?.debug('contract', 'join-member dropped: the device is already owned by this member', ids);
87
+ }
88
+ else {
89
+ log?.warn('contract', 'join-member dropped: the device is owned by another member', {
90
+ ...ids,
91
+ owner: hex(author.memberId)
92
+ });
93
+ }
94
+ return;
95
+ }
96
+ const attestation = claimAttestation(meshPublicKey, author.id, node.key);
97
+ const valid = await verifyMemberClaim(proof, {
98
+ memberId: member.id,
99
+ deviceId: author.id,
100
+ attestation
101
+ });
102
+ if (!valid) {
103
+ log?.warn('contract', 'join-member dropped: the claim does not bind this mesh and writer', {
104
+ ...ids,
105
+ mesh: hex(meshPublicKey),
106
+ proofBytes: proof.byteLength
107
+ });
108
+ return;
109
+ }
110
+ const stored = bareDeviceProof(proof);
111
+ if (!stored) {
112
+ log?.warn('contract', 'join-member dropped: the proof does not re-encode', ids);
113
+ return;
114
+ }
115
+ const existing = await tx.get(MEMBERS, { id: member.id });
116
+ const joined = existing ?? {
117
+ id: member.id,
118
+ name: member.name,
119
+ joinedAt: member.joinedAt,
120
+ updatedAt: member.updatedAt
121
+ };
122
+ if (!existing)
123
+ await tx.insert(MEMBERS, joined);
124
+ await tx.insert(DEVICES, link(author, member.id, stored, member.joinedAt));
125
+ log?.info('contract', 'member joined', ids);
126
+ return joined;
127
+ }));
62
128
  router.add('@qvac/attest-member-device', async (op, { tx, node, log }) => {
63
129
  const device = await tx.get(DEVICES, { id: op.deviceId });
64
130
  if (!device) {
@@ -1,7 +1,8 @@
1
1
  import crypto from 'hypercore-crypto';
2
2
  import { markWriterRevoked, trackActivity } from "./activity.js";
3
+ import { verifyWriterClaim } from "../device-attestation.js";
3
4
  const DEVICES = '@qvac/devices';
4
- async function admitDevice({ tx, log }, id, device, writerKey) {
5
+ async function admitDevice({ tx, meshPublicKey, log }, id, device, writerKey, claim) {
5
6
  const existing = await tx.get(DEVICES, { id });
6
7
  if (!device) {
7
8
  if (!existing)
@@ -14,6 +15,19 @@ async function admitDevice({ tx, log }, id, device, writerKey) {
14
15
  log?.debug('contract', 'admission refused: claim is not newer than the device row');
15
16
  return 'refused';
16
17
  }
18
+ if (existing?.writerKey &&
19
+ !existing.writerKey.equals(writerKey) &&
20
+ !verifyWriterClaim(claim?.deviceSignature, {
21
+ meshPublicKey,
22
+ deviceId: id,
23
+ writerKey,
24
+ joinedAt: device.joinedAt
25
+ })) {
26
+ log?.warn('contract', 'admission refused: the device did not sign for this writer key', {
27
+ id: id.toString('hex').slice(0, 16)
28
+ });
29
+ return 'refused';
30
+ }
17
31
  const alreadyAdmitted = existing && !existing.revoked && existing.writerKey?.equals(writerKey) === true;
18
32
  await tx.insert(DEVICES, {
19
33
  ...existing,
@@ -30,6 +44,8 @@ async function admitDevice({ tx, log }, id, device, writerKey) {
30
44
  appBuild: device.appBuild ?? existing?.appBuild,
31
45
  appChannel: device.appChannel ?? existing?.appChannel,
32
46
  platform: device.platform ?? existing?.platform,
47
+ claimedMemberId: claim?.claimedMemberId ?? existing?.claimedMemberId,
48
+ inviteToken: claim?.inviteToken ?? existing?.inviteToken,
33
49
  id,
34
50
  writerKey,
35
51
  revoked: false,
@@ -51,7 +67,7 @@ export function registerWriterRoutes(router) {
51
67
  await context.host.addWriter(payload.writerKey);
52
68
  return;
53
69
  }
54
- const admission = await admitDevice(context, payload.device.id, payload.device, payload.writerKey);
70
+ const admission = await admitDevice(context, payload.device.id, payload.device, payload.writerKey, payload);
55
71
  if (admission !== 'admitted')
56
72
  return;
57
73
  await context.host.addWriter(payload.writerKey);
@@ -103,7 +119,7 @@ export function registerWriterRoutes(router) {
103
119
  await context.host.addWriter(context.node.key);
104
120
  return;
105
121
  }
106
- const admission = await admitDevice(context, id, payload.device, context.node.key);
122
+ const admission = await admitDevice(context, id, payload.device, context.node.key, payload);
107
123
  if (admission === 'refused')
108
124
  return;
109
125
  await context.host.addWriter(context.node.key);
@@ -10,6 +10,7 @@ interface DepartureRows {
10
10
  }
11
11
  export interface PendingDeparturesOptions {
12
12
  swarm: Hyperswarm;
13
+ isPooled: (key: Buffer) => boolean;
13
14
  logger?: Logger | null;
14
15
  blindPeerKeys?: ReadonlyArray<Buffer>;
15
16
  blindPeeringOpts?: BlindPeeringOpts;
@@ -23,12 +24,13 @@ export declare class PendingDepartures {
23
24
  private readonly _blindPeerKeys;
24
25
  private readonly _blindPeeringOpts;
25
26
  private readonly _wakeup;
27
+ private readonly _isPooled;
26
28
  private readonly _active;
27
29
  private readonly _parked;
28
30
  private readonly _lock;
29
31
  private _closing;
30
32
  constructor(store: Corestore, local: DepartureRows, opts: PendingDeparturesOptions);
31
- flush(activeKey?: Buffer | null): void;
33
+ flush(): void;
32
34
  private _flush;
33
35
  private _deliver;
34
36
  park(key: Buffer): Promise<void>;
@@ -9,6 +9,7 @@ export class PendingDepartures {
9
9
  _blindPeerKeys;
10
10
  _blindPeeringOpts;
11
11
  _wakeup;
12
+ _isPooled;
12
13
  _active = new Map();
13
14
  _parked = new Set();
14
15
  _lock = new ScopeLock();
@@ -17,15 +18,16 @@ export class PendingDepartures {
17
18
  this._store = store;
18
19
  this._local = local;
19
20
  this._swarm = opts.swarm;
21
+ this._isPooled = opts.isPooled;
20
22
  this._log = opts.logger ?? null;
21
23
  this._blindPeerKeys = opts.blindPeerKeys ?? [];
22
24
  this._blindPeeringOpts = opts.blindPeeringOpts;
23
25
  this._wakeup = opts.wakeup;
24
26
  }
25
- flush(activeKey) {
26
- void this._flush(activeKey ?? null).catch((err) => this._log?.warn(SCOPE, 'departure flush failed', err));
27
+ flush() {
28
+ void this._flush().catch((err) => this._log?.warn(SCOPE, 'departure flush failed', err));
27
29
  }
28
- async _flush(activeKey) {
30
+ async _flush() {
29
31
  await this._lock.lock();
30
32
  try {
31
33
  if (this._closing)
@@ -34,7 +36,7 @@ export class PendingDepartures {
34
36
  if (this._closing)
35
37
  return;
36
38
  const hex = row.key.toString('hex');
37
- if (activeKey?.equals(row.key) || this._parked.has(hex) || this._active.has(hex)) {
39
+ if (this._isPooled(row.key) || this._parked.has(hex) || this._active.has(hex)) {
38
40
  continue;
39
41
  }
40
42
  const mesh = new Mesh(this._store, {
@@ -1,6 +1,14 @@
1
+ export interface WriterClaimBinding {
2
+ readonly meshPublicKey: Buffer;
3
+ readonly deviceId: Buffer;
4
+ readonly writerKey: Buffer;
5
+ readonly joinedAt: number;
6
+ }
1
7
  export interface DeviceAttestation {
2
8
  readonly deviceId: Buffer;
3
9
  readonly signature: Buffer;
4
10
  }
5
11
  export declare function signDeviceAttestation(secretKey: Buffer, deviceId: Buffer): DeviceAttestation;
6
12
  export declare function verifyDeviceAttestation(publicKey: Buffer, attestation: DeviceAttestation): boolean;
13
+ export declare function signWriterClaim(secretKey: Buffer, binding: WriterClaimBinding): Buffer;
14
+ export declare function verifyWriterClaim(signature: Buffer | null | undefined, binding: WriterClaimBinding): boolean;