my-durable 0.0.76 → 0.0.78
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/archived.ts +54 -9
- package/apps/dpi-backend/src/git.ts +178 -78
- package/apps/dpi-backend/src/pairing.ts +3 -1
- package/apps/dpi-backend/src/salvage.ts +70 -4
- package/apps/dpi-backend/src/store.ts +273 -15
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-h81haD43.css → index-BF6mtGF4.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DAF9D074.js +82 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-rules.ts +38 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-store.ts +64 -19
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +26 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GitPanel.vue +46 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +11 -3
- package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +25 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +44 -4
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +52 -6
- package/apps/dpi-sdk/src/api.ts +5 -1
- package/apps/dpi-sdk/src/models.ts +180 -19
- package/apps/dpi-sdk/src/node/config.ts +13 -2
- package/apps/dpi-sdk/src/node/ops.ts +33 -6
- package/apps/dpi-sdk/src/node/registry-migration.ts +76 -3
- package/apps/dpi-sdk/src/node/registry.ts +5 -2
- package/apps/dpi-sdk/src/transcript.ts +1 -0
- package/apps/dpi-tui/src/app.ts +7 -6
- package/apps/dpi-tui/src/pairing.ts +15 -11
- package/apps/dpi-tui/src/pickers.ts +11 -8
- package/apps/dpi-tui/src/sanitize.ts +5 -0
- package/apps/dpi-tui/src/views.ts +16 -16
- package/apps/dpi-tui/src/welcome.ts +9 -4
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +0 -82
|
@@ -59,22 +59,83 @@ export interface SalvageOutcome {
|
|
|
59
59
|
*/
|
|
60
60
|
const WORKER_SRC = `
|
|
61
61
|
const { parentPort, workerData } = require("node:worker_threads");
|
|
62
|
-
const { copyFileSync, existsSync,
|
|
62
|
+
const { copyFileSync, existsSync, lstatSync, statSync, fstatSync, readSync, openSync, closeSync, rmSync, writeSync } = require("node:fs");
|
|
63
|
+
const fsConstants = require("node:fs").constants;
|
|
63
64
|
const { DatabaseSync } = require("node:sqlite");
|
|
64
65
|
const main = workerData.dbPath;
|
|
65
66
|
const copy = workerData.copyPath; // R10 5.2: unique per attempt — two workers never share scratch files
|
|
66
67
|
const fail = (reason) => parentPort.postMessage({ ok: false, reason: String(reason).slice(0, 80) });
|
|
68
|
+
/** run-8 U7: the copy source must be a REGULAR file of bounded size. Nothing
|
|
69
|
+
* validated it (archived.ts lstats the same name for reads), so a planted
|
|
70
|
+
* symlink to /dev/zero, a FIFO or a huge file turned this into an unbounded
|
|
71
|
+
* synchronous copy — and the 5s ceiling only settles the parent promise, it
|
|
72
|
+
* cannot recall a thread blocked in a native fs call. */
|
|
73
|
+
const MAX_DB_BYTES = 256 * 1024 * 1024;
|
|
74
|
+
function assertRegular(path, label) {
|
|
75
|
+
let st;
|
|
76
|
+
try {
|
|
77
|
+
st = lstatSync(path, { throwIfNoEntry: false });
|
|
78
|
+
} catch {
|
|
79
|
+
return "unreadable";
|
|
80
|
+
}
|
|
81
|
+
if (!st) return "missing";
|
|
82
|
+
if (!st.isFile()) return label + " is not a regular file";
|
|
83
|
+
if (st.size > MAX_DB_BYTES) return label + " is too large to salvage";
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
67
86
|
function run() {
|
|
68
87
|
try {
|
|
69
88
|
// 1. Copy main + sidecars aside. The original is only ever read.
|
|
89
|
+
const bad = assertRegular(main, "database");
|
|
90
|
+
if (bad) return fail(bad);
|
|
91
|
+
for (const suffix of ["-wal", "-shm"]) {
|
|
92
|
+
if (!existsSync(main + suffix)) continue;
|
|
93
|
+
const sideBad = assertRegular(main + suffix, "database" + suffix);
|
|
94
|
+
if (sideBad && sideBad !== "missing") return fail(sideBad);
|
|
95
|
+
}
|
|
70
96
|
rmSync(copy, { force: true });
|
|
71
|
-
copyFileSync
|
|
97
|
+
// cold-3 M4: the lstat above is a PATH pre-check; copyFileSync re-opens the
|
|
98
|
+
// path, so a same-user swap re-opened a different file (the exact race
|
|
99
|
+
// archived.ts pinned with O_NOFOLLOW). Pin the source fd, fstat THAT fd, and
|
|
100
|
+
// copy from it — a swap after the open cannot change what we read.
|
|
101
|
+
const srcFd = openSync(main, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
|
|
102
|
+
try {
|
|
103
|
+
const fst = fstatSync(srcFd);
|
|
104
|
+
if (!fst.isFile()) return fail("database is not a regular file");
|
|
105
|
+
if (fst.size > MAX_DB_BYTES) return fail("database is too large to salvage");
|
|
106
|
+
const dstFd = openSync(copy, "w", 0o600);
|
|
107
|
+
try {
|
|
108
|
+
const buf = Buffer.allocUnsafe(256 * 1024);
|
|
109
|
+
let pos = 0;
|
|
110
|
+
for (;;) {
|
|
111
|
+
const n = readSync(srcFd, buf, 0, buf.length, pos);
|
|
112
|
+
if (n <= 0) break;
|
|
113
|
+
writeSync(dstFd, buf, 0, n);
|
|
114
|
+
pos += n;
|
|
115
|
+
}
|
|
116
|
+
} finally {
|
|
117
|
+
closeSync(dstFd);
|
|
118
|
+
}
|
|
119
|
+
} finally {
|
|
120
|
+
closeSync(srcFd);
|
|
121
|
+
}
|
|
72
122
|
for (const suffix of ["-wal", "-shm"]) {
|
|
73
123
|
if (existsSync(main + suffix)) copyFileSync(main + suffix, copy + suffix);
|
|
74
124
|
else rmSync(copy + suffix, { force: true });
|
|
75
125
|
}
|
|
76
126
|
// 2. Patch the copy's header: only fields sqlite validates at open (see module doc).
|
|
77
|
-
|
|
127
|
+
// run-8 U7: patch the first 100 header bytes positionally — reading and
|
|
128
|
+
// rewriting the WHOLE database cost ~2x its size in RSS for a 100-byte fix.
|
|
129
|
+
const HEADER_BYTES = 100;
|
|
130
|
+
const fd = openSync(copy, "r+");
|
|
131
|
+
let b;
|
|
132
|
+
try {
|
|
133
|
+
b = Buffer.alloc(HEADER_BYTES);
|
|
134
|
+
const n = readSync(fd, b, 0, HEADER_BYTES, 0);
|
|
135
|
+
if (n < HEADER_BYTES) return fail("truncated database header");
|
|
136
|
+
} finally {
|
|
137
|
+
closeSync(fd);
|
|
138
|
+
}
|
|
78
139
|
const MAGIC = "SQLite format 3\\0";
|
|
79
140
|
if (b.slice(0, 16).toString("latin1") !== MAGIC) b.write(MAGIC, 0, 16, "latin1");
|
|
80
141
|
const pageSize = b.readUInt16BE(16);
|
|
@@ -90,7 +151,12 @@ try {
|
|
|
90
151
|
b.writeUInt32BE(0, 52); // largest root b-tree page: nonzero garbage turns ptrmap validation on
|
|
91
152
|
const encoding = b.readUInt32BE(56);
|
|
92
153
|
if (!(encoding >= 1 && encoding <= 3)) b.writeUInt32BE(1, 56); // UTF-8
|
|
93
|
-
|
|
154
|
+
const wfd = openSync(copy, "r+");
|
|
155
|
+
try {
|
|
156
|
+
writeSync(wfd, b, 0, b.length, 0);
|
|
157
|
+
} finally {
|
|
158
|
+
closeSync(wfd);
|
|
159
|
+
}
|
|
94
160
|
// 3. Integrity is the ONLY gate for promotion.
|
|
95
161
|
let db;
|
|
96
162
|
try {
|
|
@@ -47,7 +47,7 @@ import {
|
|
|
47
47
|
} from "../../dpi-sdk/src/transcript.js";
|
|
48
48
|
import { ApiFault, invalid, isStorageBusy, isUnreadableStorage, notFound, storageBusyFault } from "./errors.js";
|
|
49
49
|
import { searchHistory } from "./history.js";
|
|
50
|
-
import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
|
|
50
|
+
import { configureGitRootGuard, git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
|
|
51
51
|
import { DatabaseSync } from "node:sqlite";
|
|
52
52
|
import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
|
|
53
53
|
import { deviceVitals, type DeviceVitals } from "./vitals.js";
|
|
@@ -73,6 +73,7 @@ import {
|
|
|
73
73
|
import {
|
|
74
74
|
listArchived,
|
|
75
75
|
findBundle,
|
|
76
|
+
BUNDLE_DIR_PATTERN,
|
|
76
77
|
readArchiveManifest,
|
|
77
78
|
archivedTranscript,
|
|
78
79
|
restoreArchive,
|
|
@@ -82,7 +83,7 @@ import {
|
|
|
82
83
|
import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
|
|
83
84
|
import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
|
|
84
85
|
import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
|
|
85
|
-
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
|
|
86
|
+
import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, rmSync, statSync, realpathSync } from "node:fs";
|
|
86
87
|
import { lstat } from "node:fs/promises";
|
|
87
88
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
88
89
|
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
@@ -433,6 +434,11 @@ export class Store {
|
|
|
433
434
|
readonly models = createModels({ credentials: this.pi.credentials });
|
|
434
435
|
readonly opened = new Map<string, Opened>();
|
|
435
436
|
readonly errors = new Map<string, string>();
|
|
437
|
+
/** run-7 B1-A: archive() bumps this as its FIRST act; openAgent compares
|
|
438
|
+
* its entry snapshot before arming — a reopen that raced the archive
|
|
439
|
+
* window (opened.delete → rename → catalog DELETE) must not re-arm a live
|
|
440
|
+
* harness over the moved-away bundle. */
|
|
441
|
+
readonly archiveEpoch = new Map<string, number>();
|
|
436
442
|
readonly catalog: DatabaseSync;
|
|
437
443
|
readonly startedAt = Date.now();
|
|
438
444
|
shared!: SharedState;
|
|
@@ -622,6 +628,138 @@ export class Store {
|
|
|
622
628
|
* committed storage at boot; a session whose db fails to open keeps its row with the
|
|
623
629
|
* boot loop's failure message. Names are placeholders — the transcript is intact.
|
|
624
630
|
*/
|
|
631
|
+
/** run-8 U1: the newest archive bundle for a session id, or null. Used by
|
|
632
|
+
* archive() to finish an interrupted archive idempotently. */
|
|
633
|
+
private findBundleDir(sessionId: string): string | null {
|
|
634
|
+
let names: string[];
|
|
635
|
+
try {
|
|
636
|
+
names = readdirSync(this.archiveDir);
|
|
637
|
+
} catch {
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
// cold-3 M3: the SAME grammar every other reader uses (BUNDLE_DIR_PATTERN,
|
|
641
|
+
// 13-digit ms). A looser prefix+Number() match accepted `<id>-17e5` /
|
|
642
|
+
// `<id>-0x1f` / `<id>-`, and this helper gates row DELETION — so a bundle
|
|
643
|
+
// restore cannot see was treated as "already archived" and the row went away
|
|
644
|
+
// with its name/cwd.
|
|
645
|
+
let best: string | null = null;
|
|
646
|
+
let bestTs = -1;
|
|
647
|
+
for (const name of names) {
|
|
648
|
+
const match = BUNDLE_DIR_PATTERN.exec(name);
|
|
649
|
+
if (!match || match[1] !== sessionId) continue;
|
|
650
|
+
const ts = Number(match[2]);
|
|
651
|
+
if (ts > bestTs) {
|
|
652
|
+
bestTs = ts;
|
|
653
|
+
best = name;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return best ? join(this.archiveDir, best) : null;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* run-8 U1: reconcile the two crash windows the archive lifecycle left open
|
|
661
|
+
* (leader-probed all three variants before this existed):
|
|
662
|
+
*
|
|
663
|
+
* A. a row whose sessions/<id> dir is gone but whose bundle sits in
|
|
664
|
+
* archive/ — the process died between the rename and the catalog
|
|
665
|
+
* DELETEs. restore then refused forever ("a live session with this id
|
|
666
|
+
* already exists") and DELETE /v1/sessions re-threw ENOENT, so the row
|
|
667
|
+
* was immortal. Complete the archive: repair/write the manifest from the
|
|
668
|
+
* row's own fields, then delete the row (one transaction).
|
|
669
|
+
* A2. same window before the manifest was written — the bundle was
|
|
670
|
+
* unrestorable even after manual row removal ("no usable cwd"). The row
|
|
671
|
+
* carries every manifest field, so this is fully recoverable here.
|
|
672
|
+
* B. a sessions/<uuid> dir with no catalog row (a restore that died
|
|
673
|
+
* between the rename and the INSERT, or a rolled-back INSERT): invisible
|
|
674
|
+
* to list() and a 404 on restore retry. Re-add a recovered row.
|
|
675
|
+
*
|
|
676
|
+
* Bounded: one readdir of sessions/ + one of archive/, no per-row spawns.
|
|
677
|
+
*/
|
|
678
|
+
private reconcileArchiveWindows(): void {
|
|
679
|
+
let dirs: string[];
|
|
680
|
+
try {
|
|
681
|
+
dirs = readdirSync(this.sessionsDir);
|
|
682
|
+
} catch (e) {
|
|
683
|
+
// cold-3 L6: EACCES/EMFILE/EIO is NOT "no sessions exist" — reconciling on
|
|
684
|
+
// a transient readdir failure would complete-and-delete every row whose
|
|
685
|
+
// bundle exists, losing name/model/cwd. Only a genuinely absent dir is
|
|
686
|
+
// "nothing to do".
|
|
687
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const onDisk = new Set(dirs);
|
|
691
|
+
const rows = this.list();
|
|
692
|
+
const known = new Set(rows.map((r) => r.id));
|
|
693
|
+
|
|
694
|
+
for (const row of rows) {
|
|
695
|
+
if (onDisk.has(row.id)) continue; // live dir present: nothing to repair
|
|
696
|
+
const bundle = this.findBundleDir(row.id);
|
|
697
|
+
if (!bundle) {
|
|
698
|
+
// Data genuinely gone (offline wipe / manual rm): a bounded, distinct
|
|
699
|
+
// fault instead of a permanent per-request ENOENT error row.
|
|
700
|
+
this.errors.set(row.id, "session data is missing and no archived bundle exists");
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
const manifest = readArchiveManifest(bundle);
|
|
704
|
+
if (!manifest || !manifest.cwd) {
|
|
705
|
+
try {
|
|
706
|
+
writeArchiveManifest(bundle, {
|
|
707
|
+
sessionId: row.id,
|
|
708
|
+
name: row.name,
|
|
709
|
+
cwd: row.cwd,
|
|
710
|
+
model: row.model,
|
|
711
|
+
provider: row.provider,
|
|
712
|
+
createdAt: row.createdAt,
|
|
713
|
+
archivedAt: Date.now(),
|
|
714
|
+
packageVersion: PACKAGE_VERSION,
|
|
715
|
+
});
|
|
716
|
+
} catch {
|
|
717
|
+
// Unwritable bundle: keep the row and the fault, never delete data.
|
|
718
|
+
this.errors.set(row.id, "interrupted archive: bundle is not writable");
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
this.catalog.exec("BEGIN");
|
|
723
|
+
try {
|
|
724
|
+
this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
|
|
725
|
+
this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
|
|
726
|
+
this.catalog.exec("COMMIT");
|
|
727
|
+
} catch (e) {
|
|
728
|
+
this.catalog.exec("ROLLBACK");
|
|
729
|
+
this.errors.set(row.id, `interrupted archive: ${e instanceof Error ? e.message : String(e)}`);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// Variant B: an orphan session dir with no row.
|
|
734
|
+
for (const name of onDisk) {
|
|
735
|
+
if (known.has(name)) continue;
|
|
736
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(name)) continue;
|
|
737
|
+
const dbPath = join(this.sessionsDir, name, "agent.sqlite");
|
|
738
|
+
let createdAt = Date.now();
|
|
739
|
+
try {
|
|
740
|
+
createdAt = Math.round(statSync(dbPath).mtimeMs);
|
|
741
|
+
} catch {
|
|
742
|
+
continue; // no database in it: not a session
|
|
743
|
+
}
|
|
744
|
+
const fallback = this.defaultModelRef();
|
|
745
|
+
try {
|
|
746
|
+
this.catalog
|
|
747
|
+
.prepare(
|
|
748
|
+
"INSERT OR IGNORE INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)",
|
|
749
|
+
)
|
|
750
|
+
.run(
|
|
751
|
+
name,
|
|
752
|
+
`Recovered session ${name.slice(0, 8)}`,
|
|
753
|
+
this.startDirs[0] ?? homedir(),
|
|
754
|
+
dbPath,
|
|
755
|
+
createdAt,
|
|
756
|
+
fallback?.modelId ?? "unknown",
|
|
757
|
+
fallback?.provider ?? "unknown",
|
|
758
|
+
);
|
|
759
|
+
} catch {}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
625
763
|
private reseedCatalog(db: DatabaseSync): void {
|
|
626
764
|
let entries;
|
|
627
765
|
try {
|
|
@@ -671,6 +809,23 @@ export class Store {
|
|
|
671
809
|
}
|
|
672
810
|
// Start dirs are where new sessions begin; create any that do not exist yet.
|
|
673
811
|
await Promise.all(options.startDirs.map((dir) => mkdir(dir, { recursive: true }).catch(() => {})));
|
|
812
|
+
// run-7 D1: every git effect (status disclosure, watcher, .gitignore write)
|
|
813
|
+
// must stay under the start dirs even when git's repo discovery walks up
|
|
814
|
+
// from a contained slice to an enclosing repo rooted OUTSIDE the sandbox.
|
|
815
|
+
// Installed before any gitStatus call below can seed projects from a walk-up.
|
|
816
|
+
configureGitRootGuard(async (root) => {
|
|
817
|
+
// run-7 cold-1 M2: git prints FORWARD-SLASHED, drive-case-variant paths
|
|
818
|
+
// on win32 while realpath roots are backslashed — compare normalized
|
|
819
|
+
// forms or every Windows repo fails confinement (all git features die).
|
|
820
|
+
const norm = (p: string) =>
|
|
821
|
+
process.platform === "win32" ? p.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase() : p;
|
|
822
|
+
const sep = process.platform === "win32" ? "\\" : "/";
|
|
823
|
+
const n = norm(root);
|
|
824
|
+
return (await store.startDirRoots()).some((r) => {
|
|
825
|
+
const b = norm(r);
|
|
826
|
+
return !!b && (n === b || n.startsWith(b + sep));
|
|
827
|
+
});
|
|
828
|
+
});
|
|
674
829
|
try {
|
|
675
830
|
store.projects = await ProjectRegistry.open(store.projectsPath, {
|
|
676
831
|
warn: (m) => process.emitWarning(`projects: ${m}`),
|
|
@@ -714,6 +869,10 @@ export class Store {
|
|
|
714
869
|
store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
|
|
715
870
|
store.shared = await SharedState.open(store.sharedStatePath);
|
|
716
871
|
store.shared.harness.subscribeCommits(() => store.notify());
|
|
872
|
+
// run-8 U1: repair the archive/restore crash windows BEFORE the open
|
|
873
|
+
// loop, so a zombie row is completed (or faulted) instead of producing a
|
|
874
|
+
// permanent ENOENT error session that search and the tree keep paying for.
|
|
875
|
+
store.reconcileArchiveWindows();
|
|
717
876
|
for (const row of store.list()) {
|
|
718
877
|
try {
|
|
719
878
|
await store.openAgent(row);
|
|
@@ -794,7 +953,18 @@ export class Store {
|
|
|
794
953
|
durableVersion: DURABLE_VERSION,
|
|
795
954
|
packageVersion: PACKAGE_VERSION,
|
|
796
955
|
startedAt: this.startedAt,
|
|
797
|
-
|
|
956
|
+
// run-8 U4: report the REALPATH spelling — session cwds and the git/fs
|
|
957
|
+
// enforcement roots are realpath'd (startDirRoots), so a configured
|
|
958
|
+
// spelling with a symlink component (macOS /tmp -> /private/tmp, win
|
|
959
|
+
// junctions) made the FE advisory pre-check reject every session under
|
|
960
|
+
// it with a permanent, un-retryable error while the device answered 200.
|
|
961
|
+
startDirs: this.startDirs.map((d) => {
|
|
962
|
+
try {
|
|
963
|
+
return realpathSync(d);
|
|
964
|
+
} catch {
|
|
965
|
+
return d;
|
|
966
|
+
}
|
|
967
|
+
}),
|
|
798
968
|
models: this.modelList,
|
|
799
969
|
defaultModel: this.defaultModel(),
|
|
800
970
|
provider: this.options.provider,
|
|
@@ -1535,6 +1705,9 @@ export class Store {
|
|
|
1535
1705
|
|
|
1536
1706
|
/** Stop all work, close the harness and move its files to archive/. Nothing is deleted. */
|
|
1537
1707
|
async archive(row: SessionRow) {
|
|
1708
|
+
// FIRST act, before any await: reopens racing the window below compare
|
|
1709
|
+
// against this epoch and fail like any dead row (run-7 B1-A).
|
|
1710
|
+
this.archiveEpoch.set(row.id, (this.archiveEpoch.get(row.id) ?? 0) + 1);
|
|
1538
1711
|
const opened = this.opened.get(row.id);
|
|
1539
1712
|
if (opened) {
|
|
1540
1713
|
for (const record of await this.scanAll(opened.harness)) {
|
|
@@ -1556,6 +1729,27 @@ export class Store {
|
|
|
1556
1729
|
await renamePath(dirname(row.dbPath), target);
|
|
1557
1730
|
} catch (e) {
|
|
1558
1731
|
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
|
1732
|
+
// run-8 U1: a missing source dir used to be treated as success, and the
|
|
1733
|
+
// manifest write then threw into a never-created target — the row was
|
|
1734
|
+
// immortal through the API (probe: ENOENT + row survives forever). An
|
|
1735
|
+
// earlier interrupted archive already holds the bundle, so finish the
|
|
1736
|
+
// row removal idempotently instead of minting an empty one.
|
|
1737
|
+
// cold-3 L8: rename() also ENOENTs when the DESTINATION parent vanished
|
|
1738
|
+
// (e.g. a concurrent gc of archive/), so require the source dir to be
|
|
1739
|
+
// gone before the idempotent completion below can delete the row.
|
|
1740
|
+
if (existsSync(dirname(row.dbPath))) throw e;
|
|
1741
|
+
const existing = this.findBundleDir(row.id);
|
|
1742
|
+
if (!existing) {
|
|
1743
|
+
this.errors.set(row.id, "session directory is missing (no archived bundle); row left in place");
|
|
1744
|
+
throw new Error("session directory is missing and no archived bundle exists");
|
|
1745
|
+
}
|
|
1746
|
+
this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
|
|
1747
|
+
this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
|
|
1748
|
+
this.opened.delete(row.id);
|
|
1749
|
+
this.salvageFailedSessions.delete(row.id);
|
|
1750
|
+
this.errors.delete(row.id);
|
|
1751
|
+
this.notify();
|
|
1752
|
+
return { archived: existing };
|
|
1559
1753
|
}
|
|
1560
1754
|
// The bundle keeps its identity: from now on every archive carries a
|
|
1561
1755
|
// session.json so the archive stays browsable years later (old bundles
|
|
@@ -1633,14 +1827,30 @@ export class Store {
|
|
|
1633
1827
|
// VALIDATED pre-move manifest, not restoreArchive's second, unpinned
|
|
1634
1828
|
// re-read — a manifest swapped in during the move can no longer skew
|
|
1635
1829
|
// id/dbPath (cwd stays the validated realpath either way).
|
|
1830
|
+
// run-7 B1-B: the create/rename choke points must hold for restores too
|
|
1831
|
+
// — a planted manifest (the r18 same-user-planter threat) must not land a
|
|
1832
|
+
// ~1MiB / control-char / reserved-'search' name or unbounded model strings
|
|
1833
|
+
// in the catalog: they reach every tree() broadcast, notify titles and
|
|
1834
|
+
// harness.root. A bad name degrades to a bounded fallback (the bundle
|
|
1835
|
+
// stays restorable); model strings are bounded and stripped.
|
|
1836
|
+
const rawName = pre?.name || manifest.name || "Untitled session";
|
|
1837
|
+
const name = (() => {
|
|
1838
|
+
try {
|
|
1839
|
+
return assertSessionName(rawName) || "Untitled session";
|
|
1840
|
+
} catch {
|
|
1841
|
+
return `archived-${sessionId.slice(0, 8)}`;
|
|
1842
|
+
}
|
|
1843
|
+
})();
|
|
1844
|
+
const boundModelish = (v: string | undefined): string | undefined =>
|
|
1845
|
+
typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200) || undefined : undefined;
|
|
1636
1846
|
const row: SessionRow = {
|
|
1637
1847
|
id: sessionId,
|
|
1638
|
-
name
|
|
1848
|
+
name,
|
|
1639
1849
|
cwd: restoredCwd,
|
|
1640
1850
|
dbPath: join(this.sessionsDir, sessionId, "agent.sqlite"),
|
|
1641
1851
|
createdAt: pre?.createdAt ?? manifest.createdAt,
|
|
1642
|
-
model: pre?.model ?? manifest.model,
|
|
1643
|
-
provider: pre?.provider ?? manifest.provider,
|
|
1852
|
+
model: boundModelish(pre?.model ?? manifest.model) ?? "faux",
|
|
1853
|
+
provider: boundModelish(pre?.provider ?? manifest.provider) ?? "faux",
|
|
1644
1854
|
};
|
|
1645
1855
|
this.catalog.exec("BEGIN");
|
|
1646
1856
|
try {
|
|
@@ -1663,15 +1873,39 @@ export class Store {
|
|
|
1663
1873
|
async openAgent(row: SessionRow, create = false, thinkingLevel: ThinkingLevel = "medium") {
|
|
1664
1874
|
const current = this.opened.get(row.id);
|
|
1665
1875
|
if (current) return current.harness;
|
|
1876
|
+
const epoch = this.archiveEpoch.get(row.id) ?? 0; // run-7 B1-A: liveness is re-checked at the arm point
|
|
1666
1877
|
// R20 (run-6 h6): attempt-once — the memo was only read by the search
|
|
1667
1878
|
// path, so every agent-touching request re-ran the FULL salvage (leader
|
|
1668
1879
|
// probe: 5.0 s per request on a corrupt session, unbounded). Fail fast
|
|
1669
1880
|
// from the recorded fault without touching storage.
|
|
1670
1881
|
if (!create && this.salvageFailedSessions.has(row.id))
|
|
1671
1882
|
throw new ApiFault("unavailable", this.errors.get(row.id) ?? "session database is unreadable (salvage failed)");
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1883
|
+
let unlock: () => void;
|
|
1884
|
+
try {
|
|
1885
|
+
if (!create) await stat(row.dbPath);
|
|
1886
|
+
await mkdir(dirname(row.dbPath), { recursive: true });
|
|
1887
|
+
unlock = lockFile(`${row.dbPath}.lock`);
|
|
1888
|
+
} catch (e) {
|
|
1889
|
+
// run-7 B1-A (variant 3): archive() moved the session dir between the
|
|
1890
|
+
// entry stat and here — mkdir may have just RESURRECTED an empty
|
|
1891
|
+
// sessions/<id>/ husk that permanently blocks a later restore. When the
|
|
1892
|
+
// epoch proves archive ran in the window, remove the husk and refuse.
|
|
1893
|
+
if ((this.archiveEpoch.get(row.id) ?? 0) !== epoch) {
|
|
1894
|
+
// run-7 cold-1 M4: ONLY remove the empty husk THIS call resurrected —
|
|
1895
|
+
// a concurrent restore may have just moved the REAL bundle back into
|
|
1896
|
+
// sessions/<id>/ (the archive copy is consumed by the move); deleting
|
|
1897
|
+
// it would be unrecoverable data loss. A husk has no agent.sqlite.
|
|
1898
|
+
const dir = dirname(row.dbPath);
|
|
1899
|
+
let entries: string[] = [];
|
|
1900
|
+
try {
|
|
1901
|
+
entries = readdirSync(dir);
|
|
1902
|
+
} catch {}
|
|
1903
|
+
if (!entries.some((f) => f === "agent.sqlite" || f.endsWith(".sqlite-wal") || f.endsWith(".sqlite-shm")))
|
|
1904
|
+
rmSync(dir, { recursive: true, force: true });
|
|
1905
|
+
throw new ApiFault("unavailable", "session was archived while opening");
|
|
1906
|
+
}
|
|
1907
|
+
throw e;
|
|
1908
|
+
}
|
|
1675
1909
|
try {
|
|
1676
1910
|
const shellEnv = Object.fromEntries(
|
|
1677
1911
|
["PATH", "HOME", "USER", "SHELL", "TMPDIR", "LANG", "TERM"].flatMap((k) =>
|
|
@@ -1787,6 +2021,15 @@ export class Store {
|
|
|
1787
2021
|
row.model = rootModel.modelId;
|
|
1788
2022
|
this.catalog.prepare("UPDATE sessions SET provider=?,model=? WHERE id=?").run(row.provider, row.model, row.id);
|
|
1789
2023
|
const unsubscribe = harness.subscribeCommits(() => this.notify());
|
|
2024
|
+
// run-7 B1-A: the row was ALIVE at entry, but archive() may have moved
|
|
2025
|
+
// the session dir away while the opens above were awaiting — arming now
|
|
2026
|
+
// would park a live harness over the archived bundle (post-archive
|
|
2027
|
+
// writes, mis-bound restores, silent loss when gc unlinks it).
|
|
2028
|
+
if ((this.archiveEpoch.get(row.id) ?? 0) !== epoch) {
|
|
2029
|
+
await harness.close(ctx).catch(() => {});
|
|
2030
|
+
unlock();
|
|
2031
|
+
throw new ApiFault("unavailable", "session was archived while opening");
|
|
2032
|
+
}
|
|
1790
2033
|
this.opened.set(row.id, { harness, unlock, unsubscribe, jobs, addons });
|
|
1791
2034
|
this.errors.delete(row.id);
|
|
1792
2035
|
// pi-durable 1.2+: any failed Storage call closes the Session, without waiting for the next event.
|
|
@@ -1930,18 +2173,33 @@ export class Store {
|
|
|
1930
2173
|
// version (git truth, not snapshots) and re-apply the recorded tool calls
|
|
1931
2174
|
// in order; a turn's ±n is the net line delta at its boundary.
|
|
1932
2175
|
const lines = (t: string | null | undefined) => (t == null ? 0 : t.split("\n").length - (t.endsWith("\n") ? 1 : 0));
|
|
1933
|
-
|
|
2176
|
+
// run-7 cold-2 M3: this was the ONE git effect skipping the confinement
|
|
2177
|
+
// the store itself installs — discovery could walk up out of a start-dir
|
|
2178
|
+
// slice (or a planted .git gitdir redirect) and make `git show HEAD:<rel>`
|
|
2179
|
+
// an existence oracle over an OUTSIDE repo, with rel bounded against the
|
|
2180
|
+
// foreign root. Resolve the pin through the same guard, pin both spawns,
|
|
2181
|
+
// and bound rel against the PINNED (validated) worktree.
|
|
2182
|
+
const { resolveRepoPin } = await import("./git.js");
|
|
2183
|
+
let pin: Awaited<ReturnType<typeof resolveRepoPin>> = undefined;
|
|
1934
2184
|
try {
|
|
1935
|
-
|
|
1936
|
-
} catch {
|
|
1937
|
-
|
|
1938
|
-
|
|
2185
|
+
pin = await resolveRepoPin(row.cwd);
|
|
2186
|
+
} catch (e) {
|
|
2187
|
+
// Fail CLOSED on confinement AND on transient resolve failures (a
|
|
2188
|
+
// timeout here with a later unpinned walk-up spawn succeeding would
|
|
2189
|
+
// reopen the counts oracle for that request). Only a GENUINE non-repo
|
|
2190
|
+
// (the common case before the first commit) keeps the no-pin fallback.
|
|
2191
|
+
const msg = String((e as Error).message);
|
|
2192
|
+
if (msg.includes("start dirs")) return [];
|
|
2193
|
+
if (!msg.includes("not a git repository")) return [];
|
|
2194
|
+
}
|
|
2195
|
+
const root = pin?.workTree ?? row.cwd;
|
|
2196
|
+
const gP = (args: string[]) => git(row.cwd, args, undefined, pin);
|
|
1939
2197
|
const headOf = async (p: string) => {
|
|
1940
2198
|
const abs = resolve(row.cwd, p);
|
|
1941
2199
|
const rel = relative(root, abs);
|
|
1942
2200
|
if (!rel || rel.startsWith("..")) return null;
|
|
1943
2201
|
try {
|
|
1944
|
-
return await
|
|
2202
|
+
return await gP(["show", `HEAD:${rel}`]);
|
|
1945
2203
|
} catch {
|
|
1946
2204
|
return null;
|
|
1947
2205
|
}
|