my-durable 0.0.64 → 0.0.65

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.
@@ -39,8 +39,14 @@ const DB_NAME = "agent.sqlite";
39
39
  const FILE_MODE = 0o600;
40
40
  const DIR_MODE = 0o700;
41
41
 
42
- /** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. 36 uuid chars + 13 ms digits. */
43
- export const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
42
+ /** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. R11 4.1:
43
+ * CANONICAL uuid shape (8-4-4-4-12 lowercase hex) — the old `[0-9a-f-]{36}`
44
+ * character class also matched 36 dashes, hex-without-dashes and other
45
+ * lookalikes an operator might drop in archive/ from another tool; those are
46
+ * now skipped+reported by BOTH gc and the browser (this ONE pattern is the
47
+ * shared source — real bundles are canonical-uuid session ids by
48
+ * construction, so nothing legitimate is lost). */
49
+ export const BUNDLE_DIR_PATTERN = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-(\d{13})$/;
44
50
  /** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
45
51
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
46
52
 
@@ -82,7 +82,13 @@ export async function archivedEntries(
82
82
  const entries: ArchivedEntry[] = [];
83
83
  const skipped: GcPlan["skipped"] = [];
84
84
  for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
85
- if (!entry.isDirectory()) continue;
85
+ if (!entry.isDirectory()) {
86
+ // R11 4.2: files and SYMLINKED dirs at archive/ root used to be silently
87
+ // invisible (not in total, not in skipped, never explained). Now the plan
88
+ // says what it ignored and why — an honest plan is auditable.
89
+ skipped.push({ name: entry.name, reason: "not a directory (file or symlink) — left untouched" });
90
+ continue;
91
+ }
86
92
  const parsed = parseArchivedName(entry.name);
87
93
  if (!parsed) {
88
94
  skipped.push({ name: entry.name, reason: "not an archived-session directory" });
@@ -50,6 +50,12 @@ export function v1(
50
50
  // (/V1/DEVICE used to answer 200 over loopback and 404 through the tunnel).
51
51
  // Every client (sdk/TUI/web) speaks lowercase — verified against sdk client.ts.
52
52
  const r = Router({ caseSensitive: true });
53
+ // R11 6.3 (doc): `create` auto-keys un-keyed mutations (sha256 of method+path+body,
54
+ // 24 h retention) — a deliberate second identical create (same body) within 24 h
55
+ // REPLAYS the first response instead of creating again. That collapse is the
56
+ // accepted retry-safety tradeoff; clients that need deliberate repeats must send
57
+ // their own Idempotency-Key (which always wins over the auto-key), and replays
58
+ // are visible in the Idempotent-Replay: true response header.
53
59
  const create = idempotent(store);
54
60
  // `dpi device stop`: graceful local shutdown (token-authed like every /v1
55
61
  // route). The response flushes BEFORE the daemon tears down so the caller
@@ -316,7 +322,10 @@ export function v1(
316
322
  r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
317
323
  r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
318
324
  r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
319
- r.post("/schedules/:id/run", route(async (req, res) => res.json(await store.runScheduleNow(param(req, "id")))));
325
+ // R11 2.3: 202 Accepted — the run is ARMED, not finished; the turn is bounded
326
+ // by the dispatch deadlines (60 s submit + 120 s settle) and its outcome lands
327
+ // in the schedule record (GET /schedules) and the schedule.ok/failed events.
328
+ r.post("/schedules/:id/run", route(async (_req, res) => res.status(202).json(await store.runScheduleNow(param(_req, "id")))));
320
329
 
321
330
  // ---------------------------------------------------------- sessions
322
331
  r.get("/sessions", route(async (_req, res) => res.json((await store.tree()).sessions)));
@@ -188,14 +188,21 @@ export async function scheduleCli(argv: readonly string[], io: ScheduleIo = defa
188
188
  return 0;
189
189
  }
190
190
  if (sub === "run") {
191
- io.print(`${target.name}: running…`);
191
+ io.print(`${target.name}: starting…`);
192
+ // R11 2.3: the route answers 202 as soon as the run is ARMED — the turn
193
+ // itself is bounded by the dispatch deadlines and lands in the record and
194
+ // the schedule.ok/failed events. `dpi schedule list` shows the outcome.
192
195
  const ran = await call<ScheduleView>(io, "POST", `/v1/schedules/${target.id}/run`, {});
193
196
  if (!ran.ok) {
194
197
  io.printErr(`dpi schedule: ${ran.error}`);
195
198
  return 1;
196
199
  }
197
- io.print(`${ran.data.lastOutcome ?? "ok"}${ran.data.lastError ? ` — ${ran.data.lastError}` : ""}; next ${when(ran.data.nextRunAt)}`);
198
- return ran.data.lastOutcome === "failed" ? 1 : 0;
200
+ io.print(
201
+ ran.data.running
202
+ ? `run started (watch \`dpi schedule list\` for the outcome); next ${when(ran.data.nextRunAt)}`
203
+ : `armed; next ${when(ran.data.nextRunAt)}`,
204
+ );
205
+ return 0;
199
206
  }
200
207
  if (sub === "remove") {
201
208
  const removed = await call<{ removed: boolean }>(io, "DELETE", `/v1/schedules/${target.id}`);
@@ -2605,11 +2605,23 @@ export class Store {
2605
2605
  * Throws ApiFault("busy") (HTTP 409, "already running") when the schedule
2606
2606
  * has a run in flight: the guard lives in the shared dispatch entry point
2607
2607
  * (R8 2.1), so a double-clicked Run button gets a typed fault instead of a
2608
- * second concurrent run with duplicated side effects. */
2608
+ * second concurrent run with duplicated side effects.
2609
+ *
2610
+ * R11 2.3: returns AS SOON AS the run is armed, not when the turn finishes —
2611
+ * a slow turn used to hold the HTTP request (and the hub tunnel) hostage
2612
+ * for up to the full 60 s dispatch deadline + 120 s settle cap; browsers
2613
+ * and proxies time out long before that. No awaits sit between the busy
2614
+ * pre-check and the dispatch (whose guard-add also runs synchronously), so
2615
+ * two Run clicks in one turn cannot both pass. The outcome lands in the
2616
+ * record (scheduleList/view) and the schedule.ok/failed events, exactly as
2617
+ * the timer path's outcomes always have. The route answers 202. */
2609
2618
  async runScheduleNow(id: string): Promise<ScheduleView> {
2610
2619
  const record = this.schedules.get(id);
2611
2620
  if (!record) throw notFound(`no schedule ${id}`);
2612
- await this.dispatchSchedule(record);
2621
+ if (this.scheduleInFlight.has(record.id)) {
2622
+ throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
2623
+ }
2624
+ void this.dispatchSchedule(record).catch(() => undefined);
2613
2625
  return this.scheduleView(this.schedules.get(id) ?? record);
2614
2626
  }
