skillar 0.2.1 → 0.3.1
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/NOTICE +280 -0
- package/README.md +37 -5
- package/dist/analysis/finding.js +8 -190
- package/dist/analysis/kernel.js +896 -0
- package/dist/analysis/tree.js +7 -154
- package/dist/analysis/usage.js +9 -394
- package/dist/api/flows.js +42 -212
- package/dist/api/report-kernel.js +1063 -0
- package/dist/api/routes.js +12 -2
- package/dist/catalog/fields.js +138 -146
- package/dist/catalog/watcher.js +7 -2
- package/dist/cli/init.js +45 -0
- package/dist/cli/main.js +76 -3
- package/dist/cli/private-skills.js +122 -0
- package/dist/cli/serve.js +15 -1
- package/dist/cli/sync.js +124 -0
- package/dist/dashboard/NOTICE +280 -0
- package/dist/dashboard/assets/app.js +737 -275
- package/dist/dashboard/assets/astryx-reset.css +407 -0
- package/dist/dashboard/assets/astryx.css +1077 -0
- package/dist/dashboard/assets/charts.css +54 -0
- package/dist/dashboard/assets/chunk-TPGDA2J4.js +1 -0
- package/dist/dashboard/assets/chunk-YLWHVDMP.js +36 -0
- package/dist/dashboard/assets/controls.css +207 -0
- package/dist/dashboard/assets/overlays.css +132 -0
- package/dist/dashboard/assets/p1.css +135 -0
- package/dist/dashboard/assets/shell.css +71 -0
- package/dist/dashboard/assets/skillar-theme.css +692 -0
- package/dist/dashboard/assets/styles.css +224 -121
- package/dist/dashboard/assets/tokens.css +278 -0
- package/dist/dashboard/assets/widgets.css +83 -0
- package/dist/dashboard/index.html +11 -2
- package/dist/dashboard/viewers/viewers.css +61 -0
- package/dist/ingest/attribution.js +5 -1
- package/dist/ingest/pipeline.js +2 -0
- package/dist/ingest/request-recorder.js +39 -0
- package/dist/mcp/dispatch.js +2 -2
- package/dist/mcp/http.js +43 -3
- package/dist/mcp/skills-extension.js +42 -15
- package/dist/mcp/stdio-proxy.js +24 -3
- package/dist/mcp/tools.js +38 -24
- package/dist/packs/claude-code.js +22 -11
- package/dist/packs/cursor.js +9 -4
- package/dist/packs/gemini.js +9 -4
- package/dist/packs/json-config.js +41 -0
- package/dist/packs/omo.js +15 -6
- package/dist/request-status.js +81 -0
- package/dist/search/fts.js +93 -58
- package/dist/search/fusion.js +49 -47
- package/dist/search/guidance.js +18 -6
- package/dist/search/index.js +291 -70
- package/dist/search/lexical.js +71 -63
- package/dist/server.js +12 -0
- package/dist/skills/apply.js +130 -0
- package/dist/skills/capture.js +54 -0
- package/dist/skills/cloud-plan.js +57 -0
- package/dist/skills/cloud.js +81 -0
- package/dist/skills/fs.js +133 -0
- package/dist/skills/package.js +734 -0
- package/dist/skills/plan.js +83 -0
- package/dist/skills/receipt.js +44 -0
- package/dist/skills/rollback.js +119 -0
- package/dist/skills/transfer.js +51 -0
- package/dist/store/db.js +7 -1
- package/dist/store/execution.js +2 -34
- package/dist/store/export.js +25 -4
- package/dist/store/migrations/007_sync.sql +49 -0
- package/dist/store/migrations/008_connector_commands.sql +12 -0
- package/dist/store/queries.js +33 -7
- package/dist/store/writes.js +38 -5
- package/dist/sync/cloud-blobs.js +175 -0
- package/dist/sync/cloud-commands.js +101 -0
- package/dist/sync/cloud-connection.js +105 -0
- package/dist/sync/cloud-delivery.js +114 -0
- package/dist/sync/cloud-documents.js +103 -0
- package/dist/sync/cloud-export.js +67 -0
- package/dist/sync/cloud-http.js +150 -0
- package/dist/sync/cloud-jobs.js +94 -0
- package/dist/sync/cloud-pending.js +143 -0
- package/dist/sync/cloud-prepare.js +101 -0
- package/dist/sync/cloud-restore.js +136 -0
- package/dist/sync/cloud-rollback.js +24 -0
- package/dist/sync/cloud-runner.js +86 -0
- package/dist/sync/cloud-runtime.js +293 -0
- package/dist/sync/cloud-schema.js +32 -0
- package/dist/sync/cloud-stage.js +112 -0
- package/dist/sync/cloud-wire.js +693 -0
- package/dist/sync/cloud-worker.js +57 -0
- package/dist/sync/cloud.js +157 -0
- package/dist/sync/command-apply.js +140 -0
- package/dist/sync/command-control.js +25 -0
- package/dist/sync/command-wire.js +437 -0
- package/dist/sync/consent.js +130 -0
- package/dist/sync/journal.js +43 -0
- package/dist/sync/outbox.js +134 -0
- package/dist/sync/restore-rows.js +125 -0
- package/dist/sync/restore.js +174 -0
- package/dist/sync/snapshot.js +78 -0
- package/dist/sync/spool-request.js +103 -0
- package/dist/sync/tables.js +27 -0
- package/dist/sync/triggers.js +34 -0
- package/dist/workflow/compare.js +3 -43
- package/docs/cloud-sync.md +94 -0
- package/docs/private-skills.md +75 -0
- package/docs/sync-p4.md +102 -0
- package/docs/sync-restore.md +167 -0
- package/package.json +18 -5
- package/src/store/migrations/007_sync.sql +49 -0
- package/src/store/migrations/008_connector_commands.sql +12 -0
- package/dist/dashboard/assets/chunk-5DFWNJC2.js +0 -1
- package/dist/dashboard/assets/chunk-S6B2HJQA.js +0 -17
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { watch } from "node:fs";
|
|
2
|
+
import { basename, dirname } from "node:path";
|
|
3
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { atomicCloudJson, cloudHome } from "./cloud-connection.js";
|
|
6
|
+
import { runCloudStep } from "./cloud.js";
|
|
7
|
+
import { requestRuntimeCapture, runCloudRuntimeStep } from "./cloud-runtime.js";
|
|
8
|
+
import { requestCommandApply, runCloudCommandStep } from "./cloud-commands.js";
|
|
9
|
+
const { home, source, captureRuntime, applyCommands } = z.strictObject({
|
|
10
|
+
home: z.string(), source: z.string(), captureRuntime: z.boolean().default(false),
|
|
11
|
+
applyCommands: z.boolean().default(false),
|
|
12
|
+
}).parse(workerData);
|
|
13
|
+
let busy = false, again = false, timer;
|
|
14
|
+
const wake = () => {
|
|
15
|
+
if (timer !== undefined)
|
|
16
|
+
clearTimeout(timer);
|
|
17
|
+
if (busy) {
|
|
18
|
+
again = true;
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
busy = true;
|
|
22
|
+
void runCloudStep(home, source).then(progress => captureRuntime ? runCloudRuntimeStep(home, source, progress, request => requestRuntimeCapture(parentPort, request)) : progress).then(progress => applyCommands ? runCloudCommandStep(home, progress, (command, instanceId) => requestCommandApply(parentPort, command, instanceId)) : progress).then(progress => {
|
|
23
|
+
parentPort?.postMessage(progress);
|
|
24
|
+
busy = false;
|
|
25
|
+
if (again || progress.phase === "queued") {
|
|
26
|
+
again = false;
|
|
27
|
+
setImmediate(wake);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const delay = progress.phase === "retry" && progress.retryAtMs !== undefined
|
|
31
|
+
? Math.min(30_000, Math.max(1, progress.retryAtMs - Date.now())) : 30_000;
|
|
32
|
+
timer = setTimeout(wake, delay);
|
|
33
|
+
}).catch(() => {
|
|
34
|
+
// Unexpected failures stop this worker; no token, row, or request body is logged.
|
|
35
|
+
const failed = {
|
|
36
|
+
version: 1, instanceId: "", updatedAtMs: Date.now(), phase: "quarantine",
|
|
37
|
+
code: "worker_failed", attempts: 0, excluded: 0, liveTurns: 0,
|
|
38
|
+
};
|
|
39
|
+
atomicCloudJson(home, "status.json", failed);
|
|
40
|
+
parentPort?.postMessage(failed);
|
|
41
|
+
process.exitCode = 1;
|
|
42
|
+
sourceWatch.close();
|
|
43
|
+
controlWatch.close();
|
|
44
|
+
parentPort?.close();
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
const sourceWatch = watch(dirname(source), (_event, filename) => {
|
|
48
|
+
if (filename === basename(source) || filename === `${basename(source)}-wal`)
|
|
49
|
+
wake();
|
|
50
|
+
});
|
|
51
|
+
const controlWatch = watch(cloudHome(home), (_event, filename) => {
|
|
52
|
+
if (filename === "control.json" || filename === "connection.json" || filename === "commands.json")
|
|
53
|
+
wake();
|
|
54
|
+
});
|
|
55
|
+
parentPort?.on("message", value => { if (value === "wake")
|
|
56
|
+
wake(); });
|
|
57
|
+
wake();
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { openDb } from "../store/db.js";
|
|
5
|
+
import { CloudBlobs, CloudSyncError } from "./cloud-blobs.js";
|
|
6
|
+
import { atomicCloudJson, cloudHome, currentCloudDevice, readConnection } from "./cloud-connection.js";
|
|
7
|
+
import { deliverCloudJob } from "./cloud-delivery.js";
|
|
8
|
+
import { CloudHttp, CloudRequestError } from "./cloud-http.js";
|
|
9
|
+
import { liveStream, requireJob } from "./cloud-jobs.js";
|
|
10
|
+
import { bindSource } from "./cloud-prepare.js";
|
|
11
|
+
import { migrationPrefix, stageBaseline, stageLive } from "./cloud-stage.js";
|
|
12
|
+
import { journalHead } from "./journal.js";
|
|
13
|
+
import { SyncError } from "./tables.js";
|
|
14
|
+
import { ActivityContractError, authorizeUpload, parseContentBatch } from "./cloud-wire.js";
|
|
15
|
+
export const cloudProgressSchema = z.strictObject({
|
|
16
|
+
version: z.literal(1), instanceId: z.string(), updatedAtMs: z.number().int(),
|
|
17
|
+
phase: z.enum(["disconnected", "local-only", "metadata-only", "disabled", "busy",
|
|
18
|
+
"queued", "caught-up", "auth-required", "consent-required", "retry", "quarantine", "paused"]),
|
|
19
|
+
sourceDomain: z.string().optional(), acknowledgedCut: z.number().int().nonnegative().optional(),
|
|
20
|
+
excluded: z.number().int().nonnegative().default(0),
|
|
21
|
+
attempts: z.number().int().nonnegative().default(0),
|
|
22
|
+
retryAtMs: z.number().int().optional(), code: z.string().optional(),
|
|
23
|
+
liveTurns: z.number().int().nonnegative().default(0),
|
|
24
|
+
});
|
|
25
|
+
export function cloudStatus(home) {
|
|
26
|
+
const path = join(cloudHome(home), "status.json");
|
|
27
|
+
return existsSync(path) ? cloudProgressSchema.parse(JSON.parse(readFileSync(path, "utf8"))) : null;
|
|
28
|
+
}
|
|
29
|
+
export function pauseCloud(home, paused = true) {
|
|
30
|
+
atomicCloudJson(home, "control.json", { paused });
|
|
31
|
+
}
|
|
32
|
+
function isPaused(home) {
|
|
33
|
+
const path = join(cloudHome(home), "control.json");
|
|
34
|
+
return existsSync(path) && z.strictObject({ paused: z.boolean() })
|
|
35
|
+
.parse(JSON.parse(readFileSync(path, "utf8"))).paused;
|
|
36
|
+
}
|
|
37
|
+
function validatePending(consent, payload) {
|
|
38
|
+
const job = requireJob(payload);
|
|
39
|
+
const common = job.kind === "migration" ? job.begin : parseContentBatch(JSON.parse(job.body));
|
|
40
|
+
if (consent.mode !== "managed-content")
|
|
41
|
+
throw new CloudSyncError("content_consent_required");
|
|
42
|
+
const scope = {
|
|
43
|
+
deviceId: common.deviceId, projectId: common.projectId, rootId: common.rootId,
|
|
44
|
+
consentVersion: common.consentVersion, fromMs: common.range.fromMs, toMs: common.range.toMs,
|
|
45
|
+
contentKinds: consent.contentKinds, backfill: common.backfill,
|
|
46
|
+
};
|
|
47
|
+
authorizeUpload(consent, scope);
|
|
48
|
+
}
|
|
49
|
+
/** One bounded background step. Network backoff is persisted, never slept through. */
|
|
50
|
+
export async function runCloudStep(home, sourcePath, options = {}) {
|
|
51
|
+
const connection = readConnection(home);
|
|
52
|
+
const previous = cloudStatus(home);
|
|
53
|
+
const same = connection !== null && previous?.instanceId === connection.instanceId ? previous : null;
|
|
54
|
+
const save = (phase, fields = {}) => {
|
|
55
|
+
const progress = cloudProgressSchema.parse({
|
|
56
|
+
version: 1, instanceId: connection?.instanceId ?? "", updatedAtMs: Date.now(),
|
|
57
|
+
excluded: same?.excluded ?? 0, liveTurns: same?.liveTurns ?? 0, ...fields, phase,
|
|
58
|
+
});
|
|
59
|
+
atomicCloudJson(home, "status.json", progress);
|
|
60
|
+
return progress;
|
|
61
|
+
};
|
|
62
|
+
if (connection === null)
|
|
63
|
+
return save("disconnected");
|
|
64
|
+
if (options.resume)
|
|
65
|
+
pauseCloud(home, false);
|
|
66
|
+
if (isPaused(home))
|
|
67
|
+
return save("paused");
|
|
68
|
+
if (!options.resume && same?.phase === "quarantine")
|
|
69
|
+
return same;
|
|
70
|
+
if (!options.resume && same?.phase === "retry" && (same.retryAtMs ?? 0) > Date.now())
|
|
71
|
+
return same;
|
|
72
|
+
const blobs = new CloudBlobs(join(cloudHome(home), "spool.sqlite"));
|
|
73
|
+
if (!blobs.acquire()) {
|
|
74
|
+
blobs.close();
|
|
75
|
+
return { version: 1, instanceId: connection.instanceId, updatedAtMs: Date.now(),
|
|
76
|
+
phase: "busy", attempts: 0, excluded: 0, liveTurns: 0 };
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const self = await currentCloudDevice(connection, options.fetcher, same?.attempts ?? 0);
|
|
80
|
+
if (self.consent.mode === "local-only")
|
|
81
|
+
return save("local-only");
|
|
82
|
+
if (self.consent.mode === "metadata")
|
|
83
|
+
return save("metadata-only", { code: "raw_transport_not_enabled" });
|
|
84
|
+
if (!self.ingestEnabled)
|
|
85
|
+
return save("disabled");
|
|
86
|
+
blobs.prune();
|
|
87
|
+
bindSource(sourcePath, connection);
|
|
88
|
+
const source = openDb(sourcePath);
|
|
89
|
+
try {
|
|
90
|
+
const head = journalHead(source), streamId = liveStream(connection.instanceId, head.sourceDomain);
|
|
91
|
+
let migration = blobs.pendingPrefix(migrationPrefix(connection, head.sourceDomain));
|
|
92
|
+
const cursor = blobs.cursor(streamId);
|
|
93
|
+
const historical = self.consent.backfill;
|
|
94
|
+
const backfillDone = historical !== undefined && (blobs.cursor(`${migrationPrefix(connection, head.sourceDomain)}${historical.snapshotId}`)?.ack_sequence ?? 0) > 0;
|
|
95
|
+
if (cursor === null && migration === null) {
|
|
96
|
+
await stageBaseline(home, source, blobs, connection, self.consent, "initial");
|
|
97
|
+
migration = blobs.pendingPrefix(migrationPrefix(connection, head.sourceDomain));
|
|
98
|
+
}
|
|
99
|
+
else if (cursor !== null && migration === null && !backfillDone &&
|
|
100
|
+
(options.backfill || historical !== undefined)) {
|
|
101
|
+
await stageBaseline(home, source, blobs, connection, self.consent, "backfill");
|
|
102
|
+
migration = blobs.pendingPrefix(migrationPrefix(connection, head.sourceDomain));
|
|
103
|
+
}
|
|
104
|
+
let batch = blobs.pending(streamId);
|
|
105
|
+
const migrationTurn = migration !== null && (cursor === null || (same?.liveTurns ?? 0) >= 5);
|
|
106
|
+
if (cursor !== null && batch === null && !migrationTurn) {
|
|
107
|
+
await stageLive(source, blobs, connection, self.consent);
|
|
108
|
+
batch = blobs.pending(streamId);
|
|
109
|
+
}
|
|
110
|
+
batch = migrationTurn ? migration : batch ?? migration;
|
|
111
|
+
if (batch === null)
|
|
112
|
+
return save("caught-up", {
|
|
113
|
+
sourceDomain: head.sourceDomain, acknowledgedCut: cursor?.ack_cut ?? 0,
|
|
114
|
+
});
|
|
115
|
+
if (isPaused(home))
|
|
116
|
+
return save("paused");
|
|
117
|
+
validatePending(self.consent, batch.payload);
|
|
118
|
+
const job = requireJob(batch.payload);
|
|
119
|
+
const result = await deliverCloudJob(blobs, new CloudHttp(connection.origin, connection.token, options.fetcher, 30_000, same?.attempts ?? 0), batch);
|
|
120
|
+
if (result.accepted) {
|
|
121
|
+
if (result.kind === "migration" && job.kind === "migration" && job.begin.purpose === "initial") {
|
|
122
|
+
blobs.initialize({
|
|
123
|
+
streamId, deviceId: connection.deviceId, sourceDomain: head.sourceDomain,
|
|
124
|
+
sequence: result.status.cursor.sequence, cut: result.status.cursor.journalThrough,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
blobs.acknowledge({
|
|
128
|
+
streamId: batch.stream_id, sequence: batch.sequence, payloadHash: batch.payload_hash,
|
|
129
|
+
});
|
|
130
|
+
blobs.prune();
|
|
131
|
+
}
|
|
132
|
+
return save("queued", {
|
|
133
|
+
sourceDomain: head.sourceDomain, acknowledgedCut: blobs.cursor(streamId)?.ack_cut ?? 0,
|
|
134
|
+
excluded: (same?.excluded ?? 0) + (result.accepted ? result.excluded : 0),
|
|
135
|
+
liveTurns: result.kind === "cdc" ? (same?.liveTurns ?? 0) + 1 : 0,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
source.close();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (error instanceof CloudRequestError)
|
|
144
|
+
return save(error.state === "quarantined" ? "quarantine" : error.state, {
|
|
145
|
+
code: error.code, retryAtMs: error.retryAtMs ?? undefined, attempts: (same?.attempts ?? 0) + 1,
|
|
146
|
+
});
|
|
147
|
+
if (error instanceof z.ZodError)
|
|
148
|
+
return save("quarantine", { code: "invalid_contract" });
|
|
149
|
+
if (error instanceof CloudSyncError || error instanceof SyncError || error instanceof ActivityContractError)
|
|
150
|
+
return save(/consent/.test(error.code) ? "consent-required" :
|
|
151
|
+
/credentials|identity/.test(error.code) ? "auth-required" : "quarantine", { code: error.code });
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
blobs.close();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { workflowSpecSchema } from "../workflow/spec.js";
|
|
4
|
+
import { CloudSyncError } from "./cloud-blobs.js";
|
|
5
|
+
import { canonicalCommandPayload, commandResultSchema, sourceCommandSchema, } from "./command-wire.js";
|
|
6
|
+
const headSchema = z.object({ source_domain: z.string(), cut: z.number().int().nonnegative() });
|
|
7
|
+
const receiptSchema = z.object({ payload_hash: z.string(), result_json: z.string() });
|
|
8
|
+
class CommandRejected extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code) {
|
|
11
|
+
super(code);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.name = "CommandRejected";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function execute(store, operation) {
|
|
17
|
+
switch (operation.kind) {
|
|
18
|
+
case "workflow.put": {
|
|
19
|
+
const { row, created } = store.putWorkflowSpec(workflowSpecSchema.parse(operation.spec));
|
|
20
|
+
return { id: row.id, name: row.name, version: row.version, digest: row.digest, createdMs: row.createdMs, created };
|
|
21
|
+
}
|
|
22
|
+
case "flow.create": {
|
|
23
|
+
const spec = store.workflowSpec(operation.spec.name, operation.spec.version);
|
|
24
|
+
if (spec === undefined)
|
|
25
|
+
throw new CommandRejected("spec_not_found");
|
|
26
|
+
const result = store.createFlow({
|
|
27
|
+
workspaceId: operation.workspaceId, specId: spec.id,
|
|
28
|
+
...(operation.tabId === undefined ? {} : { tabId: operation.tabId }),
|
|
29
|
+
...(operation.label === undefined ? {} : { label: operation.label }),
|
|
30
|
+
});
|
|
31
|
+
if (!result.created)
|
|
32
|
+
throw new CommandRejected("flow_already_open");
|
|
33
|
+
return {
|
|
34
|
+
id: result.flow.id, workspaceId: result.flow.workspaceId, tabId: result.flow.tabId ?? null,
|
|
35
|
+
label: result.flow.label ?? null, registeredMs: result.flow.registeredMs,
|
|
36
|
+
spec: { id: spec.id, name: spec.name, version: spec.version },
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
case "flow.map-step": {
|
|
40
|
+
const flow = store.getFlow(operation.flowId);
|
|
41
|
+
if (flow === undefined)
|
|
42
|
+
throw new CommandRejected("flow_not_found");
|
|
43
|
+
if (!flow.spec?.spec.steps.some(step => step.id === operation.stepId))
|
|
44
|
+
throw new CommandRejected("unknown_step");
|
|
45
|
+
const { created } = store.mapFlowStep(flow.id, operation.paneId, operation.stepId);
|
|
46
|
+
return { flowId: flow.id, paneId: operation.paneId, stepId: operation.stepId, created };
|
|
47
|
+
}
|
|
48
|
+
case "flow.end": {
|
|
49
|
+
const ended = store.endFlow(operation.flowId);
|
|
50
|
+
if (ended === undefined)
|
|
51
|
+
throw new CommandRejected("flow_not_found");
|
|
52
|
+
return { id: operation.flowId, ...ended };
|
|
53
|
+
}
|
|
54
|
+
case "eval.add":
|
|
55
|
+
store.addEvalCase({
|
|
56
|
+
query: operation.query,
|
|
57
|
+
...(operation.expectedUri === undefined ? {} : { expectedUri: operation.expectedUri }),
|
|
58
|
+
...(operation.fromTraceId === undefined ? {} : { fromTraceId: operation.fromTraceId }),
|
|
59
|
+
});
|
|
60
|
+
return { stored: true };
|
|
61
|
+
default: {
|
|
62
|
+
const exhaustive = operation;
|
|
63
|
+
return exhaustive;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Main-thread only. Mutation, recording boundaries, CDC triggers and receipt
|
|
69
|
+
* commit together. An ACK lost after commit replays this receipt, not the write.
|
|
70
|
+
*/
|
|
71
|
+
export function applySourceCommand(db, store, connection, input, now = Date.now()) {
|
|
72
|
+
const command = sourceCommandSchema.parse(input);
|
|
73
|
+
if (command.accountId !== connection.accountId || command.generation !== connection.generation ||
|
|
74
|
+
command.deviceId !== connection.deviceId)
|
|
75
|
+
throw new CloudSyncError("command_identity_mismatch");
|
|
76
|
+
const binding = db.prepare("SELECT value FROM meta WHERE key='cloud.binding'").get();
|
|
77
|
+
if (binding?.["value"] !== connection.instanceId)
|
|
78
|
+
throw new CloudSyncError("command_binding_mismatch");
|
|
79
|
+
const hash = createHash("sha256").update(canonicalCommandPayload({
|
|
80
|
+
profile: { deviceId: command.deviceId, sourceDomain: command.sourceDomain },
|
|
81
|
+
commandId: command.commandId, baseRevision: command.baseRevision, operation: command.operation,
|
|
82
|
+
})).digest("hex");
|
|
83
|
+
if (hash !== command.payloadHash)
|
|
84
|
+
throw new CloudSyncError("command_payload_mismatch");
|
|
85
|
+
const identity = [command.accountId, command.generation, command.deviceId, command.sourceDomain, command.commandId];
|
|
86
|
+
db.exec("BEGIN IMMEDIATE");
|
|
87
|
+
try {
|
|
88
|
+
const head = headSchema.parse(db.prepare(`SELECT source_domain,
|
|
89
|
+
COALESCE((SELECT MAX(seq) FROM sync_journal),0) AS cut FROM sync_identity`).get());
|
|
90
|
+
if (head.source_domain !== command.sourceDomain)
|
|
91
|
+
throw new CloudSyncError("command_source_mismatch");
|
|
92
|
+
const previous = db.prepare(`SELECT payload_hash,result_json FROM connector_command_receipts
|
|
93
|
+
WHERE account_id=? AND generation=? AND device_id=? AND source_domain=? AND command_id=?`).get(...identity);
|
|
94
|
+
if (previous !== undefined) {
|
|
95
|
+
const saved = receiptSchema.parse(previous);
|
|
96
|
+
if (saved.payload_hash !== hash)
|
|
97
|
+
throw new CloudSyncError("command_receipt_conflict");
|
|
98
|
+
const result = commandResultSchema.parse(JSON.parse(saved.result_json));
|
|
99
|
+
db.exec("COMMIT");
|
|
100
|
+
return result;
|
|
101
|
+
}
|
|
102
|
+
let state = "applied";
|
|
103
|
+
let result = null;
|
|
104
|
+
let error = null;
|
|
105
|
+
if (command.expiresAtMs <= now) {
|
|
106
|
+
state = "rejected";
|
|
107
|
+
error = "command_expired";
|
|
108
|
+
}
|
|
109
|
+
else if (head.cut !== command.baseRevision) {
|
|
110
|
+
state = "conflict";
|
|
111
|
+
error = "source_revision_conflict";
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
try {
|
|
115
|
+
result = execute(store, command.operation);
|
|
116
|
+
}
|
|
117
|
+
catch (failure) {
|
|
118
|
+
if (!(failure instanceof CommandRejected))
|
|
119
|
+
throw failure;
|
|
120
|
+
state = "rejected";
|
|
121
|
+
error = failure.code;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const after = headSchema.parse(db.prepare(`SELECT source_domain,
|
|
125
|
+
COALESCE((SELECT MAX(seq) FROM sync_journal),0) AS cut FROM sync_identity`).get());
|
|
126
|
+
const receipt = commandResultSchema.parse({
|
|
127
|
+
commandId: command.commandId, payloadHash: hash, state,
|
|
128
|
+
sourceRevision: after.cut, result, error,
|
|
129
|
+
});
|
|
130
|
+
db.prepare(`INSERT INTO connector_command_receipts
|
|
131
|
+
(account_id,generation,device_id,source_domain,command_id,payload_hash,result_json)
|
|
132
|
+
VALUES(?,?,?,?,?,?,?)`).run(...identity, hash, JSON.stringify(receipt));
|
|
133
|
+
db.exec("COMMIT");
|
|
134
|
+
return receipt;
|
|
135
|
+
}
|
|
136
|
+
catch (failure) {
|
|
137
|
+
db.exec("ROLLBACK");
|
|
138
|
+
throw failure;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { CloudSyncError } from "./cloud-blobs.js";
|
|
5
|
+
import { atomicCloudJson, cloudHome, readConnection } from "./cloud-connection.js";
|
|
6
|
+
const approvalSchema = z.strictObject({ instanceId: z.string().uuid(), enabled: z.boolean() });
|
|
7
|
+
/** Local approval is bound to this connection, never inherited by a new account. */
|
|
8
|
+
export function sourceCommandsEnabled(home) {
|
|
9
|
+
const connection = readConnection(home);
|
|
10
|
+
const path = join(cloudHome(home), "commands.json");
|
|
11
|
+
if (connection === null || !existsSync(path))
|
|
12
|
+
return false;
|
|
13
|
+
const approval = approvalSchema.parse(JSON.parse(readFileSync(path, "utf8")));
|
|
14
|
+
const control = join(cloudHome(home), "control.json");
|
|
15
|
+
if (existsSync(control) && z.object({ paused: z.boolean() })
|
|
16
|
+
.parse(JSON.parse(readFileSync(control, "utf8"))).paused)
|
|
17
|
+
return false;
|
|
18
|
+
return approval.enabled && approval.instanceId === connection.instanceId;
|
|
19
|
+
}
|
|
20
|
+
export function approveSourceCommands(home, enabled) {
|
|
21
|
+
const connection = readConnection(home);
|
|
22
|
+
if (connection === null)
|
|
23
|
+
throw new CloudSyncError("not_connected");
|
|
24
|
+
atomicCloudJson(home, "commands.json", { instanceId: connection.instanceId, enabled });
|
|
25
|
+
}
|