@yu_robotics/remote-cli 1.6.215 → 1.6.217
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/README.md +1 -1
- package/dist/delegation/AgySessionDeletion.d.ts +50 -0
- package/dist/delegation/AgySessionDeletion.d.ts.map +1 -0
- package/dist/delegation/AgySessionDeletion.js +339 -0
- package/dist/delegation/AgySessionDeletion.js.map +1 -0
- package/dist/delegation/DelegatedWorkerSessionStore.js +1 -2
- package/dist/delegation/DelegatedWorkerSessionStore.js.map +1 -1
- package/dist/delegation/DelegationManager.d.ts.map +1 -1
- package/dist/delegation/DelegationManager.js +36 -5
- package/dist/delegation/DelegationManager.js.map +1 -1
- package/dist/delegation/DshManagedHistory.d.ts +14 -0
- package/dist/delegation/DshManagedHistory.d.ts.map +1 -0
- package/dist/delegation/DshManagedHistory.js +106 -0
- package/dist/delegation/DshManagedHistory.js.map +1 -0
- package/dist/delegation/DshSessionDeletion.d.ts +57 -0
- package/dist/delegation/DshSessionDeletion.d.ts.map +1 -0
- package/dist/delegation/DshSessionDeletion.js +313 -0
- package/dist/delegation/DshSessionDeletion.js.map +1 -0
- package/dist/delegation/NativeSessionDeletion.d.ts +10 -2
- package/dist/delegation/NativeSessionDeletion.d.ts.map +1 -1
- package/dist/delegation/NativeSessionDeletion.js +63 -10
- package/dist/delegation/NativeSessionDeletion.js.map +1 -1
- package/dist/delegation/OpenCodeSessionDeletion.d.ts +55 -0
- package/dist/delegation/OpenCodeSessionDeletion.d.ts.map +1 -0
- package/dist/delegation/OpenCodeSessionDeletion.js +287 -0
- package/dist/delegation/OpenCodeSessionDeletion.js.map +1 -0
- package/dist/delegation/ZCodeOwnedHistory.d.ts +53 -0
- package/dist/delegation/ZCodeOwnedHistory.d.ts.map +1 -0
- package/dist/delegation/ZCodeOwnedHistory.js +762 -0
- package/dist/delegation/ZCodeOwnedHistory.js.map +1 -0
- package/dist/delegation/ZCodeSessionDeletion.d.ts +70 -0
- package/dist/delegation/ZCodeSessionDeletion.d.ts.map +1 -0
- package/dist/delegation/ZCodeSessionDeletion.js +163 -0
- package/dist/delegation/ZCodeSessionDeletion.js.map +1 -0
- package/dist/executor/AcpExecutor.d.ts +11 -0
- package/dist/executor/AcpExecutor.d.ts.map +1 -1
- package/dist/executor/AcpExecutor.js +27 -13
- package/dist/executor/AcpExecutor.js.map +1 -1
- package/dist/executor/AgyExecutor.d.ts +15 -1
- package/dist/executor/AgyExecutor.d.ts.map +1 -1
- package/dist/executor/AgyExecutor.js +126 -7
- package/dist/executor/AgyExecutor.js.map +1 -1
- package/dist/executor/DshExecutor.d.ts +2 -0
- package/dist/executor/DshExecutor.d.ts.map +1 -1
- package/dist/executor/DshExecutor.js +9 -1
- package/dist/executor/DshExecutor.js.map +1 -1
- package/dist/executor/OpenCodeExecutor.d.ts.map +1 -1
- package/dist/executor/OpenCodeExecutor.js +7 -0
- package/dist/executor/OpenCodeExecutor.js.map +1 -1
- package/dist/executor/ZCodeExecutor.d.ts +9 -2
- package/dist/executor/ZCodeExecutor.d.ts.map +1 -1
- package/dist/executor/ZCodeExecutor.js +150 -7
- package/dist/executor/ZCodeExecutor.js.map +1 -1
- package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
- package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
- package/dist/executor/dsh/DshAcpClient.js +4 -2
- package/dist/executor/dsh/DshAcpClient.js.map +1 -1
- package/dist/executor/dsh/DshPrivacy.d.ts +1 -1
- package/dist/executor/dsh/DshPrivacy.d.ts.map +1 -1
- package/dist/executor/dsh/DshPrivacy.js +2 -2
- package/dist/executor/dsh/DshPrivacy.js.map +1 -1
- package/dist/executor/zcode/ZCodeClient.d.ts +4 -0
- package/dist/executor/zcode/ZCodeClient.d.ts.map +1 -1
- package/dist/executor/zcode/ZCodeClient.js +21 -2
- package/dist/executor/zcode/ZCodeClient.js.map +1 -1
- package/dist/executor/zcode/ZCodeStorageSelection.d.ts +13 -0
- package/dist/executor/zcode/ZCodeStorageSelection.d.ts.map +1 -0
- package/dist/executor/zcode/ZCodeStorageSelection.js +85 -0
- package/dist/executor/zcode/ZCodeStorageSelection.js.map +1 -0
- package/dist/maintenance/release-notes.json +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,762 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.provisionZCodeOwnedHistory = provisionZCodeOwnedHistory;
|
|
7
|
+
exports.configuredZCodeOwnedHistory = configuredZCodeOwnedHistory;
|
|
8
|
+
exports.ownedZCodeLaunch = ownedZCodeLaunch;
|
|
9
|
+
exports.captureZCodeSharedHistory = captureZCodeSharedHistory;
|
|
10
|
+
exports.observeZCodeSharedPrompt = observeZCodeSharedPrompt;
|
|
11
|
+
exports.captureZCodeOwnedHistory = captureZCodeOwnedHistory;
|
|
12
|
+
exports.validZCodeOwnedTarget = validZCodeOwnedTarget;
|
|
13
|
+
exports.inspectZCodeOwnedTree = inspectZCodeOwnedTree;
|
|
14
|
+
exports.preserveZCodeArtifacts = preserveZCodeArtifacts;
|
|
15
|
+
exports.verifyZCodeArtifacts = verifyZCodeArtifacts;
|
|
16
|
+
exports.deleteOwnedZCodeHistory = deleteOwnedZCodeHistory;
|
|
17
|
+
const fs_1 = __importDefault(require("fs"));
|
|
18
|
+
const path_1 = __importDefault(require("path"));
|
|
19
|
+
const crypto_1 = require("crypto");
|
|
20
|
+
const NativeHistoryFiles_1 = require("./NativeHistoryFiles");
|
|
21
|
+
const ZCodeSessionDeletion_1 = require("./ZCodeSessionDeletion");
|
|
22
|
+
const ZCodeClient_1 = require("../executor/zcode/ZCodeClient");
|
|
23
|
+
const ZCodeCommand_1 = require("../executor/zcode/ZCodeCommand");
|
|
24
|
+
// Format contract: zai-org/ZCode@a9fe401eede6e6e5e01be9048679c206fe6f02d9,
|
|
25
|
+
// session-store/repositories/sessions.ts and session-data-files/index.ts.
|
|
26
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
27
|
+
const LANE = /^delegate-lane-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
|
28
|
+
const OWNED_TYPES = new Set(['selection_side_chat', 'workflow_child', 'subagent_child', 'nested_workflow_child']);
|
|
29
|
+
const INDEPENDENT_TYPES = new Set(['interactive', 'fork', 'workflow_parent', null]);
|
|
30
|
+
const FILE_KINDS = ['artifacts', 'exec', 'agents', 'sessions'];
|
|
31
|
+
const LIMIT = 4096;
|
|
32
|
+
const MAX_BYTES = 256 * 1024 * 1024;
|
|
33
|
+
const shared = (target) => target.ownership.contract === 'zcode-shared-storage-v1';
|
|
34
|
+
const digest = (bytes) => (0, crypto_1.createHash)('sha256').update(bytes).digest('hex');
|
|
35
|
+
const absent = (e) => e.code === 'ENOENT';
|
|
36
|
+
function identity(file, directory = true) {
|
|
37
|
+
const stat = fs_1.default.lstatSync(file, { bigint: true });
|
|
38
|
+
if (fs_1.default.realpathSync(file) !== file || (directory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1n)
|
|
39
|
+
|| !stat.ino || process.getuid && stat.uid !== BigInt(process.getuid()))
|
|
40
|
+
throw new Error('ZCode storage identity is unavailable');
|
|
41
|
+
return { path: file, dev: String(stat.dev), ino: String(stat.ino) };
|
|
42
|
+
}
|
|
43
|
+
function sameIdentity(expected, directory = true) {
|
|
44
|
+
if ((0, NativeHistoryFiles_1.stableHistoryHash)(identity(expected.path, directory)) !== (0, NativeHistoryFiles_1.stableHistoryHash)(expected))
|
|
45
|
+
throw new Error('ZCode storage identity changed');
|
|
46
|
+
}
|
|
47
|
+
function mkdir(directory) {
|
|
48
|
+
if (!path_1.default.isAbsolute(directory) || path_1.default.normalize(directory) !== directory)
|
|
49
|
+
throw new Error('Invalid ZCode directory');
|
|
50
|
+
let current = path_1.default.parse(directory).root;
|
|
51
|
+
for (const component of directory.slice(current.length).split(path_1.default.sep).filter(Boolean)) {
|
|
52
|
+
current = path_1.default.join(current, component);
|
|
53
|
+
try {
|
|
54
|
+
if (!fs_1.default.lstatSync(current).isDirectory())
|
|
55
|
+
throw new Error('Redirected ZCode directory');
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (!absent(error))
|
|
59
|
+
throw error;
|
|
60
|
+
fs_1.default.mkdirSync(current, { mode: 0o700 });
|
|
61
|
+
syncDirectory(path_1.default.dirname(current));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return identity(directory);
|
|
65
|
+
}
|
|
66
|
+
function json(file) {
|
|
67
|
+
identity(file, false);
|
|
68
|
+
if (fs_1.default.statSync(file).size > MAX_BYTES)
|
|
69
|
+
throw new Error('ZCode metadata exceeds the supported bound');
|
|
70
|
+
return JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
|
|
71
|
+
}
|
|
72
|
+
function durable(file, bytes) {
|
|
73
|
+
const fd = fs_1.default.openSync(file, 'wx', 0o600);
|
|
74
|
+
try {
|
|
75
|
+
fs_1.default.writeFileSync(fd, bytes);
|
|
76
|
+
fs_1.default.fsyncSync(fd);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
fs_1.default.closeSync(fd);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function syncDirectory(directory) {
|
|
83
|
+
if (process.platform === 'win32')
|
|
84
|
+
return;
|
|
85
|
+
const fd = fs_1.default.openSync(directory, 'r');
|
|
86
|
+
try {
|
|
87
|
+
fs_1.default.fsyncSync(fd);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
fs_1.default.closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function saveMarker(marker) {
|
|
94
|
+
const file = path_1.default.join(marker.namespace.path, 'ownership.json');
|
|
95
|
+
const temporary = file + '.' + (0, crypto_1.randomUUID)();
|
|
96
|
+
durable(temporary, JSON.stringify(marker));
|
|
97
|
+
fs_1.default.renameSync(temporary, file);
|
|
98
|
+
syncDirectory(marker.namespace.path);
|
|
99
|
+
}
|
|
100
|
+
function readSharedMarker(ns, lane) {
|
|
101
|
+
sameIdentity(ns);
|
|
102
|
+
const marker = json(path_1.default.join(ns.path, 'ownership.json'));
|
|
103
|
+
if (marker.version !== 2 || marker.lane !== lane || (0, NativeHistoryFiles_1.stableHistoryHash)(marker.namespace) !== (0, NativeHistoryFiles_1.stableHistoryHash)(ns)
|
|
104
|
+
|| !marker.roots || Array.isArray(marker.roots) || Object.keys(marker.roots).length > LIMIT)
|
|
105
|
+
throw new Error('ZCode shared ownership marker changed');
|
|
106
|
+
return marker;
|
|
107
|
+
}
|
|
108
|
+
function readMarker(ns, lane) {
|
|
109
|
+
sameIdentity(ns);
|
|
110
|
+
const marker = json(path_1.default.join(ns.path, 'ownership.json'));
|
|
111
|
+
if (marker.version !== 1 || marker.lane !== lane || (0, NativeHistoryFiles_1.stableHistoryHash)(marker.namespace) !== (0, NativeHistoryFiles_1.stableHistoryHash)(ns)
|
|
112
|
+
|| !marker.roots || Array.isArray(marker.roots) || Object.keys(marker.roots).length > LIMIT)
|
|
113
|
+
throw new Error('ZCode ownership marker changed');
|
|
114
|
+
sameIdentity(marker.storage);
|
|
115
|
+
if (marker.storage.path !== path_1.default.join(ns.path, 'storage'))
|
|
116
|
+
throw new Error('ZCode storage escaped its namespace');
|
|
117
|
+
return marker;
|
|
118
|
+
}
|
|
119
|
+
/** Called before native creation. Existing ordinary/adopted pointers are never migrated. */
|
|
120
|
+
function provisionZCodeOwnedHistory(home, lane, pointer) {
|
|
121
|
+
if (!LANE.test(lane))
|
|
122
|
+
throw new Error('ZCode ownership requires a managed lane');
|
|
123
|
+
const homeIdentity = identity(home);
|
|
124
|
+
const pointerRoot = identity(path_1.default.dirname(pointer));
|
|
125
|
+
if (path_1.default.basename(pointer) !== lane + '.json')
|
|
126
|
+
throw new Error('Unexpected ZCode pointer');
|
|
127
|
+
const nsPath = path_1.default.join(home, '.remote-cli', 'zcode-owned', lane);
|
|
128
|
+
let saved;
|
|
129
|
+
try {
|
|
130
|
+
saved = json(pointer);
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
if (!absent(e))
|
|
134
|
+
throw e;
|
|
135
|
+
}
|
|
136
|
+
let ns;
|
|
137
|
+
let marker;
|
|
138
|
+
if (fs_1.default.existsSync(nsPath)) {
|
|
139
|
+
ns = identity(nsPath);
|
|
140
|
+
marker = readMarker(ns, lane);
|
|
141
|
+
if (saved && (saved.adopted === true || !marker.roots[saved.id]))
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
if (saved)
|
|
146
|
+
return undefined;
|
|
147
|
+
ns = mkdir(nsPath);
|
|
148
|
+
marker = { version: 1, lane, namespace: ns, storage: mkdir(path_1.default.join(nsPath, 'storage')), roots: {} };
|
|
149
|
+
saveMarker(marker);
|
|
150
|
+
}
|
|
151
|
+
return { home: homeIdentity, namespace: ns, storage: marker.storage, pointerRoot, pointer, lane,
|
|
152
|
+
database: path_1.default.join(marker.storage.path, 'sessions.sqlite') };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Storage is not a history-only setting: it also selects agents, plugins and
|
|
156
|
+
* memory; the SQLite database contains local permission preferences. Never
|
|
157
|
+
* manufacture these overrides to obtain deletion ownership. A caller that
|
|
158
|
+
* already explicitly selected this namespace can retain its existing settings.
|
|
159
|
+
*/
|
|
160
|
+
function explicitlyConfigured(launch, storage, database) {
|
|
161
|
+
const aliases = [launch.env.ZCODE_SESSION_DB_PATH, launch.env.ZCODE_SESSION_DB].filter(value => value !== undefined);
|
|
162
|
+
return launch.env.ZCODE_STORAGE_DIR === storage && aliases.length > 0 && aliases.every(value => value === database);
|
|
163
|
+
}
|
|
164
|
+
/** Do not read, copy, or reinterpret native user/project configuration files. */
|
|
165
|
+
function configuredZCodeOwnedHistory(launch, home, lane, pointer) {
|
|
166
|
+
if (!LANE.test(lane))
|
|
167
|
+
throw new Error('ZCode ownership requires a managed lane');
|
|
168
|
+
const namespace = path_1.default.join(home, '.remote-cli', 'zcode-owned', lane);
|
|
169
|
+
const storage = path_1.default.join(namespace, 'storage');
|
|
170
|
+
if (explicitlyConfigured(launch, storage, path_1.default.join(storage, 'sessions.sqlite'))) {
|
|
171
|
+
return provisionZCodeOwnedHistory(home, lane, pointer);
|
|
172
|
+
}
|
|
173
|
+
// An old private pointer must not be resumed against a different database or
|
|
174
|
+
// silently replaced after "session not found". Keep its receipt/history intact.
|
|
175
|
+
if (fs_1.default.existsSync(namespace) && fs_1.default.existsSync(pointer)) {
|
|
176
|
+
const marker = readMarker(identity(namespace), lane);
|
|
177
|
+
const saved = json(pointer);
|
|
178
|
+
if (typeof saved?.id === 'string' && Object.hasOwn(marker.roots, saved.id)) {
|
|
179
|
+
throw new Error('ZCode context uses previously isolated storage. Restore its explicit storage configuration or clear this worker context before continuing; history was retained.');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
/** Validate an explicit choice; this function must not change effective settings. */
|
|
185
|
+
function ownedZCodeLaunch(launch, ns) {
|
|
186
|
+
readMarker(ns.namespace, ns.lane);
|
|
187
|
+
if (!explicitlyConfigured(launch, ns.storage.path, ns.database)) {
|
|
188
|
+
throw new Error('ZCode history isolation would change native configuration; automatic cleanup is unavailable');
|
|
189
|
+
}
|
|
190
|
+
return { ...launch, args: [...launch.args], env: { ...launch.env } };
|
|
191
|
+
}
|
|
192
|
+
function withDatabase(file, callback) {
|
|
193
|
+
const before = identity(file, false);
|
|
194
|
+
// Read-only SQLite does not bootstrap ZCode, migrate schemas, or load providers/plugins.
|
|
195
|
+
// Older Node runtimes without node:sqlite leave ownership unconfirmed.
|
|
196
|
+
const { DatabaseSync } = require('node:sqlite');
|
|
197
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
198
|
+
try {
|
|
199
|
+
db.prepare('BEGIN').all();
|
|
200
|
+
const result = callback(db);
|
|
201
|
+
sameIdentity(before, false);
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
db.close();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function rows(db, sql, ...params) {
|
|
209
|
+
const result = db.prepare(sql + ' LIMIT 4097').all(...params);
|
|
210
|
+
if (result.length > LIMIT)
|
|
211
|
+
throw new Error('ZCode inventory exceeds the supported bound');
|
|
212
|
+
return result;
|
|
213
|
+
}
|
|
214
|
+
/** Record a native reservation without redirecting storage or copying configuration. */
|
|
215
|
+
function captureZCodeSharedHistory(home, lane, pointer, selected, sessionId, cwd, command, launch) {
|
|
216
|
+
if (!LANE.test(lane) || !/^sess_[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(sessionId)
|
|
217
|
+
|| path_1.default.resolve(cwd) !== cwd || path_1.default.basename(pointer) !== lane + '.json')
|
|
218
|
+
throw new Error('Unsupported ZCode creation metadata');
|
|
219
|
+
const namespace = mkdir(path_1.default.join(home, '.remote-cli', 'zcode-shared', lane));
|
|
220
|
+
const marker = fs_1.default.existsSync(path_1.default.join(namespace.path, 'ownership.json')) ? readSharedMarker(namespace, lane)
|
|
221
|
+
: { version: 2, lane, namespace, roots: {} };
|
|
222
|
+
if (marker.roots[sessionId])
|
|
223
|
+
throw new Error('ZCode new-session reply reused an existing identity');
|
|
224
|
+
// The audited create operation reserves an ID before writing any session row.
|
|
225
|
+
// Existing IDs are never adopted as newly created, even with matching cwd.
|
|
226
|
+
if (withDatabase(selected.database, db => rows(db, 'SELECT id FROM session WHERE id = ?', sessionId)).length) {
|
|
227
|
+
throw new Error('ZCode creation returned a pre-existing persisted session');
|
|
228
|
+
}
|
|
229
|
+
const target = { version: 1, backend: 'zcode', nativeVersion: 'zcode-session-data-v4', provenance: 'created',
|
|
230
|
+
sessionId, executorThreadId: lane, cwd, command, home: identity(home), nativeHome: identity(selected.storage),
|
|
231
|
+
pointerHash: (0, NativeHistoryFiles_1.stableHistoryHash)({ id: sessionId, cwd }), ownership: { contract: 'zcode-shared-storage-v1', namespace,
|
|
232
|
+
database: identity(selected.database, false), databaseParent: identity(path_1.default.dirname(selected.database)),
|
|
233
|
+
pointerRoot: identity(path_1.default.dirname(pointer)), pointer, initialRow: 'reserved', launch: { command: launch.command, args: [...launch.args] } } };
|
|
234
|
+
if (!validZCodeOwnedTarget(target))
|
|
235
|
+
throw new Error('Invalid ZCode shared receipt');
|
|
236
|
+
marker.roots[sessionId] = { hash: (0, NativeHistoryFiles_1.stableHistoryHash)(target), target, phase: 'reserved' };
|
|
237
|
+
saveMarker(marker);
|
|
238
|
+
return target;
|
|
239
|
+
}
|
|
240
|
+
/** Durable prompt fence also covers resume after process recreation. No receipt/hash migration. */
|
|
241
|
+
function observeZCodeSharedPrompt(home, lane, sessionId, selected, confirmed) {
|
|
242
|
+
const ns = identity(path_1.default.join(home, '.remote-cli', 'zcode-shared', lane));
|
|
243
|
+
const marker = readSharedMarker(ns, lane);
|
|
244
|
+
const entry = marker.roots[sessionId];
|
|
245
|
+
if (!entry || !validZCodeOwnedTarget(entry.target) || !shared(entry.target) || entry.hash !== (0, NativeHistoryFiles_1.stableHistoryHash)(entry.target)
|
|
246
|
+
|| entry.target.nativeHome.path !== selected.storage || entry.target.ownership.database.path !== selected.database)
|
|
247
|
+
throw new Error('ZCode resumed storage is not owned');
|
|
248
|
+
owned(entry.target);
|
|
249
|
+
if ((0, NativeHistoryFiles_1.stableHistoryHash)(json(entry.target.ownership.pointer)) !== entry.target.pointerHash)
|
|
250
|
+
throw new Error('ZCode resumed pointer is not owned');
|
|
251
|
+
if (confirmed) {
|
|
252
|
+
const found = withDatabase(selected.database, db => rows(db, 'SELECT id, parent_id, directory, time_deleted FROM session WHERE id = ?', sessionId));
|
|
253
|
+
if (found.length !== 1 || found[0].parent_id !== null || found[0].directory !== entry.target.cwd || found[0].time_deleted !== null) {
|
|
254
|
+
throw new Error('ZCode prompted session was not confirmed in its original database');
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
entry.phase = confirmed ? 'confirmed' : 'prompted';
|
|
258
|
+
saveMarker(marker);
|
|
259
|
+
}
|
|
260
|
+
/** Must finish, including the store observer, before the first model prompt. */
|
|
261
|
+
function captureZCodeOwnedHistory(ns, sessionId, cwd, command, beforePointerSave = false, launch) {
|
|
262
|
+
if (!ID.test(sessionId) || path_1.default.resolve(cwd) !== cwd)
|
|
263
|
+
throw new Error('Invalid ZCode creation metadata');
|
|
264
|
+
sameIdentity(ns.home);
|
|
265
|
+
sameIdentity(ns.pointerRoot);
|
|
266
|
+
const marker = readMarker(ns.namespace, ns.lane);
|
|
267
|
+
// The executor can observe the native create reply before ACP saves its pointer.
|
|
268
|
+
// This records the expected binding without changing or adopting an old pointer.
|
|
269
|
+
const pointer = beforePointerSave ? { id: sessionId, cwd } : json(ns.pointer);
|
|
270
|
+
if (pointer.id !== sessionId || pointer.cwd !== cwd || pointer.adopted === true)
|
|
271
|
+
throw new Error('ZCode pointer is not newly owned');
|
|
272
|
+
const session = withDatabase(ns.database, db => rows(db, 'SELECT id, parent_id, directory, time_deleted FROM session WHERE id = ?', sessionId));
|
|
273
|
+
// Native session/create reserves an ID; events.ts persists its row on the first
|
|
274
|
+
// activity. The creation reply and exclusive database bind this reservation.
|
|
275
|
+
if (session.length > 1 || session.length === 1 && (session[0].parent_id !== null || session[0].directory !== cwd || session[0].time_deleted != null))
|
|
276
|
+
throw new Error('ZCode creation was not confirmed');
|
|
277
|
+
const target = { version: 1, backend: 'zcode', nativeVersion: 'zcode-session-data-v4', provenance: 'created',
|
|
278
|
+
sessionId, executorThreadId: ns.lane, cwd, command, home: ns.home, nativeHome: ns.storage,
|
|
279
|
+
pointerHash: (0, NativeHistoryFiles_1.stableHistoryHash)(pointer), ownership: { contract: 'zcode-exclusive-storage-v1', namespace: ns.namespace,
|
|
280
|
+
database: identity(ns.database, false), pointerRoot: ns.pointerRoot, pointer: ns.pointer,
|
|
281
|
+
initialRow: session.length ? 'persisted' : 'reserved',
|
|
282
|
+
...(launch ? { launch: { command: launch.command, args: [...launch.args] } } : {}) } };
|
|
283
|
+
const hash = (0, NativeHistoryFiles_1.stableHistoryHash)(target);
|
|
284
|
+
if (marker.roots[sessionId] && marker.roots[sessionId] !== hash)
|
|
285
|
+
throw new Error('ZCode creation receipt changed');
|
|
286
|
+
marker.roots[sessionId] = hash;
|
|
287
|
+
saveMarker(marker);
|
|
288
|
+
return target;
|
|
289
|
+
}
|
|
290
|
+
/** Pure persisted-shape check for the shared store; never rewrites old receipts. */
|
|
291
|
+
function validZCodeOwnedTarget(value) {
|
|
292
|
+
if (!(0, ZCodeSessionDeletion_1.validZCodeDeletionTarget)(value))
|
|
293
|
+
return false;
|
|
294
|
+
const o = value.ownership;
|
|
295
|
+
return !!o && ['zcode-exclusive-storage-v1', 'zcode-shared-storage-v1'].includes(o.contract) && ['reserved', 'persisted'].includes(o.initialRow)
|
|
296
|
+
&& (0, NativeHistoryFiles_1.validHistoryDirectory)(o.namespace) && (0, NativeHistoryFiles_1.validHistoryDirectory)(o.database) && (0, NativeHistoryFiles_1.validHistoryDirectory)(o.pointerRoot)
|
|
297
|
+
&& o.namespace.path === path_1.default.join(value.home.path, '.remote-cli', o.contract === 'zcode-shared-storage-v1' ? 'zcode-shared' : 'zcode-owned', value.executorThreadId)
|
|
298
|
+
&& (o.contract === 'zcode-shared-storage-v1' ? (0, NativeHistoryFiles_1.validHistoryDirectory)(o.databaseParent)
|
|
299
|
+
&& o.databaseParent.path === path_1.default.dirname(o.database.path) && !!o.launch
|
|
300
|
+
: o.database.path === path_1.default.join(value.nativeHome.path, 'sessions.sqlite'))
|
|
301
|
+
&& o.pointer === path_1.default.join(o.pointerRoot.path, value.executorThreadId + '.json')
|
|
302
|
+
&& (!o.launch || typeof o.launch.command === 'string' && !!o.launch.command && !o.launch.command.includes('\0')
|
|
303
|
+
&& Array.isArray(o.launch.args) && o.launch.args.length <= 64 && o.launch.args.every(arg => typeof arg === 'string' && !arg.includes('\0')));
|
|
304
|
+
}
|
|
305
|
+
function owned(target) {
|
|
306
|
+
if (!validZCodeOwnedTarget(target))
|
|
307
|
+
throw new Error('Missing ZCode exclusive ownership');
|
|
308
|
+
const o = target.ownership;
|
|
309
|
+
sameIdentity(target.home);
|
|
310
|
+
sameIdentity(target.nativeHome);
|
|
311
|
+
sameIdentity(o.database, false);
|
|
312
|
+
sameIdentity(o.pointerRoot);
|
|
313
|
+
if (shared(target)) {
|
|
314
|
+
sameIdentity(o.databaseParent);
|
|
315
|
+
const entry = readSharedMarker(o.namespace, target.executorThreadId).roots[target.sessionId];
|
|
316
|
+
if (!entry || entry.hash !== (0, NativeHistoryFiles_1.stableHistoryHash)(target) || (0, NativeHistoryFiles_1.stableHistoryHash)(entry.target) !== entry.hash
|
|
317
|
+
|| !['reserved', 'prompted', 'confirmed'].includes(entry.phase))
|
|
318
|
+
throw new Error('ZCode shared receipt is not owned');
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const marker = readMarker(o.namespace, target.executorThreadId);
|
|
322
|
+
if ((0, NativeHistoryFiles_1.stableHistoryHash)(marker.storage) !== (0, NativeHistoryFiles_1.stableHistoryHash)(target.nativeHome)
|
|
323
|
+
|| marker.roots[target.sessionId] !== (0, NativeHistoryFiles_1.stableHistoryHash)(target))
|
|
324
|
+
throw new Error('ZCode creation receipt is not owned');
|
|
325
|
+
}
|
|
326
|
+
function checkPointers(target, ids, detached) {
|
|
327
|
+
const files = fs_1.default.readdirSync(target.ownership.pointerRoot.path).filter(x => x.endsWith('.json'));
|
|
328
|
+
if (files.length > LIMIT)
|
|
329
|
+
throw new Error('ZCode pointer inventory exceeds the supported bound');
|
|
330
|
+
let matched = false;
|
|
331
|
+
for (const name of files) {
|
|
332
|
+
const file = path_1.default.join(target.ownership.pointerRoot.path, name);
|
|
333
|
+
const pointer = json(file);
|
|
334
|
+
// An unrelated valid native ID, including non-UUID IDs, is not a conflict.
|
|
335
|
+
if (!pointer || typeof pointer.id !== 'string' || !ID.test(pointer.id))
|
|
336
|
+
throw new Error('Invalid ZCode pointer inventory');
|
|
337
|
+
if (!ids.includes(pointer.id))
|
|
338
|
+
continue;
|
|
339
|
+
if (file !== target.ownership.pointer || pointer.id !== target.sessionId || pointer.adopted === true
|
|
340
|
+
|| (0, NativeHistoryFiles_1.stableHistoryHash)(pointer) !== target.pointerHash)
|
|
341
|
+
throw new Error('ZCode history is referenced by another pointer');
|
|
342
|
+
matched = true;
|
|
343
|
+
}
|
|
344
|
+
if (!matched && !detached)
|
|
345
|
+
throw new Error('ZCode pointer detached without authorization');
|
|
346
|
+
}
|
|
347
|
+
function inventory(target, expected = []) {
|
|
348
|
+
if (shared(target))
|
|
349
|
+
return withDatabase(target.ownership.database.path, db => {
|
|
350
|
+
const seen = new Set([target.sessionId, ...expected]);
|
|
351
|
+
const sessions = [];
|
|
352
|
+
const links = [];
|
|
353
|
+
for (const id of seen) {
|
|
354
|
+
if (seen.size > LIMIT)
|
|
355
|
+
throw new Error('ZCode owned closure exceeds the supported bound');
|
|
356
|
+
sessions.push(...rows(db, 'SELECT id, parent_id, directory, task_type, time_deleted FROM session WHERE id = ?', id));
|
|
357
|
+
const children = rows(db, 'SELECT id, task_type FROM session WHERE parent_id = ?', id);
|
|
358
|
+
if (children.some(child => !OWNED_TYPES.has(child.task_type) && !INDEPENDENT_TYPES.has(child.task_type)))
|
|
359
|
+
throw new Error('Unknown ZCode descendant ownership format');
|
|
360
|
+
const edges = rows(db, 'SELECT parent_session_id, child_session_id FROM session_task_link WHERE parent_session_id = ? OR child_session_id = ?', id, id);
|
|
361
|
+
links.push(...edges);
|
|
362
|
+
for (const child of children)
|
|
363
|
+
if (OWNED_TYPES.has(child.task_type))
|
|
364
|
+
seen.add(child.id);
|
|
365
|
+
for (const edge of edges)
|
|
366
|
+
if (edge.parent_session_id === id)
|
|
367
|
+
seen.add(edge.child_session_id);
|
|
368
|
+
if (links.length > LIMIT * 4)
|
|
369
|
+
throw new Error('ZCode link inventory exceeds the supported bound');
|
|
370
|
+
}
|
|
371
|
+
return { sessions, links };
|
|
372
|
+
});
|
|
373
|
+
return withDatabase(target.ownership.database.path, db => ({
|
|
374
|
+
sessions: rows(db, 'SELECT id, parent_id, directory, task_type, time_deleted FROM session'),
|
|
375
|
+
links: rows(db, 'SELECT parent_session_id, child_session_id FROM session_task_link'),
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
function inspectSharedTree(target, prepared, detached) {
|
|
379
|
+
const { sessions, links } = inventory(target, prepared?.sessionIds);
|
|
380
|
+
const byId = new Map(sessions.map(row => [row.id, row]));
|
|
381
|
+
if (byId.size !== sessions.length || sessions.some(row => !ID.test(row.id) || row.time_deleted !== null
|
|
382
|
+
|| row.parent_id !== null && !ID.test(row.parent_id) || row.task_type === 'fork'
|
|
383
|
+
|| !OWNED_TYPES.has(row.task_type) && !INDEPENDENT_TYPES.has(row.task_type)))
|
|
384
|
+
throw new Error('Unsupported ZCode owned session metadata');
|
|
385
|
+
for (const link of links)
|
|
386
|
+
if (!byId.has(link.parent_session_id) || !byId.has(link.child_session_id))
|
|
387
|
+
throw new Error('ZCode tree has a foreign or dangling task reference');
|
|
388
|
+
let ids;
|
|
389
|
+
const root = byId.get(target.sessionId);
|
|
390
|
+
if (root) {
|
|
391
|
+
if (root.parent_id !== null || root.directory !== target.cwd || links.some(link => link.child_session_id === target.sessionId))
|
|
392
|
+
throw new Error('ZCode root identity changed');
|
|
393
|
+
ids = [...byId.keys()].sort();
|
|
394
|
+
for (const row of sessions)
|
|
395
|
+
if (row.parent_id !== null && !byId.has(row.parent_id))
|
|
396
|
+
throw new Error('ZCode descendant has a foreign parent');
|
|
397
|
+
// No other independently recorded root may be consumed by this cascade.
|
|
398
|
+
for (const kind of ['zcode-shared', 'zcode-owned']) {
|
|
399
|
+
const base = path_1.default.join(target.home.path, '.remote-cli', kind);
|
|
400
|
+
if (!fs_1.default.existsSync(base))
|
|
401
|
+
continue;
|
|
402
|
+
identity(base);
|
|
403
|
+
const lanes = fs_1.default.readdirSync(base);
|
|
404
|
+
if (lanes.length > LIMIT)
|
|
405
|
+
throw new Error('ZCode receipt inventory exceeds the supported bound');
|
|
406
|
+
for (const lane of lanes) {
|
|
407
|
+
if (!LANE.test(lane))
|
|
408
|
+
throw new Error('Unexpected ZCode receipt namespace');
|
|
409
|
+
const ns = identity(path_1.default.join(base, lane));
|
|
410
|
+
// A failed capture can create the directory before its marker. It does
|
|
411
|
+
// not establish any ownership and cannot authorize deletion itself.
|
|
412
|
+
if (!fs_1.default.existsSync(path_1.default.join(ns.path, 'ownership.json')))
|
|
413
|
+
continue;
|
|
414
|
+
if (kind === 'zcode-shared') {
|
|
415
|
+
const marker = readSharedMarker(ns, lane);
|
|
416
|
+
for (const id of ids) {
|
|
417
|
+
const entry = marker.roots[id];
|
|
418
|
+
if (!entry)
|
|
419
|
+
continue;
|
|
420
|
+
if (!validZCodeOwnedTarget(entry.target) || entry.hash !== (0, NativeHistoryFiles_1.stableHistoryHash)(entry.target))
|
|
421
|
+
throw new Error('Invalid ZCode receipt inventory');
|
|
422
|
+
if (entry.target.ownership.database.path === target.ownership.database.path
|
|
423
|
+
&& (lane !== target.executorThreadId || id !== target.sessionId))
|
|
424
|
+
throw new Error('ZCode cascade includes an independent root');
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
const marker = readMarker(ns, lane);
|
|
429
|
+
if (path_1.default.join(marker.storage.path, 'sessions.sqlite') === target.ownership.database.path && ids.some(id => marker.roots[id])) {
|
|
430
|
+
throw new Error('ZCode cascade includes an exclusive root');
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (prepared && JSON.stringify(ids) !== JSON.stringify(prepared.sessionIds))
|
|
436
|
+
throw new Error('ZCode cascade changed');
|
|
437
|
+
}
|
|
438
|
+
else {
|
|
439
|
+
const phase = readSharedMarker(target.ownership.namespace, target.executorThreadId).roots[target.sessionId].phase;
|
|
440
|
+
if (sessions.length || links.length || !prepared && phase !== 'reserved')
|
|
441
|
+
throw new Error('ZCode prompted or partial history has no confirmed root');
|
|
442
|
+
ids = prepared?.sessionIds ?? [target.sessionId];
|
|
443
|
+
withDatabase(target.ownership.database.path, db => {
|
|
444
|
+
for (const table of ['dwf_run', 'workflow_run']) {
|
|
445
|
+
if (rows(db, `SELECT id FROM ${table} WHERE parent_session_id IN (${ids.map(() => '?').join(',')})`, ...ids).length)
|
|
446
|
+
throw new Error('ZCode absent root has orphan outputs');
|
|
447
|
+
}
|
|
448
|
+
for (const table of ['part', 'input_history']) {
|
|
449
|
+
if (rows(db, `SELECT id FROM ${table} WHERE session_id IN (${ids.map(() => '?').join(',')})`, ...ids).length)
|
|
450
|
+
throw new Error('ZCode absent root has orphan activity');
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
checkPointers(target, ids, detached);
|
|
455
|
+
// Foreign artifact references are checked by native purge. Do not read other
|
|
456
|
+
// sessions' part/transcript text in our shared-store preflight.
|
|
457
|
+
return ids;
|
|
458
|
+
}
|
|
459
|
+
async function inspectZCodeOwnedTree(target, prepared, detached = false) {
|
|
460
|
+
owned(target);
|
|
461
|
+
if (prepared && !(0, ZCodeSessionDeletion_1.validZCodeDeletionPreparation)(target, prepared))
|
|
462
|
+
throw new Error('ZCode preparation changed');
|
|
463
|
+
if (shared(target))
|
|
464
|
+
return inspectSharedTree(target, prepared, detached);
|
|
465
|
+
const { sessions, links } = inventory(target);
|
|
466
|
+
const byId = new Map(sessions.map(row => [row.id, row]));
|
|
467
|
+
if (byId.size !== sessions.length || sessions.some(row => !ID.test(row.id) || row.parent_id !== null && !ID.test(row.parent_id)))
|
|
468
|
+
throw new Error('Unsupported ZCode session metadata');
|
|
469
|
+
for (const link of links)
|
|
470
|
+
if (!byId.has(link.parent_session_id) || !byId.has(link.child_session_id))
|
|
471
|
+
throw new Error('Incomplete ZCode task link');
|
|
472
|
+
const walk = (root) => {
|
|
473
|
+
const seen = new Set([root]);
|
|
474
|
+
for (const id of seen) {
|
|
475
|
+
const children = sessions.filter(row => row.parent_id === id && OWNED_TYPES.has(row.task_type)).map(row => row.id);
|
|
476
|
+
children.push(...links.filter(row => row.parent_session_id === id).map(row => row.child_session_id));
|
|
477
|
+
for (const child of children) {
|
|
478
|
+
if (child === root)
|
|
479
|
+
throw new Error('Cyclic ZCode ownership');
|
|
480
|
+
seen.add(child);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return seen;
|
|
484
|
+
};
|
|
485
|
+
const marker = readMarker(target.ownership.namespace, target.executorThreadId);
|
|
486
|
+
const covered = new Set();
|
|
487
|
+
for (const root of Object.keys(marker.roots).filter(id => byId.has(id))) {
|
|
488
|
+
const record = byId.get(root);
|
|
489
|
+
if (record.parent_id !== null || record.time_deleted != null)
|
|
490
|
+
throw new Error('ZCode root changed');
|
|
491
|
+
for (const id of walk(root)) {
|
|
492
|
+
if (covered.has(id))
|
|
493
|
+
throw new Error('ZCode tree is shared between owned roots');
|
|
494
|
+
covered.add(id);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
if (sessions.some(row => !covered.has(row.id)))
|
|
498
|
+
throw new Error('ZCode namespace contains foreign or orphan sessions');
|
|
499
|
+
let ids;
|
|
500
|
+
if (byId.has(target.sessionId)) {
|
|
501
|
+
if (byId.get(target.sessionId).directory !== target.cwd)
|
|
502
|
+
throw new Error('ZCode workspace changed');
|
|
503
|
+
ids = [...walk(target.sessionId)].sort();
|
|
504
|
+
if (prepared && JSON.stringify(ids) !== JSON.stringify(prepared.sessionIds))
|
|
505
|
+
throw new Error('ZCode cascade changed');
|
|
506
|
+
}
|
|
507
|
+
else {
|
|
508
|
+
if (!prepared && target.ownership.initialRow !== 'reserved' || prepared?.sessionIds.some(id => byId.has(id)))
|
|
509
|
+
throw new Error('ZCode missing root has no complete preparation');
|
|
510
|
+
ids = prepared?.sessionIds ?? [target.sessionId];
|
|
511
|
+
withDatabase(target.ownership.database.path, db => {
|
|
512
|
+
for (const table of ['dwf_run', 'workflow_run']) {
|
|
513
|
+
if (rows(db, `SELECT id FROM ${table} WHERE parent_session_id IN (${ids.map(() => '?').join(',')})`, ...ids).length)
|
|
514
|
+
throw new Error('ZCode missing root has orphan workflow outputs');
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
checkPointers(target, ids, detached);
|
|
519
|
+
// Native purge also checks artifact references. Preflight them before exporting.
|
|
520
|
+
withDatabase(target.ownership.database.path, db => {
|
|
521
|
+
for (const row of rows(db, "SELECT session_id, data FROM part WHERE data LIKE '%zcode-artifact://%'")) {
|
|
522
|
+
if (ids.includes(row.session_id))
|
|
523
|
+
continue;
|
|
524
|
+
for (const match of String(row.data).matchAll(/zcode-artifact:\/\/([^/"\\\s]+)\//g)) {
|
|
525
|
+
if (ids.includes(decodeURIComponent(match[1])))
|
|
526
|
+
throw new Error('ZCode artifacts have a foreign reference');
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
return ids;
|
|
531
|
+
}
|
|
532
|
+
function databaseOutputs(target, ids) {
|
|
533
|
+
return withDatabase(target.ownership.database.path, db => {
|
|
534
|
+
const marks = ids.map(() => '?').join(',');
|
|
535
|
+
const result = {};
|
|
536
|
+
// Preserve deliverables, not the session/message/entry/input-history transcript.
|
|
537
|
+
for (const table of ['dwf_run', 'workflow_run']) {
|
|
538
|
+
const columns = table === 'dwf_run' ? 'id, parent_session_id, script_text, result_json, failure_json' : 'id, parent_session_id, script_path';
|
|
539
|
+
const runs = rows(db, `SELECT ${columns} FROM ${table} WHERE parent_session_id IN (${marks}) ORDER BY id`, ...ids);
|
|
540
|
+
result[table] = runs;
|
|
541
|
+
const runIds = runs.map(row => row.id);
|
|
542
|
+
const runMarks = runIds.map(() => '?').join(',');
|
|
543
|
+
const child = table === 'dwf_run' ? 'dwf_node' : 'workflow_activity';
|
|
544
|
+
result[child] = runIds.length ? rows(db, `SELECT id, run_id, result_json, error_json FROM ${child} WHERE run_id IN (${runMarks}) ORDER BY id`, ...runIds) : [];
|
|
545
|
+
const events = table === 'dwf_run' ? 'dwf_event' : 'workflow_event';
|
|
546
|
+
result[events] = runIds.length ? rows(db, `SELECT run_id, sequence, type, payload_json FROM ${events} WHERE run_id IN (${runMarks}) AND (type LIKE '%artifact%' OR type = 'report') ORDER BY run_id, sequence`, ...runIds) : [];
|
|
547
|
+
}
|
|
548
|
+
result.attachments = rows(db, `SELECT id, session_id, attachments FROM input_history WHERE session_id IN (${marks}) AND attachments IS NOT NULL ORDER BY id`, ...ids);
|
|
549
|
+
result.parts = rows(db, `SELECT id, session_id, json_extract(data, '$.type') AS type, data FROM part WHERE session_id IN (${marks}) AND json_extract(data, '$.type') IN ('file', 'image', 'tool') ORDER BY id`, ...ids)
|
|
550
|
+
.map(row => {
|
|
551
|
+
const data = JSON.parse(row.data);
|
|
552
|
+
if (row.type !== 'tool')
|
|
553
|
+
return row;
|
|
554
|
+
return { id: row.id, session_id: row.session_id, type: row.type,
|
|
555
|
+
output: data.state?.output, attachments: data.state?.attachments, metadata: data.state?.metadata };
|
|
556
|
+
});
|
|
557
|
+
const bytes = Buffer.from(JSON.stringify(result));
|
|
558
|
+
if (bytes.length > MAX_BYTES)
|
|
559
|
+
throw new Error('ZCode database outputs exceed the export bound');
|
|
560
|
+
return bytes;
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
/** Read only single components through live directory descriptors on Linux. */
|
|
564
|
+
function readFiles(root, anchors = []) {
|
|
565
|
+
if (process.platform !== 'linux')
|
|
566
|
+
throw new Error('ZCode export anchoring requires Linux');
|
|
567
|
+
const result = new Map();
|
|
568
|
+
const handles = [];
|
|
569
|
+
let total = 0, directories = 0;
|
|
570
|
+
let entered = false;
|
|
571
|
+
try {
|
|
572
|
+
let parent = fs_1.default.openSync(path_1.default.parse(root).root, fs_1.default.constants.O_RDONLY | fs_1.default.constants.O_DIRECTORY | fs_1.default.constants.O_NOFOLLOW);
|
|
573
|
+
handles.push(parent);
|
|
574
|
+
let current = path_1.default.parse(root).root;
|
|
575
|
+
for (const component of root.slice(current.length).split(path_1.default.sep).filter(Boolean)) {
|
|
576
|
+
parent = fs_1.default.openSync(`/proc/self/fd/${parent}/${component}`, fs_1.default.constants.O_RDONLY | fs_1.default.constants.O_DIRECTORY | fs_1.default.constants.O_NOFOLLOW);
|
|
577
|
+
handles.push(parent);
|
|
578
|
+
current = path_1.default.join(current, component);
|
|
579
|
+
const expected = anchors.find(value => value.path === current);
|
|
580
|
+
if (expected) {
|
|
581
|
+
const stat = fs_1.default.fstatSync(parent, { bigint: true });
|
|
582
|
+
if (String(stat.ino) !== expected.ino || String(stat.dev) !== expected.dev)
|
|
583
|
+
throw new Error('ZCode export ancestor changed');
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const visit = (fd, prefix, depth) => {
|
|
587
|
+
if (depth > 64 || ++directories > LIMIT)
|
|
588
|
+
throw new Error('ZCode export nesting exceeds the supported bound');
|
|
589
|
+
for (const name of fs_1.default.readdirSync(`/proc/self/fd/${fd}`).sort()) {
|
|
590
|
+
if (name === '.' || name === '..' || name.includes(path_1.default.sep))
|
|
591
|
+
throw new Error('Invalid export entry');
|
|
592
|
+
const anchored = `/proc/self/fd/${fd}/${name}`;
|
|
593
|
+
const stat = fs_1.default.lstatSync(anchored, { bigint: true });
|
|
594
|
+
if (stat.isDirectory()) {
|
|
595
|
+
const child = fs_1.default.openSync(anchored, fs_1.default.constants.O_RDONLY | fs_1.default.constants.O_DIRECTORY | fs_1.default.constants.O_NOFOLLOW);
|
|
596
|
+
try {
|
|
597
|
+
const actual = fs_1.default.fstatSync(child, { bigint: true });
|
|
598
|
+
if (actual.ino !== stat.ino || actual.dev !== stat.dev)
|
|
599
|
+
throw new Error('ZCode export directory changed');
|
|
600
|
+
visit(child, prefix + name + '/', depth + 1);
|
|
601
|
+
}
|
|
602
|
+
finally {
|
|
603
|
+
fs_1.default.closeSync(child);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
if (!stat.isFile() || stat.nlink !== 1n || total + Number(stat.size) > MAX_BYTES || result.size >= LIMIT)
|
|
608
|
+
throw new Error('Unsupported ZCode artifact file');
|
|
609
|
+
const file = fs_1.default.openSync(anchored, fs_1.default.constants.O_RDONLY | fs_1.default.constants.O_NOFOLLOW);
|
|
610
|
+
try {
|
|
611
|
+
const before = fs_1.default.fstatSync(file, { bigint: true });
|
|
612
|
+
if (before.ino !== stat.ino || before.dev !== stat.dev)
|
|
613
|
+
throw new Error('ZCode artifact changed');
|
|
614
|
+
const bytes = fs_1.default.readFileSync(file);
|
|
615
|
+
const after = fs_1.default.fstatSync(file, { bigint: true });
|
|
616
|
+
if (before.size !== after.size || before.mtimeNs !== after.mtimeNs || after.nlink !== 1n)
|
|
617
|
+
throw new Error('ZCode artifact changed while reading');
|
|
618
|
+
result.set(prefix + name, bytes);
|
|
619
|
+
total += bytes.length;
|
|
620
|
+
}
|
|
621
|
+
finally {
|
|
622
|
+
fs_1.default.closeSync(file);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
entered = true;
|
|
628
|
+
visit(parent, '', 0);
|
|
629
|
+
}
|
|
630
|
+
catch (e) {
|
|
631
|
+
if (entered || !absent(e))
|
|
632
|
+
throw e; /* Absent per-session directories contain no outputs. */
|
|
633
|
+
}
|
|
634
|
+
finally {
|
|
635
|
+
for (const fd of handles.reverse())
|
|
636
|
+
fs_1.default.closeSync(fd);
|
|
637
|
+
}
|
|
638
|
+
return result;
|
|
639
|
+
}
|
|
640
|
+
function nativeFiles(target, ids) {
|
|
641
|
+
const files = new Map();
|
|
642
|
+
let total = 0;
|
|
643
|
+
for (const kind of FILE_KINDS)
|
|
644
|
+
for (const id of ids) {
|
|
645
|
+
if (!ID.test(id))
|
|
646
|
+
throw new Error('Invalid ZCode export session');
|
|
647
|
+
const cli = path_1.default.basename(target.nativeHome.path) === 'cli' ? target.nativeHome.path : path_1.default.join(target.nativeHome.path, 'cli');
|
|
648
|
+
for (const [name, bytes] of readFiles(path_1.default.join(cli, kind, id), [target.home, target.ownership.namespace, target.nativeHome])) {
|
|
649
|
+
total += bytes.length;
|
|
650
|
+
if (files.size >= LIMIT || total > MAX_BYTES)
|
|
651
|
+
throw new Error('ZCode exports exceed the supported bound');
|
|
652
|
+
files.set(`${kind}/${id}/${name}`, bytes);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return files;
|
|
656
|
+
}
|
|
657
|
+
function exportPath(target) {
|
|
658
|
+
return path_1.default.join(target.home.path, '.remote-cli', 'zcode-exports', target.executorThreadId, (0, NativeHistoryFiles_1.stableHistoryHash)(target));
|
|
659
|
+
}
|
|
660
|
+
async function preserveZCodeArtifacts(target, ids) {
|
|
661
|
+
owned(target);
|
|
662
|
+
const root = exportPath(target);
|
|
663
|
+
if (root === target.cwd || root.startsWith(target.cwd + path_1.default.sep))
|
|
664
|
+
throw new Error('ZCode exports must be outside the disposable workspace');
|
|
665
|
+
if (fs_1.default.existsSync(root)) {
|
|
666
|
+
const receipt = { root: identity(root), manifestHash: digest(fs_1.default.readFileSync(path_1.default.join(root, 'manifest.json'))) };
|
|
667
|
+
await verifyZCodeArtifacts(receipt, target, ids);
|
|
668
|
+
return receipt;
|
|
669
|
+
}
|
|
670
|
+
const files = nativeFiles(target, ids);
|
|
671
|
+
files.set('database-outputs.json', databaseOutputs(target, ids));
|
|
672
|
+
const parent = mkdir(path_1.default.dirname(root));
|
|
673
|
+
const staging = root + '.' + (0, crypto_1.randomUUID)();
|
|
674
|
+
mkdir(staging);
|
|
675
|
+
const manifest = { version: 1, targetHash: (0, NativeHistoryFiles_1.stableHistoryHash)(target), sessionIds: [...ids], files: [] };
|
|
676
|
+
for (const [name, bytes] of files) {
|
|
677
|
+
mkdir(path_1.default.dirname(path_1.default.join(staging, name)));
|
|
678
|
+
durable(path_1.default.join(staging, name), bytes);
|
|
679
|
+
syncDirectory(path_1.default.dirname(path_1.default.join(staging, name)));
|
|
680
|
+
manifest.files.push({ name, size: bytes.length, hash: digest(bytes) });
|
|
681
|
+
}
|
|
682
|
+
const bytes = JSON.stringify(manifest);
|
|
683
|
+
durable(path_1.default.join(staging, 'manifest.json'), bytes);
|
|
684
|
+
syncDirectory(staging);
|
|
685
|
+
// Persist every intermediate directory entry before publishing the manifest.
|
|
686
|
+
const syncTree = (directory) => {
|
|
687
|
+
for (const entry of fs_1.default.readdirSync(directory, { withFileTypes: true }))
|
|
688
|
+
if (entry.isDirectory())
|
|
689
|
+
syncTree(path_1.default.join(directory, entry.name));
|
|
690
|
+
syncDirectory(directory);
|
|
691
|
+
};
|
|
692
|
+
syncTree(staging);
|
|
693
|
+
sameIdentity(parent);
|
|
694
|
+
fs_1.default.renameSync(staging, root);
|
|
695
|
+
syncDirectory(parent.path);
|
|
696
|
+
const receipt = { root: identity(root), manifestHash: digest(bytes) };
|
|
697
|
+
await verifyZCodeArtifacts(receipt, target, ids);
|
|
698
|
+
return receipt;
|
|
699
|
+
}
|
|
700
|
+
async function verifyZCodeArtifacts(receipt, target, ids) {
|
|
701
|
+
owned(target);
|
|
702
|
+
await (0, NativeHistoryFiles_1.verifyHistoryDirectory)(receipt.root);
|
|
703
|
+
if (receipt.root.path !== exportPath(target))
|
|
704
|
+
throw new Error('ZCode export root changed');
|
|
705
|
+
const files = readFiles(receipt.root.path, [target.home, receipt.root]);
|
|
706
|
+
const bytes = files.get('manifest.json');
|
|
707
|
+
if (!bytes || digest(bytes) !== receipt.manifestHash)
|
|
708
|
+
throw new Error('ZCode export manifest changed');
|
|
709
|
+
const manifest = JSON.parse(bytes.toString());
|
|
710
|
+
if (manifest.version !== 1 || manifest.targetHash !== (0, NativeHistoryFiles_1.stableHistoryHash)(target) || JSON.stringify(manifest.sessionIds) !== JSON.stringify(ids)
|
|
711
|
+
|| !Array.isArray(manifest.files) || files.size !== manifest.files.length + 1)
|
|
712
|
+
throw new Error('ZCode export receipt changed');
|
|
713
|
+
const expected = new Map();
|
|
714
|
+
for (const entry of manifest.files) {
|
|
715
|
+
const data = files.get(entry.name);
|
|
716
|
+
if (!data || expected.has(entry.name) || data.length !== entry.size || digest(data) !== entry.hash)
|
|
717
|
+
throw new Error('ZCode exported bytes changed');
|
|
718
|
+
expected.set(entry.name, entry.hash);
|
|
719
|
+
}
|
|
720
|
+
for (const [name, bytes] of nativeFiles(target, ids))
|
|
721
|
+
if (expected.get(name) !== digest(bytes))
|
|
722
|
+
throw new Error('ZCode outputs changed after export');
|
|
723
|
+
// Native purge deletes database rows atomically after files. Missing rows on retry
|
|
724
|
+
// use the immutable export, while surviving rows must still match it exactly.
|
|
725
|
+
if (inventory(target).sessions.some(row => ids.includes(row.id))) {
|
|
726
|
+
if (expected.get('database-outputs.json') !== digest(databaseOutputs(target, ids)))
|
|
727
|
+
throw new Error('ZCode database outputs changed after export');
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
/** Shared dispatcher must call this wrapper, after generation/ownership/writer checks. */
|
|
731
|
+
async function deleteOwnedZCodeHistory(target, recovery, factory) {
|
|
732
|
+
let prepared = recovery.prepared;
|
|
733
|
+
const result = await (0, ZCodeSessionDeletion_1.deleteOwnedZCodeSession)(target, { ...recovery,
|
|
734
|
+
persistPrepared: recovery.persistPrepared ? async (value) => { await recovery.persistPrepared(value); prepared = value; } : undefined,
|
|
735
|
+
inspectOwnedTree: (value, prepared) => inspectZCodeOwnedTree(value, prepared, recovery.detachedPointer),
|
|
736
|
+
preserveArtifacts: preserveZCodeArtifacts, verifyArtifacts: verifyZCodeArtifacts, }, factory ?? (value => {
|
|
737
|
+
owned(value);
|
|
738
|
+
const launch = (0, ZCodeCommand_1.resolveZCodeLaunch)(value.command);
|
|
739
|
+
// Storage RPCs need no disposable task cwd or project-local model initialization.
|
|
740
|
+
return new ZCodeClient_1.ZCodeClient({ cwd: value.nativeHome.path, command: value.command, maintenance: true, delegationWorker: true,
|
|
741
|
+
launch: { ...launch, ...value.ownership.launch, env: { ...launch.env, ZCODE_STORAGE_DIR: value.nativeHome.path,
|
|
742
|
+
ZCODE_SESSION_DB_PATH: value.ownership.database.path, ZCODE_SESSION_DB: value.ownership.database.path } } }, {});
|
|
743
|
+
}));
|
|
744
|
+
if (result.state !== 'deleted')
|
|
745
|
+
return result;
|
|
746
|
+
try {
|
|
747
|
+
owned(target);
|
|
748
|
+
if (!prepared || inventory(target, prepared.sessionIds).sessions.some(row => prepared.sessionIds.includes(row.id)))
|
|
749
|
+
throw new Error('ZCode purge left resumable history');
|
|
750
|
+
if (shared(target)) {
|
|
751
|
+
await inspectZCodeOwnedTree(target, prepared, recovery.detachedPointer);
|
|
752
|
+
if (nativeFiles(target, prepared.sessionIds).size)
|
|
753
|
+
throw new Error('ZCode purge left native session files');
|
|
754
|
+
}
|
|
755
|
+
await verifyZCodeArtifacts(prepared.artifacts, target, prepared.sessionIds);
|
|
756
|
+
return result;
|
|
757
|
+
}
|
|
758
|
+
catch {
|
|
759
|
+
return { state: 'uncertain', reason: 'ZCode purge acknowledgement could not be verified; preparation and exports are retained' };
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
//# sourceMappingURL=ZCodeOwnedHistory.js.map
|