my-durable 0.0.112 → 0.0.114
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/src/backup-cli.ts +10 -6
- package/apps/dpi-backend/src/backup.ts +13 -3
- package/apps/dpi-backend/src/diagnostics.ts +183 -18
- package/apps/dpi-backend/src/git.ts +49 -9
- package/apps/dpi-backend/src/store.ts +21 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-DbCm0j9f.js → index-DrpVM1aK.js} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-lji31QeB.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +25 -25
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +8 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +4 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +45 -4
- package/apps/dpi-sdk/src/node/config.ts +20 -2
- package/apps/dpi-sdk/src/node/drivers.ts +46 -19
- package/apps/dpi-sdk/src/node/ops.ts +90 -18
- package/apps/dpi-sdk/src/node/private-file.ts +31 -9
- package/apps/dpi-sdk/src/node/registry.ts +7 -2
- package/apps/dpi-tui/src/main.ts +7 -0
- package/apps/dpi-tui/src/pickers.ts +6 -6
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D_y3xKcl.css +0 -1
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Piggery's rule, borrowed from `dpi gc`: a destructive op asks once. `restore`
|
|
6
6
|
* prints the plan (file count, target home, where the old home goes) and exits
|
|
7
|
-
* 0 without touching anything unless `--yes` is passed — and
|
|
8
|
-
* at all, plan included, while the device daemon
|
|
9
|
-
* DPI_HOST/DPI_PORT rule `dpi doctor` uses;
|
|
7
|
+
* 0 without touching anything unless `--yes` is passed — and create and
|
|
8
|
+
* restore both refuse to run at all, plan included, while the device daemon
|
|
9
|
+
* answers on its port (the same DPI_HOST/DPI_PORT rule `dpi doctor` uses;
|
|
10
|
+
* healthz needs no auth).
|
|
10
11
|
*
|
|
11
12
|
* The CLI io extends the module's `BackupIo` with print/printErr/env/homedir,
|
|
12
13
|
* so one object is faked in tests. Exit codes: 0 ok, 1 backup error, 2 usage
|
|
@@ -66,8 +67,9 @@ const HELP = `dpi backup — device home backup/restore (checklist Wave 2)
|
|
|
66
67
|
--dir DIR where list looks (default: the create dir for that home)
|
|
67
68
|
--yes actually restore — without it, restore only prints the plan
|
|
68
69
|
|
|
69
|
-
Restore
|
|
70
|
-
DPI_PORT, default 127.0.0.1:4780) —
|
|
70
|
+
Restore and create refuse to run while the device daemon answers on its
|
|
71
|
+
port (DPI_HOST / DPI_PORT, default 127.0.0.1:4780) — a backup taken under a
|
|
72
|
+
live daemon is torn — stop it first with \`dpi device stop\`.
|
|
71
73
|
Exit codes: 0 ok, 1 backup error, 2 usage error.`;
|
|
72
74
|
|
|
73
75
|
const flagValue = (argv: readonly string[], name: string): string | undefined => {
|
|
@@ -158,7 +160,9 @@ async function createCmd(rest: readonly string[], io: BackupCliIo): Promise<numb
|
|
|
158
160
|
const out = outArg
|
|
159
161
|
? resolve(expand(outArg, io.homedir()))
|
|
160
162
|
: join(defaultBackupDir(home), `dpi-backup-${stamp(io.now())}.zip`);
|
|
161
|
-
|
|
163
|
+
// R9 (run-8 u7): same probe, same URL rule as restoreCmd — a live daemon
|
|
164
|
+
// means a torn backup, so create refuses before touching anything.
|
|
165
|
+
const result = await createBackup(io, { home, out, healthzUrl: await healthzUrl(io) });
|
|
162
166
|
io.print(result.path);
|
|
163
167
|
io.print(`backed up ${result.files} file(s), ${humanBytes(result.bytes)} from ${home}`);
|
|
164
168
|
return 0;
|
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
* - `restoreBackup` deletes nothing either — an existing home is renamed to
|
|
10
10
|
* `<home>.bak-<timestamp>` and kept, so the one rollback a restore has is
|
|
11
11
|
* also the only copy it needs;
|
|
12
|
-
* - restore
|
|
13
|
-
* copy taken under a live sqlite handle is not a backup, it
|
|
12
|
+
* - create and restore both refuse to run while the device daemon answers
|
|
13
|
+
* on its port: a copy taken under a live sqlite handle is not a backup, it
|
|
14
|
+
* is a lie.
|
|
14
15
|
*
|
|
15
16
|
* The zip is built in memory, so the walk is capped (256 MiB by default,
|
|
16
17
|
* `maxBytes`). The writer here emits the same three records as `zip.ts` (local
|
|
@@ -81,7 +82,7 @@ export interface BackupIo {
|
|
|
81
82
|
readdir(path: string): Promise<string[]>;
|
|
82
83
|
chmod(path: string, mode: number): Promise<void>;
|
|
83
84
|
exists(path: string): Promise<boolean>;
|
|
84
|
-
/** Daemon probe for restore. A fetch that THROWS is a refused connection, i.e. "not running". */
|
|
85
|
+
/** Daemon probe for create and restore. A fetch that THROWS is a refused connection, i.e. "not running". */
|
|
85
86
|
fetch?(url: string, init?: { signal?: AbortSignal }): Promise<{ ok: boolean; status: number }>;
|
|
86
87
|
now(): number;
|
|
87
88
|
}
|
|
@@ -129,6 +130,8 @@ export interface CreateBackupOptions {
|
|
|
129
130
|
deviceName?: string;
|
|
130
131
|
/** Total-bytes guard for the in-memory zip build. Defaults to `MAX_BACKUP_BYTES` (256 MiB). */
|
|
131
132
|
maxBytes?: number;
|
|
133
|
+
/** When set, create first refuses if the daemon answers here — the same probe restore runs (healthz needs no auth). */
|
|
134
|
+
healthzUrl?: string;
|
|
132
135
|
}
|
|
133
136
|
|
|
134
137
|
export interface CreateBackupResult {
|
|
@@ -193,6 +196,13 @@ async function walkHome(io: BackupIo, home: string, out: string, maxBytes: numbe
|
|
|
193
196
|
* module's.
|
|
194
197
|
*/
|
|
195
198
|
export async function createBackup(io: BackupIo, opts: CreateBackupOptions): Promise<CreateBackupResult> {
|
|
199
|
+
// R9 (run-8 u7): the probe restore already runs, mirrored verbatim — a
|
|
200
|
+
// backup taken while the daemon answers captures catalog.sqlite,
|
|
201
|
+
// agent.sqlite and -wal/-shm at different instants, i.e. a live "backup"
|
|
202
|
+
// is torn. First thing, like restore: fail before any fs work starts.
|
|
203
|
+
if (opts.healthzUrl && (await deviceIsRunning(io, opts.healthzUrl))) {
|
|
204
|
+
throw new BackupError("device_running", "the device is running — stop it first (`dpi device stop`)");
|
|
205
|
+
}
|
|
196
206
|
const home = resolve(opts.home);
|
|
197
207
|
const out = resolve(opts.out);
|
|
198
208
|
let homeStat: BackupStat;
|
|
@@ -21,9 +21,17 @@
|
|
|
21
21
|
* synchronous (`existsSync`/`readFileSync`/`accessSync`), so the io carries
|
|
22
22
|
* that surface too and `diagnosticsDoctorIo` bridges the two worlds — one
|
|
23
23
|
* object to fake in tests, never the real fs or network.
|
|
24
|
+
*
|
|
25
|
+
* R9 caps (run-8 u7): every collected byte has a ceiling — device.log is read
|
|
26
|
+
* tail-bounded (`readFileTail`, at most DEVICE_LOG_TAIL_BYTES off disk), API
|
|
27
|
+
* bodies over API_BODY_MAX_BYTES are refused unparsed, every section's final
|
|
28
|
+
* text is capped at SECTION_MAX_BYTES with an explicit truncation marker, and
|
|
29
|
+
* the whole bundle answers to BUNDLE_MAX_BYTES export-refusal style. The
|
|
30
|
+
* `shareable` mode goes further: no device.log at all and env VALUES hard-
|
|
31
|
+
* redacted — the operator-shareable bundle never carries env/log payloads.
|
|
24
32
|
*/
|
|
25
33
|
import { accessSync, existsSync, readFileSync } from "node:fs";
|
|
26
|
-
import { access, chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
34
|
+
import { access, chmod, mkdir, open, readFile, writeFile } from "node:fs/promises";
|
|
27
35
|
import { homedir } from "node:os";
|
|
28
36
|
import { dirname, join, resolve } from "node:path";
|
|
29
37
|
import {
|
|
@@ -36,7 +44,7 @@ import {
|
|
|
36
44
|
type DoctorIo,
|
|
37
45
|
} from "./doctor.js";
|
|
38
46
|
import { PACKAGE_VERSION } from "./store.js";
|
|
39
|
-
import { zipSync, type ZipEntry } from "./zip.js";
|
|
47
|
+
import { zipRawBytes, zipSync, type ZipEntry } from "./zip.js";
|
|
40
48
|
|
|
41
49
|
export type DiagnosticsErrorCode = "invalid";
|
|
42
50
|
|
|
@@ -61,6 +69,48 @@ const SECTION_TIMEOUT_MS = 10_000;
|
|
|
61
69
|
/** The device.log tail: the last 400 lines, never the whole file. */
|
|
62
70
|
export const DEVICE_LOG_LINES = 400;
|
|
63
71
|
|
|
72
|
+
// ------------------------------------------------------------------ R9 caps
|
|
73
|
+
// The run-8 u7 finding: a hostile device (or a huge log) could blow up RAM and
|
|
74
|
+
// the bundle — whole device.log into RAM, uncapped apiSection bodies, zipSync
|
|
75
|
+
// with no total ceiling. Every collected byte now has a ceiling:
|
|
76
|
+
|
|
77
|
+
/** Max UTF-8 bytes of any ONE section's final text (post-redaction, pre-zip). */
|
|
78
|
+
export const SECTION_MAX_BYTES = 256 * 1024;
|
|
79
|
+
/** Max raw bytes of an API response body BEFORE it is parsed — bounds the
|
|
80
|
+
* JSON.parse amplification a hostile device could otherwise force. */
|
|
81
|
+
export const API_BODY_MAX_BYTES = 512 * 1024;
|
|
82
|
+
/** Max raw bytes ever read from device.log — the tail read's ceiling. */
|
|
83
|
+
export const DEVICE_LOG_TAIL_BYTES = 512 * 1024;
|
|
84
|
+
/** Aggregate ceiling: total raw section bytes (and, as a backstop, the zipped
|
|
85
|
+
* bytes) a bundle may hold. With per-section caps this cannot trip in practice
|
|
86
|
+
* — it is the named backstop the same style zip.ts's export guards use. */
|
|
87
|
+
export const BUNDLE_MAX_BYTES = 8 * 1024 * 1024;
|
|
88
|
+
|
|
89
|
+
/** Byte-safe truncation with an explicit marker — a section never silently
|
|
90
|
+
* exceeds its ceiling. The marker's bytes come out of the budget, so the
|
|
91
|
+
* truncated text is still ≤ maxBytes. */
|
|
92
|
+
function capSectionText(name: string, text: string): { text: string; truncated: boolean } {
|
|
93
|
+
if (Buffer.byteLength(text, "utf8") <= SECTION_MAX_BYTES) return { text, truncated: false };
|
|
94
|
+
const marker = `\n[${name}: truncated at ${SECTION_MAX_BYTES} bytes]\n`;
|
|
95
|
+
const budget = Math.max(0, SECTION_MAX_BYTES - Buffer.byteLength(marker, "utf8"));
|
|
96
|
+
// subarray + toString drops an invalid trailing multibyte fragment
|
|
97
|
+
const cut = Buffer.from(text, "utf8").subarray(0, budget).toString("utf8");
|
|
98
|
+
return { text: `${cut}${marker}`, truncated: true };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Shareable bundles never carry env VALUES: every string becomes a fixed
|
|
102
|
+
* marker (key names stay — they are schema, and what a bug report needs). */
|
|
103
|
+
function hardRedactValues(value: unknown): unknown {
|
|
104
|
+
if (typeof value === "string") return "«redacted»";
|
|
105
|
+
if (Array.isArray(value)) return value.map(hardRedactValues);
|
|
106
|
+
if (value && typeof value === "object") {
|
|
107
|
+
const out: Record<string, unknown> = {};
|
|
108
|
+
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[key] = hardRedactValues(entry);
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
|
|
64
114
|
/** Narrow fetch surface, `doctor.ts`'s init shape so its checks pass through unchanged. */
|
|
65
115
|
export interface DiagnosticsFetchInit {
|
|
66
116
|
method?: string;
|
|
@@ -77,6 +127,11 @@ export interface DiagnosticsResponse {
|
|
|
77
127
|
|
|
78
128
|
export interface DiagnosticsIo {
|
|
79
129
|
readFile(path: string): Promise<string>;
|
|
130
|
+
/** R9 tail-bounded read: at most `maxBytes` from the END of the file,
|
|
131
|
+
* line-aligned (a partial first line is dropped — tail semantics). Optional
|
|
132
|
+
* for io compatibility; production's default io implements it, and callers
|
|
133
|
+
* without it fall back to `readFile` (still line- and byte-capped after). */
|
|
134
|
+
readFileTail?(path: string, maxBytes: number): Promise<string>;
|
|
80
135
|
/** `mode` applies when the file is created; an explicit `chmod` follows, like backup.ts's persist. */
|
|
81
136
|
writeFile(path: string, data: Uint8Array, mode?: number): Promise<void>;
|
|
82
137
|
chmod(path: string, mode: number): Promise<void>;
|
|
@@ -110,6 +165,22 @@ export const defaultDiagnosticsIo = (): DiagnosticsIo => ({
|
|
|
110
165
|
return false;
|
|
111
166
|
}
|
|
112
167
|
},
|
|
168
|
+
// R9: never read a whole file to keep its tail — stat, then read only the
|
|
169
|
+
// last maxBytes (a file at or under the ceiling still comes back whole).
|
|
170
|
+
readFileTail: async (path, maxBytes) => {
|
|
171
|
+
const handle = await open(path, "r");
|
|
172
|
+
try {
|
|
173
|
+
const { size } = await handle.stat();
|
|
174
|
+
if (size <= maxBytes) return await handle.readFile("utf8");
|
|
175
|
+
const buf = Buffer.alloc(maxBytes);
|
|
176
|
+
await handle.read(buf, 0, maxBytes, size - maxBytes);
|
|
177
|
+
const text = buf.toString("utf8");
|
|
178
|
+
const nl = text.indexOf("\n");
|
|
179
|
+
return nl >= 0 ? text.slice(nl + 1) : text; // drop the partial first line
|
|
180
|
+
} finally {
|
|
181
|
+
await handle.close();
|
|
182
|
+
}
|
|
183
|
+
},
|
|
113
184
|
fetch: (url, init) => fetch(url, init as RequestInit | undefined),
|
|
114
185
|
now: () => Date.now(),
|
|
115
186
|
env: process.env as Record<string, string | undefined>,
|
|
@@ -157,13 +228,16 @@ export interface DiagnosticsSection {
|
|
|
157
228
|
bytes: number;
|
|
158
229
|
/** Present when the section failed: what the CLI prints after the colon. */
|
|
159
230
|
error?: string;
|
|
231
|
+
/** Present when the section's text was capped at SECTION_MAX_BYTES. */
|
|
232
|
+
truncated?: boolean;
|
|
160
233
|
}
|
|
161
234
|
|
|
162
|
-
/** The `GET /v1/...` routes that become json sections, in bundle order.
|
|
163
|
-
|
|
235
|
+
/** The `GET /v1/...` routes that become json sections, in bundle order. `shareable`
|
|
236
|
+
* marks sections whose VALUES never enter a shareable bundle (env). */
|
|
237
|
+
const API_SECTIONS: ReadonlyArray<{ name: string; route: string; shareable?: boolean }> = [
|
|
164
238
|
{ name: "device.json", route: "/v1/device" },
|
|
165
239
|
{ name: "vitals.json", route: "/v1/device/vitals" },
|
|
166
|
-
{ name: "env.json", route: "/v1/device/env" },
|
|
240
|
+
{ name: "env.json", route: "/v1/device/env", shareable: true },
|
|
167
241
|
{ name: "sessions.json", route: "/v1/sessions" },
|
|
168
242
|
{ name: "projects.json", route: "/v1/projects" },
|
|
169
243
|
{ name: "schedules.json", route: "/v1/schedules" },
|
|
@@ -190,12 +264,15 @@ function diagnosticsDoctorIo(io: DiagnosticsIo): DoctorIo {
|
|
|
190
264
|
};
|
|
191
265
|
}
|
|
192
266
|
|
|
193
|
-
/** One JSON section from the device API: ok → redacted body; failure → `{"error": ...}` and the bundle carries on.
|
|
267
|
+
/** One JSON section from the device API: ok → redacted body; failure → `{"error": ...}` and the bundle carries on.
|
|
268
|
+
* R9: a body over API_BODY_MAX_BYTES is refused with the size named — it is
|
|
269
|
+
* never parsed — and a `shareable` section's string VALUES never survive. */
|
|
194
270
|
async function apiSection(
|
|
195
271
|
io: DiagnosticsIo,
|
|
196
272
|
url: string,
|
|
197
273
|
route: string,
|
|
198
274
|
headers: Record<string, string>,
|
|
275
|
+
opts: { hardRedact?: boolean } = {},
|
|
199
276
|
): Promise<{ text: string; ok: boolean; error?: string }> {
|
|
200
277
|
let ok: boolean;
|
|
201
278
|
let status: number;
|
|
@@ -204,7 +281,15 @@ async function apiSection(
|
|
|
204
281
|
const res = await io.fetch(url, { headers, signal: AbortSignal.timeout(SECTION_TIMEOUT_MS) });
|
|
205
282
|
ok = res.ok;
|
|
206
283
|
status = res.status;
|
|
207
|
-
|
|
284
|
+
// R9 cold review: never buffer the whole body before the cap — a hostile
|
|
285
|
+
// device can stream gigabytes inside the 10s section timeout (duration is
|
|
286
|
+
// not a byte budget). Precheck content-length, then read at most the cap.
|
|
287
|
+
const declared = Number(res.headers?.get?.("content-length") ?? "");
|
|
288
|
+
if (Number.isFinite(declared) && declared > API_BODY_MAX_BYTES) {
|
|
289
|
+
const detail = `body over ${API_BODY_MAX_BYTES} bytes (content-length ${declared})`;
|
|
290
|
+
return { text: jsonText({ error: `GET ${route} → ${detail}` }), ok: false, error: detail };
|
|
291
|
+
}
|
|
292
|
+
raw = await readCappedBody(res, API_BODY_MAX_BYTES);
|
|
208
293
|
} catch (error) {
|
|
209
294
|
const detail = describeError(error, SECTION_TIMEOUT_MS);
|
|
210
295
|
return { text: jsonText({ error: `GET ${route} unreachable — ${detail}` }), ok: false, error: detail };
|
|
@@ -212,22 +297,66 @@ async function apiSection(
|
|
|
212
297
|
if (!ok) {
|
|
213
298
|
return { text: jsonText({ error: `GET ${route} → ${status}` }), ok: false, error: String(status) };
|
|
214
299
|
}
|
|
300
|
+
if (Buffer.byteLength(raw, "utf8") > API_BODY_MAX_BYTES) {
|
|
301
|
+
const detail = `body over ${API_BODY_MAX_BYTES} bytes`;
|
|
302
|
+
return { text: jsonText({ error: `GET ${route} → ${detail}` }), ok: false, error: detail };
|
|
303
|
+
}
|
|
215
304
|
let body: unknown;
|
|
216
305
|
try {
|
|
217
306
|
body = JSON.parse(raw);
|
|
218
307
|
} catch {
|
|
219
308
|
return { text: jsonText({ error: `GET ${route} → non-JSON body` }), ok: false, error: "non-JSON body" };
|
|
220
309
|
}
|
|
221
|
-
return { text: jsonText(redactJson(body)), ok: true };
|
|
310
|
+
return { text: jsonText(redactJson(opts.hardRedact ? hardRedactValues(body) : body)), ok: true };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Read at most `cap` bytes off the wire, cancelling the stream past that (R9
|
|
314
|
+
* cold-review finding 1: the old `res.text()` buffered the entire body first).
|
|
315
|
+
* Non-stream bodies (test mocks) fall back to `text()` — the post-read byte
|
|
316
|
+
* check still refuses those. Over-cap returns a `cap+1`-byte marker string so
|
|
317
|
+
* the existing refusal names the cap without having buffered the payload. */
|
|
318
|
+
async function readCappedBody(
|
|
319
|
+
res: { body?: unknown; text(): Promise<string> },
|
|
320
|
+
cap: number,
|
|
321
|
+
): Promise<string> {
|
|
322
|
+
const body = res.body as ReadableStream<Uint8Array> | undefined;
|
|
323
|
+
if (!body || typeof body.getReader !== "function") return res.text();
|
|
324
|
+
const reader = body.getReader();
|
|
325
|
+
const chunks: Uint8Array[] = [];
|
|
326
|
+
let total = 0;
|
|
327
|
+
for (;;) {
|
|
328
|
+
const { done, value } = await reader.read();
|
|
329
|
+
if (done) break;
|
|
330
|
+
total += value.byteLength;
|
|
331
|
+
chunks.push(value);
|
|
332
|
+
if (total > cap) {
|
|
333
|
+
try {
|
|
334
|
+
await reader.cancel();
|
|
335
|
+
} catch {
|
|
336
|
+
/* already closed */
|
|
337
|
+
}
|
|
338
|
+
return "\u0000".repeat(cap + 1); // marker: byteLength === cap+1 → the refusal fires
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const merged = new Uint8Array(total);
|
|
342
|
+
let off = 0;
|
|
343
|
+
for (const c of chunks) {
|
|
344
|
+
merged.set(c, off);
|
|
345
|
+
off += c.byteLength;
|
|
346
|
+
}
|
|
347
|
+
return new TextDecoder("utf-8").decode(merged);
|
|
222
348
|
}
|
|
223
349
|
|
|
224
|
-
/** The device.log tail: last 400 lines, redacted. Missing → skipped (undefined); unreadable → a failed section.
|
|
350
|
+
/** The device.log tail: last 400 lines, redacted. Missing → skipped (undefined); unreadable → a failed section.
|
|
351
|
+
* R9: the READ is tail-bounded — at most DEVICE_LOG_TAIL_BYTES raw bytes come
|
|
352
|
+
* off disk (io.readFileTail); ios without the tail surface fall back to
|
|
353
|
+
* readFile, and the per-section cap still bounds what enters the bundle. */
|
|
225
354
|
async function logSection(io: DiagnosticsIo, home: string): Promise<{ text: string; ok: boolean; error?: string } | undefined> {
|
|
226
355
|
const logPath = join(home, "device.log");
|
|
227
356
|
if (!(await io.exists(logPath))) return undefined;
|
|
228
357
|
let raw: string;
|
|
229
358
|
try {
|
|
230
|
-
raw = await io.readFile(logPath);
|
|
359
|
+
raw = io.readFileTail ? await io.readFileTail(logPath, DEVICE_LOG_TAIL_BYTES) : await io.readFile(logPath);
|
|
231
360
|
} catch (error) {
|
|
232
361
|
const detail = describeError(error, 0);
|
|
233
362
|
return { text: `# cannot read ${logPath}: ${detail}\n`, ok: false, error: detail };
|
|
@@ -243,6 +372,14 @@ async function logSection(io: DiagnosticsIo, home: string): Promise<{ text: stri
|
|
|
243
372
|
export interface CollectDiagnosticsOptions {
|
|
244
373
|
home: string;
|
|
245
374
|
out: string;
|
|
375
|
+
/** R9 shareable mode: the bundle operators paste into bug reports. Strips
|
|
376
|
+
* device.log entirely (not even read) and hard-redacts env section values —
|
|
377
|
+
* the run-8 "redaction boundary no unit owns" now has an owner. Default
|
|
378
|
+
* false: the local bundle keeps the (masked) log and env sections. */
|
|
379
|
+
shareable?: boolean;
|
|
380
|
+
/** R9 aggregate-ceiling override (raw section bytes); tests use tiny values
|
|
381
|
+
* to prove enforcement. Default BUNDLE_MAX_BYTES. */
|
|
382
|
+
maxBundleBytes?: number;
|
|
246
383
|
}
|
|
247
384
|
|
|
248
385
|
export interface CollectDiagnosticsResult {
|
|
@@ -273,8 +410,16 @@ export async function collectDiagnostics(
|
|
|
273
410
|
const sections: DiagnosticsSection[] = [];
|
|
274
411
|
const entries: ZipEntry[] = [];
|
|
275
412
|
const push = (name: string, text: string, ok: boolean, error?: string): void => {
|
|
276
|
-
|
|
277
|
-
|
|
413
|
+
// R9: every section is byte-capped on its way in — the marker is explicit.
|
|
414
|
+
const capped = capSectionText(name, text);
|
|
415
|
+
entries.push({ path: name, text: capped.text });
|
|
416
|
+
sections.push({
|
|
417
|
+
name,
|
|
418
|
+
ok,
|
|
419
|
+
bytes: Buffer.byteLength(capped.text, "utf8"),
|
|
420
|
+
...(error ? { error } : {}),
|
|
421
|
+
...(capped.truncated ? { truncated: true } : {}),
|
|
422
|
+
});
|
|
278
423
|
};
|
|
279
424
|
|
|
280
425
|
// doctor.json — doctor's own runner, through this module's io.
|
|
@@ -292,20 +437,24 @@ export async function collectDiagnostics(
|
|
|
292
437
|
push("doctor.json", jsonText(report), ok, error);
|
|
293
438
|
}
|
|
294
439
|
|
|
295
|
-
// the seven registry/summary routes — summaries by design (no transcripts)
|
|
440
|
+
// the seven registry/summary routes — summaries by design (no transcripts);
|
|
441
|
+
// env values are hard-redacted in shareable mode
|
|
296
442
|
for (const section of API_SECTIONS) {
|
|
297
|
-
const r = await apiSection(io, `${cfg.baseUrl}${section.route}`, section.route, headers
|
|
443
|
+
const r = await apiSection(io, `${cfg.baseUrl}${section.route}`, section.route, headers, {
|
|
444
|
+
hardRedact: Boolean(section.shareable && opts.shareable),
|
|
445
|
+
});
|
|
298
446
|
push(section.name, r.text, r.ok, r.error);
|
|
299
447
|
}
|
|
300
448
|
|
|
301
|
-
// device.log — on-disk facts, tail only, redacted
|
|
302
|
-
{
|
|
449
|
+
// device.log — on-disk facts, tail only, redacted; NEVER in a shareable bundle
|
|
450
|
+
if (!opts.shareable) {
|
|
303
451
|
const r = await logSection(io, home);
|
|
304
452
|
if (r) push("device.log", r.text, r.ok, r.error);
|
|
305
453
|
}
|
|
306
454
|
|
|
307
455
|
// The manifest is entry 0 (backup.ts's rule), so it lists the sections that
|
|
308
456
|
// actually made it in — including device.log only when the log was there.
|
|
457
|
+
// R9: it is a section like any other, so it passes the same byte cap.
|
|
309
458
|
const manifest = redactJson({
|
|
310
459
|
createdAt: new Date(io.now()).toISOString(),
|
|
311
460
|
packageVersion: PACKAGE_VERSION,
|
|
@@ -315,10 +464,26 @@ export async function collectDiagnostics(
|
|
|
315
464
|
home,
|
|
316
465
|
sections: sections.map((s) => s.name),
|
|
317
466
|
});
|
|
318
|
-
|
|
319
|
-
|
|
467
|
+
const manifestCapped = capSectionText("manifest.json", jsonText(manifest));
|
|
468
|
+
entries.unshift({ path: "manifest.json", text: manifestCapped.text });
|
|
469
|
+
sections.unshift({
|
|
470
|
+
name: "manifest.json",
|
|
471
|
+
ok: true,
|
|
472
|
+
bytes: Buffer.byteLength(manifestCapped.text, "utf8"),
|
|
473
|
+
...(manifestCapped.truncated ? { truncated: true } : {}),
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
// R9 aggregate ceiling — the refusal style zip.ts's export guards use: the
|
|
477
|
+
// size is named and nothing is written. With per-section caps this cannot
|
|
478
|
+
// trip at defaults; it is the backstop that makes that true by construction.
|
|
479
|
+
const ceiling = opts.maxBundleBytes ?? BUNDLE_MAX_BYTES;
|
|
480
|
+
const rawBytes = zipRawBytes(entries);
|
|
481
|
+
if (rawBytes > ceiling)
|
|
482
|
+
throw invalid(`diagnostic bundle refused: sections are ${rawBytes} bytes, over the ${ceiling} byte ceiling`);
|
|
320
483
|
|
|
321
484
|
const zip = zipSync(entries, new Date(io.now()));
|
|
485
|
+
if (zip.length > ceiling)
|
|
486
|
+
throw invalid(`diagnostic bundle refused: zip is ${zip.length} bytes, over the ${ceiling} byte ceiling`);
|
|
322
487
|
await io.mkdir(dirname(out), DIR_MODE);
|
|
323
488
|
await io.writeFile(out, zip, FILE_MODE);
|
|
324
489
|
await io.chmod(out, FILE_MODE);
|
|
@@ -198,16 +198,56 @@ export function isNotARepoError(e: unknown): boolean {
|
|
|
198
198
|
return /not a git repository/i.test(msg) || /does not have any commits yet/i.test(msg);
|
|
199
199
|
}
|
|
200
200
|
|
|
201
|
-
/**
|
|
201
|
+
/** run-9 B (status-batch spawn fan-out): one 50-path /git/status-batch is
|
|
202
|
+
* ~650 git children (2 guard spawns + 11 parallel data spawns per path, every
|
|
203
|
+
* path in one Promise.all) — and the UIs POLL, so overlapping batches used
|
|
204
|
+
* to stack all of them at once. This is the process-wide ceiling on LIVE git
|
|
205
|
+
* children: one backend process = one device, so a process-wide budget IS
|
|
206
|
+
* the per-device budget. Every git() spawn takes a slot from ONE semaphore;
|
|
207
|
+
* callers beyond the budget QUEUE FIFO (they are never refused) and start
|
|
208
|
+
* the moment a slot frees. A spawn's own timeout starts when the child
|
|
209
|
+
* actually starts, so queueing never eats the timeout. */
|
|
210
|
+
export const GIT_SPAWN_BUDGET = 12;
|
|
211
|
+
let gitSpawnLive = 0;
|
|
212
|
+
const gitSpawnQueue: (() => void)[] = [];
|
|
213
|
+
|
|
214
|
+
/** Take a slot (or queue FIFO for one) — the caller owns the slot until
|
|
215
|
+
* releaseGitSpawn(). No nesting: a slot is held across exactly ONE child,
|
|
216
|
+
* so a queued git child can never be waiting on a spawn that needs this
|
|
217
|
+
* queue to drain — no deadlock. */
|
|
218
|
+
function acquireGitSpawn(): Promise<void> {
|
|
219
|
+
if (gitSpawnLive < GIT_SPAWN_BUDGET) {
|
|
220
|
+
gitSpawnLive++;
|
|
221
|
+
return Promise.resolve();
|
|
222
|
+
}
|
|
223
|
+
return new Promise<void>((wake) => gitSpawnQueue.push(wake));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Free a slot — handed straight to the longest-waiting caller when one
|
|
227
|
+
* exists (the live count already covers the handover), else returned. */
|
|
228
|
+
function releaseGitSpawn() {
|
|
229
|
+
const next = gitSpawnQueue.shift();
|
|
230
|
+
if (next) next();
|
|
231
|
+
else gitSpawnLive--;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** One git call; rejects on non-zero exit with stderr in the message. Every
|
|
235
|
+
* spawn runs under the budget above — see GIT_SPAWN_BUDGET. (gh() stays
|
|
236
|
+
* outside: forge calls are single, user-initiated, and never fan out.) */
|
|
202
237
|
export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT, pin?: RepoPin): Promise<string> {
|
|
203
|
-
return
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
238
|
+
return acquireGitSpawn()
|
|
239
|
+
.then(
|
|
240
|
+
() =>
|
|
241
|
+
new Promise<string>((ok, fail) => {
|
|
242
|
+
// `-C` is ARGV, so the path goes out forward-slashed (see gitPath).
|
|
243
|
+
execFileImpl("git", ["-C", gitPath(cwd), ...args], GIT_EXEC_OPTS(timeout, pin), (error, stdout, stderr) => {
|
|
244
|
+
if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
|
|
245
|
+
// git chats on stderr for worktree add/switch/fetch — keep both.
|
|
246
|
+
else ok(`${String(stdout)}${String(stdout) && String(stderr) ? "\n" : ""}${String(stderr)}`);
|
|
247
|
+
});
|
|
248
|
+
}),
|
|
249
|
+
)
|
|
250
|
+
.finally(releaseGitSpawn);
|
|
211
251
|
}
|
|
212
252
|
|
|
213
253
|
/** One GitHub CLI call — PRs, checks and comments are forge territory and gh
|
|
@@ -1839,6 +1839,7 @@ export class Store {
|
|
|
1839
1839
|
this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
|
|
1840
1840
|
this.opened.delete(row.id);
|
|
1841
1841
|
this.salvageFailedSessions.delete(row.id);
|
|
1842
|
+
this.missingDirSessions.delete(row.id); // run-9 G: the row is gone — drop the memo with it
|
|
1842
1843
|
this.errors.delete(row.id);
|
|
1843
1844
|
this.notify();
|
|
1844
1845
|
return { archived: existing };
|
|
@@ -1859,6 +1860,7 @@ export class Store {
|
|
|
1859
1860
|
this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
|
|
1860
1861
|
this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
|
|
1861
1862
|
this.salvageFailedSessions.delete(row.id); // R20 h6: clear AFTER the move commits — a failed rename must not re-arm salvage
|
|
1863
|
+
this.missingDirSessions.delete(row.id); // run-9 G: same lifecycle — the row left the catalog
|
|
1862
1864
|
this.errors.delete(row.id);
|
|
1863
1865
|
this.notify();
|
|
1864
1866
|
return { archived: target };
|
|
@@ -1958,6 +1960,7 @@ export class Store {
|
|
|
1958
1960
|
}
|
|
1959
1961
|
this.notify();
|
|
1960
1962
|
this.salvageFailedSessions.delete(sessionId); // R20 h6: clear AFTER the bundle actually came back — a REFUSED restore must not re-arm salvage
|
|
1963
|
+
this.missingDirSessions.delete(sessionId); // run-9 G: same lifecycle — the dir is back under sessions/
|
|
1961
1964
|
this.errors.delete(sessionId); // R20 cold-1 minor: the fast-fault note may predate the archive — do not surface a stale reason
|
|
1962
1965
|
// sessionSummary handles a not-yet-opened session (the closed-bundle path).
|
|
1963
1966
|
return await this.sessionSummary(row);
|
|
@@ -1997,6 +2000,11 @@ export class Store {
|
|
|
1997
2000
|
rmSync(dir, { recursive: true, force: true });
|
|
1998
2001
|
throw new ApiFault("unavailable", "session was archived while opening");
|
|
1999
2002
|
}
|
|
2003
|
+
// run-9 G (run-8 u1): the pre-open stat failed ENOENT — the session dir
|
|
2004
|
+
// is gone (zombie row). Memo it so scope=all search stops paying for it;
|
|
2005
|
+
// any later SUCCESSFUL open un-memos (the dir may come back: restore,
|
|
2006
|
+
// manual copy-back — crash-window variant B).
|
|
2007
|
+
if (!create && (e as NodeJS.ErrnoException)?.code === "ENOENT") this.missingDirSessions.add(row.id);
|
|
2000
2008
|
throw e;
|
|
2001
2009
|
}
|
|
2002
2010
|
try {
|
|
@@ -2125,6 +2133,7 @@ export class Store {
|
|
|
2125
2133
|
}
|
|
2126
2134
|
this.opened.set(row.id, { harness, unlock, unsubscribe, jobs, addons });
|
|
2127
2135
|
this.errors.delete(row.id);
|
|
2136
|
+
this.missingDirSessions.delete(row.id); // run-9 G: the dir is back — searchable again
|
|
2128
2137
|
// pi-durable 1.2+: any failed Storage call closes the Session, without waiting for the next event.
|
|
2129
2138
|
// Surface it as unavailable and clean up the handle/listener/lock; never auto-reopen in a loop —
|
|
2130
2139
|
// a later request reopens it once from committed storage (see openAgent), and fails cleanly if it still fails.
|
|
@@ -2988,6 +2997,11 @@ export class Store {
|
|
|
2988
2997
|
// integrity_check on EVERY query (262 MB corrupt db: 5.0 s per query,
|
|
2989
2998
|
// memoization-free), and the FE fires scope=all per keystroke.
|
|
2990
2999
|
if (this.salvageFailedSessions.has(row.id)) continue;
|
|
3000
|
+
// run-9 G (run-8 u1): a zombie row (storage missing, probed once at boot
|
|
3001
|
+
// or on the first failed open) never burns a TRANSCRIPT_SESSION_LIMIT
|
|
3002
|
+
// slot — skipped BEFORE the budget check, so the slots go to sessions
|
|
3003
|
+
// whose data is actually present. Un-memoed when the dir comes back.
|
|
3004
|
+
if (this.missingDirSessions.has(row.id)) continue;
|
|
2991
3005
|
if (sessionsScanned >= TRANSCRIPT_SESSION_LIMIT || entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
|
|
2992
3006
|
truncated = true;
|
|
2993
3007
|
break;
|
|
@@ -3243,6 +3257,13 @@ export class Store {
|
|
|
3243
3257
|
private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
|
|
3244
3258
|
/** R19 (run-5 h1): sessions whose salvage already failed — searched cheaply skipped, salvage never re-run. */
|
|
3245
3259
|
private salvageFailedSessions = new Set<string>();
|
|
3260
|
+
/** run-9 G (run-8 u1 hardening): rows whose sessions/<id> storage is missing
|
|
3261
|
+
* (zombie rows — dir gone, row alive, no bundle). scope=all search skips
|
|
3262
|
+
* them WITHOUT burning one of the 100 TRANSCRIPT_SESSION_LIMIT slots per
|
|
3263
|
+
* query (they used to cost a harness-throw + reopen stat attempt AND a
|
|
3264
|
+
* slot, newest-first). Mirrors the salvage memo's lifecycle: cleared when
|
|
3265
|
+
* the dir is back — any successful open, a completed archive, a restore. */
|
|
3266
|
+
private missingDirSessions = new Set<string>();
|
|
3246
3267
|
|
|
3247
3268
|
/**
|
|
3248
3269
|
* R19 (run-5 h1): the salvage memo is per-process so a corrupt session is not
|