my-durable 0.0.61 → 0.0.63
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/apps/dpi-backend/scripts/bench-store.mjs +284 -0
- package/apps/dpi-backend/src/archived.ts +1 -1
- package/apps/dpi-backend/src/gc.ts +27 -6
- package/apps/dpi-backend/src/pairing-files.ts +65 -0
- package/apps/dpi-backend/src/pairing.ts +25 -9
- package/apps/dpi-backend/src/routes.ts +24 -1
- package/apps/dpi-backend/src/schedules.ts +65 -11
- package/apps/dpi-backend/src/store.ts +215 -43
- package/apps/dpi-backend/src/tunnel.ts +45 -13
- package/apps/dpi-backend/src/zip.ts +376 -10
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-4Kyozhl0.js → index-D10XyhhO.js} +23 -23
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BkSQ2clA.css → index-DCz-aq0b.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +10 -13
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +1 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +1 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/credentials.ts +46 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +21 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +101 -7
- package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +19 -5
- package/apps/dpi-playground/apps/dpi-playground-hub/src/rotation.ts +80 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +25 -4
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +183 -36
- package/apps/dpi-sdk/src/client.ts +73 -6
- package/apps/dpi-sdk/src/protocol/limits.ts +27 -0
- package/apps/dpi-sdk/src/protocol/tunnel.ts +18 -10
- package/package.json +1 -1
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* R8 store-perf benchmark — plain node script, no test framework.
|
|
4
|
+
*
|
|
5
|
+
* Measures per-op latency (p50/p95/max in ms) of the real Store APIs against a
|
|
6
|
+
* throwaway sandbox home (default /tmp/r8perf), plus a paired raw-sqlite
|
|
7
|
+
* commit control (synchronous=FULL vs NORMAL) so any catalog pragma change is
|
|
8
|
+
* evidence-backed rather than assumed.
|
|
9
|
+
*
|
|
10
|
+
* Mix (flags tune the counts):
|
|
11
|
+
* - N session creates (Store.create → catalog INSERT + per-session sqlite open)
|
|
12
|
+
* - M catalog insert+commit cycles (BEGIN/INSERT/COMMIT on the real catalog,
|
|
13
|
+
* the exact shape idempotency.ts writes per POST)
|
|
14
|
+
* - A entry appends (conversation commit → tx.appendEntry → per-session DB)
|
|
15
|
+
* - P entry-list pages (Store.entries, first-page + full-walk pages)
|
|
16
|
+
* - G git-status cycles (fresh spawn each, cache bypassed via a future `now`)
|
|
17
|
+
*
|
|
18
|
+
* Run with the backend's tsx loader (same as `npm start`):
|
|
19
|
+
* cd apps/dpi-backend && node --import tsx scripts/bench-store.mjs
|
|
20
|
+
* (equivalently: npx tsx scripts/bench-store.mjs)
|
|
21
|
+
*
|
|
22
|
+
* Flags: --home /tmp/r8perf --sessions 100 --appends 2000 --pages 500
|
|
23
|
+
* --git 6 --catalog-commits 300 --label before
|
|
24
|
+
*
|
|
25
|
+
* The sandbox home's data dir is WIPED at start so every run (before/after a
|
|
26
|
+
* store change) starts from the same empty state.
|
|
27
|
+
*/
|
|
28
|
+
import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
|
|
29
|
+
import { DatabaseSync } from "node:sqlite";
|
|
30
|
+
import { execFileSync } from "node:child_process";
|
|
31
|
+
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
32
|
+
import { join } from "node:path";
|
|
33
|
+
import { loadavg } from "node:os";
|
|
34
|
+
import { performance } from "node:perf_hooks";
|
|
35
|
+
import { randomUUID } from "node:crypto";
|
|
36
|
+
import { fileURLToPath } from "node:url";
|
|
37
|
+
import { dirname } from "node:path";
|
|
38
|
+
|
|
39
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
40
|
+
const { Store } = await import(join(here, "../src/store.js"));
|
|
41
|
+
const { gitStatus } = await import(join(here, "../src/git.js"));
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------- flags
|
|
44
|
+
const arg = (name, fallback) => {
|
|
45
|
+
const i = process.argv.indexOf(`--${name}`);
|
|
46
|
+
return i >= 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : fallback;
|
|
47
|
+
};
|
|
48
|
+
const HOME = String(arg("home", "/tmp/r8perf"));
|
|
49
|
+
const N_SESSIONS = Number(arg("sessions", 100));
|
|
50
|
+
const N_APPENDS = Number(arg("appends", 2000));
|
|
51
|
+
const N_PAGES = Number(arg("pages", 500));
|
|
52
|
+
const N_GIT = Number(arg("git", 6));
|
|
53
|
+
const N_CATALOG_COMMITS = Number(arg("catalog-commits", 300));
|
|
54
|
+
const LABEL = String(arg("label", "run"));
|
|
55
|
+
|
|
56
|
+
// ---------------------------------------------------------------- sandbox
|
|
57
|
+
const DATA_DIR = join(HOME, "backend");
|
|
58
|
+
const WORK = join(HOME, "work");
|
|
59
|
+
const REPO = join(WORK, "repo");
|
|
60
|
+
rmSync(DATA_DIR, { recursive: true, force: true });
|
|
61
|
+
rmSync(REPO, { recursive: true, force: true });
|
|
62
|
+
mkdirSync(join(REPO, "nested"), { recursive: true });
|
|
63
|
+
writeFileSync(join(REPO, "README.md"), "# r8 bench\n");
|
|
64
|
+
const git = (...args) => execFileSync("git", args, { cwd: REPO, stdio: "ignore" });
|
|
65
|
+
git("init", "-q");
|
|
66
|
+
git("config", "user.email", "bench@example.com");
|
|
67
|
+
git("config", "user.name", "r8 bench");
|
|
68
|
+
git("add", ".");
|
|
69
|
+
git("commit", "-qm", "bench seed");
|
|
70
|
+
|
|
71
|
+
// ---------------------------------------------------------------- stats
|
|
72
|
+
const pct = (samples, p) => {
|
|
73
|
+
const s = [...samples].sort((a, b) => a - b);
|
|
74
|
+
const idx = Math.min(s.length - 1, Math.max(0, Math.ceil((p / 100) * s.length) - 1));
|
|
75
|
+
return s[idx];
|
|
76
|
+
};
|
|
77
|
+
const mean = (s) => s.reduce((a, b) => a + b, 0) / s.length;
|
|
78
|
+
const r = (ms) => (ms >= 100 ? Math.round(ms) : Math.round(ms * 1000) / 1000);
|
|
79
|
+
const results = [];
|
|
80
|
+
const bench = (name, count, fn) => {
|
|
81
|
+
const samples = [];
|
|
82
|
+
const t0 = performance.now();
|
|
83
|
+
for (let i = 0; i < count; i += 1) {
|
|
84
|
+
const s = performance.now();
|
|
85
|
+
fn(i);
|
|
86
|
+
samples.push(performance.now() - s);
|
|
87
|
+
}
|
|
88
|
+
const total = performance.now() - t0;
|
|
89
|
+
const row = {
|
|
90
|
+
op: name,
|
|
91
|
+
count,
|
|
92
|
+
totalMs: r(total),
|
|
93
|
+
meanMs: r(mean(samples)),
|
|
94
|
+
p50: r(pct(samples, 50)),
|
|
95
|
+
p95: r(pct(samples, 95)),
|
|
96
|
+
max: r(Math.max(...samples)),
|
|
97
|
+
over20ms: samples.filter((x) => x > 20).length,
|
|
98
|
+
};
|
|
99
|
+
results.push(row);
|
|
100
|
+
return row;
|
|
101
|
+
};
|
|
102
|
+
const benchAsync = async (name, count, fn) => {
|
|
103
|
+
const samples = [];
|
|
104
|
+
const t0 = performance.now();
|
|
105
|
+
for (let i = 0; i < count; i += 1) {
|
|
106
|
+
const s = performance.now();
|
|
107
|
+
await fn(i);
|
|
108
|
+
samples.push(performance.now() - s);
|
|
109
|
+
}
|
|
110
|
+
const total = performance.now() - t0;
|
|
111
|
+
const row = {
|
|
112
|
+
op: name,
|
|
113
|
+
count,
|
|
114
|
+
totalMs: r(total),
|
|
115
|
+
meanMs: r(mean(samples)),
|
|
116
|
+
p50: r(pct(samples, 50)),
|
|
117
|
+
p95: r(pct(samples, 95)),
|
|
118
|
+
max: r(Math.max(...samples)),
|
|
119
|
+
over20ms: samples.filter((x) => x > 20).length,
|
|
120
|
+
};
|
|
121
|
+
results.push(row);
|
|
122
|
+
return row;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
// ---------------------------------------------------------------- run
|
|
126
|
+
const started = performance.now();
|
|
127
|
+
const load0 = loadavg()[0];
|
|
128
|
+
console.log(`[r8-bench] home=${HOME} label=${LABEL} load1m(start)=${load0.toFixed(2)}`);
|
|
129
|
+
|
|
130
|
+
const store = await Store.open({
|
|
131
|
+
dataDir: DATA_DIR,
|
|
132
|
+
startDirs: [WORK],
|
|
133
|
+
name: "r8-bench",
|
|
134
|
+
provider: "faux",
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// 1) Session creates: catalog insert + openAgent (fresh per-session sqlite) + gitStatus.
|
|
138
|
+
console.log("[r8-bench] store open — starting session.create");
|
|
139
|
+
const ids = [];
|
|
140
|
+
await benchAsync("session.create", N_SESSIONS, async (i) => {
|
|
141
|
+
const s = await store.create({ name: `bench-${String(i).padStart(4, "0")}`, cwd: REPO });
|
|
142
|
+
ids.push(s.id);
|
|
143
|
+
});
|
|
144
|
+
console.log("[r8-bench] session.create done");
|
|
145
|
+
|
|
146
|
+
// 2) Catalog insert+commit cycles — the exact write shape idempotency.ts does per POST.
|
|
147
|
+
// This is the pragma-sensitive path: journal WAL + synchronous=<default FULL> today.
|
|
148
|
+
const insert = store.catalog.prepare(
|
|
149
|
+
"INSERT OR REPLACE INTO requests(key,route,status,body,createdAt) VALUES(?,?,?,?,?)",
|
|
150
|
+
);
|
|
151
|
+
console.log("[r8-bench] starting catalog.insert+commit");
|
|
152
|
+
bench("catalog.insert+commit", N_CATALOG_COMMITS, (i) => {
|
|
153
|
+
store.catalog.exec("BEGIN");
|
|
154
|
+
try {
|
|
155
|
+
insert.run(`bench-${LABEL}-${i}`, "POST /v1/sessions", 201, '"bench"', Date.now());
|
|
156
|
+
store.catalog.exec("COMMIT");
|
|
157
|
+
} catch (e) {
|
|
158
|
+
store.catalog.exec("ROLLBACK");
|
|
159
|
+
throw e;
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// 2b) openAgent isolation: catalog rows inserted by hand, then ONLY the harness/sqlite
|
|
164
|
+
// open is timed — splits session.create's cost between the catalog write and the
|
|
165
|
+
// per-session DB open (migrations + Harness.open).
|
|
166
|
+
const agentRows = [];
|
|
167
|
+
for (let i = 0; i < Math.min(10, N_SESSIONS); i += 1) {
|
|
168
|
+
const base = store.row(ids[i]);
|
|
169
|
+
const id = randomUUID();
|
|
170
|
+
const row = {
|
|
171
|
+
id,
|
|
172
|
+
name: `bench-agent-${String(i).padStart(4, "0")}`,
|
|
173
|
+
cwd: REPO,
|
|
174
|
+
dbPath: join(store.sessionsDir, id, "agent.sqlite"),
|
|
175
|
+
createdAt: Date.now(),
|
|
176
|
+
model: base.model,
|
|
177
|
+
provider: base.provider,
|
|
178
|
+
};
|
|
179
|
+
store.catalog
|
|
180
|
+
.prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
|
|
181
|
+
.run(row.id, row.name, row.cwd, row.dbPath, row.createdAt, row.model, row.provider);
|
|
182
|
+
agentRows.push(row);
|
|
183
|
+
}
|
|
184
|
+
await benchAsync("agent.open(solo)", agentRows.length, async (i) => {
|
|
185
|
+
await store.openAgent(agentRows[i], true);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// 3) Entry appends into session 0's conversation (real append API: commit → tx.appendEntry).
|
|
189
|
+
console.log("[r8-bench] starting entry.append");
|
|
190
|
+
const row0 = store.row(ids[0]);
|
|
191
|
+
const { c } = await store.resolveAgent(row0.id, "main");
|
|
192
|
+
await benchAsync("entry.append", N_APPENDS, async (i) => {
|
|
193
|
+
await c.commit(async (tx) => {
|
|
194
|
+
await tx.appendEntry(c.id, {
|
|
195
|
+
kind: "bench.entry",
|
|
196
|
+
data: { i, text: `r8 benchmark entry ${i} — realistic mixed-length payload ${"x".repeat(80 + (i % 120))}` },
|
|
197
|
+
});
|
|
198
|
+
}, ctx);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// 4) Entry-list pages: first page re-reads (UI poll shape) + one full walk (deep pages).
|
|
202
|
+
console.log("[r8-bench] starting entries pages");
|
|
203
|
+
await benchAsync("entries.page(first)", N_PAGES, async () => {
|
|
204
|
+
const page = await store.entries(c, undefined, 100);
|
|
205
|
+
if (!page.items.length) throw Error("expected entries");
|
|
206
|
+
});
|
|
207
|
+
await benchAsync("entries.page(full-walk)", N_PAGES, async () => {
|
|
208
|
+
let cursor;
|
|
209
|
+
let pages = 0;
|
|
210
|
+
let items = 0;
|
|
211
|
+
for (;;) {
|
|
212
|
+
const page = await store.entries(c, cursor, 100);
|
|
213
|
+
pages += 1;
|
|
214
|
+
items += page.items.length;
|
|
215
|
+
cursor = page.next;
|
|
216
|
+
if (!cursor) break;
|
|
217
|
+
if (pages > 500) throw Error("walk did not terminate");
|
|
218
|
+
}
|
|
219
|
+
if (items === 0) throw Error("expected entries");
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// 5) Git-status cycles: fresh git spawn each time (cache bypassed via a future `now`).
|
|
223
|
+
console.log("[r8-bench] starting git.status");
|
|
224
|
+
const futureNow = () => Date.now() + 3_600_000;
|
|
225
|
+
bench("git.status(fresh)", N_GIT, (i) => {
|
|
226
|
+
writeFileSync(join(REPO, `scratch-${i}.txt`), `dirty ${i}\n`);
|
|
227
|
+
const st = gitStatus(REPO, futureNow());
|
|
228
|
+
if (!st) throw Error("no status");
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// 6) Paired pragma control on throwaway files: identical commit loop, FULL vs NORMAL.
|
|
232
|
+
// Directly quantifies what the catalog's missing synchronous=NORMAL costs per commit.
|
|
233
|
+
console.log("[r8-bench] starting pragma control");
|
|
234
|
+
const pragmaControl = (path, synchronous) => {
|
|
235
|
+
const db = new DatabaseSync(path);
|
|
236
|
+
db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=${synchronous};
|
|
237
|
+
CREATE TABLE IF NOT EXISTS requests(key TEXT PRIMARY KEY,route TEXT NOT NULL,status INTEGER NOT NULL,body TEXT NOT NULL,createdAt INTEGER NOT NULL);`);
|
|
238
|
+
const ins = db.prepare("INSERT OR REPLACE INTO requests(key,route,status,body,createdAt) VALUES(?,?,?,?,?)");
|
|
239
|
+
const samples = [];
|
|
240
|
+
for (let i = 0; i < N_CATALOG_COMMITS; i += 1) {
|
|
241
|
+
const s = performance.now();
|
|
242
|
+
db.exec("BEGIN");
|
|
243
|
+
ins.run(`ctl-${synchronous}-${i}`, "POST /v1/sessions", 201, '"ctl"', Date.now());
|
|
244
|
+
db.exec("COMMIT");
|
|
245
|
+
samples.push(performance.now() - s);
|
|
246
|
+
}
|
|
247
|
+
db.close();
|
|
248
|
+
return samples;
|
|
249
|
+
};
|
|
250
|
+
const full = pragmaControl(join(HOME, "ctl-full.sqlite"), "FULL");
|
|
251
|
+
const normal = pragmaControl(join(HOME, "ctl-normal.sqlite"), "NORMAL");
|
|
252
|
+
for (const [name, samples] of [
|
|
253
|
+
["control.commit(sync=FULL)", full],
|
|
254
|
+
["control.commit(sync=NORMAL)", normal],
|
|
255
|
+
]) {
|
|
256
|
+
results.push({
|
|
257
|
+
op: name,
|
|
258
|
+
count: samples.length,
|
|
259
|
+
totalMs: r(samples.reduce((a, b) => a + b, 0)),
|
|
260
|
+
meanMs: r(mean(samples)),
|
|
261
|
+
p50: r(pct(samples, 50)),
|
|
262
|
+
p95: r(pct(samples, 95)),
|
|
263
|
+
max: r(Math.max(...samples)),
|
|
264
|
+
over20ms: samples.filter((x) => x > 20).length,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
await store.close().catch(() => {});
|
|
269
|
+
|
|
270
|
+
// ---------------------------------------------------------------- report
|
|
271
|
+
const pad = (v, n) => String(v).padStart(n);
|
|
272
|
+
console.log(`\n[r8-bench] label=${LABEL} totalMs=${r(performance.now() - started)} load1m(end)=${loadavg()[0].toFixed(2)}`);
|
|
273
|
+
console.log(
|
|
274
|
+
`${pad("op", 26)} ${pad("count", 7)} ${pad("totalMs", 9)} ${pad("meanMs", 9)} ${pad("p50", 9)} ${pad("p95", 9)} ${pad("max", 9)} ${pad(">20ms", 7)}`,
|
|
275
|
+
);
|
|
276
|
+
for (const row of results)
|
|
277
|
+
console.log(
|
|
278
|
+
`${pad(row.op, 26)} ${pad(row.count, 7)} ${pad(row.totalMs, 9)} ${pad(row.meanMs, 9)} ${pad(row.p50, 9)} ${pad(row.p95, 9)} ${pad(row.max, 9)} ${pad(row.over20ms, 7)}`,
|
|
279
|
+
);
|
|
280
|
+
writeFileSync(join(HOME, `bench-${LABEL}.json`), JSON.stringify({ label: LABEL, home: HOME, results }, null, 2));
|
|
281
|
+
console.log(`[r8-bench] json → ${join(HOME, `bench-${LABEL}.json`)}`);
|
|
282
|
+
// The Store's watchers (awake/git/telegram timers) keep the event loop alive after
|
|
283
|
+
// close(); the measurements are done — exit explicitly.
|
|
284
|
+
process.exit(0);
|
|
@@ -40,7 +40,7 @@ const FILE_MODE = 0o600;
|
|
|
40
40
|
const DIR_MODE = 0o700;
|
|
41
41
|
|
|
42
42
|
/** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. 36 uuid chars + 13 ms digits. */
|
|
43
|
-
const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
|
|
43
|
+
export const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
|
|
44
44
|
/** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
|
|
45
45
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
46
46
|
|
|
@@ -7,11 +7,17 @@
|
|
|
7
7
|
* explicitly. `--dry-run` is the default at the CLI, following piggery's
|
|
8
8
|
* `gc --closed-before DURATION [--dry-run]` shape.
|
|
9
9
|
*
|
|
10
|
-
* An archived session directory is `<archiveDir>/<
|
|
11
|
-
*
|
|
10
|
+
* An archived session directory is `<archiveDir>/<uuid>-<closedAtMs>` — parsed
|
|
11
|
+
* with the SAME strict `BUNDLE_DIR_PATTERN` the archive browser and restore use
|
|
12
|
+
* (audit 3.1: the old loose `<name>-<10+ digits>` form let gc delete operator
|
|
13
|
+
* directories like `nas-backup-2025010112` that the UI never listed). Any
|
|
14
|
+
* directory in archive/ that does not parse strictly — or whose closedAt is out
|
|
15
|
+
* of range — is reported as skipped and never deleted, so age and size remain
|
|
16
|
+
* readable without opening any database.
|
|
12
17
|
*/
|
|
13
18
|
import { readdir, rm, stat } from "node:fs/promises";
|
|
14
19
|
import { join } from "node:path";
|
|
20
|
+
import { BUNDLE_DIR_PATTERN } from "./archived.js";
|
|
15
21
|
|
|
16
22
|
export interface ArchivedEntry {
|
|
17
23
|
/** Directory name inside archive/. */
|
|
@@ -49,16 +55,25 @@ async function dirBytes(path: string): Promise<number> {
|
|
|
49
55
|
return total;
|
|
50
56
|
}
|
|
51
57
|
|
|
52
|
-
/**
|
|
58
|
+
/**
|
|
59
|
+
* Parse `<uuid>-<closedAtMs>` with the exact strict pattern the archive browser
|
|
60
|
+
* and restore use (`archived.ts` BUNDLE_DIR_PATTERN); anything else is reported
|
|
61
|
+
* as skipped, never guessed at. A shape-match with an out-of-range value (13
|
|
62
|
+
* zeros → closedAt 0) is refused too: skip, don't delete.
|
|
63
|
+
*/
|
|
53
64
|
export function parseArchivedName(name: string): { sessionId: string; closedAt: number } | undefined {
|
|
54
|
-
const match =
|
|
65
|
+
const match = BUNDLE_DIR_PATTERN.exec(name);
|
|
55
66
|
if (!match) return undefined;
|
|
56
67
|
const closedAt = Number(match[2]);
|
|
57
68
|
if (!Number.isFinite(closedAt) || closedAt <= 0) return undefined;
|
|
58
69
|
return { sessionId: match[1], closedAt };
|
|
59
70
|
}
|
|
60
71
|
|
|
61
|
-
export async function archivedEntries(
|
|
72
|
+
export async function archivedEntries(
|
|
73
|
+
archiveDir: string,
|
|
74
|
+
/** Clock for the future-closedAt guard; defaults to wall time. */
|
|
75
|
+
now: number = Date.now(),
|
|
76
|
+
): Promise<{ entries: ArchivedEntry[]; skipped: GcPlan["skipped"] }> {
|
|
62
77
|
const entries: ArchivedEntry[] = [];
|
|
63
78
|
const skipped: GcPlan["skipped"] = [];
|
|
64
79
|
for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
|
|
@@ -68,6 +83,12 @@ export async function archivedEntries(archiveDir: string): Promise<{ entries: Ar
|
|
|
68
83
|
skipped.push({ name: entry.name, reason: "not an archived-session directory" });
|
|
69
84
|
continue;
|
|
70
85
|
}
|
|
86
|
+
if (parsed.closedAt > now) {
|
|
87
|
+
// A bundle stamped in the future (bad clock, corrupted name) is reported
|
|
88
|
+
// and never considered for deletion.
|
|
89
|
+
skipped.push({ name: entry.name, reason: "closedAt is in the future — never auto-deleted" });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
71
92
|
const path = join(archiveDir, entry.name);
|
|
72
93
|
entries.push({ name: entry.name, path, ...parsed, bytes: await dirBytes(path) });
|
|
73
94
|
}
|
|
@@ -81,7 +102,7 @@ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: nu
|
|
|
81
102
|
// Sub-day cutoffs are legal (R5 finding 6): the CLI advertises 90m/12h and
|
|
82
103
|
// parseDuration delivers them as fractional days. Only non-positive values refuse.
|
|
83
104
|
if (!Number.isFinite(days) || days <= 0) throw new Error(`closedBeforeDays must be positive, got ${String(days)}`);
|
|
84
|
-
const { entries, skipped } = await archivedEntries(archiveDir);
|
|
105
|
+
const { entries, skipped } = await archivedEntries(archiveDir, now);
|
|
85
106
|
const cutoff = now - days * 86_400_000;
|
|
86
107
|
const candidates = entries
|
|
87
108
|
.filter((entry) => entry.closedAt <= cutoff)
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import {
|
|
11
11
|
chmodSync,
|
|
12
12
|
closeSync,
|
|
13
|
+
copyFileSync,
|
|
13
14
|
fsyncSync,
|
|
14
15
|
openSync,
|
|
15
16
|
readFileSync,
|
|
@@ -101,6 +102,70 @@ export function loadJson<T>(path: string): T | undefined {
|
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
|
|
105
|
+
/** Outcome of loading the device pairing state. Exactly one of `file`/`corrupt` is set; a fresh device has neither. */
|
|
106
|
+
export interface PairingFileLoad {
|
|
107
|
+
/** A parseable pairing.json (shape is judged by the caller). */
|
|
108
|
+
file?: PairingFile;
|
|
109
|
+
/** pairing.json existed but was not valid JSON — it was quarantined (or, if that failed, left in place). */
|
|
110
|
+
corrupt?: { quarantinedAs: string };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* R9 (audit 1.1): a corrupt pairing.json must never read as a silent "unpaired" —
|
|
115
|
+
* that orphans a live hub credential with no trace on disk. Following the
|
|
116
|
+
* schedules registry pattern (schedules.ts load(): move aside + warn): a parse
|
|
117
|
+
* failure renames the file aside so the bytes survive for inspection/restore,
|
|
118
|
+
* with a loud warning naming the quarantine path. A read failure (permissions,
|
|
119
|
+
* I/O) keeps the file in place — its bytes may be fine — but is warned about,
|
|
120
|
+
* never swallowed.
|
|
121
|
+
*/
|
|
122
|
+
export function loadPairingFile(home: string): PairingFileLoad {
|
|
123
|
+
const path = pairingPath(home);
|
|
124
|
+
let raw: string;
|
|
125
|
+
try {
|
|
126
|
+
raw = readFileSync(path, "utf8");
|
|
127
|
+
} catch (e) {
|
|
128
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") return {}; // fresh device: nothing to load
|
|
129
|
+
console.warn(
|
|
130
|
+
`[pairing] ${path} could not be read (${(e as Error).message}); the device reads as unpaired — fix the file before re-pairing, or a live hub credential stays orphaned`,
|
|
131
|
+
);
|
|
132
|
+
return {};
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
return { file: JSON.parse(raw) as PairingFile };
|
|
136
|
+
} catch (e) {
|
|
137
|
+
const aside = `${path}.corrupt-${Date.now()}`;
|
|
138
|
+
try {
|
|
139
|
+
renameSync(path, aside);
|
|
140
|
+
} catch {
|
|
141
|
+
console.warn(
|
|
142
|
+
`[pairing] pairing.json is not valid JSON (${(e as Error).message}) and could not be moved aside; it was left untouched in place`,
|
|
143
|
+
);
|
|
144
|
+
return { corrupt: { quarantinedAs: path } };
|
|
145
|
+
}
|
|
146
|
+
console.warn(
|
|
147
|
+
`[pairing] pairing.json was not valid JSON (${(e as Error).message}) — a live hub credential may now be orphaned. ` +
|
|
148
|
+
`The unreadable file was quarantined as ${aside}; recover it from a backup (or the last-good ${path}.bak), or re-pair this device`,
|
|
149
|
+
);
|
|
150
|
+
return { corrupt: { quarantinedAs: aside } };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Keep the previous good pairing.json as `.bak` before it is replaced (R9 1.1,
|
|
156
|
+
* same recovery story as the schedules registry): even after the corrupt
|
|
157
|
+
* original was quarantined there is a known-good recovery source on disk.
|
|
158
|
+
* Best effort — a failed backup never blocks the atomic replacement.
|
|
159
|
+
*/
|
|
160
|
+
export function backUpPairingFile(path: string): void {
|
|
161
|
+
try {
|
|
162
|
+
copyFileSync(path, `${path}.bak`);
|
|
163
|
+
ensureFileMode0600(`${path}.bak`);
|
|
164
|
+
} catch {
|
|
165
|
+
/* nothing to back up (first pairing) or the copy failed — the new file still lands atomically */
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
104
169
|
/**
|
|
105
170
|
* The device key, or undefined when there is none yet. Anything else that keeps it from being read (permissions,
|
|
106
171
|
* I/O error, truncated or damaged contents) throws: the caller must not answer that by minting a new identity
|
|
@@ -24,10 +24,11 @@ import {
|
|
|
24
24
|
import { hostname, platform } from "node:os";
|
|
25
25
|
import type { Store } from "./store.js";
|
|
26
26
|
import {
|
|
27
|
+
backUpPairingFile,
|
|
27
28
|
ensureFileMode0600,
|
|
28
29
|
ensurePrivateDir,
|
|
29
30
|
keypairPath,
|
|
30
|
-
|
|
31
|
+
loadPairingFile,
|
|
31
32
|
pairingPath,
|
|
32
33
|
readKeypairFile,
|
|
33
34
|
removeStaleTemps,
|
|
@@ -80,7 +81,8 @@ export interface PairingStartInput {
|
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
export type PairingStatus = {
|
|
83
|
-
|
|
84
|
+
/** `file-error`: pairing.json was present but unreadable/unparseable — it was quarantined (R9 1.1); lastError names the path. */
|
|
85
|
+
state: "unpaired" | "pairing" | "paired" | "revoked" | "file-error";
|
|
84
86
|
deviceUid: string;
|
|
85
87
|
deviceName: string;
|
|
86
88
|
fingerprint: string; // from the LOCAL key — never echoed from the hub
|
|
@@ -180,6 +182,8 @@ export class DevicePairing {
|
|
|
180
182
|
private keypair: DeviceKeypair | undefined;
|
|
181
183
|
private paired: PairingFile | undefined;
|
|
182
184
|
private revokedNotice = false;
|
|
185
|
+
/** R9 1.1: pairing.json was quarantined at boot — a live hub credential may be orphaned (detail names the path). */
|
|
186
|
+
private fileError: string | undefined;
|
|
183
187
|
|
|
184
188
|
constructor(
|
|
185
189
|
private readonly store: Store,
|
|
@@ -197,7 +201,12 @@ export class DevicePairing {
|
|
|
197
201
|
ensurePrivateDir(home);
|
|
198
202
|
removeStaleTemps(home);
|
|
199
203
|
this.loadKeypair();
|
|
200
|
-
|
|
204
|
+
const loaded = loadPairingFile(home);
|
|
205
|
+
if (loaded.corrupt)
|
|
206
|
+
this.fileError =
|
|
207
|
+
`pairing.json was not valid JSON and was quarantined as ${loaded.corrupt.quarantinedAs}; ` +
|
|
208
|
+
`a live hub credential may be orphaned — recover it from a backup or ${pairingPath(home)}.bak, or re-pair`;
|
|
209
|
+
this.paired = loaded.file;
|
|
201
210
|
if (this.paired) ensureFileMode0600(pairingPath(home));
|
|
202
211
|
if (this.paired) ensurePrivateDir(home);
|
|
203
212
|
}
|
|
@@ -229,11 +238,13 @@ export class DevicePairing {
|
|
|
229
238
|
const base: PairingStatus = {
|
|
230
239
|
state: this.pending
|
|
231
240
|
? "pairing"
|
|
232
|
-
: this.
|
|
233
|
-
? "
|
|
234
|
-
: this.
|
|
235
|
-
? "
|
|
236
|
-
:
|
|
241
|
+
: this.fileError
|
|
242
|
+
? "file-error"
|
|
243
|
+
: this.revokedNotice
|
|
244
|
+
? "revoked"
|
|
245
|
+
: this.paired
|
|
246
|
+
? "paired"
|
|
247
|
+
: "unpaired",
|
|
237
248
|
deviceUid: this.store.uid,
|
|
238
249
|
deviceName: this.deviceName,
|
|
239
250
|
fingerprint: this.keypair!.fingerprint,
|
|
@@ -254,7 +265,9 @@ export class DevicePairing {
|
|
|
254
265
|
},
|
|
255
266
|
}
|
|
256
267
|
: {}),
|
|
257
|
-
...(this.lastFailure
|
|
268
|
+
...((this.lastFailure ?? this.fileError)
|
|
269
|
+
? { lastError: this.lastFailure ?? this.fileError }
|
|
270
|
+
: {}),
|
|
258
271
|
};
|
|
259
272
|
return base;
|
|
260
273
|
}
|
|
@@ -680,6 +693,8 @@ export class DevicePairing {
|
|
|
680
693
|
// never authenticated (the proof was checked at the challenge, not here).
|
|
681
694
|
...(pending.kfp ? { hubKeyFingerprint: pending.kfp } : {}),
|
|
682
695
|
};
|
|
696
|
+
// R9 1.1: keep the previous good file recoverable before it is replaced.
|
|
697
|
+
backUpPairingFile(pairingPath(this.home));
|
|
683
698
|
writeAtomic(pairingPath(this.home), JSON.stringify(file, null, 2));
|
|
684
699
|
// Re-check: a newer operation/pairing must not be clobbered by this commit.
|
|
685
700
|
if (this.pending?.operationId !== pending.operationId) return;
|
|
@@ -688,6 +703,7 @@ export class DevicePairing {
|
|
|
688
703
|
this.paired = file;
|
|
689
704
|
this.pending = undefined;
|
|
690
705
|
this.lastFailure = undefined;
|
|
706
|
+
this.fileError = undefined; // a good file just landed; the quarantine notice is obsolete
|
|
691
707
|
this.revokedNotice = false;
|
|
692
708
|
// The old hub keeps its tunnel and its pairing right up to here: only a persisted replacement ends them.
|
|
693
709
|
if (previous && previous.hubOrigin !== file.hubOrigin) {
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
// REST v1. Every route requires the device token (see auth.ts). Session refs are a UUID or a
|
|
2
2
|
// unique name; agent refs are a numeric id, `main`, or a unique name.
|
|
3
3
|
import { Router, type Request, type Response, type NextFunction } from "express";
|
|
4
|
+
import { createReadStream } from "node:fs";
|
|
5
|
+
import { pipeline } from "node:stream/promises";
|
|
4
6
|
import type { Conversation, Harness } from "@earendil-works/pi-durable";
|
|
5
7
|
import { DEVICE_DOC_KINDS, type SessionRow, type Store } from "./store.js";
|
|
6
8
|
import { agentStream, deviceStream, sessionStream } from "./streams.js";
|
|
7
9
|
import { idempotent } from "./idempotency.js";
|
|
8
10
|
import { invalid, notFound } from "./errors.js";
|
|
11
|
+
import { streamSessionBundle } from "./zip.js";
|
|
9
12
|
import type { DevicePairing } from "./pairing.js";
|
|
10
13
|
|
|
11
14
|
type Async = (req: Request, res: Response) => Promise<unknown>;
|
|
@@ -332,7 +335,27 @@ export function v1(
|
|
|
332
335
|
res.status(201).json(await store.restoreArchivedSession(param(req, "id"))),
|
|
333
336
|
));
|
|
334
337
|
// One downloadable .zip: manifest + session record + every agent's transcript/config.
|
|
335
|
-
|
|
338
|
+
// R8: the bundle streams through a temp file (deflate piped to disk, never the
|
|
339
|
+
// whole archive in RAM) and the route pipes that file out, unlinks it in the
|
|
340
|
+
// finally, and speaks plain zip bytes — Content-Disposition names the download.
|
|
341
|
+
// Guards (256 MiB uncompressed ceiling, zip64-less limits) run during the temp
|
|
342
|
+
// write, so refusals surface as the usual JSON faults before any byte is sent.
|
|
343
|
+
r.get(
|
|
344
|
+
"/sessions/:s/export",
|
|
345
|
+
route(async (_req, res) => {
|
|
346
|
+
const bundle = await streamSessionBundle(store, L(res).row);
|
|
347
|
+
try {
|
|
348
|
+
res.set({
|
|
349
|
+
"Content-Type": bundle.mime,
|
|
350
|
+
"Content-Length": String(bundle.bytes),
|
|
351
|
+
"Content-Disposition": `attachment; filename="${bundle.filename}"`,
|
|
352
|
+
});
|
|
353
|
+
await pipeline(createReadStream(bundle.path), res);
|
|
354
|
+
} finally {
|
|
355
|
+
await bundle.cleanup();
|
|
356
|
+
}
|
|
357
|
+
}),
|
|
358
|
+
);
|
|
336
359
|
r.get("/sessions/:s/events", route(async (_req, res) => sessionStream(store, L(res).row, res)));
|
|
337
360
|
// The zcode flagship, adapted: which files has THIS session's agent touched?
|
|
338
361
|
// Powers "commit session changes" in the git panel.
|