2615
2627
 
@@ -2642,6 +2654,10 @@ export class Store {
2642
2654
  private scheduleInFlight = new Set<string>();
2643
2655
  private scheduleTimer?: ReturnType<typeof setTimeout>;
2644
2656
 
2657
+ /** R11 2.2: schedules whose registry (schedules.json) is currently
2658
+ * unwritable — each is reported ONCE per degraded episode, not per tick. */
2659
+ private scheduleRegistryDegraded = new Set<string>();
2660
+
2645
2661
  /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2646
2662
  * corrupt session share ONE bounded attempt instead of racing scratch files. */
2647
2663
  private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
@@ -2718,14 +2734,42 @@ export class Store {
2718
2734
  this.scheduleInFlight.add(record.id);
2719
2735
  this.notify();
2720
2736
  try {
2721
- // Persist the intent before any await that can wedge. If this persist
2722
- // itself fails (disk full), the run still proceeds — it just loses the
2723
- // crash-safety guarantee, like every version before R8.
2724
- await deadline(
2737
+ // R11 2.2: the intent marker is the at-most-once anchor. Without it,
2738
+ // `due()` re-offers this slot on EVERY tick while the registry is
2739
+ // unwritable (disk full, AV lock) and the prompt would re-fire at tick
2740
+ // rate — up to 2,880 duplicate real runs/day, each with a notify event.
2741
+ // So a failed intent persist now SKIPS the dispatch (the run has not
2742
+ // started, so not running it is correct) and surfaces the degraded
2743
+ // state ONCE per episode; the next successful write ends the episode.
2744
+ // Outcome persists inside dispatchBounded stay best-effort.
2745
+ const intentOk = await deadline(
2725
2746
  this.schedules.markRun(record.id, { outcome: "started" }),
2726
2747
  SCHEDULE_REGISTRY_IO_MS,
2727
2748
  "schedule registry write timed out (started)",
2728
- ).catch(() => undefined);
2749
+ ).then(
2750
+ () => true,
2751
+ () => false,
2752
+ );
2753
+ if (!intentOk) {
2754
+ if (!this.scheduleRegistryDegraded.has(record.id)) {
2755
+ this.scheduleRegistryDegraded.add(record.id);
2756
+ void this.notifyEvent({
2757
+ kind: "schedule.failed",
2758
+ title: `Schedule paused: ${record.name}`,
2759
+ body: "its registry is unwritable (disk full or locked) — the run was skipped so it cannot re-fire every tick; it resumes when the registry is writable again",
2760
+ data: { scheduleId: record.id },
2761
+ });
2762
+ }
2763
+ return;
2764
+ }
2765
+ if (this.scheduleRegistryDegraded.delete(record.id)) {
2766
+ void this.notifyEvent({
2767
+ kind: "schedule.ok",
2768
+ title: `Schedule resumed: ${record.name}`,
2769
+ body: "registry writes recovered; scheduled runs continue",
2770
+ data: { scheduleId: record.id },
2771
+ });
2772
+ }
2729
2773
  await this.dispatchBounded(record);
2730
2774
  } finally {
2731
2775
  this.scheduleInFlight.delete(record.id);
@@ -130,7 +130,12 @@ async function readBodyCapped(
130
130
  * absent for textual responses so older hubs see an unchanged frame. */
131
131
  const TEXTUAL_CT_RE = /^(?:text\/|application\/(?:json|javascript|xml|x-www-form-urlencoded)(?:;|$))/i;
132
132
  /** base64 inflates by 4/3 and the serialized envelope must still fit the chunk budget
133
- * (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom. */
133
+ * (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom.
134
+ * R11 3.2 (doc): this 12 MB is the ceiling for EVERY tunnelled binary — an export
135
+ * larger than this refuses with response_too_large (deflate ≈ 3-5× on transcripts,
136
+ * so most sessions fit; the LOCAL device ceiling is the 256 MiB streaming one in
137
+ * zip.ts). The asymmetry is physics: textual frames get 16 MiB logical because
138
+ * they never carry the 4/3 inflation; binaries pay it, so they get 12 MB pre-base64. */
134
139
  const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
135
140
  const safeHeaderValue = (value: string | null | undefined): string | undefined => {
136
141
  if (!value) return undefined;
@@ -739,7 +744,13 @@ export class DeviceConnector {
739
744
  tooLarge(
740
745
  textual
741
746
  ? `Device response exceeds ${LOGICAL_MESSAGE_MAX_BYTES} bytes`
742
- : `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget`,
747
+ : `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget` +
748
+ // R11 1.3: the two export ceilings must tell ONE story — the
749
+ // tunnel cap is 12 MB compressed, the local one 256 MiB raw;
750
+ // name the remedies instead of a bare byte count.
751
+ (frame.path.endsWith("/export")
752
+ ? " — compact the session (archive old agents), or export it directly from the device"
753
+ : ""),
743
754
  );
744
755
  return;
745
756
  }
@@ -13,13 +13,20 @@
13
13
  * whole bundle (raw texts + deflate + base64 ≈ 2-3× transcript size, the R5
14
14
  * audit's scale cliff) — `streamSessionBundle` composes the same entries from
15
15
  * the store's public APIs, deflates each one through a pipe while writing a
16
- * temp file under `os.tmpdir()`, and the route pipes that file to the HTTP
17
- * response before unlinking it. Entries keep today's paths/payloads; the only
18
- * layout difference is the streaming form's data descriptor (spec bit 3) so
19
- * entry sizes can be written after the deflated body without buffering it.
16
+ * temp file, and the route pipes that file to the HTTP response before
17
+ * unlinking it. Entries keep today's paths/payloads; the only layout
18
+ * difference is the streaming form's data descriptor (spec bit 3) so entry
19
+ * sizes can be written after the deflated body without buffering it.
20
+ *
21
+ * R11 1.1: the temp file lives BESIDE THE DATA DIR (same volume as the store,
22
+ * DPI_EXPORT_TMPDIR overrides), not `os.tmpdir()` — a tmpfs-backed /tmp is
23
+ * RAM, and the R5 cliff would return through the back door (or ENOSPC at
24
+ * tmpfs size while the real disk sits empty). "Streaming lifted the RAM
25
+ * cliff" is volume-dependent: the deflate WINDOW is always RAM-bounded, the
26
+ * spill file is disk-bounded only where the data dir lives on real disk.
20
27
  */
21
28
  import { randomUUID } from "node:crypto";
22
- import { open, rm } from "node:fs/promises";
29
+ import { open, rm, stat } from "node:fs/promises";
23
30
  import { tmpdir, hostname, platform } from "node:os";
24
31
  import { join } from "node:path";
25
32
  import { Readable } from "node:stream";
@@ -218,10 +225,20 @@ const FLAG_DESCRIPTOR = 0x0008;
218
225
  const DATA_DESCRIPTOR_SIG = 0x08074b50;
219
226
 
220
227
  /**
221
- * A temp file under the OS temp dir (never a hardcoded path — Windows-safe),
222
- * written 0600 like every other transcript-bearing file on the device.
228
+ * A temp file (never a hardcoded path — Windows-safe), written 0600 like
229
+ * every other transcript-bearing file on the device. R11 1.1: the SPILL
230
+ * volume is the data dir (real disk, same filesystem the store already
231
+ * writes), `DPI_EXPORT_TMPDIR` overrides, `os.tmpdir()` is the last resort —
232
+ * tmpfs-backed /tmp is RAM and would silently reintroduce the R5 cliff.
223
233
  */
224
- const tempZipPath = () => join(tmpdir(), `dpi-export-${process.pid}-${randomUUID()}.zip`);
234
+ const tempZipPath = (baseDir: string) => join(baseDir, `.dpi-export-${process.pid}-${randomUUID()}.zip`);
235
+
236
+ /** Where the export spill file goes: explicit operator override → the store's
237
+ * own data dir (R11 1.1) → the OS temp dir. Dot-prefixed so a casual `ls`
238
+ * of the data dir does not read as a session artifact. */
239
+ export function exportTempDir(dataDir: string): string {
240
+ return process.env.DPI_EXPORT_TMPDIR || dataDir || tmpdir();
241
+ }
225
242
 
226
243
  /**
227
244
  * The streaming half of the zip writer. Entries are deflated through a pipe and
@@ -252,8 +269,8 @@ class ZipStreamWriter {
252
269
  }
253
270
 
254
271
  /** Create the temp file exclusively, so two exports never share one archive. */
255
- static async create(): Promise<ZipStreamWriter> {
256
- const path = tempZipPath();
272
+ static async create(baseDir: string): Promise<ZipStreamWriter> {
273
+ const path = tempZipPath(baseDir);
257
274
  const handle = await open(path, "wx", 0o600);
258
275
  return new ZipStreamWriter(path, handle);
259
276
  }
@@ -416,7 +433,38 @@ export async function streamSessionBundle(
416
433
  opts: { ceilingBytes?: number } = {},
417
434
  ): Promise<StreamedBundle> {
418
435
  const ceilingBytes = opts.ceilingBytes ?? EXPORT_TOTAL_LIMIT_BYTES;
419
- const writer = await ZipStreamWriter.create();
436
+ // R11 1.2: refuse MONSTROUS sessions BEFORE the first stringify. The store db
437
+ // holds every entry the bundle re-serializes, so a db over the ceiling can
438
+ // only refuse later — after a ~2-4× transient (entries clone + pretty JSON)
439
+ // that OOMs instead of answering. A cheap stat converts heap death into the
440
+ // polite, remedy-naming refusal. (A db under the ceiling can still overflow
441
+ // mid-write — json+md ≈ 2× content — and the streaming `add()` guard catches
442
+ // that gracefully, as it always has.)
443
+ const dbBytes = await stat(row.dbPath).then(
444
+ (s) => s.size,
445
+ () => 0,
446
+ );
447
+ if (dbBytes > ceilingBytes) {
448
+ throw invalid(
449
+ `Export refused: this session's store is ${mb(dbBytes)} of data, over the ${mb(ceilingBytes)} export ceiling. ` +
450
+ `Compact the session first (archive old agents), or export it directly from the device`,
451
+ );
452
+ }
453
+ const tempDir = exportTempDir(store.options.dataDir);
454
+ let writer: ZipStreamWriter;
455
+ try {
456
+ writer = await ZipStreamWriter.create(tempDir);
457
+ } catch (e) {
458
+ // R11 1.4: disk-full surfaces as a typed invalid fault naming the remedy
459
+ // (which volume, which knob), not a raw ENOSPC string on a 500.
460
+ if ((e as NodeJS.ErrnoException).code === "ENOSPC") {
461
+ throw invalid(
462
+ `disk full while creating the export temp file under ${tempDir} — free space on that volume ` +
463
+ `(or point DPI_EXPORT_TMPDIR at one with room) and retry`,
464
+ );
465
+ }
466
+ throw e;
467
+ }
420
468
  try {
421
469
  for await (const entry of sessionBundleEntries(store, row)) await writer.add(entry, ceilingBytes);
422
470
  const bytes = await writer.finish();
@@ -430,6 +478,13 @@ export async function streamSessionBundle(
430
478
  };
431
479
  } catch (cause) {
432
480
  await writer.dispose();
481
+ if ((cause as NodeJS.ErrnoException).code === "ENOSPC") {
482
+ // R11 1.4: mid-write disk-full gets the same typed refusal as create-time.
483
+ throw invalid(
484
+ `disk full while writing the export under ${tempDir} — free space on that volume ` +
485
+ `(or point DPI_EXPORT_TMPDIR at one with room) and retry`,
486
+ );
487
+ }
433
488
  throw cause;
434
489
  }
435
490
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.64",
3
+ "version": "0.0.65",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {