pi-web-ui 0.116.0 → 0.117.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.
- package/CHANGELOG.md +38 -4
- package/bin/device-hub-cli.mjs +26 -3
- package/bin/pi-web-ui.mjs +138 -70
- package/dist/server/agent-service-daemon.js +52 -6
- package/dist/server/agent-service.js +495 -141
- package/dist/server/canvas/canvas-workspace.js +18 -86
- package/dist/server/client-state.js +35 -6
- package/dist/server/compaction-markers.js +43 -24
- package/dist/server/dangling-tools.js +172 -16
- package/dist/server/device-center/bot-execution.js +48 -1
- package/dist/server/device-center/collab-service.js +26 -8
- package/dist/server/device-center/collab-tool.js +394 -18
- package/dist/server/device-center/connector.js +107 -37
- package/dist/server/device-center/delivery-authority.js +98 -0
- package/dist/server/device-center/delivery-subject.js +30 -0
- package/dist/server/device-center/device-integration.js +453 -183
- package/dist/server/device-center/execution-guides.js +15 -5
- package/dist/server/device-center/executor.js +47 -5
- package/dist/server/device-center/hub-conversations.js +14 -4
- package/dist/server/device-center/hub-deliveries.js +120 -15
- package/dist/server/device-center/hub-integration.js +655 -334
- package/dist/server/device-center/hub-page.js +5 -4
- package/dist/server/device-center/hub-setup.js +23 -1
- package/dist/server/device-center/hub-transaction-log.js +197 -0
- package/dist/server/device-center/hub.js +772 -354
- package/dist/server/device-center/integration-verification.js +113 -0
- package/dist/server/device-center/local-hub.js +6 -2
- package/dist/server/device-center/local-publication.js +423 -0
- package/dist/server/device-center/local-verification-job.js +97 -0
- package/dist/server/device-center/local-verification.js +274 -0
- package/dist/server/device-center/local.js +107 -12
- package/dist/server/device-center/main.js +4 -1
- package/dist/server/device-center/partition-log.js +62 -25
- package/dist/server/device-center/publication-journal.js +312 -0
- package/dist/server/device-center/publish-intent.js +379 -0
- package/dist/server/device-center/relay.js +134 -24
- package/dist/server/device-center/runtime.js +426 -42
- package/dist/server/device-center/store.js +225 -47
- package/dist/server/device-center/task-outcome.js +81 -0
- package/dist/server/device-center/task-recovery.js +603 -178
- package/dist/server/device-center/task-settlement.js +353 -0
- package/dist/server/device-center/task-workspace.js +443 -0
- package/dist/server/device-center/verification-limits.js +10 -0
- package/dist/server/device-center/work-contract.js +995 -0
- package/dist/server/dispatch-domain-handlers.js +15 -0
- package/dist/server/dsh/dsh-agent-service.js +9 -2
- package/dist/server/index.js +26 -1
- package/dist/server/patch-node-pty.js +3 -2
- package/dist/server/patch-remote-catalog.js +3 -2
- package/dist/server/preset-fields.js +17 -1
- package/dist/server/preset-share.js +1 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/quick-ask-settings.js +28 -0
- package/dist/server/quick-ask.js +164 -0
- package/dist/server/resolve-global-sdk.js +61 -11
- package/dist/server/scheduler-tasks.js +35 -8
- package/dist/server/session-list-scan.js +223 -0
- package/dist/server/session-open.js +93 -0
- package/dist/server/session-parser.js +4 -0
- package/dist/server/session-scan.js +90 -38
- package/dist/server/settings-service.js +9 -1
- package/dist/server/soft-cap.js +5 -0
- package/dist/server/transcript-prepare.js +73 -0
- package/dist/server/universal/drivers/claude-code.js +98 -34
- package/dist/server/universal/universal-session.js +4 -0
- package/dist/server/workspace-handle.js +428 -0
- package/docs/architecture-plugins.md +18 -5
- package/docs/device-center.md +30 -22
- package/package.json +3 -4
- package/plugin-sdk/README.md +16 -8
- package/plugin-sdk/client.d.ts +27 -0
- package/plugin-sdk/client.mjs +82 -0
- package/plugin-sdk/index.d.ts +10 -0
- package/plugin-sdk/index.mjs +4 -683
- package/plugin-sdk/package.json +15 -4
- package/plugin-sdk/testing.d.ts +10 -0
- package/plugin-sdk/testing.mjs +566 -0
- package/themes/flow-cristallo.css +168 -0
- package/themes/flow-ink.css +169 -0
- package/themes/flow-obsidian.css +169 -0
- package/themes/flow-zurich.css +169 -0
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
- package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
- package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
- package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
- package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
- package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
- package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
- package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
- package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
- package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
- package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
- package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
- package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
- package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
- package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
- package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
- package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
- package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
- package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
- package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
- package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
- package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
- package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
- package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
- package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
- package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
- package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
- package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
- package/web/dist/assets/index-BawF7ZP5.js +397 -0
- package/web/dist/assets/index-BoGCoq5X.js +397 -0
- package/web/dist/assets/index-CVW9FoY2.css +1 -0
- package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
- package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
- package/web/dist/index.html +11 -11
- package/web/dist/sw.js +1 -1
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/device-center/local-page.js +0 -17
- package/dist/server/device-center/smoke-preview.js +0 -3
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/patch-turn-end-boundary.js +0 -77
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
- package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
- package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
- package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
- package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
- package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
- package/web/dist/assets/index-C6DwztqE.css +0 -1
- package/web/dist/assets/index-CuN802Sj.js +0 -93
- package/web/dist/assets/index-EH5Fw9fa.js +0 -93
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
import { mkdir, readFile, open, rename, unlink } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { PartitionedAppendLog } from "./partition-log.js";
|
|
4
|
+
import { HubTransactionLog, } from "./hub-transaction-log.js";
|
|
4
5
|
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
6
|
import { projectConversationState, reconcileConversationState, } from "./task-state.js";
|
|
6
|
-
export const taskPending = (task) => !isTerminal(task.status) ||
|
|
7
|
+
export const taskPending = (task) => !isTerminal(task.status) ||
|
|
8
|
+
!!(task.cancelRequested && !task.stopConfirmed) ||
|
|
9
|
+
(task.recoveryUntil !== undefined && task.recoveryUntil > Date.now());
|
|
10
|
+
/** Contract authority and captured evidence survive automatic retention until explicit room data reset. */
|
|
11
|
+
export const taskHasImmutableEvidence = (task) => !!task.contract ||
|
|
12
|
+
!!task.artifact ||
|
|
13
|
+
task.artifactProduced === true ||
|
|
14
|
+
(task.executionMode === "code" && task.executionCompleted === true);
|
|
7
15
|
export const isTerminal = (status) => ["completed", "failed", "interrupted"].includes(status);
|
|
8
16
|
export const hashSecret = (secret) => createHash("sha256").update(secret).digest("hex");
|
|
9
17
|
export function secretMatches(secret, hash) {
|
|
@@ -35,8 +43,8 @@ function createHubLogs(dataDir) {
|
|
|
35
43
|
partition: (task) => task.roomId,
|
|
36
44
|
id: (task) => task.id,
|
|
37
45
|
retention: HUB_LOG_RETENTION,
|
|
38
|
-
//
|
|
39
|
-
protect: (task) => taskPending(task),
|
|
46
|
+
// Retain live work and immutable code evidence across checkpoint compaction and restarts.
|
|
47
|
+
protect: (task) => taskPending(task) || taskHasImmutableEvidence(task),
|
|
40
48
|
}),
|
|
41
49
|
conversationMessages: new PartitionedAppendLog({
|
|
42
50
|
dir: join(root, "conversation-messages"),
|
|
@@ -48,6 +56,7 @@ function createHubLogs(dataDir) {
|
|
|
48
56
|
function emptyHubState() {
|
|
49
57
|
return {
|
|
50
58
|
version: 2,
|
|
59
|
+
checkpointSeq: 0,
|
|
51
60
|
conversations: [],
|
|
52
61
|
conversationMessages: [],
|
|
53
62
|
deliveries: [],
|
|
@@ -85,11 +94,98 @@ function mergeRows(stored, inline) {
|
|
|
85
94
|
merged.set(row.id, row);
|
|
86
95
|
return [...merged.values()];
|
|
87
96
|
}
|
|
97
|
+
function computeCollectionDiff(oldRows, newRows) {
|
|
98
|
+
const oldMap = new Map();
|
|
99
|
+
for (const row of oldRows) {
|
|
100
|
+
oldMap.set(row.id, JSON.stringify(row));
|
|
101
|
+
}
|
|
102
|
+
const upsert = [];
|
|
103
|
+
const newIds = new Set();
|
|
104
|
+
for (const row of newRows) {
|
|
105
|
+
newIds.add(row.id);
|
|
106
|
+
const serialized = JSON.stringify(row);
|
|
107
|
+
if (oldMap.get(row.id) !== serialized) {
|
|
108
|
+
upsert.push(row);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const deleteIds = [];
|
|
112
|
+
for (const row of oldRows) {
|
|
113
|
+
if (!newIds.has(row.id)) {
|
|
114
|
+
deleteIds.push(row.id);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { upsert, deleteIds };
|
|
118
|
+
}
|
|
119
|
+
function applyCollectionDiff(target, diff) {
|
|
120
|
+
const deleteSet = new Set(diff.deleteIds);
|
|
121
|
+
let i = 0;
|
|
122
|
+
while (i < target.length) {
|
|
123
|
+
if (deleteSet.has(target[i].id)) {
|
|
124
|
+
target.splice(i, 1);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
i++;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const indexMap = new Map();
|
|
131
|
+
for (let j = 0; j < target.length; j++) {
|
|
132
|
+
indexMap.set(target[j].id, j);
|
|
133
|
+
}
|
|
134
|
+
for (const item of diff.upsert) {
|
|
135
|
+
const existingIndex = indexMap.get(item.id);
|
|
136
|
+
if (existingIndex !== undefined) {
|
|
137
|
+
target[existingIndex] = item;
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
target.push(item);
|
|
141
|
+
indexMap.set(item.id, target.length - 1);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function extractIndexState(state) {
|
|
146
|
+
const { messages: _m, tasks: _t, conversationMessages: _cm, ...index } = state;
|
|
147
|
+
return index;
|
|
148
|
+
}
|
|
149
|
+
async function persistIndexTo(indexPath, state, checkpointSeq) {
|
|
150
|
+
const temporary = `${indexPath}.${randomUUID()}.tmp`;
|
|
151
|
+
const index = {
|
|
152
|
+
...state,
|
|
153
|
+
messages: [],
|
|
154
|
+
tasks: [],
|
|
155
|
+
conversationMessages: [],
|
|
156
|
+
checkpointSeq,
|
|
157
|
+
};
|
|
158
|
+
delete index.checkpointSeqRaw;
|
|
159
|
+
try {
|
|
160
|
+
const file = await open(temporary, "wx", 0o600);
|
|
161
|
+
try {
|
|
162
|
+
await file.writeFile(JSON.stringify(index));
|
|
163
|
+
await file.sync();
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
await file.close();
|
|
167
|
+
}
|
|
168
|
+
await rename(temporary, indexPath);
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
await unlink(temporary).catch((error) => {
|
|
172
|
+
if (error.code !== "ENOENT")
|
|
173
|
+
throw error;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
88
177
|
async function loadHubFiles(dataDir, options = {}) {
|
|
89
|
-
|
|
178
|
+
if (!options.readOnly) {
|
|
179
|
+
await mkdir(dataDir, { recursive: true, mode: 0o700 });
|
|
180
|
+
}
|
|
90
181
|
let state;
|
|
182
|
+
let checkpointSeq = 0;
|
|
91
183
|
try {
|
|
92
|
-
|
|
184
|
+
const rawText = await readFile(join(dataDir, "device-hub.json"), "utf8");
|
|
185
|
+
const rawJson = JSON.parse(rawText);
|
|
186
|
+
checkpointSeq = typeof rawJson.checkpointSeq === "number" ? rawJson.checkpointSeq : 0;
|
|
187
|
+
state = rawJson;
|
|
188
|
+
delete state.checkpointSeq;
|
|
93
189
|
if (state.version !== 2 ||
|
|
94
190
|
![
|
|
95
191
|
state.accounts,
|
|
@@ -108,6 +204,7 @@ async function loadHubFiles(dataDir, options = {}) {
|
|
|
108
204
|
if (error.code !== "ENOENT")
|
|
109
205
|
throw error;
|
|
110
206
|
state = emptyHubState();
|
|
207
|
+
delete state.checkpointSeq;
|
|
111
208
|
}
|
|
112
209
|
state.conversations ??= [];
|
|
113
210
|
state.conversationMessages ??= [];
|
|
@@ -124,9 +221,19 @@ async function loadHubFiles(dataDir, options = {}) {
|
|
|
124
221
|
state.integrations,
|
|
125
222
|
].every(Array.isArray))
|
|
126
223
|
throw new Error("Invalid conversation store");
|
|
224
|
+
// Read the WAL before loading/sweeping projections: a committed parent may not be in the old index yet.
|
|
225
|
+
const wal = new HubTransactionLog({ walPath: join(dataDir, "hub-wal.jsonl") });
|
|
226
|
+
const { records } = await wal.readTransactions({ readOnly: options.readOnly });
|
|
227
|
+
const unprojectedRecords = records.filter((record) => record.seq > checkpointSeq);
|
|
127
228
|
const logs = createHubLogs(dataDir);
|
|
128
229
|
const roomPartitions = roomPartitionsOf(state);
|
|
129
230
|
const conversations = new Set(state.conversations.map((conversation) => conversation.id));
|
|
231
|
+
for (const record of unprojectedRecords) {
|
|
232
|
+
for (const partition of roomPartitionsOf(record.index))
|
|
233
|
+
roomPartitions.add(partition);
|
|
234
|
+
for (const conversation of record.index.conversations)
|
|
235
|
+
conversations.add(conversation.id);
|
|
236
|
+
}
|
|
130
237
|
// Logs are the authority; inline rows only exist in files written before the split (or by an older Hub).
|
|
131
238
|
const storedMessages = await logs.messages.load(roomPartitions, options);
|
|
132
239
|
const storedTasks = await logs.tasks.load(roomPartitions, options);
|
|
@@ -135,19 +242,42 @@ async function loadHubFiles(dataDir, options = {}) {
|
|
|
135
242
|
state.messages = mergeRows(storedMessages, state.messages);
|
|
136
243
|
state.tasks = mergeRows(storedTasks, state.tasks);
|
|
137
244
|
state.conversationMessages = mergeRows(storedConversationMessages, state.conversationMessages);
|
|
245
|
+
if (unprojectedRecords.length > 0) {
|
|
246
|
+
for (const record of unprojectedRecords) {
|
|
247
|
+
const { checkpointSeq: _recSeq, ...indexProps } = record.index;
|
|
248
|
+
Object.assign(state, indexProps);
|
|
249
|
+
applyCollectionDiff(state.messages, record.diff.messages);
|
|
250
|
+
applyCollectionDiff(state.tasks, record.diff.tasks);
|
|
251
|
+
applyCollectionDiff(state.conversationMessages, record.diff.conversationMessages);
|
|
252
|
+
checkpointSeq = record.seq;
|
|
253
|
+
}
|
|
254
|
+
// Catch-up projection: if not read-only, project recovered uncommitted states to logs and index checkpoint
|
|
255
|
+
if (!options.readOnly) {
|
|
256
|
+
const recoveryRooms = roomPartitionsOf(state);
|
|
257
|
+
const recoveryConversations = new Set(state.conversations.map((conversation) => conversation.id));
|
|
258
|
+
// Projection order: 1. commit logs
|
|
259
|
+
await logs.messages.commit(state.messages, recoveryRooms);
|
|
260
|
+
await logs.tasks.commit(state.tasks, recoveryRooms);
|
|
261
|
+
await logs.conversationMessages.commit(state.conversationMessages, recoveryConversations);
|
|
262
|
+
// Projection order: 2. commit index checkpoint
|
|
263
|
+
await persistIndexTo(join(dataDir, "device-hub.json"), state, checkpointSeq);
|
|
264
|
+
// 3. checkpoint WAL
|
|
265
|
+
await wal.checkpoint(checkpointSeq);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
138
268
|
// Legacy state is a baseline, not evidence that historical transitions were observed.
|
|
139
269
|
for (const conversation of state.conversations) {
|
|
140
270
|
conversation.taskState = projectConversationState(state, conversation);
|
|
141
271
|
conversation.events ??= [];
|
|
142
272
|
}
|
|
143
|
-
return { state, logs, legacy };
|
|
273
|
+
return { state, logs, wal, checkpointSeq, legacy };
|
|
144
274
|
}
|
|
145
275
|
/** Read the durable state without open() side effects (no interrupt marking); used by tests and tooling. */
|
|
146
276
|
export async function readPersistedHub(dataDir) {
|
|
147
|
-
// Read-only: never sweep orphan files or repair tails from an inspection path.
|
|
148
|
-
return (await loadHubFiles(dataDir, { sweep: false })).state;
|
|
277
|
+
// Read-only: never sweep orphan files or repair tails or mutate checkpoints from an inspection path.
|
|
278
|
+
return (await loadHubFiles(dataDir, { sweep: false, readOnly: true })).state;
|
|
149
279
|
}
|
|
150
|
-
/** A single process owns a data directory.
|
|
280
|
+
/** A single process owns a data directory. The fsynced WAL is the transaction commit point. */
|
|
151
281
|
export class DeviceHubStore {
|
|
152
282
|
state;
|
|
153
283
|
listeners = new Set();
|
|
@@ -160,34 +290,61 @@ export class DeviceHubStore {
|
|
|
160
290
|
tail = Promise.resolve();
|
|
161
291
|
path;
|
|
162
292
|
logs;
|
|
293
|
+
wal;
|
|
163
294
|
logDir;
|
|
164
|
-
|
|
295
|
+
lastSeq;
|
|
296
|
+
checkpointSeq;
|
|
297
|
+
projectionFailed = false;
|
|
298
|
+
lastProjectionError;
|
|
299
|
+
constructor(dataDir, state, logs, wal, checkpointSeq) {
|
|
165
300
|
this.path = join(dataDir, "device-hub.json");
|
|
166
301
|
this.logDir = join(dataDir, "hub-log");
|
|
167
302
|
this.state = state;
|
|
168
303
|
this.logs = logs;
|
|
304
|
+
this.wal = wal;
|
|
305
|
+
this.checkpointSeq = checkpointSeq;
|
|
306
|
+
this.lastSeq = checkpointSeq;
|
|
169
307
|
}
|
|
170
|
-
static async open(dataDir) {
|
|
171
|
-
const { state, logs, legacy } = await loadHubFiles(dataDir);
|
|
172
|
-
const store = new DeviceHubStore(dataDir, state, logs);
|
|
308
|
+
static async open(dataDir, options = {}) {
|
|
309
|
+
const { state, logs, wal, checkpointSeq, legacy } = await loadHubFiles(dataDir);
|
|
310
|
+
const store = new DeviceHubStore(dataDir, state, logs, wal, checkpointSeq);
|
|
173
311
|
// Move collections that older Hubs kept inline into their append logs. Logs are written first so
|
|
174
312
|
// an interrupted migration can be retried from the still-inline index without losing rows.
|
|
175
313
|
if (legacy)
|
|
176
314
|
await store.migrateInlineCollections();
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
const recoveryGraceMs = 60_000;
|
|
317
|
+
const tasksToInterrupt = state.tasks.filter((task) => {
|
|
318
|
+
if (isTerminal(task.status))
|
|
319
|
+
return false;
|
|
320
|
+
if (options.retainUnleasedQueued) {
|
|
321
|
+
if (task.status === "running")
|
|
322
|
+
return true;
|
|
323
|
+
if (task.status === "queued" && (task.leaseToken || task.leaseGeneration !== undefined))
|
|
324
|
+
return true;
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
return true;
|
|
328
|
+
});
|
|
329
|
+
if (tasksToInterrupt.length > 0) {
|
|
180
330
|
await store.transact((draft) => {
|
|
181
|
-
for (const task of draft.tasks)
|
|
182
|
-
if (
|
|
331
|
+
for (const task of draft.tasks) {
|
|
332
|
+
if (isTerminal(task.status))
|
|
333
|
+
continue;
|
|
334
|
+
const shouldInterrupt = options.retainUnleasedQueued
|
|
335
|
+
? task.status === "running" ||
|
|
336
|
+
(task.status === "queued" && (task.leaseToken || task.leaseGeneration !== undefined))
|
|
337
|
+
: true;
|
|
338
|
+
if (shouldInterrupt) {
|
|
183
339
|
task.status = "interrupted";
|
|
184
340
|
task.report = "Hub restarted before execution was confirmed; submit a new turn to retry.";
|
|
185
341
|
task.updatedAt = now;
|
|
186
|
-
if (task.leaseToken) {
|
|
342
|
+
if (task.leaseToken || task.leaseGeneration !== undefined) {
|
|
187
343
|
// Retain recovery grace window for active leases to claim on reconnect!
|
|
188
344
|
task.recoveryUntil = now + recoveryGraceMs;
|
|
189
345
|
}
|
|
190
346
|
}
|
|
347
|
+
}
|
|
191
348
|
});
|
|
192
349
|
}
|
|
193
350
|
return store;
|
|
@@ -211,6 +368,9 @@ export class DeviceHubStore {
|
|
|
211
368
|
}
|
|
212
369
|
async transact(update) {
|
|
213
370
|
const operation = this.tail.then(async () => {
|
|
371
|
+
if (this.wal.isPoisoned()) {
|
|
372
|
+
throw new Error("Store is poisoned due to previous WAL rollback failure; operations halted");
|
|
373
|
+
}
|
|
214
374
|
const draft = structuredClone(this.state);
|
|
215
375
|
const result = update(draft);
|
|
216
376
|
if (result && (typeof result === "object" || typeof result === "function") && "then" in result) {
|
|
@@ -222,8 +382,17 @@ export class DeviceHubStore {
|
|
|
222
382
|
if (typeof reconcileConversationState === "function") {
|
|
223
383
|
reconcileConversationState(this.state, draft);
|
|
224
384
|
}
|
|
225
|
-
|
|
226
|
-
|
|
385
|
+
// Reject uncloneable results before commit and detach returned evidence before any I/O awaits.
|
|
386
|
+
const detachedResult = structuredClone(result);
|
|
387
|
+
// Sequence and diff calculation
|
|
388
|
+
const nextSeq = this.lastSeq + 1;
|
|
389
|
+
const diff = {
|
|
390
|
+
messages: computeCollectionDiff(this.state.messages, draft.messages),
|
|
391
|
+
tasks: computeCollectionDiff(this.state.tasks, draft.tasks),
|
|
392
|
+
conversationMessages: computeCollectionDiff(this.state.conversationMessages, draft.conversationMessages),
|
|
393
|
+
};
|
|
394
|
+
// Keep the public hook before the commit point so tests can inject a pre-commit failure.
|
|
395
|
+
await this.persist(draft, nextSeq, diff);
|
|
227
396
|
for (const listener of this.listeners) {
|
|
228
397
|
try {
|
|
229
398
|
listener();
|
|
@@ -232,18 +401,45 @@ export class DeviceHubStore {
|
|
|
232
401
|
/* notification cannot roll back a committed transaction */
|
|
233
402
|
}
|
|
234
403
|
}
|
|
235
|
-
return
|
|
404
|
+
return detachedResult;
|
|
236
405
|
});
|
|
237
406
|
this.tail = operation.catch(() => { });
|
|
238
407
|
return operation;
|
|
239
408
|
}
|
|
240
409
|
/**
|
|
241
410
|
* Kept as a method so I/O failures can be injected without replacing transaction semantics.
|
|
242
|
-
*
|
|
411
|
+
* WAL append is the commit point. Projection failures retain WAL for retry/recovery and cannot reject a commit.
|
|
243
412
|
*/
|
|
244
|
-
async persist(state) {
|
|
245
|
-
|
|
246
|
-
|
|
413
|
+
async persist(state, checkpointSeq = this.lastSeq, diff) {
|
|
414
|
+
// Detach accepted evidence before the first asynchronous write. A caller may
|
|
415
|
+
// retain its transaction inputs, but cannot subsequently rewrite durable facts.
|
|
416
|
+
state = structuredClone(state);
|
|
417
|
+
if (diff)
|
|
418
|
+
diff = structuredClone(diff);
|
|
419
|
+
if (this.projectionFailed) {
|
|
420
|
+
this.logs.messages.invalidateCache();
|
|
421
|
+
this.logs.tasks.invalidateCache();
|
|
422
|
+
this.logs.conversationMessages.invalidateCache();
|
|
423
|
+
}
|
|
424
|
+
if (diff) {
|
|
425
|
+
await this.wal.append(checkpointSeq, extractIndexState(state), diff);
|
|
426
|
+
this.state = state;
|
|
427
|
+
this.lastSeq = checkpointSeq;
|
|
428
|
+
}
|
|
429
|
+
try {
|
|
430
|
+
await this.commitLogs(state);
|
|
431
|
+
await this.persistIndex(state, checkpointSeq);
|
|
432
|
+
await this.wal.checkpoint(checkpointSeq);
|
|
433
|
+
this.checkpointSeq = checkpointSeq;
|
|
434
|
+
this.projectionFailed = false;
|
|
435
|
+
this.lastProjectionError = undefined;
|
|
436
|
+
}
|
|
437
|
+
catch (projectionError) {
|
|
438
|
+
this.projectionFailed = true;
|
|
439
|
+
this.lastProjectionError = projectionError;
|
|
440
|
+
if (!diff)
|
|
441
|
+
throw projectionError;
|
|
442
|
+
}
|
|
247
443
|
}
|
|
248
444
|
async commitLogs(state) {
|
|
249
445
|
const rooms = roomPartitionsOf(state);
|
|
@@ -255,28 +451,10 @@ export class DeviceHubStore {
|
|
|
255
451
|
/** One-time upgrade from Hubs that inlined messages/tasks/transcripts in the index file. */
|
|
256
452
|
async migrateInlineCollections() {
|
|
257
453
|
await this.commitLogs(this.state);
|
|
258
|
-
await this.persistIndex(this.state);
|
|
454
|
+
await this.persistIndex(this.state, this.checkpointSeq);
|
|
259
455
|
}
|
|
260
|
-
async persistIndex(state) {
|
|
261
|
-
|
|
262
|
-
const index = { ...state, messages: [], tasks: [], conversationMessages: [] };
|
|
263
|
-
try {
|
|
264
|
-
const file = await open(temporary, "wx", 0o600);
|
|
265
|
-
try {
|
|
266
|
-
await file.writeFile(JSON.stringify(index));
|
|
267
|
-
await file.sync();
|
|
268
|
-
}
|
|
269
|
-
finally {
|
|
270
|
-
await file.close();
|
|
271
|
-
}
|
|
272
|
-
await rename(temporary, this.path);
|
|
273
|
-
}
|
|
274
|
-
finally {
|
|
275
|
-
await unlink(temporary).catch((error) => {
|
|
276
|
-
if (error.code !== "ENOENT")
|
|
277
|
-
throw error;
|
|
278
|
-
});
|
|
279
|
-
}
|
|
456
|
+
async persistIndex(state, checkpointSeq = this.checkpointSeq) {
|
|
457
|
+
await persistIndexTo(this.path, state, checkpointSeq);
|
|
280
458
|
}
|
|
281
459
|
async close() {
|
|
282
460
|
await this.tail;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { parseReportMetadata } from "./report-metadata.js";
|
|
3
|
+
import { deviceTaskFailure } from "./task-error.js";
|
|
4
|
+
import { boundTaskReport } from "./task-report.js";
|
|
5
|
+
import { validateDeviceArtifact } from "./work-contract.js";
|
|
6
|
+
export const TASK_OUTCOME_ERROR_BYTES = 4 * 1024;
|
|
7
|
+
export function deepFreeze(obj) {
|
|
8
|
+
if (obj === null || typeof obj !== "object" || Object.isFrozen(obj))
|
|
9
|
+
return obj;
|
|
10
|
+
Object.freeze(obj);
|
|
11
|
+
for (const key of Object.keys(obj)) {
|
|
12
|
+
deepFreeze(obj[key]);
|
|
13
|
+
}
|
|
14
|
+
return obj;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Deterministically compute outcome fingerprint digest (first 16 hex chars of SHA-256).
|
|
18
|
+
* Pure function shared between Hub and Device endpoints to guarantee ACK binding.
|
|
19
|
+
* When artifactDigest or execution/artifact proof facts are provided, they are incorporated
|
|
20
|
+
* into the digest payload while preserving backward-compatibility for legacy 6-tuple payloads.
|
|
21
|
+
*/
|
|
22
|
+
export function computeOutcomeFingerprint(taskId, attemptId, status, report, error, reportMetadata, artifactDigest, executionCompleted, artifactProduced) {
|
|
23
|
+
const hasProofOrArtifact = artifactDigest !== undefined || executionCompleted !== undefined || artifactProduced !== undefined;
|
|
24
|
+
const payload = [
|
|
25
|
+
taskId,
|
|
26
|
+
attemptId,
|
|
27
|
+
status,
|
|
28
|
+
report ?? "",
|
|
29
|
+
error ?? "",
|
|
30
|
+
reportMetadata === undefined ? null : parseReportMetadata(reportMetadata),
|
|
31
|
+
...(hasProofOrArtifact ? [artifactDigest ?? null, executionCompleted ?? null, artifactProduced ?? null] : []),
|
|
32
|
+
];
|
|
33
|
+
return createHash("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
|
|
34
|
+
}
|
|
35
|
+
/** Compatibility for outcomes persisted or sent by older devices. */
|
|
36
|
+
export function computeLegacyOutcomeFingerprint(taskId, attemptId, status, report, error, reportMetadata) {
|
|
37
|
+
return createHash("sha256")
|
|
38
|
+
.update(`${taskId}:${attemptId}:${status}:${report ?? ""}:${error ?? ""}${reportMetadata ? JSON.stringify(reportMetadata) : ""}`)
|
|
39
|
+
.digest("hex")
|
|
40
|
+
.slice(0, 16);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Normalize raw outcome fields (bounding report length, sanitizing error, canonicalizing metadata,
|
|
44
|
+
* validating optional device artifact, and recording independent execution/artifact facts)
|
|
45
|
+
* and generate deterministic fingerprint.
|
|
46
|
+
*/
|
|
47
|
+
export function normalizeTaskOutcome(taskId, attemptId, outcome) {
|
|
48
|
+
const safeReport = outcome.report ? boundTaskReport(outcome.report) : undefined;
|
|
49
|
+
const safeError = outcome.error
|
|
50
|
+
? boundTaskReport(deviceTaskFailure(outcome.error), TASK_OUTCOME_ERROR_BYTES)
|
|
51
|
+
: undefined;
|
|
52
|
+
const reportMetadata = outcome.reportMetadata === undefined ? undefined : parseReportMetadata(outcome.reportMetadata);
|
|
53
|
+
let validArtifact;
|
|
54
|
+
if (outcome.artifact !== undefined) {
|
|
55
|
+
const res = validateDeviceArtifact(outcome.artifact);
|
|
56
|
+
if (!res.valid) {
|
|
57
|
+
throw new Error(`Invalid device artifact: ${res.reason}`);
|
|
58
|
+
}
|
|
59
|
+
// Deep clone and freeze to prevent caller alias mutation from corrupting recorded evidence
|
|
60
|
+
validArtifact = deepFreeze(structuredClone(res.artifact));
|
|
61
|
+
}
|
|
62
|
+
if (outcome.executionCompleted !== undefined && typeof outcome.executionCompleted !== "boolean") {
|
|
63
|
+
throw new Error("Execution proof 'executionCompleted' must be a boolean when present");
|
|
64
|
+
}
|
|
65
|
+
if (outcome.artifactProduced !== undefined && typeof outcome.artifactProduced !== "boolean") {
|
|
66
|
+
throw new Error("Artifact proof 'artifactProduced' must be a boolean when present");
|
|
67
|
+
}
|
|
68
|
+
const executionCompleted = outcome.executionCompleted;
|
|
69
|
+
const artifactProduced = outcome.artifactProduced;
|
|
70
|
+
const fingerprint = computeOutcomeFingerprint(taskId, attemptId, outcome.status, safeReport, safeError, reportMetadata, validArtifact?.digest, executionCompleted, artifactProduced);
|
|
71
|
+
return {
|
|
72
|
+
status: outcome.status,
|
|
73
|
+
report: safeReport,
|
|
74
|
+
error: safeError,
|
|
75
|
+
reportMetadata,
|
|
76
|
+
artifact: validArtifact,
|
|
77
|
+
executionCompleted,
|
|
78
|
+
artifactProduced,
|
|
79
|
+
fingerprint,
|
|
80
|
+
};
|
|
81
|
+
}
|